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
+1 -1
View File
@@ -1,5 +1,5 @@
PORT=9000
JWT_SECRET="change-me"
JWT_SECRET="<generate with: openssl rand -base64 32>"
POSTGRES_URL="postgres://postgres:password@localhost:5432/officer"
MAIL_TRANSPORT="smtp://localhost:1025"
PUBLIC_URL=http://localhost:9000
+81
View File
@@ -0,0 +1,81 @@
# Security Fixes Log
Tracks remediation progress against findings in `SECURITY_AUDIT.md`.
---
## C1. Weak JWT Secret — FIXED
**Ref:** SECURITY_AUDIT.md > C1
**Changes:**
- `src/servers/jwt.ts` — Added startup guard that throws if `JWT_SECRET` is absent or shorter than 32 characters
- `.env.example` — Updated placeholder to `<generate with: openssl rand -base64 32>`
**Note:** The actual `.env` secret must be rotated manually per deployment.
---
## C2. Global CORS Wildcard on All API Routes — FIXED
**Ref:** SECURITY_AUDIT.md > C2
**Changes:**
- `src/servers/hono.ts` — Replaced `origin: '*'` with dynamic origin validation using the `ALLOWED_ORIGINS` allowlist from `origin-validation.ts`
---
## C3. Server-Settings Routes Entirely Unauthenticated — FIXED
**Ref:** SECURITY_AUDIT.md > C3
**Changes:**
- `src/servers/hono.ts` — Moved `serverSettingsRouter` inside `protectedRouter`
- `src/servers/api/server-settings/server-settings.ts` — Added Super Admin role checks on all write operations
- `src/servers/_middlewares/super-admin-middleware.ts` — New middleware for Super Admin enforcement
- Exempted `GET /api/server-settings/onboarding-complete` as public (mounted before auth)
---
## C4. Unauthenticated Dev-Server WebSocket Proxy — FIXED
**Ref:** SECURITY_AUDIT.md > C4
**Changes:**
- `src/servers/api/dev-server/router.ts`:
- Replaced slug-based proxy URLs with server-generated UUID v4 (`proxyId`). Proxy lookup is now by UUID, eliminating cross-user slug collisions.
- Added `proxyIdIndex` map for O(1) lookup and `pendingStarts` guard against duplicate spawns.
- JWT validation required on HTML requests (`Accept: text/html`) — the iframe entry point. Sub-resources pass on proxyId alone (browsers can't add custom headers to native loads).
- `?token=` query param stripped before forwarding to dev server.
- `proxyOverrideScript` extended to inject `Authorization: Bearer` headers on fetch/XHR and append `?token=` on WebSocket connections, reading fresh tokens from localStorage.
- `src/server.tsx`:
- WebSocket upgrades require `?token=` query param. Token stored in `WSData.wsToken` for deferred async validation in the `open` handler (Bun requires synchronous `server.upgrade()`).
- `devServerWebsocket.open` validates JWT + blacklist check before opening upstream connection. Closes with code `4001` if invalid.
- `src/workspaces/officerdev/src/apps/Preview/PreviewProvider.tsx`:
- `startServer` and status check `useEffect` append `?token=` to iframe URL using `client.token`.
**Security model:** Two-layer capability — proxyId (unguessable UUID) as primary token, JWT as defense-in-depth on entry points (HTML, WebSocket).
---
## C5. AI Chat Messages Rendered with `rehype-raw` — LLM-Driven XSS — FIXED
**Ref:** SECURITY_AUDIT.md > C5
**Changes:**
- Installed `rehype-sanitize` (v6)
- `src/workspaces/officerdev/src/apps/Chat/components/MessageBubble.tsx`:
- Added `rehypeSanitize` with a schema that strips `<script>`, `<iframe>`, `<object>`, `<embed>`, `<form>` tags and all `on*` event handler attributes
- Applied to both `ReactMarkdown` instances (assistant messages + streaming bubble)
- `rehype-raw` retained so legitimate HTML (tables, `<details>`, etc.) still renders — sanitized before hitting the DOM
---
## Remaining
See `SECURITY_AUDIT.md` for the full list. Next priorities:
- **H3** — `rehype-sanitize` for the other 6 Markdown rendering locations
- **H1/H2** — Move token to `HttpOnly` cookies
- **H7/M5** — URL validation for git-clone/yt-dlp/scrape
- **H9/H10** — Rate limiting fixes
+5
View File
@@ -100,6 +100,7 @@
"recharts": "3.6.0",
"redis": "^5.8.3",
"rehype-raw": "^7.0.0",
"rehype-sanitize": "^6.0.0",
"rehype-slug": "^6.0.0",
"remark-gfm": "^4.0.1",
"shiki": "^3.22.0",
@@ -1424,6 +1425,8 @@
"hast-util-raw": ["hast-util-raw@9.1.0", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "@ungap/structured-clone": "^1.0.0", "hast-util-from-parse5": "^8.0.0", "hast-util-to-parse5": "^8.0.0", "html-void-elements": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "parse5": "^7.0.0", "unist-util-position": "^5.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0", "web-namespaces": "^2.0.0", "zwitch": "^2.0.0" } }, "sha512-Y8/SBAHkZGoNkpzqqfCldijcuUKh7/su31kEBp67cFY09Wy0mTRgtsLYsiIxMJxlu0f6AA5SUTbDR8K0rxnbUw=="],
"hast-util-sanitize": ["hast-util-sanitize@5.0.2", "", { "dependencies": { "@types/hast": "^3.0.0", "@ungap/structured-clone": "^1.0.0", "unist-util-position": "^5.0.0" } }, "sha512-3yTWghByc50aGS7JlGhk61SPenfE/p1oaFeNwkOOyrscaOkMGrcW9+Cy/QAIOBpZxP1yqDIzFMR0+Np0i0+usg=="],
"hast-util-to-html": ["hast-util-to-html@9.0.5", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "comma-separated-tokens": "^2.0.0", "hast-util-whitespace": "^3.0.0", "html-void-elements": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "stringify-entities": "^4.0.0", "zwitch": "^2.0.4" } }, "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw=="],
"hast-util-to-jsx-runtime": ["hast-util-to-jsx-runtime@2.3.6", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "hast-util-whitespace": "^3.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "style-to-js": "^1.0.0", "unist-util-position": "^5.0.0", "vfile-message": "^4.0.0" } }, "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg=="],
@@ -1938,6 +1941,8 @@
"rehype-raw": ["rehype-raw@7.0.0", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-raw": "^9.0.0", "vfile": "^6.0.0" } }, "sha512-/aE8hCfKlQeA8LmyeyQvQF3eBiLRGNlfBJEvWH7ivp9sBqs7TNqBL5X3v157rM4IFETqDnIOO+z5M/biZbo9Ww=="],
"rehype-sanitize": ["rehype-sanitize@6.0.0", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-sanitize": "^5.0.0" } }, "sha512-CsnhKNsyI8Tub6L4sm5ZFsme4puGfc6pYylvXo1AeqaGbjOYyzNv3qZPwvs0oMJ39eryyeOdmxwUIo94IpEhqg=="],
"rehype-slug": ["rehype-slug@6.0.0", "", { "dependencies": { "@types/hast": "^3.0.0", "github-slugger": "^2.0.0", "hast-util-heading-rank": "^3.0.0", "hast-util-to-string": "^3.0.0", "unist-util-visit": "^5.0.0" } }, "sha512-lWyvf/jwu+oS5+hL5eClVd3hNdmwM1kAC0BUvEGD19pajQMIzcNUd/k9GsfQ+FfECvX+JE+e9/btsKH0EjJT6A=="],
"rehype-stringify": ["rehype-stringify@10.0.1", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-to-html": "^9.0.0", "unified": "^11.0.0" } }, "sha512-k9ecfXHmIPuFVI61B9DeLPN0qFHfawM6RsuX48hoqlaKSF61RskNjSm1lI8PhBEM0MRdLxVVm4WmTqJQccH9mA=="],
+1
View File
@@ -122,6 +122,7 @@
"recharts": "3.6.0",
"redis": "^5.8.3",
"rehype-raw": "^7.0.0",
"rehype-sanitize": "^6.0.0",
"rehype-slug": "^6.0.0",
"remark-gfm": "^4.0.1",
"shiki": "^3.22.0",
+26 -6
View File
@@ -6,7 +6,7 @@ import { verify } from './servers/jwt';
import { isTokenBlacklisted } from 'officerdb';
import { terminalWebsocket, initTerminalSidecars } from './servers/api/terminal/websocket';
import { piWebsocket } from './servers/api/pi/websocket';
import { findEntryBySlug, touchEntry } from './servers/api/dev-server/router';
import { findEntryByProxyId, touchEntry } from './servers/api/dev-server/router';
import officerWeb from './apps/officer-web/index.html';
const { PORT = '5000' } = process.env;
@@ -26,6 +26,7 @@ type WSData = {
devServerPort?: number;
devServerSlug?: string;
wsProxyPath?: string;
wsToken?: string;
};
const handlers: Record<string, any> = {
@@ -38,8 +39,23 @@ type UpstreamState = { ws: WebSocket; queue: (string | Buffer)[]; ready: boolean
const devServerUpstreams = new Map<ServerWebSocket<WSData>, UpstreamState>();
const devServerWebsocket = {
open(ws: ServerWebSocket<WSData>) {
const { devServerPort, wsProxyPath } = ws.data;
async open(ws: ServerWebSocket<WSData>) {
const { devServerPort, wsProxyPath, wsToken } = ws.data;
// Validate JWT (deferred from upgrade which must be synchronous in Bun)
if (!wsToken) {
ws.close(4001, 'Unauthorized');
return;
}
try {
const payload = await verify(wsToken);
if (!payload) { ws.close(4001, 'Unauthorized'); return; }
if (payload.jti && isTokenBlacklisted(payload.jti)) { ws.close(4001, 'Unauthorized'); return; }
} catch {
ws.close(4001, 'Unauthorized');
return;
}
const upstream = new WebSocket(`ws://localhost:${devServerPort}${wsProxyPath}`);
const state: UpstreamState = { ws: upstream, queue: [], ready: false };
devServerUpstreams.set(ws, state);
@@ -116,10 +132,13 @@ function upgradeDevServerWs(req: Request, server: any) {
const match = url.pathname.match(/^\/api\/dev-server-proxy\/([^/]+)(\/.*)?$/);
if (!match) return new Response('Not found', { status: 404 });
const slug = match[1]!;
const entry = findEntryBySlug(slug);
const proxyId = match[1]!;
const entry = findEntryByProxyId(proxyId);
if (!entry) return new Response('No dev server running', { status: 404 });
const wsToken = url.searchParams.get('token');
if (!wsToken) return new Response('Unauthorized', { status: 401 });
touchEntry(entry);
const wsProxyPath = match[2] || '/';
@@ -131,8 +150,9 @@ function upgradeDevServerWs(req: Request, server: any) {
provider: 'dev-server' as const,
sandboxed: false,
devServerPort: entry.port,
devServerSlug: slug,
devServerSlug: proxyId,
wsProxyPath,
wsToken,
},
});
if (!ok) return new Response('Upgrade failed', { status: 500 });
+1
View File
@@ -3,3 +3,4 @@ export * from './user-middleware';
export * from './origin-middleware';
export * from './origin-validation';
export * from './rate-limiter';
export * from './super-admin-middleware';
+17 -16
View File
@@ -3,38 +3,39 @@ import * as errors from '../custom-errors';
const { PUBLIC_BUILD_ENV } = process.env;
const ALLOWED_ORIGINS: Record<string, string[]> = {
staging: ['https://staging.officer.dev'],
const WEB_ORIGINS: Record<string, string[]> = {
alpha: ['https://alpha.officer.dev'],
production: ['https://app.officer.dev', 'https://edge.officer.dev'],
};
const CHROME_EXTENSIONS: string[] = [
// 'chrome-extension://<id>'
];
const APP_ORIGINS: string[] = [
// Future: mobile app / webview origins
];
export function isOriginAllowed(origin: string | undefined, host?: string): boolean {
// Dev environment: allow any origin
if (!PUBLIC_BUILD_ENV || PUBLIC_BUILD_ENV === 'dev' || PUBLIC_BUILD_ENV === 'development') {
return true;
}
// If origin is present, validate it
if (origin) {
// Chrome extension check
if (origin.startsWith('chrome-extension://')) {
if (PUBLIC_BUILD_ENV === 'staging') {
return true; // Allow any extension in staging
}
if (PUBLIC_BUILD_ENV === 'production') {
return origin === 'chrome-extension://fjooappefigppfjolhadliepialebodg';
}
return CHROME_EXTENSIONS.includes(origin);
}
// Web origin check
const allowed = ALLOWED_ORIGINS[PUBLIC_BUILD_ENV];
if (APP_ORIGINS.includes(origin)) {
return true;
}
const allowed = WEB_ORIGINS[PUBLIC_BUILD_ENV];
return !!allowed?.includes(origin);
}
// No origin header: allow same-origin requests by checking Host header
// This handles cases where browsers don't send Origin for same-origin requests
if (host) {
const allowed = ALLOWED_ORIGINS[PUBLIC_BUILD_ENV];
const allowed = WEB_ORIGINS[PUBLIC_BUILD_ENV];
return !!allowed?.some((o) => o.endsWith(host));
}
@@ -0,0 +1,8 @@
import type { MiddlewareHandler } from 'hono';
import * as errors from '@@/custom-errors';
export const superAdminMiddleware: MiddlewareHandler = function (ctx, next) {
const user = ctx.get('user');
if (user?.role !== 'Super Admin') throw errors.FORBIDDEN();
return next();
};
+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
@@ -36,7 +36,7 @@ serverSettingsRouter.route('/stt', sttRouter);
serverSettingsRouter.route('/ocr', ocrRouter);
serverSettingsRouter.route('/searxng', searxngRouter);
const readSettings = async () => {
export const readSettings = async () => {
try { return await Bun.file(settingsPath).json(); } catch { return {}; }
};
+12 -3
View File
@@ -25,7 +25,7 @@ import { integrationsRouter, googleCallbackHandler } from './api/integrations/in
import { queueRouter } from './api/queue/queue';
import { emailRouter } from './api/email/email';
import { CustomError } from './custom-errors';
import { userMiddleware, bodyParser } from './_middlewares';
import { userMiddleware, bodyParser, isOriginAllowed, superAdminMiddleware } from './_middlewares';
export { Hono };
export { createRouter };
@@ -35,7 +35,10 @@ export const honoServer = new Hono<{ Variables: HonoVariables }>();
honoServer.use(
cors({
origin: '*',
origin: (origin, c) => {
const host = c.req.header('host');
return isOriginAllowed(origin, host) ? origin : '';
},
allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
allowHeaders: ['Content-Type', 'Authorization'],
}),
@@ -43,16 +46,22 @@ honoServer.use(
honoServer.get('/api', (ctx) => ctx.json({ officerAPI: 'ok' }));
honoServer.route('/api/auth', authRouter);
honoServer.route('/api/server-settings', serverSettingsRouter);
honoServer.route('/api/landing-page-data', landingPageDataRouter);
honoServer.route('/api/waitlist', waitlistRouter);
honoServer.route('/api/dev-server-proxy', devServerProxyRouter);
honoServer.get('/api/integrations/google/callback', googleCallbackHandler);
honoServer.get('/api/server-settings/onboarding-complete', async (ctx) => {
const { readSettings } = await import('./api/server-settings/server-settings');
const settings = await readSettings();
return ctx.json({ onboardingComplete: !!settings.onboardingComplete });
});
const protectedRouter = createRouter();
protectedRouter.use(bodyParser());
protectedRouter.use(userMiddleware);
serverSettingsRouter.use(superAdminMiddleware);
protectedRouter.route('/server-settings', serverSettingsRouter);
protectedRouter.route('/users', usersRouter);
protectedRouter.route('/plans', plansRouter);
protectedRouter.route('/skills', skillsRouter);
+5
View File
@@ -1,6 +1,11 @@
import { sign as jwtSign, verify as jwtVerify } from 'hono/jwt';
const { JWT_SECRET } = process.env;
if (!JWT_SECRET || JWT_SECRET.length < 32) {
throw new Error('JWT_SECRET must be set and at least 32 characters long. Generate one with: openssl rand -base64 32');
}
function parseExpiration(expiration: string): number {
const match = expiration.match(/^(\d+)([smhd])$/);
if (!match) {
@@ -2,6 +2,7 @@ import { useState, useRef } from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import rehypeRaw from 'rehype-raw';
import rehypeSanitize, { defaultSchema } from 'rehype-sanitize';
import { Volume2, Loader2, Square } from 'lucide-react';
import type { ChatMessage } from '../types';
import { ToolActivity } from './ToolActivity';
@@ -9,6 +10,15 @@ import { QuestionActivity } from './QuestionActivity';
import { getRawUrl } from '../../FileViewer/file-types';
import { useFilesAPI } from '../../../hooks/useFilesAPI';
const sanitizeSchema = {
...defaultSchema,
tagNames: (defaultSchema.tagNames ?? []).filter((tag) => tag !== 'script' && tag !== 'iframe' && tag !== 'object' && tag !== 'embed' && tag !== 'form'),
attributes: {
...defaultSchema.attributes,
'*': (defaultSchema.attributes?.['*'] ?? []).filter((attr) => typeof attr === 'string' && !attr.startsWith('on')),
},
};
// Matches absolute image file paths, e.g. /home/user/pic.png or /tmp/photo.jpg
const IMAGE_PATH_RE = /(\/(?:home\/[^/\s]+\/)?[^\s`"'<>\n\r[\]()]+\.(?:png|jpg|jpeg|gif|webp|svg|bmp|ico))/gi;
@@ -129,7 +139,7 @@ export const MessageBubble = ({ message, onAnswer }: MessageBubbleProps) => {
<div className="max-w-[85%]">
<div className="rounded-2xl rounded-tl-sm bg-muted/50 border border-border/50 px-4 py-2.5">
<div className="chat-md">
<ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeRaw]}>
<ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeRaw, [rehypeSanitize, sanitizeSchema]]}>
{injectImages(assistantText)}
</ReactMarkdown>
</div>
@@ -178,7 +188,7 @@ export const StreamingBubble = ({ text }: StreamingBubbleProps) => {
<div className="flex justify-start">
<div className="max-w-[85%] rounded-2xl rounded-tl-sm bg-muted/50 border border-border/50 px-4 py-2.5">
<div className="chat-md">
<ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeRaw]}>
<ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeRaw, [rehypeSanitize, sanitizeSchema]]}>
{injectImages(text)}
</ReactMarkdown>
<span className="inline-block w-2 h-4 bg-duck-teal/60 animate-pulse ml-0.5 align-middle" />
@@ -35,7 +35,8 @@ export const PreviewProvider = ({ children }: PreviewProviderProps) => {
setStopped(false);
try {
const res = await client.post<DevServerResponse>('/dev-server/start', { slug: targetSlug });
setUrl(res.url);
const token = client.token;
setUrl(token ? `${res.url}?token=${encodeURIComponent(token)}` : res.url);
setPort(res.port);
} catch (err: unknown) {
const msg = err && typeof err === 'object' && 'message' in err ? String(err.message) : 'Failed to start dev server';
@@ -81,7 +82,8 @@ export const PreviewProvider = ({ children }: PreviewProviderProps) => {
const status = await client.get<DevServerStatus>(`/dev-server/status?slug=${encodeURIComponent(slug)}`);
if (cancelled) return;
if (status.running && status.url) {
setUrl(status.url);
const token = client.token;
setUrl(token ? `${status.url}?token=${encodeURIComponent(token)}` : status.url);
setPort(status.port ?? null);
} else {
startServer(slug);