Merge #825: proxied dashboards render in a web tab (dsh token, relative base, dynamic imports)

The DeepSeek Harness web tab trades the dsh web launch token for its session cookie, a relative <base href> resolves against the document's own directory, and root-absolute import("/...") inside scripts is rewritten onto the proxy prefix.

# Conflicts:
#	src/web/routes/webview-routes.ts
#	test/routes/webview-routes.test.ts
This commit is contained in:
Codeman maintainer committed 2026-11-20 04:00:05 +01:00
commit f25e94141f
12 files changed
+1405 -29

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"aicodeman": patch
---
The DeepSeek Harness web tab opens on the dashboard again instead of a blank 401 page. `dsh web` now gates its own index behind a one-time launch token it prints on boot; the supervisor reads that token out of the captured output, trades it for the session cookie once at startup, and the webview proxy presents the cookie on both the HTTP and WebSocket legs — scoped to the loopback authority it was minted for. It is sent ahead of the dashboard's own cookies rather than replacing them, so a stale browser copy of the same cookie cannot shadow the one the running process minted. The banner reader scans every `dsh web:` line (diagnostics share the prefix) and only complete lines (a split write is waited for), so a `dsh web: loading profiles` line no longer makes boot give up. The printed token URL is only fetched when it names `127.0.0.1` on the port that was just spawned. A server whose exchange failed is no longer reused, so asking to start the UI again restarts it and retries the exchange. The cookie is only presented to a tab whose owner holds the privileged-commands grant, and in multi-user mode only to the owner whose request started the process: `managed` is a client-supplied field and the live port is public, so the saved record alone is not an entitlement. A dsh without the gate keeps working unchanged.
+5
View File
@@ -0,0 +1,5 @@
---
"aicodeman": patch
---
Web tabs whose dashboard ships a relative `<base href>` render again. The proxy rewrites the document URL to strip its `/webview/<cap>/` prefix, and a relative base is resolved against that URL — so `./` (what Vite builds emit, DeepSeek Harness among them) pointed at Codeman's root: every module script 404'd and the page painted its background with nothing on it. The rewrite now resolves such a base against the document's own directory inside the proxy prefix before the mask runs (a page at `/webview/<cap>/app/page.html` gets `/webview/<cap>/app/`, not the proxy root); a cross-origin base is left exactly as the author wrote it. The root-absolute `import("/...")` rewrite is confined to `<script>` bodies, so a `<pre>import("/x")</pre>` example is no longer rewritten as if it were a loader.
+33
View File
@@ -288,6 +288,39 @@ dsh fences its `/api` behind a browser-trust check on the request authority, and
Codeman web tab reaches it through Codeman's own origin via the webview proxy, not
directly. Without it the page renders and every API call fails.
Since dsh's browser-auth gate, the index is not public either: boot prints
`dsh web: http://127.0.0.1:<port>/?token=<one-time token>` and only a request
carrying that token is answered with the `dsh-auth-*` cookie that authorizes
everything after it. The saved tab deliberately keeps the clean URL, so the
browser can never present that token, and the tab used to open on dsh's 401 page.
`src/deepseek-web-server.ts` now reads the token out of the captured boot output,
trades it for the cookie once at startup, and `webview-routes.ts` presents that
cookie on both the HTTP and WebSocket legs — scoped to the exact loopback
authority it was minted for, so a repointed or stale tab cannot carry it
elsewhere. The reader scans every `dsh web:` line (dsh prints diagnostics such as
`dsh web: loading profiles` under the same prefix before the banner) and only
complete lines, so a banner split across two output chunks is waited for rather
than parsed truncated. Before the token URL is fetched it must name `127.0.0.1`
on the port the supervisor just spawned, so a banner cannot aim the server-side
request at another host or local service. A dsh without the gate prints a
token-less banner and keeps working unchanged. If a token is printed but the
exchange still fails, the server keeps running (its page serves, just 401) and is
marked unusable for reuse: the next start request stops and respawns it, which is
the "restart `dsh web`" the warning asks the user to perform.
The cookie is also bound to a person, not to a URL. `managed` is accepted from the
client on `POST/PATCH /api/webviews` and `GET /api/deepseek/web` publishes the live
port, so a saved record pointing at that port is not an entitlement by itself: the
proxy presents the cookie only when the tab's owner holds the same
privileged-commands grant `POST /api/deepseek/web` requires, and in multi-user mode
only to the owner whose request started that process. A different owner's start
request restarts the server rather than reusing a cookie that is not theirs, which
is why the shared instance is effectively single-user at a time. On a trusted
managed tab the cookie is sent ahead of whatever cookies dsh itself set in the
browser, rather than replacing them; leading matters because a `Cookie` header can
name the same cookie twice and the first value is the one the dashboard parses, so
a stale browser copy must not shadow the one the running process minted.
## 7. Docker and remote cases
Docker cases work: the agent image installs `dsh` and bootstraps a `dsh-tui`
+24 -2
View File
@@ -144,9 +144,21 @@ per-device (`localStorage`), since that is workspace layout rather than config.
Worth knowing, because it is where this feature does its least obvious work. Three
layers cooperate so a dashboard talking to its own backend just works:
1. `<base href>` handles relative URLs in the markup.
1. `<base href>` handles relative URLs in the markup. A page that ships its own
**relative** base (`<base href="./">`, what a Vite build emits) has it resolved
against the document's own directory inside the proxy prefix first, so a
document at `/webview/<cap>/app/page.html` gets `/webview/<cap>/app/` rather
than the proxy root: the page's URL is masked a few paragraphs below, a base is
resolved against that URL, so `./` would otherwise point at Codeman's root and
404 every module script behind an otherwise-painted page.
2. Attribute rewriting handles root-absolute `src`/`href`/`action` in the page the
proxy serves.
proxy serves — and root-absolute dynamic `import("/...")` specifiers inside
`<script>` bodies. The import is the one URL no other layer can reach: `<base>`
does not apply to a `/`-rooted specifier and it is not a `fetch()`. SvelteKit's
inline bootstrap is exactly this shape; without the rewrite the module loads
from Codeman's root, 404s, and the app sits on its own loading spinner forever.
Visible text is left alone: a `<pre>import("/x")</pre>` example is not a
loader and is not rewritten.
3. A small injected script rebases URLs built at **runtime**, which the first two
cannot see: `fetch('/api/data')` and `new WebSocket('/live')`, but equally
`card.innerHTML = '<img src="/api/hero">'`, `img.src = '/api/slide'`, and
@@ -190,6 +202,16 @@ then every API call fails, which looks like the dashboard being broken.
EventSource, normal markup, the DOM sinks a page uses to build markup at runtime,
and `url()` inside stylesheets. Something that constructs requests by an unusual
route can still slip through. Symptom: the page renders but a panel stays empty.
- **Root-absolute URLs the proxy never sees.** Only the HTML is rewritten, and only
literal `/`-rooted specifiers in it. Still escape: an `import()` built at runtime
(`import('/' + name)`), an import written inside an external `.js`, a static
`import x from "/x"` in an inline script, `navigator.serviceWorker.register("/sw.js")`,
and `url(/img.png)` inside an external stylesheet. They cannot be relayed either —
the masked frame's `Referer` carries no capability — so the failure is quiet: a
blank page, or a spinner that never resolves. Codeman now logs
`[Webview] <path> escaped the proxy` (once per path per five minutes) when such a
request reaches its 404, which is the fastest way to tell this class apart from a
dashboard that is genuinely broken.
- **A root-absolute `url()` inside an inline `<style>` is not rescued.** Masking the
page's URL (layer 5) trades away the `Referer` safety net of layer 4 for
requests the shim cannot see, and only HTML is rewritten server-side. An
+263 -10
View File
@@ -27,6 +27,11 @@
* - **Failures reported, not swallowed.** The shell tab used to be where the
* stack trace landed. With no tab, the spawn's own output is captured and
* handed back to the caller instead.
* - **The launch token traded, not forwarded.** `dsh web` gates its own index
* behind a one-time token it prints on stdout and exchanges for a browser
* cookie. The tab stores a clean URL, so nothing on the browser side could
* ever present that token and every load answered 401. This module trades it
* here, once, and hands the cookie to the proxy (`getDeepSeekWebCookie`).
*/
import { spawn, type ChildProcess } from 'node:child_process';
@@ -53,6 +58,23 @@ const READY_POLL_MS = 400;
const KILL_GRACE_MS = 3_000;
/** Bound on captured child output, so a chatty boot cannot grow without limit. */
const OUTPUT_CAP = 16_384;
/**
* Bound on the boot-output window searched for the launch banner.
*
* Deliberately larger and separate from {@link OUTPUT_CAP}: that one only has to
* keep an error tail, while this one must survive a chatty plugin tree's boot
* logs long enough to see a banner printed after them. 256 KB of one-line output
* is far beyond anything a real boot prints, and a bound still exists because a
* wedged child can print forever.
*/
const BANNER_SCAN_CAP = 262_144;
/** How long boot waits for `dsh web` to print the launch URL it gates itself on. */
const LAUNCH_URL_WAIT_MS = 4_000;
/** Bound on the one-shot token→cookie exchange (loopback, so this is generous). */
const TOKEN_EXCHANGE_TIMEOUT_MS = 5_000;
/** Cookie name `dsh web` mints for a browser session that presented the token. */
const DSH_AUTH_COOKIE_PREFIX = 'dsh-auth-';
export interface DeepSeekWebStatus {
running: boolean;
@@ -66,7 +88,33 @@ interface RunningServer {
child: ChildProcess;
port: number;
authority: string;
/**
* Username of the Codeman user whose request started this server. Undefined in
* single-user mode, where no owner exists. The cookie bought with the launch
* token belongs to that identity and is presented to nobody else (see
* `getDeepSeekWebCookie`).
*/
starter: string | undefined;
output: () => string;
/**
* Boot output scanned for the launch banner, on its own (larger) budget than
* `output`. Read through this rather than `output` so a banner printed after
* the error-tail cap filled is still found.
*/
banner: () => string;
/**
* The `dsh-auth-*` cookie bought with this process's launch token, once the
* exchange succeeded. Null on a dsh old enough to serve its index without a
* token, which is why "no cookie" is not a startup failure.
*/
cookie: string | null;
/**
* True when a token-bearing banner was found but the exchange produced no
* cookie. Such a server cannot authenticate its tab and must not be reused: the
* warning tells the user to restart `dsh web`, and the next start request is
* what performs that restart.
*/
cookieFailed: boolean;
}
let current: RunningServer | null = null;
@@ -105,6 +153,158 @@ async function answersHttp(port: number): Promise<boolean> {
}
}
/**
* Remove SGR sequences so a coloured banner still parses.
*
* A coloured banner would otherwise hide the URL behind escape codes and turn a
* perfectly working server into a 401.
*/
function stripSgr(output: string): string {
// Built from the code point rather than written as `\x1b` so the linter's
// no-control-regex rule does not read it as an accidental control character.
return output.replace(new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, 'g'), '');
}
/**
* The first `dsh web:` payload that parses as an absolute http(s) URL.
*
* Lines whose payload is not a URL are skipped, which is what makes a
* `dsh web: loading profiles` diagnostic harmless. `requireToken` skips an
* http(s) URL that carries no `token` as well, so a diagnostic that happens to
* contain a plain link cannot shadow the real banner. Null when no line qualifies.
*/
function firstLaunchBannerUrl(output: string, requireToken = false): string | null {
// Fresh per call: a module-level /g pattern carries lastIndex between calls.
const line = /dsh web:\s*(\S+)/g;
for (const match of stripSgr(output).matchAll(line)) {
let url: URL;
try {
url = new URL(match[1]);
} catch {
continue;
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') continue;
if (requireToken && !url.searchParams.get('token')) continue;
return url.href;
}
return null;
}
/**
* The authenticated URL `dsh web` prints once it is up.
*
* Its browser-auth gate made the index private: boot writes
* `dsh web: http://127.0.0.1:<port>/?token=<one-time token>` and only a request
* carrying that token is answered with the cookie that authorizes everything
* after it. The token is per process, so it can be neither guessed nor carried
* across restarts — it has to be read out of the boot output.
*
* Scans EVERY `dsh web:` line and returns the first one that is a usable URL
* carrying a token, because dsh also prints diagnostics under the same prefix
* before the banner.
*
* Null for output without one, which is the older-dsh case and stays working.
*
* @param output - captured stdout+stderr so far.
* @returns absolute http(s) URL carrying a `token`, or null.
*/
export function parseLaunchUrl(output: string): string | null {
return firstLaunchBannerUrl(output, true);
}
/**
* Whether a launch URL names the loopback port this supervisor just spawned.
*
* The URL is read from the child's output, but fetching it is a request made by
* the SERVER. A banner naming another host, or another local service's port, must
* not turn that exchange into an SSRF primitive, so the target is required to be
* the exact origin the token was minted for.
*/
export function launchUrlTargetsServer(launchUrl: string, port: number): boolean {
try {
const url = new URL(launchUrl);
const effectivePort = Number(url.port || (url.protocol === 'https:' ? 443 : 80));
return url.hostname === '127.0.0.1' && effectivePort === port;
} catch {
return false;
}
}
/**
* Trade the launch URL for the `dsh-auth-*` cookie the proxy will present.
*
* `redirect: 'manual'` is load-bearing: the 303 is the response that carries
* `Set-Cookie`, and following it would burn the token on a redirect to `./`
* while dropping the only credential the exchange produces.
*
* @param launchUrl - token-bearing URL from {@link parseLaunchUrl}.
* @returns `name=value` pair ready for a Cookie header, or null.
*/
async function exchangeLaunchToken(launchUrl: string): Promise<string | null> {
try {
const response = await fetch(launchUrl, {
redirect: 'manual',
signal: AbortSignal.timeout(TOKEN_EXCHANGE_TIMEOUT_MS),
});
for (const header of response.headers.getSetCookie()) {
const pair = header.split(';', 1)[0]?.trim();
if (pair?.startsWith(DSH_AUTH_COOKIE_PREFIX)) return pair;
}
return null;
} catch {
return null;
}
}
/**
* Wait for the banner, then exchange it.
*
* Never fails startup: a dsh without the gate prints a token-less banner, which
* is answered as "nothing to exchange" immediately rather than after the whole
* wait, and a gate that changes shape must not turn a serving UI into a boot
* failure.
*
* @param running - the just-started server, read for its captured output.
* @returns the cookie to hand the proxy (null when there is none) and whether a
* token was printed but could not be exchanged.
*/
async function captureSessionCookie(running: RunningServer): Promise<{ cookie: string | null; failed: boolean }> {
const deadline = Date.now() + LAUNCH_URL_WAIT_MS;
while (Date.now() < deadline) {
// Only COMPLETE lines: a chunk boundary can cut the token in half, and
// exchanging a truncated one would burn the token on a request that cannot
// authenticate. The next poll picks up the rest of the line.
const banner = running.banner();
const complete = banner.slice(0, banner.lastIndexOf('\n') + 1);
const launchUrl = parseLaunchUrl(complete);
if (launchUrl) {
if (!launchUrlTargetsServer(launchUrl, running.port)) {
console.warn(
'[DeepSeek web] the printed launch URL does not name the loopback port this server was started on; ' +
'not fetching it'
);
return { cookie: null, failed: true };
}
const cookie = await exchangeLaunchToken(launchUrl);
// The URL is a credential: never log it, only the fact that it did not work.
if (!cookie) {
console.warn(
'[DeepSeek web] the launch token was printed but could not be exchanged for a session cookie; ' +
'the next start request will restart `dsh web` so it can retry'
);
return { cookie: null, failed: true };
}
return { cookie, failed: false };
}
// Only a printed http(s) URL settles this: it is the older dsh, which needs
// no cookie. Any other line carrying the prefix (a diagnostic, a truncated
// write) is not a banner, so the wait continues instead of giving up early.
if (firstLaunchBannerUrl(complete)) return { cookie: null, failed: false };
await new Promise((resolve) => setTimeout(resolve, 100));
}
return { cookie: null, failed: false };
}
/**
* Signal the whole process group.
*
@@ -134,6 +334,25 @@ export function getDeepSeekWebStatus(): DeepSeekWebStatus {
};
}
/**
* The cookie this server's launch token bought, for the proxy to present.
*
* Keyed by `port` because the cookie is signed for the authority it was minted
* under (`127.0.0.1:<port>`): handing it to a web tab pointed at some other
* server would neither authenticate nor be that server's to receive. Null also
* covers a dsh old enough to need no cookie at all.
*
* @param port - loopback port the upstream request is bound for.
* @param owner - identity asking for it; must be the user who started the server.
* Both sides are undefined in single-user mode, where there is no owner.
* @returns `name=value` cookie pair, or null.
*/
export function getDeepSeekWebCookie(port: number, owner?: string): string | null {
if (!current || current.port !== port) return null;
if (current.starter !== owner) return null;
return current.cookie;
}
/** Stop the background server, if one is running. Safe to call when none is. */
export async function stopDeepSeekWeb(): Promise<void> {
const running = current;
@@ -174,11 +393,12 @@ let startLock: Promise<unknown> = Promise.resolve();
*
* @param dshDir directory holding the resolved `dsh` binary.
* @param authority browser authority to pass as `--trusted-host`.
* @param starter user whose request is starting it (undefined in single-user).
*/
export function startDeepSeekWeb(dshDir: string, authority: string): Promise<StartResult> {
export function startDeepSeekWeb(dshDir: string, authority: string, starter?: string): Promise<StartResult> {
const run = startLock.then(
() => startDeepSeekWebLocked(dshDir, authority),
() => startDeepSeekWebLocked(dshDir, authority)
() => startDeepSeekWebLocked(dshDir, authority, starter),
() => startDeepSeekWebLocked(dshDir, authority, starter)
);
startLock = run.then(
() => undefined,
@@ -187,13 +407,24 @@ export function startDeepSeekWeb(dshDir: string, authority: string): Promise<Sta
return run;
}
async function startDeepSeekWebLocked(dshDir: string, authority: string): Promise<StartResult> {
async function startDeepSeekWebLocked(
dshDir: string,
authority: string,
starter: string | undefined
): Promise<StartResult> {
// Reuse only when the running server is BOTH healthy and fenced for the
// authority now asking. A server trusting the other origin renders a page
// whose every API call 403s, which looks like a broken dashboard rather than
// a misconfigured one.
// authority now asking, it was started by this identity, and its credential
// works: the launch cookie is per process and per user, so handing a previous
// starter's server to another user would leave that user's tab on dsh's 401
// page, and a server whose token exchange failed would keep answering 401
// forever because reuse never gave anyone a chance to restart it.
if (current) {
if (current.authority === authority && (await answersHttp(current.port))) {
if (
!current.cookieFailed &&
current.authority === authority &&
current.starter === starter &&
(await answersHttp(current.port))
) {
return { ok: true, port: current.port, url: `http://127.0.0.1:${current.port}`, reused: true };
}
await stopDeepSeekWeb();
@@ -223,8 +454,15 @@ async function startDeepSeekWebLocked(dshDir: string, authority: string): Promis
// The pipes must be drained whether or not anyone reads them: a full pipe
// blocks the child. Storage is capped; draining is not.
let output = '';
// Scanned for the launch banner separately from `output`. That cap exists to
// bound the error tail, and a chatty profile can fill it before the banner is
// printed — losing the banner there produces exactly the 401 tab this module
// exists to prevent, so the two buffers must not share a limit.
let banner = '';
const capture = (chunk: Buffer) => {
if (output.length < OUTPUT_CAP) output += chunk.toString('utf-8');
const text = chunk.toString('utf-8');
if (output.length < OUTPUT_CAP) output += text;
if (banner.length < BANNER_SCAN_CAP) banner += text;
};
child.stdout?.on('data', capture);
child.stderr?.on('data', capture);
@@ -241,7 +479,16 @@ async function startDeepSeekWebLocked(dshDir: string, authority: string): Promis
if (current?.child === child) current = null;
});
const running: RunningServer = { child, port, authority, output: () => output };
const running: RunningServer = {
child,
port,
authority,
starter,
output: () => output,
banner: () => banner,
cookie: null,
cookieFailed: false,
};
current = running;
const deadline = Date.now() + READY_TIMEOUT_MS;
@@ -255,6 +502,12 @@ async function startDeepSeekWebLocked(dshDir: string, authority: string): Promis
return { ok: false, error: tail ? `dsh web exited during startup: ${tail}` : 'dsh web exited during startup' };
}
if (await answersHttp(port)) {
// Bought before this call resolves, so the first proxied page load
// already carries a credential — a tab opened a moment earlier would
// otherwise get the 401 this whole module exists to prevent.
const captured = await captureSessionCookie(running);
running.cookie = captured.cookie;
running.cookieFailed = captured.failed;
return { ok: true, port, url: `http://127.0.0.1:${port}`, reused: false };
}
await new Promise((r) => setTimeout(r, READY_POLL_MS));
+5 -2
View File
@@ -19,7 +19,7 @@ import { ApiErrorCode, createErrorResponse, getErrorMessage, type NiceConfig } f
import { isExplicitlyEnabled, isUnauthenticatedTunnelAcknowledged } from '../network-auth-policy.js';
import { isMultiUserMode } from '../../config/multiuser.js';
import { findUser, canUsernameRunPrivilegedCommands } from '../../user-store.js';
import { getAuthUser, isAdmin, requireAdmin, canAccessOwned, revokeUserSessions } from '../route-helpers.js';
import { getAuthUser, isAdmin, requireAdmin, canAccessOwned, revokeUserSessions, ownerFor } from '../route-helpers.js';
import {
ConfigUpdateSchema,
SettingsUpdateSchema,
@@ -663,7 +663,10 @@ export function registerSystemRoutes(
if (!dir) return createErrorResponse(ApiErrorCode.OPERATION_FAILED, getDeepSeekNotFoundMessage());
const { startDeepSeekWeb } = await import('../../deepseek-web-server.js');
const result = await startDeepSeekWeb(dir, authority);
// The launch cookie is bound to the identity whose request started the
// process, so `ownerFor` (undefined in single-user) is recorded here rather
// than the synthetic admin `getAuthUser` would report.
const result = await startDeepSeekWeb(dir, authority, ownerFor(req));
if (!result.ok) return createErrorResponse(ApiErrorCode.OPERATION_FAILED, result.error);
return { success: true, data: { port: result.port, url: result.url, reused: result.reused } };
});
+62 -4
View File
@@ -36,6 +36,7 @@ import { WebSocket as WsClient } from 'ws';
import type { ClientOptions as WsClientOptions, WebSocket } from 'ws';
import type { Response as UndiciResponse } from 'undici';
import { getDataDir } from '../../config/instance.js';
import { isMultiUserMode } from '../../config/multiuser.js';
import {
MAX_LIVE_WEBVIEW_FRAMES,
MAX_WEBVIEWS,
@@ -47,9 +48,11 @@ import {
WEBVIEW_WS_HANDSHAKE_TIMEOUT_MS,
} from '../../config/webview-limits.js';
import { readWebviews, writeWebviews } from '../../webview-store.js';
import { canUsernameRunPrivilegedCommands } from '../../user-store.js';
import { webviewCapabilities } from '../../webview-capabilities.js';
import { egressBlockedReason, webviewEgressLookup, webviewFetch, type EgressLookup } from '../webview-egress.js';
import { blockedWebviewHostReason } from '../webview-egress-policy.js';
import { getDeepSeekWebCookie } from '../../deepseek-web-server.js';
import { ApiErrorCode, createErrorResponse } from '../../types.js';
import type { Webview, WebviewOpenData, WebviewProbe } from '../../types.js';
import { AUTH_COOKIE_NAME } from '../middleware/auth.js';
@@ -67,6 +70,7 @@ import {
filterCookieHeader,
isFramableCrossOrigin,
isHtmlContentType,
mergeCookieHeader,
parseWebviewUrl,
proxyPrefixFor,
resolveUpstreamUrl,
@@ -427,6 +431,49 @@ function proxyHttp(
return proxyRequest(req, reply, req.params.cap, req.params['*'] ?? '', basePath);
}
/**
* The credential a Codeman-managed dashboard needs on every upstream request.
*
* `dsh web` now gates its index and `/api` behind a cookie minted for the
* authority it was started on, and only the URL it prints on boot carries the
* token that buys it. The managed DeepSeek tab deliberately stores the clean
* URL, so the browser can never hold that cookie: `deepseek-web-server.ts`
* exchanges the token at startup, and this is where the supervisor's result
* reaches the request.
*
* Strictly scoped to the exact loopback origin the cookie was minted for. A
* web tab the user repointed at another host, or a stale tab still naming a
* previous port, must not be handed a credential that is not its own.
*
* ⚠️ `managed` is accepted from the client on POST/PATCH /api/webviews, and the
* live port is published by GET /api/deepseek/web, so "this record is managed and
* points at the port" is NOT an entitlement: without the check below, any signed-in
* user could save `{ url: "http://127.0.0.1:<port>", managed: "deepseek-web" }` and
* be handed the cookie bought by the user allowed to start the server. The gate
* needs the owner's privileged-commands grant, which is the same bar
* `POST /api/deepseek/web` applies before it starts a server.
*
* @param webview - the saved tab being proxied.
* @param upstream - resolved upstream URL for this request.
* @returns `name=value` cookie pair, or undefined when none applies.
*/
async function managedDashboardCookie(webview: Webview, upstream: URL): Promise<string | undefined> {
if (webview.managed !== 'deepseek-web') return undefined;
if (upstream.hostname !== '127.0.0.1') return undefined;
if (isMultiUserMode()) {
// Fail closed on an ownerless legacy record: `canUsernameRunPrivilegedCommands`
// treats an absent username as privileged (right for a cron job with no owner,
// wrong here), so the owner must be present before it is asked.
if (!webview.owner) return undefined;
if (!(await canUsernameRunPrivilegedCommands(webview.owner))) return undefined;
}
const port = Number(upstream.port || (upstream.protocol === 'https:' ? 443 : 80));
// The second identity check is the supervisor's: even an entitled owner gets
// nothing from a process another user started (POST restarts it for a new
// starter, so that tab simply reopens with its own cookie).
return getDeepSeekWebCookie(port, webview.owner) ?? undefined;
}
/**
* Proxy one request to the dashboard behind `cap`, serving `wildcard` as the
* upstream path. Split out from the route handler so the 404 fallback (which has
@@ -469,12 +516,14 @@ async function proxyRequest(
}
const hasBody = req.method !== 'GET' && req.method !== 'HEAD';
const injectedCookie = await managedDashboardCookie(webview, upstream);
const headers = buildUpstreamRequestHeaders(req.headers, upstream, {
forwardCookies: webview.trusted,
sessionCookieName: AUTH_COOKIE_NAME,
refererPath:
typeof req.headers.referer === 'string' ? stripProxyPrefix(req.headers.referer, cap, basePath) : undefined,
relayBodyLength: hasBody && req.body !== undefined,
...(injectedCookie ? { injectedCookie } : {}),
});
// #237: the timeout bounds TIME-TO-HEADERS only. A plain AbortSignal.timeout on
@@ -596,7 +645,9 @@ async function proxyRequest(
// Buffer only HTML, only under the cap: `<base>` injection needs the whole
// document, and buffering an unbounded upstream body is a memory hazard.
const html = await response.text();
return reply.send(html.length <= MAX_WEBVIEW_HTML_REWRITE_BYTES ? rewriteHtml(html, cap, basePath) : html);
return reply.send(
html.length <= MAX_WEBVIEW_HTML_REWRITE_BYTES ? rewriteHtml(html, cap, basePath, wildcard) : html
);
}
return reply.send(Readable.fromWeb(response.body as Parameters<typeof Readable.fromWeb>[0]));
@@ -708,9 +759,16 @@ function proxyWebSocket(socket: WebSocket, req: FastifyRequest<{ Params: ProxyPa
};
const protocols = req.headers['sec-websocket-protocol'];
// Trusted dashboards get the browser's own cookies, but never Codeman's
// session cookie: the HTTP leg strips it the same way.
const cookie = webview.trusted ? filterCookieHeader(req.headers.cookie, [AUTH_COOKIE_NAME]) : undefined;
// The same credential the HTTP leg presents. A managed dashboard's realtime
// channel is gated exactly like its index, so without this the page loads
// and then sits there silently disconnected. Trusted dashboards get the
// browser's other cookies too, but never Codeman's own session cookie,
// with or without an injected one: the HTTP leg strips it the same way.
const injectedCookie = await managedDashboardCookie(webview, upstream);
const browserCookie = webview.trusted
? filterCookieHeader(req.headers.cookie ? String(req.headers.cookie) : undefined, [AUTH_COOKIE_NAME])
: undefined;
const cookie = injectedCookie ? mergeCookieHeader(browserCookie, injectedCookie) : browserCookie;
// `lookup` is absent from ws's ClientOptions typings but flows through
// http.request to net.connect untouched, which is where the resolved
// address is judged (see webview-egress.ts).
+38 -1
View File
@@ -269,7 +269,7 @@ import {
registerCliRegistryRoutes,
registerLocalModelRoutes,
} from './routes/index.js';
import { isLostWebviewFrameNavigation } from './webview-proxy.js';
import { escapedWebviewAssetPath, isLostWebviewFrameNavigation } from './webview-proxy.js';
import { CronService } from '../cron/cron-service.js';
import { caseSessionSettled } from '../case-rename.js';
@@ -361,6 +361,38 @@ function getOrCreateSelfSignedCert(): { key: string; cert: string } {
};
}
/**
* One warn per escaped path per few minutes.
*
* A page whose boot module 404s retries in a loop, so an undeduped warn would
* bury the log it is meant to explain. Capped so a page emitting unbounded
* unique paths cannot grow the map without limit.
*/
const escapedWebviewWarnedAt = new Map<string, number>();
const ESCAPED_WEBVIEW_WARN_TTL_MS = 5 * 60_000;
/**
* Name a root-absolute request that escaped a web tab's proxy prefix.
*
* Nothing is retried or rewritten here — the request genuinely has no capability
* to relay to. This exists because that failure is otherwise silent: the tab
* shows a blank page or a spinner that never resolves, and the log says nothing.
*
* @param path - request path already judged as that shape.
*/
function warnEscapedWebviewAsset(path: string): void {
const now = Date.now();
const last = escapedWebviewWarnedAt.get(path);
if (last !== undefined && now - last < ESCAPED_WEBVIEW_WARN_TTL_MS) return;
if (escapedWebviewWarnedAt.size >= 200) escapedWebviewWarnedAt.clear();
escapedWebviewWarnedAt.set(path, now);
console.warn(
`[Webview] ${path} escaped the proxy: a web tab asked for a root-absolute URL that no Codeman route serves. ` +
`Its URL is masked, so the Referer cannot identify the dashboard. Usual cause: a URL built at runtime ` +
`(dynamic import(), worker, service worker) or an import inside an external script. The tab will look blank or stuck.`
);
}
export class WebServer extends EventEmitter {
private app: FastifyInstance;
private sessions: Map<string, Session> = new Map();
@@ -1294,6 +1326,11 @@ export class WebServer extends EventEmitter {
// and the relay declines unless the Referer carries a live capability, so
// genuinely unknown `/api` paths still get the envelope below.
if (await tryWebviewRefererFallback(req, reply, this.basePath)) return reply;
// No capability in the Referer, so this cannot be relayed — but if it has
// the shape of a dashboard asset, say so once. Silent 404s here are what
// turned a boot-module failure into a "blank tab" mystery more than once.
const escaped = escapedWebviewAssetPath({ method: req.method, url: req.url, headers: req.headers });
if (escaped) warnEscapedWebviewAsset(escaped);
// An authenticated web-tab frame (Basic auth, or trusted mode with a cookie)
// that navigated itself off its proxy prefix: the runtime shim masks the
// prefix so the page's router sees its own path, and a reload of that page
+194 -5
View File
@@ -207,6 +207,73 @@ export function capabilityFromReferer(referer: string | undefined, basePath = ''
}
}
/** `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, string | string[] | undefined>;
}): 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
@@ -296,6 +363,20 @@ export function rewriteSetCookie(cookie: string, capability: string, secureConte
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;
@@ -311,7 +392,21 @@ export function filterCookieHeader(cookie: string | undefined, drop: string[]):
export function buildUpstreamRequestHeaders(
incoming: Record<string, string | string[] | undefined>,
upstream: URL,
opts: { forwardCookies: boolean; sessionCookieName: string; refererPath?: string; relayBodyLength?: boolean }
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<string, string> {
const headers: Record<string, string> = {};
@@ -343,6 +438,14 @@ export function buildUpstreamRequestHeaders(
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;
@@ -646,6 +749,79 @@ try{
}catch(e){}})();</script>`;
}
/**
* Make a page's own RELATIVE `<base href>` 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
* `<base href="./">` — 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 `<style>` paint (dsh paints a dark
* `#151517`), the module 404s, and nothing else ever renders.
*
* Resolving it here, while the prefix is still known, keeps the author's target
* (the document as it existed before masking) and is idempotent: an
* already-absolute path resolves to itself. Cross-origin bases are the author
* pointing at a CDN and are left exactly as written.
*
* The document path matters: a base in `/webview/<cap>/app/page.html` is
* relative to `/webview/<cap>/app/`, not to the proxy root, or a page served
* from a subdirectory would resolve its assets one level too high.
*
* @param html - document with attributes already rebased.
* @param prefix - proxy prefix the document was served from.
* @param documentPath - upstream path of the document, without the leading slash.
* @returns the document with a relative base href made absolute.
*/
function rebaseRelativeBase(html: string, prefix: string, documentPath: string): string {
const documentUrl = `http://codeman.invalid${prefix}${documentPath.replace(/^\/+/, '')}`;
return html.replace(
/(<base\b[^>]*?\bhref\s*=\s*)(["'])([^"']*)\2/i,
(match: string, head: string, quote: string, href: string) => {
let resolved: URL;
try {
// A stand-in origin: only the path is kept, and a different origin here
// is exactly the "absolute base" case this must not touch.
resolved = new URL(href, documentUrl);
} catch {
return match;
}
if (resolved.origin !== 'http://codeman.invalid') return match;
return `${head}${quote}${resolved.pathname}${resolved.search}${resolved.hash}${quote}`;
}
);
}
/**
* Rewrite root-absolute specifiers of dynamic `import()` calls in `<script>`
* bodies.
*
* A dynamic import is the one URL no other layer can reach: it is not an
* attribute, so `<base>` does not apply to it; it is not `fetch()`, so the runtime
* shim cannot rewrite it; and the browser resolves it against the ORIGIN root, not
* the document. SvelteKit's inline bootstrap is exactly this shape
* (`import("/_app/…")`), and the failure mode is silent: the module 404s against
* Codeman and the app's own loading spinner never resolves.
*
* ⚠️ Scoped to script bodies on purpose. Running the same regex over the whole
* document also rewrote visible text — `<pre>import("/x")</pre>` became a broken
* example — which is a rendering bug, not a loader the browser was going to run.
*
* @param html - document with attributes already rebased.
* @param prefix - proxy prefix to put in front of a `/`-rooted specifier.
*/
function rewriteScriptImports(html: string, prefix: string): string {
return html.replace(
/(<script\b[^>]*>)([^]*?)(<\/script>)/gi,
(_match: string, open: string, body: string, close: string) =>
open +
body.replace(/\bimport\s*\(\s*(["'])\/(?!\/)/g, (_import: string, quote: string) => `import(${quote}${prefix}`) +
close
);
}
/**
* Inject `<base href="/webview/<cap>/">` plus the runtime URL shim, and rebase
* root-absolute `src`/`href`/`action` attributes, which `<base>` alone does not
@@ -654,14 +830,27 @@ try{
* Three layers, because no single one is sufficient: `<base>` for parser-resolved
* relative URLs, attribute rewriting for root-absolute markup, and the shim for
* URLs built at runtime.
*
* @param html - the upstream document.
* @param capability - capability the document is being served under.
* @param basePath - reverse-proxy mount prefix (`''` at root).
* @param documentPath - upstream path of the document, without the leading slash.
* Used to resolve the page's own relative `<base>` against its directory.
*/
export function rewriteHtml(html: string, capability: string, basePath = ''): string {
export function rewriteHtml(html: string, capability: string, basePath = '', documentPath = ''): string {
const prefix = proxyPrefixFor(capability, basePath);
// Fresh regexes per call: module-level /g patterns carry `lastIndex` between calls.
const rebased = html
.replace(/(\s(?:src|href|action)\s*=\s*")\/(?!\/)/gi, `$1${prefix}`)
.replace(/(\s(?:src|href|action)\s*=\s*')\/(?!\/)/gi, `$1${prefix}`);
const rebased = rebaseRelativeBase(
rewriteScriptImports(
html
.replace(/(\s(?:src|href|action)\s*=\s*")\/(?!\/)/gi, `$1${prefix}`)
.replace(/(\s(?:src|href|action)\s*=\s*')\/(?!\/)/gi, `$1${prefix}`),
prefix
),
prefix,
documentPath
);
// A page that ships its own <base> keeps it (overriding it would break the
// author's intent), but it STILL needs the shim, which is the layer that
+362 -2
View File
@@ -12,10 +12,25 @@
* 2. The supervisor tracks at most ONE server. The status accessor is what every
* caller reads to decide whether to start another, so "no server" must report
* as absent rather than as a half-populated record.
* 3. `dsh web` now gates its index behind a launch token it prints on boot. The
* supervisor is the only party that can trade it, and the cookie it produces
* is authority-bound: getting that wrong is a blank tab, not a visible error.
*/
import { describe, expect, it, beforeEach } from 'vitest';
import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import http from 'node:http';
import { DeepSeekWebStartSchema } from '../src/web/schemas.js';
import { getDeepSeekWebStatus, resetDeepSeekWebForTest, stopDeepSeekWeb } from '../src/deepseek-web-server.js';
import {
getDeepSeekWebCookie,
getDeepSeekWebStatus,
launchUrlTargetsServer,
parseLaunchUrl,
resetDeepSeekWebForTest,
startDeepSeekWeb,
stopDeepSeekWeb,
} from '../src/deepseek-web-server.js';
describe('DeepSeekWebStartSchema: the authority reaching --trusted-host', () => {
it('accepts the authority shapes a browser can actually report', () => {
@@ -71,3 +86,348 @@ describe('DeepSeek web supervisor: status', () => {
expect(getDeepSeekWebStatus().running).toBe(false);
});
});
describe('parseLaunchUrl: the one-time token dsh prints on boot', () => {
it('pulls the URL out of the banner a real boot writes', () => {
const output = ['dsh web: http://127.0.0.1:3080/?token=0Yb3sJk9Qm2xLd7Tf1Vc', 'ready'].join('\n');
expect(parseLaunchUrl(output)).toBe('http://127.0.0.1:3080/?token=0Yb3sJk9Qm2xLd7Tf1Vc');
});
it('sees through SGR colouring, which would otherwise hide the token', () => {
const output = '\u001b[36mdsh web:\u001b[0m \u001b[4mhttp://127.0.0.1:3080/?token=abc123\u001b[0m\n';
expect(parseLaunchUrl(output)).toBe('http://127.0.0.1:3080/?token=abc123');
});
// dsh prints diagnostics under the same prefix before the banner. Taking the
// FIRST match made the real URL invisible and boot gave up 4 seconds later.
it('skips a diagnostic line and keeps scanning for the URL', () => {
expect(parseLaunchUrl('dsh web: loading profiles\ndsh web: http://127.0.0.1:3080/?token=abc\n')).toBe(
'http://127.0.0.1:3080/?token=abc'
);
});
it('skips a URL without a token and keeps scanning for the token one', () => {
expect(parseLaunchUrl('dsh web: http://127.0.0.1:3080/\ndsh web: http://127.0.0.1:3080/?token=abc\n')).toBe(
'http://127.0.0.1:3080/?token=abc'
);
});
it('returns null for a token-less banner, which is the older dsh', () => {
expect(parseLaunchUrl('dsh web: http://127.0.0.1:3080/\n')).toBeNull();
});
it('refuses anything that is not an http(s) URL carrying a token', () => {
expect(parseLaunchUrl('')).toBeNull();
expect(parseLaunchUrl('booting...')).toBeNull();
expect(parseLaunchUrl('dsh web: javascript:alert(1)?token=x')).toBeNull();
expect(parseLaunchUrl('dsh web: not a url?token=x')).toBeNull();
});
});
describe('launchUrlTargetsServer: the exchange must hit the spawned port', () => {
it('accepts only 127.0.0.1 on the port that was just spawned', () => {
expect(launchUrlTargetsServer('http://127.0.0.1:3080/?token=x', 3080)).toBe(true);
expect(launchUrlTargetsServer('http://127.0.0.1:3081/?token=x', 3080)).toBe(false);
expect(launchUrlTargetsServer('http://localhost:3080/?token=x', 3080)).toBe(false);
expect(launchUrlTargetsServer('http://evil.example:3080/?token=x', 3080)).toBe(false);
expect(launchUrlTargetsServer('not a url', 3080)).toBe(false);
});
});
describe('DeepSeek web supervisor: the launch-token cookie', () => {
let dir: string;
beforeEach(() => {
resetDeepSeekWebForTest();
dir = mkdtempSync(join(tmpdir(), 'codeman-dsh-web-'));
});
afterEach(async () => {
await stopDeepSeekWeb();
rmSync(dir, { recursive: true, force: true });
});
/**
* A stand-in for `dsh web` with the browser-auth gate: prints the banner,
* refuses `/` without a cookie, and trades the token for one 303.
*/
const FAKE_DSH = `#!/usr/bin/env node
const http = require('node:http');
const portArg = process.argv.indexOf('--port');
const port = Number(process.argv[portArg + 1]);
const token = 'test-launch-token';
const cookie = 'dsh-auth-test=v1.payload.sig';
process.stdout.write('dsh web: http://127.0.0.1:' + port + '/?token=' + token + '\\n');
http
.createServer((req, res) => {
const url = new URL(req.url, 'http://127.0.0.1:' + port);
if (url.pathname === '/' && url.searchParams.get('token') === token) {
res.writeHead(303, { location: './', 'set-cookie': cookie + '; Path=/; HttpOnly' });
res.end();
return;
}
if (req.headers.cookie === cookie) {
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
res.end('<!doctype html><title>harness</title>');
return;
}
res.writeHead(401, { 'content-type': 'text/plain' });
res.end('dsh web authentication required');
})
.listen(port, '127.0.0.1');
`;
it('trades the boot token for the cookie, scoped to its own port', async () => {
writeFileSync(join(dir, 'dsh'), FAKE_DSH, { mode: 0o755 });
const result = await startDeepSeekWeb(dir, 'localhost:3000');
expect(result.ok).toBe(true);
if (!result.ok) return;
// Before the exchange this page is exactly the blank tab being fixed: 401.
expect((await fetch(`http://127.0.0.1:${result.port}/`)).status).toBe(401);
expect(getDeepSeekWebCookie(result.port)).toBe('dsh-auth-test=v1.payload.sig');
// A credential minted for this authority must never travel to another port.
expect(getDeepSeekWebCookie(result.port + 1)).toBeNull();
const authed = await fetch(`http://127.0.0.1:${result.port}/`, {
headers: { cookie: getDeepSeekWebCookie(result.port) as string },
});
expect(authed.status).toBe(200);
}, 20_000);
// `managed` is a client-supplied field and the port is published by
// GET /api/deepseek/web, so the supervisor additionally binds the cookie to the
// identity whose request started the process: another user's tab must not be
// handed it, and their POST must not reuse bob's server either.
it('hands the cookie only to the identity that started the server', async () => {
writeFileSync(join(dir, 'dsh'), FAKE_DSH, { mode: 0o755 });
const bob = await startDeepSeekWeb(dir, 'localhost:3000', 'bob');
expect(bob.ok).toBe(true);
if (!bob.ok) return;
expect(getDeepSeekWebCookie(bob.port, 'bob')).toBe('dsh-auth-test=v1.payload.sig');
expect(getDeepSeekWebCookie(bob.port)).toBeNull();
expect(getDeepSeekWebCookie(bob.port, 'alice')).toBeNull();
// A different owner restarts rather than reusing bob's cookie.
const alice = await startDeepSeekWeb(dir, 'localhost:3000', 'alice');
expect(alice.ok).toBe(true);
if (!alice.ok) return;
expect(alice.reused).toBe(false);
expect(getDeepSeekWebCookie(alice.port, 'alice')).toBe('dsh-auth-test=v1.payload.sig');
expect(getDeepSeekWebCookie(alice.port, 'bob')).toBeNull();
}, 20_000);
// A failed exchange leaves a server that answers 401 to everything. Reuse used
// to hand that same server back on every POST, so the restart the warning asks
// for could never happen. The next start request must perform it.
it('restarts rather than reusing a server whose exchange failed', async () => {
writeFileSync(
join(dir, 'dsh'),
`#!/usr/bin/env node
const fs = require('node:fs');
const http = require('node:http');
const path = require('node:path');
const port = Number(process.argv[process.argv.indexOf('--port') + 1]);
const token = 'retry-token';
const cookie = 'dsh-auth-retry=v1.sig';
const marker = path.join(__dirname, '.exchange-failed');
const failedBefore = fs.existsSync(marker);
if (!failedBefore) fs.writeFileSync(marker, '1');
process.stdout.write('dsh web: http://127.0.0.1:' + port + '/?token=' + token + '\\n');
http
.createServer((req, res) => {
const url = new URL(req.url, 'http://127.0.0.1:' + port);
if (url.searchParams.get('token') === token) {
if (!failedBefore) {
res.writeHead(500, { 'content-type': 'text/plain' });
res.end('temporary failure');
return;
}
res.writeHead(303, { location: './', 'set-cookie': cookie + '; Path=/' });
res.end();
return;
}
if (req.headers.cookie === cookie) {
res.writeHead(200, { 'content-type': 'text/html' });
res.end('<html>ok</html>');
return;
}
res.writeHead(401, { 'content-type': 'text/plain' });
res.end('dsh web authentication required');
})
.listen(port, '127.0.0.1');
`,
{ mode: 0o755 }
);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
try {
const first = await startDeepSeekWeb(dir, 'localhost:3000');
expect(first.ok).toBe(true);
if (!first.ok) return;
expect(getDeepSeekWebCookie(first.port)).toBeNull();
expect(warn).toHaveBeenCalledWith(expect.stringContaining('could not be exchanged'));
} finally {
warn.mockRestore();
}
const second = await startDeepSeekWeb(dir, 'localhost:3000');
expect(second.ok).toBe(true);
if (!second.ok) return;
expect(second.reused).toBe(false);
expect(getDeepSeekWebCookie(second.port)).toBe('dsh-auth-retry=v1.sig');
// The recovered server is healthy again, so ordinary reuse resumes.
const third = await startDeepSeekWeb(dir, 'localhost:3000');
expect(third.ok).toBe(true);
if (!third.ok) return;
expect(third.reused).toBe(true);
}, 20_000);
// The exchange is a request made by the SERVER. A banner naming another local
// port would let captured child output aim it, so the URL is judged before it
// is fetched at all.
it('does not fetch a banner naming another port', async () => {
const hits: string[] = [];
const target = http.createServer((req, res) => {
hits.push(req.url ?? '');
res.writeHead(200, { 'content-type': 'text/plain' });
res.end('should never be reached');
});
await new Promise<void>((resolve) => target.listen(0, '127.0.0.1', resolve));
const address = target.address();
if (!address || typeof address === 'string') throw new Error('target has no address');
try {
writeFileSync(
join(dir, 'dsh'),
`#!/usr/bin/env node
const http = require('node:http');
const port = Number(process.argv[process.argv.indexOf('--port') + 1]);
process.stdout.write('dsh web: http://127.0.0.1:${address.port}/?token=stolen\\n');
http
.createServer((_req, res) => {
res.writeHead(401, { 'content-type': 'text/plain' });
res.end('dsh web authentication required');
})
.listen(port, '127.0.0.1');
`,
{ mode: 0o755 }
);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
try {
const result = await startDeepSeekWeb(dir, 'localhost:3000');
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(getDeepSeekWebCookie(result.port)).toBeNull();
expect(warn).toHaveBeenCalledWith(expect.stringContaining('not fetching it'));
} finally {
warn.mockRestore();
}
expect(hits).toEqual([]);
} finally {
await new Promise<void>((resolve) => target.close(() => resolve()));
}
}, 20_000);
it('leaves the old, ungated dsh working: no token means no cookie, not a failure', async () => {
writeFileSync(
join(dir, 'dsh'),
'#!/usr/bin/env node\nconst http = require("node:http");\nconst port = Number(process.argv[process.argv.indexOf("--port") + 1]);\nprocess.stdout.write("dsh web: http://127.0.0.1:" + port + "/\\n");\nhttp.createServer((_q, s) => s.end("ok")).listen(port, "127.0.0.1");\n',
{ mode: 0o755 }
);
const result = await startDeepSeekWeb(dir, 'localhost:3000');
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(getDeepSeekWebCookie(result.port)).toBeNull();
}, 20_000);
// The error-tail buffer is capped at 16 KB, and a chatty plugin tree can fill
// it before dsh prints its banner. Scanning that buffer alone lost the token
// and put the tab back on the 401 page, so the banner is matched on its own
// (larger) budget.
// The banner can arrive in two stdout writes: `capture()` sees two chunks and
// neither is a complete line. Scanning the raw buffer either missed it or, with
// a partial URL that happened to parse, exchanged a truncated token.
it('waits for a banner split across two output chunks', async () => {
writeFileSync(
join(dir, 'dsh'),
`#!/usr/bin/env node
const http = require('node:http');
const port = Number(process.argv[process.argv.indexOf('--port') + 1]);
const token = 'split-token';
const cookie = 'dsh-auth-split=v1.sig';
process.stdout.write('dsh web: loading profiles\\n');
http
.createServer((req, res) => {
const url = new URL(req.url, 'http://127.0.0.1:' + port);
if (url.searchParams.get('token') === token) {
res.writeHead(303, { location: './', 'set-cookie': cookie + '; Path=/' });
res.end();
return;
}
if (req.headers.cookie === cookie) {
res.writeHead(200, { 'content-type': 'text/html' });
res.end('<html>ok</html>');
return;
}
res.writeHead(401, { 'content-type': 'text/plain' });
res.end('dsh web authentication required');
})
.listen(port, '127.0.0.1', () => {
const line = 'dsh web: http://127.0.0.1:' + port + '/?token=' + token + '\\n';
process.stdout.write(line.slice(0, 30));
setTimeout(() => process.stdout.write(line.slice(30)), 150);
});
`,
{ mode: 0o755 }
);
const result = await startDeepSeekWeb(dir, 'localhost:3000');
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(getDeepSeekWebCookie(result.port)).toBe('dsh-auth-split=v1.sig');
}, 20_000);
it('still finds a banner printed after more than the error-tail cap', async () => {
writeFileSync(
join(dir, 'dsh'),
`#!/usr/bin/env node
const http = require('node:http');
const port = Number(process.argv[process.argv.indexOf('--port') + 1]);
const token = 'late-banner-token';
const cookie = 'dsh-auth-late=v1.sig';
process.stdout.write('warn: plugin noise '.repeat(1100) + '\\n');
http
.createServer((req, res) => {
const url = new URL(req.url, 'http://127.0.0.1:' + port);
if (url.searchParams.get('token') === token) {
res.writeHead(303, { location: './', 'set-cookie': cookie + '; Path=/' });
res.end();
return;
}
if (req.headers.cookie === cookie) {
res.writeHead(200, { 'content-type': 'text/html' });
res.end('<html>ok</html>');
return;
}
res.writeHead(401, { 'content-type': 'text/plain' });
res.end('dsh web authentication required');
})
.listen(port, '127.0.0.1');
setTimeout(() => process.stdout.write('dsh web: http://127.0.0.1:' + port + '/?token=' + token + '\\n'), 300);
`,
{ mode: 0o755 }
);
const result = await startDeepSeekWeb(dir, 'localhost:3000');
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(getDeepSeekWebCookie(result.port)).toBe('dsh-auth-late=v1.sig');
}, 20_000);
});
+237 -3
View File
@@ -9,23 +9,40 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import Fastify, { type FastifyInstance } from 'fastify';
import fastifyCookie from '@fastify/cookie';
import fastifyWebsocket from '@fastify/websocket';
import fs from 'node:fs/promises';
import { createServer, type IncomingHttpHeaders, type Server } from 'node:http';
import WebSocket, { WebSocketServer } from 'ws';
import { once } from 'node:events';
import type { AddressInfo } from 'node:net';
import fs from 'node:fs/promises';
import http, { createServer, type IncomingHttpHeaders, type Server } from 'node:http';
import os from 'node:os';
import path from 'node:path';
import WebSocket, { WebSocketServer } from 'ws';
import { registerWebviewRoutes } from '../../src/web/routes/webview-routes.js';
import { installRouteErrorHandler } from '../../src/web/route-error-handler.js';
import { webviewCapabilities } from '../../src/webview-capabilities.js';
import { capabilityFromProxyPath } from '../../src/web/webview-proxy.js';
import { writeWebviews } from '../../src/webview-store.js';
import { readUsers } from '../../src/user-store.js';
import { TabLayoutService } from '../../src/tab-layout-service.js';
import type { TabLayout } from '../../src/tab-layout.js';
/**
* The supervisor is the one process-spawning piece in this path. Its own tests
* cover the launch-token exchange and the starter binding; here a stub stands in
* for "this port has a cookie" so the route-level question stays what the proxy
* actually puts on the upstream request.
*/
const { getDeepSeekWebCookie } = vi.hoisted(() => ({
getDeepSeekWebCookie: vi.fn((_port: number, _owner?: string): string | null => null),
}));
vi.mock('../../src/deepseek-web-server.js', () => ({ getDeepSeekWebCookie }));
let app: FastifyInstance;
let tmpDir: string;
let savedDataDir: string | undefined;
let savedMultiUser: string | undefined;
/** Stands in for what the auth middleware decorates on the request. */
let currentUser: { username: string; role: 'admin' | 'user' } | undefined;
const broadcasts: Array<{ event: string; data: unknown }> = [];
const webviewCreated = vi.fn(async () => {});
const webviewDeleted = vi.fn(async () => {});
@@ -33,15 +50,23 @@ const webviewDeleted = vi.fn(async () => {});
beforeEach(async () => {
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'codeman-webviews-'));
savedDataDir = process.env.CODEMAN_DATA_DIR;
savedMultiUser = process.env.CODEMAN_MULTIUSER;
process.env.CODEMAN_DATA_DIR = tmpDir;
delete process.env.CODEMAN_MULTIUSER;
currentUser = undefined;
broadcasts.length = 0;
webviewCreated.mockClear();
webviewDeleted.mockClear();
getDeepSeekWebCookie.mockReset();
getDeepSeekWebCookie.mockReturnValue(null);
app = Fastify({ logger: false });
await app.register(fastifyCookie);
// The proxy route declares a wsHandler, so the plugin must be present.
await app.register(fastifyWebsocket);
app.addHook('onRequest', async (req) => {
if (currentUser) (req as unknown as { authUser: typeof currentUser }).authUser = currentUser;
});
registerWebviewRoutes(app, {
broadcast: (event: string, data: unknown) => broadcasts.push({ event, data }),
tabLayouts: { webviewCreated, webviewDeleted },
@@ -54,11 +79,22 @@ afterEach(async () => {
await app.close();
if (savedDataDir === undefined) delete process.env.CODEMAN_DATA_DIR;
else process.env.CODEMAN_DATA_DIR = savedDataDir;
if (savedMultiUser === undefined) delete process.env.CODEMAN_MULTIUSER;
else process.env.CODEMAN_MULTIUSER = savedMultiUser;
await fs.rm(tmpDir, { recursive: true, force: true }).catch(() => {});
});
const create = (payload: Record<string, unknown>) => app.inject({ method: 'POST', url: '/api/webviews', payload });
/** Wait for something a relayed connection reports asynchronously. */
async function waitUntil(check: () => boolean, timeoutMs = 2000): Promise<void> {
const deadline = Date.now() + timeoutMs;
while (!check()) {
if (Date.now() > deadline) throw new Error('condition not met in time');
await new Promise((resolve) => setTimeout(resolve, 10));
}
}
describe('GET /api/webviews', () => {
it('starts empty and reports the frame budget the client must honour', async () => {
const res = await app.inject({ method: 'GET', url: '/api/webviews' });
@@ -355,6 +391,204 @@ describe('proxy route: WebSocket cookie forwarding', () => {
});
});
describe('managed DeepSeek web cookie', () => {
const COOKIE = 'dsh-auth-test=v1.payload.sig';
const upstreams: Array<{ port: number; cookies: Array<string | undefined>; close: () => Promise<void> }> = [];
/** A real loopback listener, so the assertion is on the bytes dsh would receive. */
async function startUpstream() {
const cookies: Array<string | undefined> = [];
const server = http.createServer((req, res) => {
cookies.push(req.headers.cookie);
res.writeHead(200, { 'content-type': 'text/plain' });
res.end('ok');
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
if (!address || typeof address === 'string') throw new Error('upstream has no address');
const upstream = {
port: address.port,
cookies,
close: () => new Promise<void>((resolve) => server.close(() => resolve())),
};
upstreams.push(upstream);
return upstream;
}
/** The stub answers for one port and one owner, like the supervisor's two checks. */
function mintCookieOn(port: number, owner: string | undefined): void {
getDeepSeekWebCookie.mockImplementation((askedPort, askedOwner) =>
askedPort === port && askedOwner === owner ? COOKIE : null
);
}
async function openManaged(url: string): Promise<string> {
const created = (await create({ name: 'DeepSeek Harness', url, managed: 'deepseek-web', trusted: true })).json()
.data;
const opened = (await app.inject({ method: 'POST', url: `/api/webviews/${created.id}/open` })).json().data;
return capabilityFromProxyPath(opened.embedUrl)!;
}
const getThrough = (cap: string) => app.inject({ method: 'GET', url: `/webview/${cap}/` });
async function writeUsersFixture(users: Array<{ username: string; role: string; canBypassPermissions: boolean }>) {
await fs.writeFile(
path.join(tmpDir, 'users.json'),
JSON.stringify({
version: 1,
users: users.map((user) => ({
...user,
password: { algo: 'scrypt', N: 1, r: 1, p: 1, salt: '00', hash: '00' },
createdAt: 1,
})),
})
);
// The store keeps a short cache; write through it instead of waiting for the TTL.
await readUsers(true);
}
afterEach(async () => {
await Promise.all(upstreams.splice(0).map((upstream) => upstream.close()));
});
it('presents it to a managed tab on 127.0.0.1 at the minted port', async () => {
const upstream = await startUpstream();
mintCookieOn(upstream.port, undefined);
const cap = await openManaged(`http://127.0.0.1:${upstream.port}/`);
expect((await getThrough(cap)).statusCode).toBe(200);
expect(upstream.cookies).toEqual([COOKIE]);
expect(getDeepSeekWebCookie).toHaveBeenCalledWith(upstream.port, undefined);
});
it('presents nothing to a managed tab on another port', async () => {
const minted = await startUpstream();
const other = await startUpstream();
mintCookieOn(minted.port, undefined);
const cap = await openManaged(`http://127.0.0.1:${other.port}/`);
expect((await getThrough(cap)).statusCode).toBe(200);
expect(other.cookies).toEqual([undefined]);
});
it('presents nothing to an unmanaged tab on the same port', async () => {
const upstream = await startUpstream();
mintCookieOn(upstream.port, undefined);
const created = (await create({ name: 'Not managed', url: `http://127.0.0.1:${upstream.port}/` })).json().data;
const opened = (await app.inject({ method: 'POST', url: `/api/webviews/${created.id}/open` })).json().data;
const cap = capabilityFromProxyPath(opened.embedUrl)!;
expect((await getThrough(cap)).statusCode).toBe(200);
expect(upstream.cookies).toEqual([undefined]);
expect(getDeepSeekWebCookie).not.toHaveBeenCalled();
});
// `managed` comes from the client and the port is public, so this is the case
// the gate exists for: a regular user must not receive the starter's cookie.
it('presents nothing in multi-user mode when the owner has no privileged grant', async () => {
process.env.CODEMAN_MULTIUSER = '1';
currentUser = { username: 'bob', role: 'user' };
await writeUsersFixture([{ username: 'bob', role: 'user', canBypassPermissions: false }]);
const upstream = await startUpstream();
mintCookieOn(upstream.port, 'bob');
const cap = await openManaged(`http://127.0.0.1:${upstream.port}/`);
expect((await getThrough(cap)).statusCode).toBe(200);
expect(upstream.cookies).toEqual([undefined]);
expect(getDeepSeekWebCookie).not.toHaveBeenCalled();
});
it('presents it in multi-user mode to a granted owner who started the server', async () => {
process.env.CODEMAN_MULTIUSER = '1';
currentUser = { username: 'carol', role: 'user' };
await writeUsersFixture([{ username: 'carol', role: 'user', canBypassPermissions: true }]);
const upstream = await startUpstream();
mintCookieOn(upstream.port, 'carol');
const cap = await openManaged(`http://127.0.0.1:${upstream.port}/`);
expect((await getThrough(cap)).statusCode).toBe(200);
expect(upstream.cookies).toEqual([COOKIE]);
expect(getDeepSeekWebCookie).toHaveBeenCalledWith(upstream.port, 'carol');
});
/**
* A loopback listener that completes the upgrade and records the cookie on the
* handshake. The realtime leg is a separate code path from `proxyRequest`, so
* the HTTP assertions above say nothing about what it puts on the wire.
*/
async function startWebSocketUpstream() {
const cookies: Array<string | undefined> = [];
const server = http.createServer();
const wss = new WebSocketServer({ noServer: true });
server.on('upgrade', (req, socket, head) => {
cookies.push(req.headers.cookie);
wss.handleUpgrade(req, socket, head, (client) => client.close());
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
if (!address || typeof address === 'string') throw new Error('ws upstream has no address');
const upstream = {
port: address.port,
cookies,
close: () =>
new Promise<void>((resolve) => {
wss.close();
server.close(() => resolve());
}),
};
upstreams.push(upstream);
return upstream;
}
it('presents it on the websocket leg too, ahead of the browser cookies', async () => {
const upstream = await startWebSocketUpstream();
mintCookieOn(upstream.port, undefined);
const cap = await openManaged(`http://127.0.0.1:${upstream.port}/`);
// Upgrades need a real listener: inject() cannot carry them.
await app.listen({ port: 0, host: '127.0.0.1' });
const { port } = app.server.address() as AddressInfo;
const client = new WebSocket(`ws://127.0.0.1:${port}/webview/${cap}/ws`, {
headers: { cookie: 'codeman_session=SECRET; dsh-ui=dark' },
});
await once(client, 'open');
await waitUntil(() => upstream.cookies.length > 0);
// The credential leads so a stale browser copy cannot win, other dashboard
// cookies survive, and Codeman's own session cookie never goes upstream.
expect(upstream.cookies).toEqual([`${COOKIE}; dsh-ui=dark`]);
client.close();
});
});
describe('proxy HTML rewrite', () => {
// The request path is what the page's relative URLs are relative to. Proving
// it here (rather than only on rewriteHtml) pins that proxyRequest passes it.
it("resolves the document's relative base against its own directory", async () => {
const server = http.createServer((_req, res) => {
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
res.end('<html><head><base href="./"></head><body>app</body></html>');
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
if (!address || typeof address === 'string') throw new Error('upstream has no address');
try {
const created = (await create({ name: 'App', url: `http://127.0.0.1:${address.port}/app/page.html` })).json()
.data;
const opened = (await app.inject({ method: 'POST', url: `/api/webviews/${created.id}/open` })).json().data;
const cap = capabilityFromProxyPath(opened.embedUrl)!;
const res = await app.inject({ method: 'GET', url: `/webview/${cap}/app/page.html` });
expect(res.statusCode).toBe(200);
expect(res.body).toContain(`<base href="/webview/${cap}/app/">`);
} finally {
await new Promise<void>((resolve) => server.close(() => resolve()));
}
});
});
describe('POST /api/webviews/probe', () => {
it('reports an unreachable target as a normal answer, not a 500', async () => {
// Port 1 is reserved and refuses instantly.
+177
View File
@@ -13,6 +13,7 @@ import {
buildUpstreamRequestHeaders,
capabilityFromProxyPath,
capabilityFromReferer,
escapedWebviewAssetPath,
extractFrameAncestors,
filterCookieHeader,
isFramableCrossOrigin,
@@ -238,6 +239,56 @@ describe('buildUpstreamRequestHeaders', () => {
expect(headers.authorization).toBeUndefined();
});
// `dsh web` mints its session cookie for the loopback authority the proxy
// dials, which the browser has never visited and cannot store anything for.
// The supervisor holds it instead. The managed tab is trusted, so the browser's
// other dsh cookies are still present and must be kept alongside it.
it('puts the server-held credential ahead of the filtered browser cookies', () => {
const headers = buildUpstreamRequestHeaders({ cookie: 'codeman_session=SECRET; dash=1' }, upstream, {
forwardCookies: true,
sessionCookieName: 'codeman_session',
injectedCookie: 'dsh-auth-p=v1.payload.sig',
});
expect(headers.cookie).toBe('dsh-auth-p=v1.payload.sig; dash=1');
});
it('keeps every non-Codeman browser cookie when injecting the server credential', () => {
const headers = buildUpstreamRequestHeaders(
{ cookie: 'dsh-ui=dark; codeman_session=SECRET; dsh-settings=z' },
upstream,
{
forwardCookies: true,
sessionCookieName: 'codeman_session',
injectedCookie: 'dsh-auth-p=v1.payload.sig',
}
);
expect(headers.cookie).toBe('dsh-auth-p=v1.payload.sig; dsh-ui=dark; dsh-settings=z');
});
// A `Cookie` header may name the same cookie twice, and the first value is the
// one parsers keep. The browser can still hold a dsh cookie from an earlier
// proxied response, so the server's fresh copy has to lead or the stale one wins
// and the tab goes back to the 401 this whole path exists to prevent.
it('keeps the server credential in front of a stale browser copy of the same name', () => {
const headers = buildUpstreamRequestHeaders({ cookie: 'dsh-auth-p=STALE; dsh-ui=dark' }, upstream, {
forwardCookies: true,
sessionCookieName: 'codeman_session',
injectedCookie: 'dsh-auth-p=FRESH',
});
// The stale copy is still forwarded behind it (dropping it would need its own
// name parsing), but the parser sees FRESH first, which is what authenticates.
expect(headers.cookie).toBe('dsh-auth-p=FRESH; dsh-auth-p=STALE; dsh-ui=dark');
});
it('sends the server-held credential even when browser cookies are not forwarded', () => {
const headers = buildUpstreamRequestHeaders({}, upstream, {
forwardCookies: false,
sessionCookieName: 'codeman_session',
injectedCookie: 'dsh-auth-p=v1.payload.sig',
});
expect(headers.cookie).toBe('dsh-auth-p=v1.payload.sig');
});
it('presents Origin/Referer as if the browser talked to the dashboard directly', () => {
const headers = buildUpstreamRequestHeaders({ origin: 'https://codeman.local' }, upstream, {
forwardCookies: false,
@@ -345,6 +396,38 @@ describe('rewriteHtml', () => {
expect(out.match(/<base/g)).toHaveLength(1);
});
// A Vite build ships `<base href="./">`, and the runtime shim rewrites the
// document URL to strip the prefix — so "./" would resolve to Codeman's root
// and every module script would 404 behind an otherwise-painted page.
it('resolves a page-relative <base> against the prefix before the shim masks the URL', () => {
const out = rewriteHtml('<html><head><base href="./"></head></html>', CAP);
expect(out).toContain(`<base href="${PREFIX}">`);
expect(out.match(/<base/g)).toHaveLength(1);
});
it('keeps a sub-path in a relative <base> inside the proxy prefix', () => {
const out = rewriteHtml('<html><head><base target="_blank" href="./sub/"></head></html>', CAP);
expect(out).toContain(`<base target="_blank" href="${PREFIX}sub/">`);
});
// A document served from a subdirectory resolves its relative base against
// ITS directory, not the proxy root: `/webview/<cap>/app/page.html` with
// `<base href="./">` must point at `/webview/<cap>/app/`.
it("resolves a relative <base> against the document's own directory", () => {
const out = rewriteHtml('<html><head><base href="./"></head></html>', CAP, '', 'app/page.html');
expect(out).toContain(`<base href="${PREFIX}app/">`);
});
it('resolves a ../ base from the document directory', () => {
const out = rewriteHtml('<html><head><base href="../assets/"></head></html>', CAP, '', 'app/sub/page.html');
expect(out).toContain(`<base href="${PREFIX}app/assets/">`);
});
it('leaves a cross-origin <base> exactly as the author wrote it', () => {
const out = rewriteHtml('<html><head><base href="https://cdn.example/x/"></head></html>', CAP);
expect(out).toContain('<base href="https://cdn.example/x/">');
});
it('still injects the runtime shim when the page ships its own <base>', () => {
// The shim is the only layer that catches runtime-built URLs, so an early
// return on an existing <base> would silently break those pages.
@@ -358,6 +441,48 @@ describe('rewriteHtml', () => {
expect(rewriteHtml('just text', CAP)).toContain('<script>');
});
// SvelteKit's inline bootstrap does `import("/_app/…")`. A dynamic import is
// neither an attribute nor a fetch(), so `<base>` and the runtime shim both
// miss it and the module loads from Codeman's root — the app then sits on its
// own spinner forever.
it('rewrites root-absolute dynamic import() specifiers', () => {
const dq = rewriteHtml('<head><script>import("/_app/entry.js")</script></head>', CAP);
expect(dq).toContain(`import("${PREFIX}_app/entry.js")`);
const sq = rewriteHtml("<head><script>import( '/x.js' )</script></head>", CAP);
expect(sq).toContain(`import('${PREFIX}x.js' )`);
});
it('leaves relative and cross-origin import() specifiers alone', () => {
const out = rewriteHtml(
`<head><script>import("./a.js");import("//cdn.example/b.js");import("https://cdn.example/c.js")</script></head>`,
CAP
);
expect(out).toContain('import("./a.js")');
expect(out).toContain('import("//cdn.example/b.js")');
expect(out).toContain('import("https://cdn.example/c.js")');
});
// The rewrite is for specifiers a loader will execute, not for the word
// appearing in the page a reader sees.
it('leaves import() in visible text alone', () => {
const out = rewriteHtml(
`<html><body><pre>import("/example.js")</pre><code>import('/other.js')</code></body></html>`,
CAP
);
expect(out).toContain('<pre>import("/example.js")</pre>');
expect(out).toContain("<code>import('/other.js')</code>");
expect(out).not.toContain(`${PREFIX}example.js`);
});
it('rewrites imports in every script body, including one with attributes', () => {
const out = rewriteHtml(
`<head><script type="module">import("/_app/a.js")</script><script defer>import('/b.js')</script></head>`,
CAP
);
expect(out).toContain(`import("${PREFIX}_app/a.js")`);
expect(out).toContain(`import('${PREFIX}b.js')`);
});
it('rebases root-absolute src/href/action, which <base> cannot fix', () => {
const out = rewriteHtml(
`<head></head><body><script src="/static/app.js"></script><link href='/s.css'><form action="/login"></form></body>`,
@@ -858,3 +983,55 @@ describe('lost-frame recovery', () => {
expect(has({ authorization: 'Basic YWRtaW46eA==' })).toBe(true);
});
});
describe('escapedWebviewAssetPath: naming a 404 a web tab caused', () => {
const req = (over: Record<string, unknown> = {}) => ({
method: 'GET',
url: '/_app/immutable/entry/start.js',
...over,
headers: {
host: 'codeman.example:3001',
referer: 'http://codeman.example:3001/',
'sec-fetch-dest': 'script',
...((over.headers as Record<string, string | string[] | undefined> | undefined) ?? {}),
},
});
it('recognises a root-absolute module a masked frame asked for', () => {
expect(escapedWebviewAssetPath(req())).toBe('/_app/immutable/entry/start.js');
});
it('drops the query string, which carries no diagnostic value', () => {
expect(escapedWebviewAssetPath(req({ url: '/_app/x.js?v=17' }))).toBe('/_app/x.js');
});
it('ignores every shape that is not a dashboard asset', () => {
// A navigation is the lost-frame recovery's job, not this one's.
expect(
escapedWebviewAssetPath(req({ headers: { host: 'h', referer: 'http://h/', 'sec-fetch-dest': 'document' } }))
).toBeNull();
// Codeman's own missing files say nothing about a web tab.
expect(
escapedWebviewAssetPath(
req({ url: '/favicon.ico', headers: { host: 'h', referer: 'http://h/', 'sec-fetch-dest': 'image' } })
)
).toBeNull();
// A real Codeman page's assets resolve; only a masked landing (`/`) is this shape.
expect(
escapedWebviewAssetPath(req({ headers: { host: 'h', referer: 'http://h/settings', 'sec-fetch-dest': 'script' } }))
).toBeNull();
// Cross-origin referer, API paths, writes, and no referer at all.
expect(
escapedWebviewAssetPath(req({ headers: { host: 'h', referer: 'http://other/', 'sec-fetch-dest': 'script' } }))
).toBeNull();
expect(escapedWebviewAssetPath(req({ url: '/api/thing' }))).toBeNull();
expect(escapedWebviewAssetPath(req({ method: 'POST' }))).toBeNull();
expect(escapedWebviewAssetPath(req({ headers: { host: 'h' } }))).toBeNull();
});
it('accepts the array headers a proxy front end can produce', () => {
expect(
escapedWebviewAssetPath(req({ headers: { host: ['h'], referer: ['http://h/'], 'sec-fetch-dest': ['image'] } }))
).toBe('/_app/immutable/entry/start.js');
});
});