diff --git a/.changeset/dsh-web-launch-token.md b/.changeset/dsh-web-launch-token.md index 6fc62748..d0090a06 100644 --- a/.changeset/dsh-web-launch-token.md +++ b/.changeset/dsh-web-launch-token.md @@ -2,4 +2,4 @@ "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. A dsh without the gate keeps working unchanged. +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. 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. diff --git a/docs/deepseek-integration.md b/docs/deepseek-integration.md index 834054c7..c575ea8b 100644 --- a/docs/deepseek-integration.md +++ b/docs/deepseek-integration.md @@ -300,6 +300,15 @@ authority it was minted for, so a repointed or stale tab cannot carry it elsewhere. A dsh without the gate prints a token-less banner and keeps working unchanged. +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. + ## 7. Docker and remote cases Docker cases work: the agent image installs `dsh` and bootstraps a `dsh-tui` diff --git a/src/deepseek-web-server.ts b/src/deepseek-web-server.ts index 7520fb4f..b66ba2c5 100644 --- a/src/deepseek-web-server.ts +++ b/src/deepseek-web-server.ts @@ -88,6 +88,13 @@ 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 @@ -272,10 +279,13 @@ export function getDeepSeekWebStatus(): DeepSeekWebStatus { * 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): string | 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; } @@ -319,11 +329,12 @@ let startLock: Promise = 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 { +export function startDeepSeekWeb(dshDir: string, authority: string, starter?: string): Promise { const run = startLock.then( - () => startDeepSeekWebLocked(dshDir, authority), - () => startDeepSeekWebLocked(dshDir, authority) + () => startDeepSeekWebLocked(dshDir, authority, starter), + () => startDeepSeekWebLocked(dshDir, authority, starter) ); startLock = run.then( () => undefined, @@ -332,13 +343,17 @@ export function startDeepSeekWeb(dshDir: string, authority: string): Promise { +async function startDeepSeekWebLocked( + dshDir: string, + authority: string, + starter: string | undefined +): Promise { // 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, and it was started by this identity: 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. if (current) { - if (current.authority === authority && (await answersHttp(current.port))) { + if (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(); @@ -393,7 +408,15 @@ async function startDeepSeekWebLocked(dshDir: string, authority: string): Promis if (current?.child === child) current = null; }); - const running: RunningServer = { child, port, authority, output: () => output, banner: () => banner, cookie: null }; + const running: RunningServer = { + child, + port, + authority, + starter, + output: () => output, + banner: () => banner, + cookie: null, + }; current = running; const deadline = Date.now() + READY_TIMEOUT_MS; diff --git a/src/web/routes/system-routes.ts b/src/web/routes/system-routes.ts index 560155b1..63aa3e3d 100644 --- a/src/web/routes/system-routes.ts +++ b/src/web/routes/system-routes.ts @@ -18,7 +18,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, @@ -659,7 +659,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 } }; }); diff --git a/src/web/routes/webview-routes.ts b/src/web/routes/webview-routes.ts index 2cd5bc43..3ecfa0b2 100644 --- a/src/web/routes/webview-routes.ts +++ b/src/web/routes/webview-routes.ts @@ -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,6 +48,7 @@ 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'; @@ -441,15 +443,33 @@ function proxyHttp( * 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:", 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. */ -function managedDashboardCookie(webview: Webview, upstream: URL): string | undefined { +async function managedDashboardCookie(webview: Webview, upstream: URL): Promise { 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)); - return getDeepSeekWebCookie(port) ?? undefined; + // 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; } /** @@ -494,7 +514,7 @@ async function proxyRequest( } const hasBody = req.method !== 'GET' && req.method !== 'HEAD'; - const injectedCookie = managedDashboardCookie(webview, upstream); + const injectedCookie = await managedDashboardCookie(webview, upstream); const headers = buildUpstreamRequestHeaders(req.headers, upstream, { forwardCookies: webview.trusted, sessionCookieName: AUTH_COOKIE_NAME, @@ -739,7 +759,7 @@ function proxyWebSocket(socket: WebSocket, req: FastifyRequest<{ Params: ProxyPa // channel is gated exactly like its index, so without this the page loads // and then sits there silently disconnected. const cookie = - managedDashboardCookie(webview, upstream) ?? + (await managedDashboardCookie(webview, upstream)) ?? (webview.trusted && req.headers.cookie ? String(req.headers.cookie) : undefined); // `lookup` is absent from ws's ClientOptions typings but flows through // http.request to net.connect untouched, which is where the resolved diff --git a/test/deepseek-web-server.test.ts b/test/deepseek-web-server.test.ts index f7d5edc9..bac6f349 100644 --- a/test/deepseek-web-server.test.ts +++ b/test/deepseek-web-server.test.ts @@ -171,6 +171,29 @@ http 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); + it('leaves the old, ungated dsh working: no token means no cookie, not a failure', async () => { writeFileSync( join(dir, 'dsh'),