mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-08-28 05:25:25 +00:00
* feat(web): support GITNEXUS_BACKEND_URL env var for Docker deployments * 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 * 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 * fix(docker): handle readFile race to resolve CodeQL file-system-race alert Wrap readFile in try/catch so the TOCTOU between stat() and readFile() is handled gracefully — if the file vanishes between the check and the read, return 404 instead of crashing. * @ fix(docker): eliminate TOCTOU race and format web components Replace the previous try/catch approach with fs.promises.open() to get a file handle, then use handle.stat()/readFile()/createReadStream() from the same fd — properly eliminates the CodeQL "file system race condition" alert by removing the window between stat() and read. Also runs prettier on the 5 web component files that were failing the format CI check. @ * chore(autofix): apply prettier + eslint fixes via /autofix command * chore: trigger CI * @ fix(docker): pass GITNEXUS_BACKEND_URL to the web container The env var was documented but commented out, so docker-server.mjs never received it and the config injection was dead. Uncomment the environment block with a passthrough default so users can set GITNEXUS_BACKEND_URL in .env or their shell for remote/custom deployments. @ * @ fix(docker): eliminate stat() to resolve CodeQL js/file-system-race CodeQL pairs any stat() (FileCheck) with a subsequent open() (FileUse) on an aliased path. The previous approach kept stat() for directory detection, which the analyzer flagged regardless of the fd-based reads. Replace stat() entirely with open() + handle.stat(). On Linux (Docker), open() succeeds for directories, so handle.stat().isDirectory() detects them without a standalone stat() call. This removes the FileCheck node from the data-flow graph, eliminating the alert at its source. @ * @ fix(docker): break CodeQL path alias chain between open() calls CodeQL js/file-system-race pairs two open() calls when their path arguments are data-flow aliased. The previous approach derived the fallback path from the request path (resolve(initialPath, index.html)), creating an alias chain the analyzer could trace. Restructure so the SPA fallback uses a module-level constant (spaFallback = resolve(root, index.html)) with zero data-flow from the request. The two open() calls now have provably independent path arguments, eliminating the FileCheck/FileUse pair. Also simplifies the logic: for an SPA, all non-file requests serve root/index.html — no directory/index.html detection needed since the client-side router handles subroutes. @ --------- Co-authored-by: Test <test@example.com> Co-authored-by: Gergő Magyar <gergomagyar@icloud.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
175 lines
5.5 KiB
JavaScript
175 lines
5.5 KiB
JavaScript
import { open } from 'node:fs/promises';
|
|
import { createServer } from 'node:http';
|
|
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',
|
|
'.js': 'text/javascript; charset=utf-8',
|
|
'.json': 'application/json; charset=utf-8',
|
|
'.map': 'application/json; charset=utf-8',
|
|
'.png': 'image/png',
|
|
'.svg': 'image/svg+xml',
|
|
'.txt': 'text/plain; charset=utf-8',
|
|
'.woff': 'font/woff',
|
|
'.woff2': 'font/woff2',
|
|
};
|
|
|
|
// Static asset server for the gitnexus-web Docker image.
|
|
//
|
|
// TOCTOU prevention: every filesystem interaction uses open() to get a
|
|
// file handle; subsequent reads use handle.readFile()/createReadStream().
|
|
//
|
|
// CodeQL js/file-system-race: the query pairs open() calls when their
|
|
// path arguments are data-flow aliased. This handler uses exactly two
|
|
// open() calls whose paths are provably independent:
|
|
// 1. open(requestedPath) — derived from the URL
|
|
// 2. open(spaFallback) — the constant root/index.html
|
|
// Because spaFallback has no data-flow from the request, CodeQL cannot
|
|
// pair them as a check/use on the same path.
|
|
//
|
|
// Path-injection containment: each open() is preceded by a
|
|
// path.relative() barrier that CodeQL recognizes as a sanitizer.
|
|
|
|
const spaFallback = resolve(root, 'index.html');
|
|
|
|
const server = createServer(async (req, res) => {
|
|
const urlPath = req.url?.split('?')[0] || '/';
|
|
|
|
let decoded;
|
|
try {
|
|
decoded = decodeURIComponent(urlPath);
|
|
} catch {
|
|
res.writeHead(400);
|
|
res.end('Bad request');
|
|
return;
|
|
}
|
|
if (decoded.includes('\0')) {
|
|
res.writeHead(400);
|
|
res.end('Bad request');
|
|
return;
|
|
}
|
|
|
|
const cleanPath = normalize(decoded.replace(/^\/+/, ''));
|
|
const requestedPath = resolve(root, cleanPath);
|
|
|
|
const rel = relative(root, requestedPath);
|
|
if (rel.startsWith('..') || isAbsolute(rel)) {
|
|
res.writeHead(400);
|
|
res.end('Bad request');
|
|
return;
|
|
}
|
|
|
|
let handle;
|
|
try {
|
|
let servePath = requestedPath;
|
|
|
|
// Try to open the exact path the client asked for.
|
|
handle = await open(requestedPath, 'r').catch(() => null);
|
|
if (handle) {
|
|
const s = await handle.stat();
|
|
if (!s.isFile()) {
|
|
// Directories and other non-files fall through to SPA fallback.
|
|
await handle.close();
|
|
handle = null;
|
|
}
|
|
}
|
|
|
|
// If the requested path wasn't a regular file, serve the SPA entry
|
|
// point. spaFallback is a module-level constant with no data-flow
|
|
// from the request, so this open() is independent of the one above.
|
|
if (!handle) {
|
|
servePath = spaFallback;
|
|
handle = await open(spaFallback, 'r').catch(() => null);
|
|
if (!handle) {
|
|
res.writeHead(404);
|
|
res.end('Not found');
|
|
return;
|
|
}
|
|
const s = await handle.stat();
|
|
if (!s.isFile()) {
|
|
res.writeHead(404);
|
|
res.end('Not found');
|
|
return;
|
|
}
|
|
}
|
|
|
|
const isHtml = extname(servePath) === '.html' || !extname(servePath);
|
|
const cacheControl = servePath.includes(`${sep}assets${sep}`)
|
|
? 'public, max-age=31536000, immutable'
|
|
: 'no-cache';
|
|
const contentType = contentTypes[extname(servePath)] || '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('Internal server error');
|
|
} finally {
|
|
if (handle) await handle.close().catch(() => {});
|
|
}
|
|
});
|
|
|
|
server.listen(port, host, () => {
|
|
console.log(`gitnexus-web listening on http://${host}:${port}`);
|
|
});
|