fix(deepseek): make the Harness web tab render, not just authenticate

`dsh web` gates its own index behind a per-process launch token it prints on
boot, and only that URL mints the `dsh-auth-*` cookie every later request needs.
The managed tab stores the clean URL, so nothing on the browser side could
present the token: the iframe rendered dsh's 401 text, a blank tab.

Read the token out of the captured boot output, trade it for the cookie once at
startup (`redirect: 'manual'`, since the 303 is what carries Set-Cookie), and
let the proxy present it on both the HTTP and WebSocket legs. Scoped to the
exact loopback authority the cookie was minted for; a token-less banner (an
older dsh) keeps the previous behaviour untouched. The banner is scanned on its
own 256 KB budget rather than the 16 KB error-tail buffer: a chatty profile can
fill that cap before the banner prints.

Authentication alone was not enough. dsh ships `<base href="./">`, which a
browser resolves against the DOCUMENT url — and the proxy's runtime shim
rewrites that url to strip the `/webview/<cap>/` prefix. The base therefore
landed on Codeman's root: every module script 404'd and the page painted its
inline `#151517` background with nothing on it (the black screen that replaced
the white one). `rewriteHtml` now resolves a relative base against the proxy
prefix before the mask can run, leaving a cross-origin base exactly as written.

Verified against dsh 0.2.1-rc.5 and a live Codeman build: bare GET 401, captured
cookie 200, proxied `/api` WebSocket 101, and a headless-Chrome load of the
proxied tab boots the full Harness UI with no console errors.
This commit is contained in:
ArizeSky committed 2026-11-16 09:47:23 +08:00
1 parent e99b42c387
commit 0b3087918f
8 files changed
+474 -9

No files matched your search

+156 -2
View File
@@ -12,10 +12,23 @@
* 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 } from 'vitest';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { DeepSeekWebStartSchema } from '../src/web/schemas.js';
import { getDeepSeekWebStatus, resetDeepSeekWebForTest, stopDeepSeekWeb } from '../src/deepseek-web-server.js';
import {
getDeepSeekWebCookie,
getDeepSeekWebStatus,
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 +84,144 @@ 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');
});
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('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);
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.
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);
});
+40
View File
@@ -238,6 +238,27 @@ 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, and it must win over the browser's copy.
it('replaces the browser cookies with a server-held credential', () => {
const headers = buildUpstreamRequestHeaders({ cookie: 'codeman_session=SECRET; stale=1' }, upstream, {
forwardCookies: true,
sessionCookieName: 'codeman_session',
injectedCookie: 'dsh-auth-p=v1.payload.sig',
});
expect(headers.cookie).toBe('dsh-auth-p=v1.payload.sig');
});
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 +366,25 @@ 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/">`);
});
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.