Critical Securities (5) fixes

This commit is contained in:
2026-02-25 19:44:38 +00:00
parent 10acd14755
commit 5d4f0114cd
14 changed files with 302 additions and 103 deletions
+128 -72
View File
@@ -6,24 +6,23 @@ import { createRouter } from '@@/create-router';
import { getUserProjectsDir } from '@@/data-path';
import { CustomError } from '@@/custom-errors';
import * as errors from '@@/custom-errors';
import { verify } from '@@/jwt';
import { isTokenBlacklisted } from 'officerdb';
export const devServerRouter = createRouter();
export const devServerProxyRouter = createRouter();
export type ServerEntry = { proc: Subprocess; port: number; slug: string; logs: string[]; idleTimer: Timer | null };
export type ServerEntry = { proc: Subprocess; port: number; slug: string; proxyId: string; logs: string[]; idleTimer: Timer | null };
const IDLE_TIMEOUT_MS = 5 * 60 * 1000;
const servers = new Map<string, ServerEntry>();
const proxyIdIndex = new Map<string, ServerEntry>();
const pendingStarts = new Set<string>();
const serverKey = (email: string, slug: string) => `${email}:${slug}`;
export const findEntryBySlug = (slug: string): ServerEntry | undefined => {
for (const entry of servers.values()) {
if (entry.slug === slug) return entry;
}
return undefined;
};
export const findEntryByProxyId = (proxyId: string): ServerEntry | undefined => proxyIdIndex.get(proxyId);
export const touchEntry = (entry: ServerEntry) => {
if (entry.idleTimer) clearTimeout(entry.idleTimer);
@@ -36,6 +35,7 @@ export const touchEntry = (entry: ServerEntry) => {
const killEntry = (entry: ServerEntry, key: string) => {
if (entry.idleTimer) clearTimeout(entry.idleTimer);
entry.proc.kill();
proxyIdIndex.delete(entry.proxyId);
servers.delete(key);
};
@@ -93,57 +93,68 @@ devServerRouter.post('/start', async (ctx) => {
const existing = servers.get(key);
if (existing) {
touchEntry(existing);
return ctx.json({ url: `/api/dev-server-proxy/${slug}/`, port: existing.port });
return ctx.json({ url: `/api/dev-server-proxy/${existing.proxyId}/`, port: existing.port });
}
const projectDir = join(getUserProjectsDir(user.email), slug);
if (!existsSync(projectDir)) throw errors.BAD_REQUEST(`Project directory not found: ${slug}`);
if (pendingStarts.has(key)) throw errors.BAD_REQUEST('Server is already starting');
pendingStarts.add(key);
const pkgPath = join(projectDir, 'package.json');
if (!existsSync(pkgPath)) throw errors.BAD_REQUEST('No package.json found in project');
try {
const pkg = JSON.parse(await Bun.file(pkgPath).text());
if (!pkg.scripts?.dev) throw errors.BAD_REQUEST('No "dev" script in package.json');
} catch (err) {
if (err instanceof CustomError) throw err;
throw errors.BAD_REQUEST('Failed to read package.json');
}
const projectDir = join(getUserProjectsDir(user.email), slug);
if (!existsSync(projectDir)) throw errors.BAD_REQUEST(`Project directory not found: ${slug}`);
const port = await findFreePort();
const proc = Bun.spawn(['bun', 'dev'], {
cwd: projectDir,
env: { ...process.env, PORT: String(port) },
stdout: 'pipe',
stderr: 'pipe',
});
console.log(`[dev-server] started ${slug} on port ${port} (pid ${proc.pid})`);
const entry: ServerEntry = { proc, port, slug, logs: [], idleTimer: null };
servers.set(key, entry);
touchEntry(entry);
collectLogs(entry, proc.stdout, 'stdout');
collectLogs(entry, proc.stderr, 'stderr');
proc.exited.then((code) => {
console.log(`[dev-server] ${slug} exited with code ${code}`);
entry.logs.push(`[system] Process exited with code ${code}`);
if (entry.idleTimer) clearTimeout(entry.idleTimer);
servers.delete(key);
});
const ready = await waitForPort(port);
if (!ready) {
const exitCode = proc.exitCode;
if (exitCode !== null) {
if (entry.idleTimer) clearTimeout(entry.idleTimer);
servers.delete(key);
throw errors.BAD_REQUEST(`Dev server exited with code ${exitCode}. Logs:\n${entry.logs.slice(-20).join('\n')}`);
const pkgPath = join(projectDir, 'package.json');
if (!existsSync(pkgPath)) throw errors.BAD_REQUEST('No package.json found in project');
try {
const pkg = JSON.parse(await Bun.file(pkgPath).text());
if (!pkg.scripts?.dev) throw errors.BAD_REQUEST('No "dev" script in package.json');
} catch (err) {
if (err instanceof CustomError) throw err;
throw errors.BAD_REQUEST('Failed to read package.json');
}
}
return ctx.json({ url: `/api/dev-server-proxy/${slug}/`, port });
const port = await findFreePort();
const proxyId = crypto.randomUUID();
const proc = Bun.spawn(['bun', 'dev'], {
cwd: projectDir,
env: { ...process.env, PORT: String(port) },
stdout: 'pipe',
stderr: 'pipe',
});
console.log(`[dev-server] started ${slug} on port ${port} (pid ${proc.pid}) proxyId=${proxyId}`);
const entry: ServerEntry = { proc, port, slug, proxyId, logs: [], idleTimer: null };
servers.set(key, entry);
proxyIdIndex.set(proxyId, entry);
touchEntry(entry);
collectLogs(entry, proc.stdout, 'stdout');
collectLogs(entry, proc.stderr, 'stderr');
proc.exited.then((code) => {
console.log(`[dev-server] ${slug} exited with code ${code}`);
entry.logs.push(`[system] Process exited with code ${code}`);
if (entry.idleTimer) clearTimeout(entry.idleTimer);
proxyIdIndex.delete(entry.proxyId);
servers.delete(key);
});
const ready = await waitForPort(port);
if (!ready) {
const exitCode = proc.exitCode;
if (exitCode !== null) {
if (entry.idleTimer) clearTimeout(entry.idleTimer);
proxyIdIndex.delete(entry.proxyId);
servers.delete(key);
throw errors.BAD_REQUEST(`Dev server exited with code ${exitCode}. Logs:\n${entry.logs.slice(-20).join('\n')}`);
}
}
return ctx.json({ url: `/api/dev-server-proxy/${proxyId}/`, port });
} finally {
pendingStarts.delete(key);
}
});
devServerRouter.post('/stop', async (ctx) => {
@@ -170,7 +181,7 @@ devServerRouter.get('/status', async (ctx) => {
const entry = servers.get(key);
if (entry) {
return ctx.json({ running: true, url: `/api/dev-server-proxy/${slug}/`, port: entry.port });
return ctx.json({ running: true, url: `/api/dev-server-proxy/${entry.proxyId}/`, port: entry.port });
}
return ctx.json({ running: false });
@@ -193,10 +204,10 @@ devServerRouter.get('/logs', async (ctx) => {
// Proxy router — mounted outside protected router (no auth needed for sub-resources).
// Security: only proxies to ports that were started via authenticated /start calls.
type ProxyParams = { entry: ServerEntry; slug: string; proxyPath: string; search: string; method: string; rawReq: Request };
type ProxyParams = { entry: ServerEntry; proxyId: string; proxyPath: string; search: string; method: string; rawReq: Request };
async function proxyRequest({ entry, slug, proxyPath, search, method, rawReq }: ProxyParams): Promise<Response> {
const prefix = `/api/dev-server-proxy/${slug}`;
async function proxyRequest({ entry, proxyId, proxyPath, search, method, rawReq }: ProxyParams): Promise<Response> {
const prefix = `/api/dev-server-proxy/${proxyId}`;
const targetUrl = `http://localhost:${entry.port}${proxyPath}${search}`;
touchEntry(entry);
@@ -236,31 +247,63 @@ async function proxyRequest({ entry, slug, proxyPath, search, method, rawReq }:
}
}
// Proxy handler: tries slug from URL first, falls back to Referer for misrouted
const isLikelyHtmlRequest = (req: Request): boolean => {
const accept = req.headers.get('accept') ?? '';
return accept.includes('text/html');
};
const stripTokenParam = (search: string): string => {
if (!search) return search;
const params = new URLSearchParams(search);
params.delete('token');
const result = params.toString();
return result ? `?${result}` : '';
};
async function validateJwt(req: Request): Promise<boolean> {
const authHeader = req.headers.get('authorization');
const token = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : new URL(req.url).searchParams.get('token');
if (!token) return false;
try {
const payload = await verify(token);
if (!payload) return false;
if (payload.jti && isTokenBlacklisted(payload.jti)) return false;
return true;
} catch {
return false;
}
}
// Proxy handler: tries proxyId from URL first, falls back to Referer for misrouted
// chunk requests caused by relative imports resolving at wrong path depth.
devServerProxyRouter.all('/:slug/*', async (ctx) => {
const slug = ctx.req.param('slug');
if (!slug) return ctx.text('Not found', 404);
devServerProxyRouter.all('/:proxyId/*', async (ctx) => {
const proxyId = ctx.req.param('proxyId');
if (!proxyId) return ctx.text('Not found', 404);
const originalUrl = new URL(ctx.req.url);
const entry = findEntryBySlug(slug);
const entry = proxyIdIndex.get(proxyId);
if (entry) {
const prefix = `/api/dev-server-proxy/${slug}`;
if (isLikelyHtmlRequest(ctx.req.raw)) {
const valid = await validateJwt(ctx.req.raw);
if (!valid) return ctx.text('Unauthorized', 401);
}
const prefix = `/api/dev-server-proxy/${proxyId}`;
const proxyPath = originalUrl.pathname.replace(prefix, '') || '/';
return proxyRequest({ entry, slug, proxyPath, search: originalUrl.search, method: ctx.req.method, rawReq: ctx.req.raw });
const search = stripTokenParam(originalUrl.search);
return proxyRequest({ entry, proxyId, proxyPath, search, method: ctx.req.method, rawReq: ctx.req.raw });
}
// Slug didn't match a dev server — check Referer for the real slug
// proxyId didn't match — check Referer for the real proxyId
const referer = ctx.req.header('referer');
if (referer) {
const match = referer.match(/\/api\/dev-server-proxy\/([^/]+)/);
if (match) {
const realSlug = match[1]!;
const realEntry = findEntryBySlug(realSlug);
const realProxyId = match[1]!;
const realEntry = proxyIdIndex.get(realProxyId);
if (realEntry) {
const proxyPath = originalUrl.pathname.replace('/api/dev-server-proxy', '') || '/';
return proxyRequest({ entry: realEntry, slug: realSlug, proxyPath, search: originalUrl.search, method: ctx.req.method, rawReq: ctx.req.raw });
const search = stripTokenParam(originalUrl.search);
return proxyRequest({ entry: realEntry, proxyId: realProxyId, proxyPath, search, method: ctx.req.method, rawReq: ctx.req.raw });
}
}
}
@@ -268,12 +311,13 @@ devServerProxyRouter.all('/:slug/*', async (ctx) => {
return ctx.text('No dev server running', 404);
});
// Injected into proxied HTML to intercept fetch/XHR so absolute paths (e.g. /api/hello)
// Injected into proxied HTML to intercept fetch/XHR/WebSocket so absolute paths
// go through the proxy instead of hitting the host server directly.
// Handles string paths, URL objects, and Request objects.
// Also injects JWT auth headers from localStorage for authenticated requests.
const proxyOverrideScript = (base: string) =>
`<script>(function(){` +
`var b=${JSON.stringify(base)},o=location.origin;` +
`function gt(){try{return localStorage.getItem("BEARER_TOKEN")||localStorage.getItem("PERTENTO_EDITOR_AUTH_TOKEN")}catch(e){return null}}` +
`function rw(u){` +
`if(typeof u==="string"){` +
`if(u.startsWith("/")&&!u.startsWith("//")&&!u.startsWith(b))return b+u;` +
@@ -285,9 +329,21 @@ const proxyOverrideScript = (base: string) =>
`if(p.origin===o&&!p.pathname.startsWith(b))` +
`return new Request(o+b+p.pathname+p.search+p.hash,u)}` +
`return u}` +
`var F=window.fetch;window.fetch=function(i,n){return F.call(this,rw(i),n)};` +
`var X=XMLHttpRequest.prototype.open;XMLHttpRequest.prototype.open=function(){` +
`arguments[1]=rw(arguments[1]);return X.apply(this,arguments)};` +
`var F=window.fetch;window.fetch=function(i,n){` +
`var t=gt();if(t){n=n||{};var h=new Headers(n.headers||{});` +
`if(!h.has("Authorization"))h.set("Authorization","Bearer "+t);n.headers=h}` +
`return F.call(this,rw(i),n)};` +
`var XO=XMLHttpRequest.prototype.open,XS=XMLHttpRequest.prototype.send;` +
`XMLHttpRequest.prototype.open=function(){arguments[1]=rw(arguments[1]);this._authSet=false;return XO.apply(this,arguments)};` +
`XMLHttpRequest.prototype.send=function(d){` +
`if(!this._authSet){var t=gt();if(t)try{this.setRequestHeader("Authorization","Bearer "+t)}catch(e){}}` +
`return XS.call(this,d)};` +
`var NWS=window.WebSocket;window.WebSocket=function(u,p){` +
`if(typeof u==="string"&&(u.startsWith("ws://"+location.host)||u.startsWith("wss://"+location.host)||u.startsWith("/"))){` +
`var t=gt();if(t){var sep=u.indexOf("?")>-1?"&":"?";u=u+sep+"token="+encodeURIComponent(t)}}` +
`return p!==undefined?new NWS(u,p):new NWS(u)};` +
`window.WebSocket.prototype=NWS.prototype;window.WebSocket.CONNECTING=NWS.CONNECTING;` +
`window.WebSocket.OPEN=NWS.OPEN;window.WebSocket.CLOSING=NWS.CLOSING;window.WebSocket.CLOSED=NWS.CLOSED;` +
`})()</script>`;
// HTML: rewrite src/href/action attributes with absolute paths + inject fetch/XHR override