fix(webview): require the owner's privilege grant for the dsh cookie

`managed` is accepted from the client on POST/PATCH /api/webviews and
GET /api/deepseek/web publishes the live port, so a saved managed record
pointing at that port was enough to receive the dsh-auth cookie. Gate it
on the same privileged-commands grant POST /api/deepseek/web requires,
fail closed for an ownerless record in multi-user mode, and record the
user whose request started the process so the supervisor only hands its
cookie to that identity. A request from another owner restarts the server
rather than reusing a cookie that is not theirs.
This commit is contained in:
ArizeSky committed 2026-11-16 16:05:22 +08:00
1 parent 0ea97d62ec
commit 28ed4016bd
6 files changed
+95 -17

No files matched your search

+1 -1
View File
@@ -2,4 +2,4 @@
"aicodeman": patch "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.
+9
View File
@@ -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 elsewhere. A dsh without the gate prints a token-less banner and keeps working
unchanged. 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 ## 7. Docker and remote cases
Docker cases work: the agent image installs `dsh` and bootstraps a `dsh-tui` Docker cases work: the agent image installs `dsh` and bootstraps a `dsh-tui`
+33 -10
View File
@@ -88,6 +88,13 @@ interface RunningServer {
child: ChildProcess; child: ChildProcess;
port: number; port: number;
authority: string; 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; output: () => string;
/** /**
* Boot output scanned for the launch banner, on its own (larger) budget than * 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. * covers a dsh old enough to need no cookie at all.
* *
* @param port - loopback port the upstream request is bound for. * @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. * @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 || current.port !== port) return null;
if (current.starter !== owner) return null;
return current.cookie; return current.cookie;
} }
@@ -319,11 +329,12 @@ let startLock: Promise<unknown> = Promise.resolve();
* *
* @param dshDir directory holding the resolved `dsh` binary. * @param dshDir directory holding the resolved `dsh` binary.
* @param authority browser authority to pass as `--trusted-host`. * @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( const run = startLock.then(
() => startDeepSeekWebLocked(dshDir, authority), () => startDeepSeekWebLocked(dshDir, authority, starter),
() => startDeepSeekWebLocked(dshDir, authority) () => startDeepSeekWebLocked(dshDir, authority, starter)
); );
startLock = run.then( startLock = run.then(
() => undefined, () => undefined,
@@ -332,13 +343,17 @@ export function startDeepSeekWeb(dshDir: string, authority: string): Promise<Sta
return run; 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 // 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 // authority now asking, and it was started by this identity: the launch cookie
// whose every API call 403s, which looks like a broken dashboard rather than // is per process and per user, so handing a previous starter's server to
// a misconfigured one. // another user would leave that user's tab on dsh's 401 page.
if (current) { 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 }; return { ok: true, port: current.port, url: `http://127.0.0.1:${current.port}`, reused: true };
} }
await stopDeepSeekWeb(); await stopDeepSeekWeb();
@@ -393,7 +408,15 @@ async function startDeepSeekWebLocked(dshDir: string, authority: string): Promis
if (current?.child === child) current = null; 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; current = running;
const deadline = Date.now() + READY_TIMEOUT_MS; const deadline = Date.now() + READY_TIMEOUT_MS;
+5 -2
View File
@@ -18,7 +18,7 @@ import { ApiErrorCode, createErrorResponse, getErrorMessage, type NiceConfig } f
import { isExplicitlyEnabled, isUnauthenticatedTunnelAcknowledged } from '../network-auth-policy.js'; import { isExplicitlyEnabled, isUnauthenticatedTunnelAcknowledged } from '../network-auth-policy.js';
import { isMultiUserMode } from '../../config/multiuser.js'; import { isMultiUserMode } from '../../config/multiuser.js';
import { findUser, canUsernameRunPrivilegedCommands } from '../../user-store.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 { import {
ConfigUpdateSchema, ConfigUpdateSchema,
SettingsUpdateSchema, SettingsUpdateSchema,
@@ -659,7 +659,10 @@ export function registerSystemRoutes(
if (!dir) return createErrorResponse(ApiErrorCode.OPERATION_FAILED, getDeepSeekNotFoundMessage()); if (!dir) return createErrorResponse(ApiErrorCode.OPERATION_FAILED, getDeepSeekNotFoundMessage());
const { startDeepSeekWeb } = await import('../../deepseek-web-server.js'); 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); if (!result.ok) return createErrorResponse(ApiErrorCode.OPERATION_FAILED, result.error);
return { success: true, data: { port: result.port, url: result.url, reused: result.reused } }; return { success: true, data: { port: result.port, url: result.url, reused: result.reused } };
}); });
+24 -4
View File
@@ -36,6 +36,7 @@ import { WebSocket as WsClient } from 'ws';
import type { ClientOptions as WsClientOptions, WebSocket } from 'ws'; import type { ClientOptions as WsClientOptions, WebSocket } from 'ws';
import type { Response as UndiciResponse } from 'undici'; import type { Response as UndiciResponse } from 'undici';
import { getDataDir } from '../../config/instance.js'; import { getDataDir } from '../../config/instance.js';
import { isMultiUserMode } from '../../config/multiuser.js';
import { import {
MAX_LIVE_WEBVIEW_FRAMES, MAX_LIVE_WEBVIEW_FRAMES,
MAX_WEBVIEWS, MAX_WEBVIEWS,
@@ -47,6 +48,7 @@ import {
WEBVIEW_WS_HANDSHAKE_TIMEOUT_MS, WEBVIEW_WS_HANDSHAKE_TIMEOUT_MS,
} from '../../config/webview-limits.js'; } from '../../config/webview-limits.js';
import { readWebviews, writeWebviews } from '../../webview-store.js'; import { readWebviews, writeWebviews } from '../../webview-store.js';
import { canUsernameRunPrivilegedCommands } from '../../user-store.js';
import { webviewCapabilities } from '../../webview-capabilities.js'; import { webviewCapabilities } from '../../webview-capabilities.js';
import { egressBlockedReason, webviewEgressLookup, webviewFetch, type EgressLookup } from '../webview-egress.js'; import { egressBlockedReason, webviewEgressLookup, webviewFetch, type EgressLookup } from '../webview-egress.js';
import { blockedWebviewHostReason } from '../webview-egress-policy.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 * 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. * 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 webview - the saved tab being proxied.
* @param upstream - resolved upstream URL for this request. * @param upstream - resolved upstream URL for this request.
* @returns `name=value` cookie pair, or undefined when none applies. * @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<string | undefined> {
if (webview.managed !== 'deepseek-web') return undefined; if (webview.managed !== 'deepseek-web') return undefined;
if (upstream.hostname !== '127.0.0.1') 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)); 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 hasBody = req.method !== 'GET' && req.method !== 'HEAD';
const injectedCookie = managedDashboardCookie(webview, upstream); const injectedCookie = await managedDashboardCookie(webview, upstream);
const headers = buildUpstreamRequestHeaders(req.headers, upstream, { const headers = buildUpstreamRequestHeaders(req.headers, upstream, {
forwardCookies: webview.trusted, forwardCookies: webview.trusted,
sessionCookieName: AUTH_COOKIE_NAME, 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 // channel is gated exactly like its index, so without this the page loads
// and then sits there silently disconnected. // and then sits there silently disconnected.
const cookie = const cookie =
managedDashboardCookie(webview, upstream) ?? (await managedDashboardCookie(webview, upstream)) ??
(webview.trusted && req.headers.cookie ? String(req.headers.cookie) : undefined); (webview.trusted && req.headers.cookie ? String(req.headers.cookie) : undefined);
// `lookup` is absent from ws's ClientOptions typings but flows through // `lookup` is absent from ws's ClientOptions typings but flows through
// http.request to net.connect untouched, which is where the resolved // http.request to net.connect untouched, which is where the resolved
+23
View File
@@ -171,6 +171,29 @@ http
expect(authed.status).toBe(200); expect(authed.status).toBe(200);
}, 20_000); }, 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 () => { it('leaves the old, ungated dsh working: no token means no cookie, not a failure', async () => {
writeFileSync( writeFileSync(
join(dir, 'dsh'), join(dir, 'dsh'),