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

+33 -10
View File
@@ -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<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,
@@ -332,13 +343,17 @@ 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, 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;
+5 -2
View File
@@ -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 } };
});
+24 -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,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:<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.
*/
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 (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