/** * @fileoverview Pure helpers for the web-tab reverse proxy. No I/O, no Fastify. * * The proxy exists because an iframe pointing straight at a dashboard cannot work * in the deployment that matters: prod serves HTTPS (behind `tailscale serve`), so * a plain-HTTP dashboard is hard-blocked as mixed content; many dashboards also * refuse framing outright via `X-Frame-Options` / `frame-ancestors`; and Codeman's * own CSP (`default-src 'self'`) blocks cross-origin frames anyway. Serving the * dashboard through Codeman's own origin dissolves all three at once, and keeps * the production CSP byte-for-byte unchanged because `/webview/...` is `'self'`. * * ## Origin-scoped, not path-scoped * * `/webview//x/y` always maps to `/x/y`, never to * `/x/y`. Dashboards reference assets with * root-absolute paths (`/public/build/app.js`), so origin-scoping is the only * mapping under which those resolve. The saved URL's own path+query is used for * exactly one thing: what `/webview//` itself serves (the landing page). * * ## What gets rewritten, and why each one is load-bearing * * - `x-frame-options` / CSP `frame-ancestors`: dropped, else the browser refuses * to render the frame. This is the whole point of the proxy. * - `content-encoding` / `content-length`: dropped from responses, because * undici's `fetch` already decoded the body. Forwarding them makes the browser * try to gunzip plaintext. * - Request `content-length`: RELAYED with a body. The body reaches undici as a * stream, which it sends chunked unless told the length, and a server that * reads only Content-Length (Python's `http.server`, many small Go/C ones) * then sees an EMPTY body: every POST to such a dashboard arrived blank. * - `authorization` + the `codeman_session` cookie: stripped on the way OUT. In * trusted mode the iframe is same-origin, so the browser attaches Codeman's own * Basic-auth header and session cookie to every proxied request. Forwarding * those would hand CODEMAN_PASSWORD to the dashboard. * - `Location` and `Set-Cookie`: remapped into the proxy path, else a redirect or * a login cookie escapes the prefix and lands on Codeman's root. * - `` + root-absolute attribute rewriting: relative and `/`-rooted * URLs in the HTML resolve back through the proxy instead of hitting Codeman. * * No `X-Forwarded-*` is sent deliberately: apps that honor it generate absolute * URLs against Codeman's root, which would bypass the `/webview//` prefix * that everything else here works to preserve. */ import { createHash } from 'node:crypto'; import { WEBVIEW_PROXY_PREFIX } from '../config/webview-limits.js'; import { stripBasePath } from '../config/base-path.js'; /** Headers that are per-connection and must never be relayed in either direction. */ const HOP_BY_HOP = new Set([ 'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'proxy-connection', 'te', 'trailer', 'transfer-encoding', 'upgrade', ]); /** * Request headers dropped on the way to the upstream. `authorization` and `cookie` * carry Codeman's own credentials on a same-origin (trusted) frame; `host` and * `accept-encoding` are recomputed by undici. `content-length` is NOT recomputed * for a streamed body; it is listed here only so the copy loop never relays it * blindly, and `buildUpstreamRequestHeaders` puts it back when a body goes with it. */ const DROP_REQUEST_HEADERS = new Set([ ...HOP_BY_HOP, 'host', 'content-length', 'accept-encoding', 'authorization', 'cookie', 'origin', 'referer', 'x-codeman-hook-secret', ]); /** Response headers dropped on the way back to the browser. */ const DROP_RESPONSE_HEADERS = new Set([ ...HOP_BY_HOP, 'content-encoding', 'content-length', 'x-frame-options', 'content-security-policy-report-only', // Cross-origin isolation headers describe the UPSTREAM's origin policy; applied // to a frame on Codeman's origin they only produce blocked-resource surprises. 'cross-origin-opener-policy', 'cross-origin-embedder-policy', 'cross-origin-resource-policy', 'set-cookie', 'location', 'content-security-policy', // The upstream's CORS answer describes ITS origin; the frame asking is // opaque-origin on ours, so ours must replace it (see buildProxyCorsHeaders). 'access-control-allow-origin', 'access-control-allow-credentials', 'access-control-allow-methods', 'access-control-allow-headers', 'access-control-expose-headers', 'access-control-max-age', // The capability rides in every proxied URL, so the upstream's own referrer // policy must not decide whether third parties receive it. Ours is stamped in // buildDownstreamResponseHeaders. 'referrer-policy', ]); /** * The same-origin path prefix an iframe loads for a given capability. * * `basePath` is the reverse-proxy mount prefix (`''` at root, or `/foo`). It is * INCLUDED here because this value is browser-facing — the iframe src, the * ``, the runtime shim's rewrite target, Location/Set-Cookie rebasing — * and all of those must ride the mount or they escape it. Requests coming the other * way are base-stripped before routing, so the parsers (`capabilityFromProxyPath`, * `resolveUpstreamUrl`) deliberately do NOT take a base. */ export function proxyPrefixFor(capability: string, basePath = ''): string { return `${basePath}${WEBVIEW_PROXY_PREFIX}/${capability}/`; } /** * Parse and validate a user-supplied dashboard URL. * * Rejects everything that is not plain `http:`/`https:`, anything carrying * embedded credentials (they would be silently forwarded and logged), and * anything without a hostname. Returns the normalized `URL` or null. */ export function parseWebviewUrl(raw: string): URL | null { if (typeof raw !== 'string' || raw.trim() === '') return null; let url: URL; try { url = new URL(raw.trim()); } catch { return null; } if (url.protocol !== 'http:' && url.protocol !== 'https:') return null; if (url.username !== '' || url.password !== '') return null; if (!url.hostname) return null; return url; } /** Convenience predicate for Zod refinements. */ export function isValidWebviewUrl(raw: string): boolean { return parseWebviewUrl(raw) !== null; } /** * Map a proxy request path to its upstream URL. * * `wildcard` is Fastify's `*` param: the path after `/webview//`, without a * leading slash. An empty wildcard means the landing page, which is the saved * URL's own path and query. * * Returns null when the result would escape the upstream origin (a `..` chain, a * protocol-relative `//evil.com` wildcard, or an absolute URL smuggled into the * path). That check is what keeps this from being an open proxy. */ export function resolveUpstreamUrl(savedUrl: string, wildcard: string, search: string): URL | null { const base = parseWebviewUrl(savedUrl); if (!base) return null; if (wildcard === '' || wildcard === '/') { const landing = new URL(base.pathname + (search || base.search), base.origin); return landing.origin === base.origin ? landing : null; } // A wildcard starting with `//` would parse as protocol-relative and jump host. const path = wildcard.startsWith('/') ? wildcard : `/${wildcard}`; if (path.startsWith('//')) return null; let target: URL; try { target = new URL(path + (search || ''), base.origin); } catch { return null; } return target.origin === base.origin ? target : null; } /** Extract the capability from a `/webview//...` pathname, or null. */ export function capabilityFromProxyPath(pathname: string): string | null { if (typeof pathname !== 'string') return null; const prefix = `${WEBVIEW_PROXY_PREFIX}/`; if (!pathname.startsWith(prefix)) return null; const rest = pathname.slice(prefix.length); const slash = rest.indexOf('/'); const cap = slash === -1 ? rest : rest.slice(0, slash); return /^[A-Za-z0-9_-]{16,128}$/.test(cap) ? cap : null; } /** * Extract the capability a `Referer` belongs to. Backs the 404 fallback that * catches root-absolute asset requests (`/static/app.js`) which `` cannot fix. */ export function capabilityFromReferer(referer: string | undefined, basePath = ''): string | null { if (!referer) return null; try { // The Referer is browser-supplied, so under a sub-path mount it carries the // prefix (`/foo/webview//...`); strip it back to the internal path the // capability parser expects. return capabilityFromProxyPath(stripBasePath(basePath, new URL(referer).pathname)); } catch { return null; } } /** `Sec-Fetch-Dest` values that describe a page fetching for itself, not navigating. */ const ASSET_FETCH_DESTS = new Set([ 'script', 'style', 'image', 'font', 'manifest', 'worker', 'sharedworker', 'audio', 'video', 'track', 'embed', 'object', 'empty', ]); /** Codeman's own missing files: a 404 here says nothing about a web tab. */ const CODEMAN_OWN_404 = /^\/(?:favicon\.ico|manifest\.json|manifest\.webmanifest|robots\.txt|apple-touch-icon[\w.-]*)$/i; /** * Whether a 404 looks like a proxied dashboard's root-absolute request that * escaped the prefix. * * This decides NOTHING about the response — the request cannot be relayed (a * masked frame's `Referer` carries no capability, which is exactly why the * Referer fallback above declined). It exists so the failure is diagnosable: * the symptom of an escaped URL is a blank page or a spinner that never * resolves, with nothing in the log to say why. Naming the path turns that into * one grep. * * Deliberately conservative — a masked landing frame (`Referer` path `/`), an * asset-shaped `Sec-Fetch-Dest`, same origin, not the API, not one of Codeman's * own files. A false positive is a log line, never a behaviour change. * * @param input - method, request URL and headers of the 404. * @returns the escaped path (no query), or null when it is not that shape. */ export function escapedWebviewAssetPath(input: { method: string; url: string; headers: Record; }): string | null { if (input.method !== 'GET' && input.method !== 'HEAD') return null; const path = input.url.split('?')[0] ?? ''; if (path.startsWith('/api') || CODEMAN_OWN_404.test(path)) return null; const single = (value: string | string[] | undefined): string | undefined => Array.isArray(value) ? value[0] : value; const dest = single(input.headers['sec-fetch-dest']); if (!dest || !ASSET_FETCH_DESTS.has(dest.toLowerCase())) return null; const host = single(input.headers.host); const referer = single(input.headers.referer); if (!host || !referer) return null; try { const from = new URL(referer); // Same origin, and the masked landing path: a real Codeman page's assets all // resolve, so a 404 from one is not this shape. if (from.host !== host || from.pathname !== '/') return null; } catch { return null; } return path; } /** Remove the `frame-ancestors` directive from a CSP, preserving the rest. */ export function stripFrameAncestors(csp: string): string { return csp .split(';') .map((d) => d.trim()) .filter((d) => d !== '' && !/^frame-ancestors\b/i.test(d)) .join('; '); } /** The `frame-ancestors` directive value from a CSP, or undefined. */ export function extractFrameAncestors(csp: string | undefined): string | undefined { if (!csp) return undefined; for (const directive of csp.split(';')) { const trimmed = directive.trim(); if (/^frame-ancestors\b/i.test(trimmed)) { return trimmed.slice('frame-ancestors'.length).trim(); } } return undefined; } /** * Whether a target permits being framed by a different origin, judged from its * `X-Frame-Options` and CSP. Used only to recommend proxy vs direct mode in the * editor; the proxy path works either way. */ export function isFramableCrossOrigin(xFrameOptions: string | undefined, csp: string | undefined): boolean { const xfo = xFrameOptions?.trim().toLowerCase(); if (xfo === 'deny' || xfo === 'sameorigin') return false; const ancestors = extractFrameAncestors(csp)?.toLowerCase(); if (ancestors === undefined) return true; if (ancestors.includes("'none'")) return false; // 'self' alone means same-origin only, which a cross-origin embed is not. if (ancestors === "'self'") return false; return ancestors.includes('*') || ancestors.includes('http'); } /** * Rewrite an upstream `Location` into the proxy path. * * Same-origin redirects (relative or absolute) are remapped so the browser stays * inside the frame. Cross-origin redirects are returned unchanged rather than * proxied: relaying them would turn this into an open proxy for any host the * upstream chooses to name. */ export function rewriteLocation(location: string, requestUrl: URL, capability: string, basePath = ''): string { let resolved: URL; try { resolved = new URL(location, requestUrl); } catch { return location; } if (resolved.origin !== requestUrl.origin) return location; const suffix = resolved.pathname.replace(/^\//, ''); return `${proxyPrefixFor(capability, basePath)}${suffix}${resolved.search}${resolved.hash}`; } /** * Rewrite an upstream `Set-Cookie` so it applies to the proxy path only. * * `Domain` is dropped (the cookie now belongs to Codeman's host), `Path` is * rebased onto the proxy prefix so two dashboards cannot collide on a shared * cookie name, and `Secure` is dropped when Codeman itself is serving plain HTTP * in dev, where a Secure cookie would simply be discarded. */ export function rewriteSetCookie(cookie: string, capability: string, secureContext: boolean, basePath = ''): string { const parts = cookie.split(';'); const out: string[] = [parts[0]]; let sawPath = false; for (const raw of parts.slice(1)) { const attr = raw.trim(); const lower = attr.toLowerCase(); if (lower.startsWith('domain=')) continue; if (lower === 'secure' && !secureContext) continue; if (lower.startsWith('path=')) { sawPath = true; const value = attr.slice('path='.length); const suffix = value.replace(/^\//, ''); out.push(`Path=${proxyPrefixFor(capability, basePath)}${suffix}`); continue; } out.push(attr); } if (!sawPath) out.push(`Path=${proxyPrefixFor(capability, basePath)}`); return out.join('; '); } /** * Put a server-held credential in front of the cookies the browser sent. * * Order matters: a `Cookie` header can name the same cookie twice, and parsers * that collapse it into a map keep the FIRST value (RFC 6265 §5.4 leaves the * choice open; the common Node parsers take the first). The browser may still * hold a stale copy of the same dsh cookie from an earlier proxied response, so * the credential minted by the running process must lead, with everything else * preserved behind it. */ export function mergeCookieHeader(browserCookie: string | undefined, injectedCookie: string): string { return browserCookie ? `${injectedCookie}; ${browserCookie}` : injectedCookie; } /** Drop named cookies from a `Cookie` request header, returning undefined if none remain. */ export function filterCookieHeader(cookie: string | undefined, drop: string[]): string | undefined { if (!cookie) return undefined; const dropSet = new Set(drop.map((n) => n.toLowerCase())); const kept = cookie .split(';') .map((c) => c.trim()) .filter((c) => c !== '' && !dropSet.has(c.slice(0, c.indexOf('=')).trim().toLowerCase())); return kept.length > 0 ? kept.join('; ') : undefined; } /** Build the header set sent upstream, from the browser's request headers. */ export function buildUpstreamRequestHeaders( incoming: Record, upstream: URL, opts: { forwardCookies: boolean; sessionCookieName: string; refererPath?: string; relayBodyLength?: boolean; /** * A credential the SERVER holds for this dashboard, put in front of whatever * browser cookies were forwarded (see `mergeCookieHeader` for why the order * matters). `dsh web` mints its session cookie for a loopback authority the * browser never visits, so the proxy is the only party that can present it * (see `deepseek-web-server.ts`); the managed tab is trusted, which means the * browser may also carry other cookies dsh set, and those must survive. */ injectedCookie?: string; } ): Record { const headers: Record = {}; for (const [key, value] of Object.entries(incoming)) { const lower = key.toLowerCase(); if (DROP_REQUEST_HEADERS.has(lower)) continue; if (value === undefined) continue; headers[lower] = Array.isArray(value) ? value.join(', ') : value; } // The body is relayed as a stream, and undici frames a stream it has no length // for as `Transfer-Encoding: chunked`. Hand it the browser's own length so the // upstream sees the framing the browser sent. Only alongside a body (a length // with none would leave the upstream waiting for bytes that never come), and // never against a transfer-encoding, which would make the length a lie. const length = incoming['content-length']; if ( opts.relayBodyLength && typeof length === 'string' && /^\d+$/.test(length) && incoming['transfer-encoding'] === undefined ) { headers['content-length'] = length; } if (opts.forwardCookies) { const raw = incoming['cookie']; const cookie = filterCookieHeader(Array.isArray(raw) ? raw.join('; ') : raw, [opts.sessionCookieName]); if (cookie) headers['cookie'] = cookie; } // In front of the relayed cookies rather than after them, so a stale browser // copy of the same cookie cannot shadow the one minted by the running process // (the parser keeps the first value). Other cookies are kept: a managed dsh tab // is trusted, so dsh's own non-auth cookies may legitimately be there. if (opts.injectedCookie) { headers['cookie'] = mergeCookieHeader(headers['cookie'], opts.injectedCookie); } // Present as if the browser were talking to the dashboard directly. Apps that // check Origin on writes (CSRF defenses) need this to match their own origin. headers['origin'] = upstream.origin; headers['referer'] = opts.refererPath ? new URL(opts.refererPath, upstream.origin).href : upstream.href; return headers; } /** * Build the response headers sent to the browser. * * Also returns the CSP to apply: the upstream's, minus `frame-ancestors`. Callers * MUST set (or explicitly clear) this, because `registerSecurityHeaders` has * already stamped Codeman's own `default-src 'self'` policy onto the reply, and * that policy would break virtually every dashboard. */ export function buildDownstreamResponseHeaders( upstreamHeaders: Iterable<[string, string]>, /** * Upstream `Set-Cookie` values, already separated. Passed in rather than read * from `upstreamHeaders` because iterating a `Headers` object JOINS duplicate * set-cookie values into one comma-separated string, which cannot be split back * apart reliably (Expires dates contain commas). Callers use * `response.headers.getSetCookie()`. */ setCookies: string[], capability: string, requestUrl: URL, secureContext: boolean, basePath = '' ): { headers: Record; setCookie: string[]; csp: string | null } { const headers: Record = {}; let csp: string | null = null; for (const [key, value] of upstreamHeaders) { const lower = key.toLowerCase(); if (lower === 'content-security-policy') { const stripped = stripFrameAncestors(value); csp = stripped === '' ? null : stripped; continue; } if (lower === 'location') { headers['location'] = rewriteLocation(value, requestUrl, capability, basePath); continue; } if (DROP_RESPONSE_HEADERS.has(lower)) continue; headers[lower] = value; } // Every URL inside the frame carries the capability, and a dashboard that sets // `no-referrer-when-downgrade` or `unsafe-url` would hand it to any third-party // host it links or embeds. `same-origin` keeps the Referer on requests back to // Codeman (the 404 fallback and `refererPath` rely on it; both compare URL // origins, which an opaque-origin frame still satisfies) and strips it for // everyone else. A `` inside the document can still // override this; that is the dashboard author's own decision about their page. headers['referrer-policy'] = 'same-origin'; const setCookie = setCookies.map((cookie) => rewriteSetCookie(cookie, capability, secureContext, basePath)); return { headers, setCookie, csp }; } /** * A tiny script injected at the top of every proxied document, rewriting * ROOT-ABSOLUTE URLs built at runtime so they stay inside the proxy prefix. * * `` only governs URLs the HTML parser resolves. A dashboard that calls * `fetch('/api/data')` bypasses it entirely and the request lands on Codeman's own * root, where it 404s. That is not a rare shape: it is how most dashboards talk to * their own backend, and it presents as the dashboard's own "Failed to fetch". * * The `Referer`-keyed 404 fallback catches some of these, but it is a rescue rather * than a fix (it only fires for a request that already missed every Codeman route, * and only when the browser sends a usable `Referer`). Rewriting inside the iframe * removes the whole class instead: the page never emits a root-absolute request in * the first place. * * ## Why the DOM sinks are patched too, not just fetch/XHR * * A dashboard that renders `container.innerHTML = ''` * or `img.src = '/api/slide?n=01'` produces exactly the same root-absolute request, * and NONE of the other layers can reach it: `` does not apply to * root-absolute URLs at all, and `rewriteHtml()` only ever sees the initial * document, not markup built later by page script. The visible symptom is very * specific and easy to misread: the dashboard's DATA loads (reads go through * `fetch`, which was already patched) while every IMAGE stays broken. So the same * `rw()` is applied to `innerHTML`/`outerHTML`/`insertAdjacentHTML`, to * `setAttribute`, and to the `src`/`href`/`srcset`/... property setters, with a * `MutationObserver` as a last net for any sink not patched above (that one costs a * wasted 404 per node, since the browser starts fetching on insert, so it is a net * and not the mechanism). * * Runs before any page script because it is injected immediately after ``. * Only same-origin, non-prefixed, root-absolute URLs are touched; relative URLs * (already handled by ``) and cross-origin URLs are passed through. Every * rewrite is idempotent, so a value that passes through two layers is unchanged by * the second. */ export function runtimeUrlShim(prefix: string): string { // Kept dependency-free and defensive: it runs inside a page we do not control, // and a throw here would break the dashboard rather than fix it. return ``; } /** * Make a page's own RELATIVE `` absolute under the proxy prefix. * * A base element is resolved against the document's URL, and {@link runtimeUrlShim} * deliberately rewrites that URL to strip the proxy prefix. So a page shipping * `` — which is what a Vite build does, DeepSeek Harness among * them — has its base re-resolved to Codeman's ROOT the moment the shim runs: * every module script, stylesheet and `fetch('./api')` then asks the Codeman * origin instead of the dashboard. The visible symptom is not an error page but * a blank one: the markup and inline `