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

+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');
});
});