Compare commits

...
Author SHA1 Message Date
Test 62fdcf9b2d @
fix(docker): eliminate TOCTOU race and format web components

Use fs.promises.open() to get a file handle, then fstat/readFile/
createReadStream from the same fd — eliminates the CodeQL
"file system race condition" alert between stat() and read.

Also runs prettier on the 5 web component files that were failing
the format CI check.
@
2026-05-25 08:16:27 +01:00
Test 81f095df05 fix(docker): harden log sanitization, fix error leak, fix killAndWait race
- Broaden log sanitization regex from [\r\n] to [\x00-\x1f\x7f] to strip
  all C0 control characters including ANSI escape sequences
- Replace error.message leak in 500 handler with generic string; log the
  real error server-side via console.error
- Fix killAndWait TOCTOU race by registering exit listener before kill
  and adding post-kill exitCode guard
2026-05-25 07:41:33 +01:00
Test 33d6ab5a33 Merge remote-tracking branch 'origin/main' into pr-1286
# Conflicts:
#	docker-server.mjs
#	gitnexus-web/test/unit/server-connection.test.ts
2026-05-25 06:54:57 +01:00
Test fe51058fe5 fix(docker): escape inline script injection to prevent XSS and add server-level integration tests
- Add jsonForScriptTag() that escapes <, >, & after JSON.stringify to prevent </script> breakout in inline config script
- Sanitize rawBackendUrl in warning log to prevent log injection via newlines
- Replace 5 duplicated-helper injection tests with 7 server-level HTTP integration tests that spawn the real docker-server.mjs with GITNEXUS_BACKEND_URL set
- Add XSS-specific test: URL containing </script> must produce exactly 1 <script> tag
- Add empty-string backendUrl frontend test
- Improve Docker Compose Linux guidance with explicit <server-ip> example
2026-05-25 06:48:23 +01:00
alaa 397488df02 feat(web): support GITNEXUS_BACKEND_URL env var for Docker deployments 2026-05-02 18:50:35 +01:00
11 changed files with 291 additions and 47 deletions
+13
View File
@@ -30,6 +30,19 @@ services:
container_name: ${WEB_CONTAINER_NAME:-gitnexus-web}
ports:
- '${WEB_HOST_PORT:-4173}:4173'
# Optional: override the backend URL served to the browser.
# Required when the gitnexus-server is not reachable at http://localhost:4747
# from the user's browser (e.g. remote server deployments).
#
# Docker Desktop (Mac/Windows):
# GITNEXUS_BACKEND_URL=http://host.docker.internal:4747
#
# Linux / remote server:
# GITNEXUS_BACKEND_URL=http://<server-ip>:4747
# (host.docker.internal requires extra_hosts on Linux Docker Engine)
#
# environment:
# - GITNEXUS_BACKEND_URL=http://host.docker.internal:4747
depends_on:
gitnexus-server:
condition: service_healthy
+88 -36
View File
@@ -1,12 +1,39 @@
import { createReadStream } from 'node:fs';
import { stat } from 'node:fs/promises';
import { open, stat } from 'node:fs/promises';
import { createServer } from 'node:http';
import { extname, isAbsolute, normalize, relative, resolve } from 'node:path';
import { extname, isAbsolute, normalize, relative, resolve, sep } from 'node:path';
const host = '0.0.0.0';
const port = Number(process.env.PORT || '4173');
const root = resolve(process.cwd(), 'dist');
function isValidUrl(value) {
try {
const u = new URL(value);
return u.protocol === 'http:' || u.protocol === 'https:';
} catch {
return false;
}
}
function jsonForScriptTag(obj) {
return JSON.stringify(obj)
.replace(/</g, '\\u003c')
.replace(/>/g, '\\u003e')
.replace(/&/g, '\\u0026');
}
const rawBackendUrl = process.env.GITNEXUS_BACKEND_URL ?? null;
if (rawBackendUrl && !isValidUrl(rawBackendUrl)) {
const safeRaw = rawBackendUrl.replace(/[\x00-\x1f\x7f]/g, ' ').slice(0, 200);
console.warn(
`[gitnexus-web] GITNEXUS_BACKEND_URL "${safeRaw}" is not a valid http/https URL -- ignoring.`,
);
}
const backendUrl = rawBackendUrl && isValidUrl(rawBackendUrl) ? rawBackendUrl : null;
const configScript = backendUrl
? `<script>window.__GITNEXUS_CONFIG__=${jsonForScriptTag({ backendUrl })};</script>`
: '';
const contentTypes = {
'.css': 'text/css; charset=utf-8',
'.html': 'text/html; charset=utf-8',
@@ -22,22 +49,14 @@ const contentTypes = {
// Static asset server for the gitnexus-web Docker image.
//
// Path-injection containment: the request handler is intentionally a single
// inline pipeline with no helper functions on the path-data flow. Each
// filesystem sink (stat, createReadStream) is immediately preceded by the
// canonical `path.relative` containment check that CodeQL's
// `js/path-injection` query recognizes as a sanitizer barrier:
// Path-injection containment: each filesystem sink is preceded by the
// canonical `path.relative` containment check that CodeQL recognizes as
// a sanitizer barrier.
//
// const rel = relative(root, candidate);
// if (rel.startsWith('..') || isAbsolute(rel)) reject;
// // candidate is now proven inside `root`
//
// Earlier iterations of this file used a helper (`resolveWithinRoot`) and a
// `startsWith(root + sep)` check. Both were semantically correct but neither
// was recognized by CodeQL: `startsWith(root + sep)` is not in the analyzer's
// barrier-pattern set, and helper-based sanitization is not followed across
// the request handler's reassignment paths in vanilla JS. The inline-at-sink
// shape below is the documented analyzer-friendly idiom.
// TOCTOU prevention: after the path barrier, the file is opened once via
// fs.promises.open() and all subsequent operations (stat, readFile,
// createReadStream) use the file handle, eliminating any race between
// the existence check and the read.
const server = createServer(async (req, res) => {
const urlPath = req.url?.split('?')[0] || '/';
@@ -66,6 +85,7 @@ const server = createServer(async (req, res) => {
return;
}
let handle;
try {
const initialStat = await stat(initialPath).catch(() => null);
@@ -80,10 +100,9 @@ const server = createServer(async (req, res) => {
finalPath = initialPath;
}
// Sanitizer barrier #2 — guards both the second stat() and the
// createReadStream() sinks. No reassignment of finalPath happens
// between this guard and either sink, so the analyzer can prove
// containment for both.
// Sanitizer barrier #2 — guards the open() sink below. No
// reassignment of finalPath happens between this guard and the
// open(), so the analyzer can prove containment.
const finalRel = relative(root, finalPath);
if (finalRel.startsWith('..') || isAbsolute(finalRel)) {
res.writeHead(400);
@@ -91,27 +110,60 @@ const server = createServer(async (req, res) => {
return;
}
const finalStat = await stat(finalPath).catch(() => null);
if (!finalStat?.isFile()) {
handle = await open(finalPath, 'r').catch(() => null);
if (!handle) {
res.writeHead(404);
res.end('Not found');
return;
}
const finalStat = await handle.stat();
if (!finalStat.isFile()) {
res.writeHead(404);
res.end('Not found');
return;
}
res.writeHead(200, {
'Cache-Control': finalPath.includes('/assets/')
? 'public, max-age=31536000, immutable'
: 'no-cache',
'Content-Type': contentTypes[extname(finalPath)] || 'application/octet-stream',
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Embedder-Policy': 'require-corp',
});
const stream = createReadStream(finalPath);
stream.on('error', () => res.destroy());
stream.pipe(res);
const isHtml = extname(finalPath) === '.html' || !extname(finalPath);
const cacheControl = finalPath.includes(`${sep}assets${sep}`)
? 'public, max-age=31536000, immutable'
: 'no-cache';
const contentType = contentTypes[extname(finalPath)] || 'application/octet-stream';
if (isHtml && configScript) {
const raw = await handle.readFile('utf8');
await handle.close();
handle = null;
if (!raw.includes('</head>')) {
console.warn('[gitnexus-web] Could not inject config: no </head> tag found in HTML');
}
const html = raw.includes('</head>') ? raw.replace('</head>', `${configScript}</head>`) : raw;
const buf = Buffer.from(html, 'utf8');
res.writeHead(200, {
'Cache-Control': cacheControl,
'Content-Type': 'text/html; charset=utf-8',
'Content-Length': buf.length,
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Embedder-Policy': 'require-corp',
});
res.end(buf);
} else {
res.writeHead(200, {
'Cache-Control': cacheControl,
'Content-Type': contentType,
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Embedder-Policy': 'require-corp',
});
const stream = handle.createReadStream();
handle = null;
stream.on('error', () => res.destroy());
stream.pipe(res);
}
} catch (error) {
console.error(error);
res.writeHead(500);
res.end(error instanceof Error ? error.message : 'Internal server error');
res.end('Internal server error');
} finally {
if (handle) await handle.close().catch(() => {});
}
});
+142 -1
View File
@@ -70,8 +70,20 @@ before(async () => {
await waitForServer(serverPort);
});
function killAndWait(proc) {
return new Promise((resolve) => {
if (!proc || proc.exitCode !== null) {
resolve();
return;
}
proc.once('exit', resolve);
proc.kill();
if (proc.exitCode !== null) resolve();
});
}
after(async () => {
child?.kill();
await killAndWait(child);
if (tmpDir) await rm(tmpDir, { recursive: true, force: true });
});
@@ -122,3 +134,132 @@ it('returns 404 when dist/index.html is missing', async () => {
const res = await rawGet(serverPort, '/nonexistent-page');
assert.equal(res.status, 404);
});
// -- Config injection: server-level integration tests ---
function spawnServerWithEnv(cwd, port, env) {
const proc = spawn(process.execPath, [serverScript], {
cwd,
env: { ...process.env, PORT: String(port), ...env },
stdio: 'pipe',
});
proc.on('error', (err) => {
throw err;
});
return proc;
}
async function withInjectionServer(envOverrides, fn) {
const dir = await mkdtemp(join(tmpdir(), 'gitnexus-inject-'));
const distDir = join(dir, 'dist');
const assetsDir = join(distDir, 'assets');
await mkdir(assetsDir, { recursive: true });
await writeFile(
join(distDir, 'index.html'),
'<!doctype html><html><head><meta charset="utf-8"></head><body>app</body></html>',
);
await writeFile(join(assetsDir, 'style.abc.css'), 'body{}');
const port = await getFreePort();
const proc = spawnServerWithEnv(dir, port, envOverrides);
try {
await waitForServer(port);
await fn(port);
} finally {
await killAndWait(proc);
await rm(dir, { recursive: true, force: true });
}
}
it('injects __GITNEXUS_CONFIG__ into / when GITNEXUS_BACKEND_URL is valid', async () => {
await withInjectionServer({ GITNEXUS_BACKEND_URL: 'http://10.0.0.1:4747' }, async (port) => {
const res = await rawGet(port, '/');
assert.equal(res.status, 200);
assert.ok(
res.body.includes('window.__GITNEXUS_CONFIG__'),
'Expected __GITNEXUS_CONFIG__ in response body',
);
assert.ok(res.body.includes('http://10.0.0.1:4747'), 'Expected backend URL in response body');
});
});
it('injects __GITNEXUS_CONFIG__ into SPA fallback routes', async () => {
await withInjectionServer({ GITNEXUS_BACKEND_URL: 'http://10.0.0.1:4747' }, async (port) => {
const res = await rawGet(port, '/some/deep/link');
assert.equal(res.status, 200);
assert.ok(
res.body.includes('window.__GITNEXUS_CONFIG__'),
'Expected __GITNEXUS_CONFIG__ in SPA fallback response',
);
assert.ok(
res.body.includes('http://10.0.0.1:4747'),
'Expected backend URL in SPA fallback response',
);
});
});
it('does not inject when GITNEXUS_BACKEND_URL is not set', async () => {
await withInjectionServer({}, async (port) => {
const res = await rawGet(port, '/');
assert.equal(res.status, 200);
assert.ok(
!res.body.includes('__GITNEXUS_CONFIG__'),
'Expected no __GITNEXUS_CONFIG__ when env var is unset',
);
});
});
it('does not inject when GITNEXUS_BACKEND_URL is invalid', async () => {
await withInjectionServer({ GITNEXUS_BACKEND_URL: 'not-a-url' }, async (port) => {
const res = await rawGet(port, '/');
assert.equal(res.status, 200);
assert.ok(
!res.body.includes('__GITNEXUS_CONFIG__'),
'Expected no __GITNEXUS_CONFIG__ for invalid URL',
);
});
});
it('does not inject when GITNEXUS_BACKEND_URL uses a non-http protocol', async () => {
await withInjectionServer({ GITNEXUS_BACKEND_URL: 'ftp://somehost:21' }, async (port) => {
const res = await rawGet(port, '/');
assert.equal(res.status, 200);
assert.ok(
!res.body.includes('__GITNEXUS_CONFIG__'),
'Expected no __GITNEXUS_CONFIG__ for non-http protocol',
);
});
});
it('escapes </script> in GITNEXUS_BACKEND_URL to prevent XSS', async () => {
const xssUrl = 'http://example.com/?x=</script><script>alert(1)</script>';
await withInjectionServer({ GITNEXUS_BACKEND_URL: xssUrl }, async (port) => {
const res = await rawGet(port, '/');
assert.equal(res.status, 200);
const scriptMatches = res.body.match(/<script>/gi) || [];
assert.equal(
scriptMatches.length,
1,
`Expected exactly 1 <script> tag but found ${scriptMatches.length}: XSS breakout detected`,
);
assert.ok(
!res.body.includes('</script><script>'),
'</script> must not appear unescaped -- would allow script breakout',
);
assert.ok(res.body.includes('\\u003c'), 'Angle brackets must be escaped as \\u003c');
});
});
it('does not inject config into static assets', async () => {
await withInjectionServer({ GITNEXUS_BACKEND_URL: 'http://10.0.0.1:4747' }, async (port) => {
const res = await rawGet(port, '/assets/style.abc.css');
assert.equal(res.status, 200);
assert.ok(
!res.body.includes('__GITNEXUS_CONFIG__'),
'Static assets must not contain injected config',
);
assert.equal(res.body, 'body{}');
});
});
@@ -381,7 +381,7 @@ export const CodeReferencesPanel = ({ onFocusNode }: CodeReferencesPanelProps) =
<X className="h-4 w-4" />
</button>
</div>
<div ref={selectedViewerRef} className="scrollbar-thin min-h-0 flex-1 overflow-auto">
<div ref={selectedViewerRef} className="min-h-0 flex-1 scrollbar-thin overflow-auto">
{isLoadingFile ? (
<div className="flex items-center justify-center gap-2 py-8 text-text-muted">
<Loader2 className="h-4 w-4 animate-spin" />
@@ -454,7 +454,7 @@ export const CodeReferencesPanel = ({ onFocusNode }: CodeReferencesPanelProps) =
{t('graph:codePanel.references', { count: aiReferences.length })}
</span>
</div>
<div className="scrollbar-thin min-h-0 flex-1 space-y-3 overflow-y-auto p-3">
<div className="min-h-0 flex-1 scrollbar-thin space-y-3 overflow-y-auto p-3">
{refsWithSnippets.map(
({ ref, content, start, highlightStart, highlightEnd, totalLines }) => {
const nodeColor = ref.label
@@ -386,7 +386,7 @@ export const FileTreePanel = ({ onFocusNode }: FileTreePanelProps) => {
</div>
{/* File tree */}
<div className="scrollbar-thin flex-1 overflow-y-auto py-2">
<div className="flex-1 scrollbar-thin overflow-y-auto py-2">
{fileTree.length === 0 ? (
<div className="px-3 py-4 text-center text-xs text-text-muted">
{t('graph:fileTree.noFilesLoaded')}
@@ -410,7 +410,7 @@ export const FileTreePanel = ({ onFocusNode }: FileTreePanelProps) => {
)}
{activeTab === 'filters' && (
<div className="scrollbar-thin flex-1 overflow-y-auto p-3">
<div className="flex-1 scrollbar-thin overflow-y-auto p-3">
<div className="mb-3">
<h3 className="mb-2 text-xs font-medium tracking-wide text-text-secondary uppercase">
{t('graph:fileTree.nodeTypes')}
@@ -364,7 +364,7 @@ export const ProcessesPanel = () => {
</div>
{/* Process list */}
<div className="scrollbar-thin flex-1 overflow-y-auto">
<div className="flex-1 scrollbar-thin overflow-y-auto">
{/* View All Processes Card */}
<div className="px-4 py-3">
<button
+1 -1
View File
@@ -343,7 +343,7 @@ export const QueryFAB = () => {
</div>
{showResults && queryResult.rows.length > 0 && (
<div className="scrollbar-thin max-h-48 overflow-auto border-t border-border-subtle">
<div className="max-h-48 scrollbar-thin overflow-auto border-t border-border-subtle">
<table className="w-full text-xs">
<thead className="sticky top-0 bg-surface">
<tr>
+2 -2
View File
@@ -292,7 +292,7 @@ export const RightPanel = () => {
)}
{/* Messages */}
<div ref={scrollContainerRef} className="scrollbar-thin flex-1 overflow-y-auto p-4">
<div ref={scrollContainerRef} className="flex-1 scrollbar-thin overflow-y-auto p-4">
{chatMessages.length === 0 ? (
<div className="flex h-full flex-col items-center justify-center px-4 text-center">
<div className="mb-4 flex h-14 w-14 items-center justify-center rounded-xl bg-gradient-to-br from-accent to-node-interface text-2xl shadow-glow">
@@ -417,7 +417,7 @@ export const RightPanel = () => {
onKeyDown={handleKeyDown}
placeholder={t('chat:input.placeholder')}
rows={1}
className="scrollbar-thin min-h-[36px] flex-1 resize-none border-none bg-transparent text-sm text-text-primary outline-none placeholder:text-text-muted"
className="min-h-[36px] flex-1 resize-none scrollbar-thin border-none bg-transparent text-sm text-text-primary outline-none placeholder:text-text-muted"
style={{ height: '36px', overflowY: 'hidden' }}
/>
<button
+3 -1
View File
@@ -2,7 +2,9 @@
export const ERROR_RESET_DELAY_MS = 3000;
export const BACKEND_URL_DEBOUNCE_MS = 500;
export const DEFAULT_BACKEND_URL = 'http://localhost:4747';
export const DEFAULT_BACKEND_URL =
(typeof window !== 'undefined' && window.__GITNEXUS_CONFIG__?.backendUrl) ||
'http://localhost:4747';
export const DEFAULT_OLLAMA_BASE_URL = 'http://localhost:11434';
export const DEFAULT_OPENROUTER_BASE_URL = 'https://openrouter.ai/api/v1';
+6
View File
@@ -1 +1,7 @@
/// <reference types="vite/client" />
interface Window {
__GITNEXUS_CONFIG__?: {
backendUrl?: string;
};
}
@@ -172,6 +172,37 @@ describe('fetchGraph', () => {
});
});
describe('DEFAULT_BACKEND_URL resolution', () => {
afterEach(() => {
delete window.__GITNEXUS_CONFIG__;
vi.resetModules();
});
it('falls back to localhost:4747 when no config is injected', async () => {
delete window.__GITNEXUS_CONFIG__;
const { DEFAULT_BACKEND_URL } = await import('../../src/config/ui-constants');
expect(DEFAULT_BACKEND_URL).toBe('http://localhost:4747');
});
it('uses window.__GITNEXUS_CONFIG__.backendUrl when set', async () => {
window.__GITNEXUS_CONFIG__ = { backendUrl: 'http://10.0.0.1:4747' };
const { DEFAULT_BACKEND_URL } = await import('../../src/config/ui-constants');
expect(DEFAULT_BACKEND_URL).toBe('http://10.0.0.1:4747');
});
it('falls back to localhost:4747 when config object has no backendUrl', async () => {
window.__GITNEXUS_CONFIG__ = {};
const { DEFAULT_BACKEND_URL } = await import('../../src/config/ui-constants');
expect(DEFAULT_BACKEND_URL).toBe('http://localhost:4747');
});
it('falls back to localhost:4747 when backendUrl is an empty string', async () => {
window.__GITNEXUS_CONFIG__ = { backendUrl: '' };
const { DEFAULT_BACKEND_URL } = await import('../../src/config/ui-constants');
expect(DEFAULT_BACKEND_URL).toBe('http://localhost:4747');
});
});
describe('validateBackendUrl', () => {
it('allows http:// URLs', () => {
expect(() => validateBackendUrl('http://localhost:4747')).not.toThrow();
@@ -225,7 +256,6 @@ describe('setBackendUrl', () => {
it('does not mutate _backendUrl when validation fails', () => {
setBackendUrl('http://localhost:4747');
expect(() => setBackendUrl('javascript:alert(1)')).toThrow();
// State must be preserved — validation must happen before the assignment
expect(getBackendUrl()).toBe('http://localhost:4747');
});
});