mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-20 13:09:33 +01:00
fix(webview): keep the browser's cookies on the websocket leg
The HTTP leg puts the server-held dsh credential in front of the browser's own cookies; the upgrade leg replaced them with it. A managed dsh tab is trusted, so its other cookies must survive there too. Filter the request the way the HTTP leg does and merge the credential in front. Order is the point: a `Cookie` header can name the same cookie twice, and the first value is the one parsers keep, so appending the credential let a stale browser copy of the same dsh cookie shadow the one the running process minted - the tab would come back to the 401 this path exists to prevent. Both legs now lead with it, and a route-level test asserts the bytes the upstream sees on the upgrade, not only on the HTTP request.
This commit is contained in:
1 parent
44a10cff39
commit
2a3496b7b3
6 files changed
+119
-22
No files matched your search
@@ -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. It is appended to the dashboard's own cookies rather than replacing them. The banner reader scans every `dsh web:` line (diagnostics share the prefix) and only complete lines (a split write is waited for), so a `dsh web: loading profiles` line no longer makes boot give up. The printed token URL is only fetched when it names `127.0.0.1` on the port that was just spawned. A server whose exchange failed is no longer reused, so asking to start the UI again restarts it and retries the exchange. 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.
|
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. It is sent ahead of the dashboard's own cookies rather than replacing them, so a stale browser copy of the same cookie cannot shadow the one the running process minted. The banner reader scans every `dsh web:` line (diagnostics share the prefix) and only complete lines (a split write is waited for), so a `dsh web: loading profiles` line no longer makes boot give up. The printed token URL is only fetched when it names `127.0.0.1` on the port that was just spawned. A server whose exchange failed is no longer reused, so asking to start the UI again restarts it and retries the exchange. 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.
|
||||||
@@ -316,8 +316,10 @@ privileged-commands grant `POST /api/deepseek/web` requires, and in multi-user m
|
|||||||
only to the owner whose request started that process. A different owner's start
|
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
|
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. On a trusted
|
is why the shared instance is effectively single-user at a time. On a trusted
|
||||||
managed tab the cookie is appended to whatever cookies dsh itself set in the
|
managed tab the cookie is sent ahead of whatever cookies dsh itself set in the
|
||||||
browser, rather than replacing them.
|
browser, rather than replacing them; leading matters because a `Cookie` header can
|
||||||
|
name the same cookie twice and the first value is the one the dashboard parses, so
|
||||||
|
a stale browser copy must not shadow the one the running process minted.
|
||||||
|
|
||||||
## 7. Docker and remote cases
|
## 7. Docker and remote cases
|
||||||
|
|
||||||
|
|||||||
@@ -67,8 +67,10 @@ import {
|
|||||||
buildUpstreamRequestHeaders,
|
buildUpstreamRequestHeaders,
|
||||||
capabilityFromReferer,
|
capabilityFromReferer,
|
||||||
extractFrameAncestors,
|
extractFrameAncestors,
|
||||||
|
filterCookieHeader,
|
||||||
isFramableCrossOrigin,
|
isFramableCrossOrigin,
|
||||||
isHtmlContentType,
|
isHtmlContentType,
|
||||||
|
mergeCookieHeader,
|
||||||
parseWebviewUrl,
|
parseWebviewUrl,
|
||||||
proxyPrefixFor,
|
proxyPrefixFor,
|
||||||
resolveUpstreamUrl,
|
resolveUpstreamUrl,
|
||||||
@@ -759,10 +761,14 @@ function proxyWebSocket(socket: WebSocket, req: FastifyRequest<{ Params: ProxyPa
|
|||||||
const protocols = req.headers['sec-websocket-protocol'];
|
const protocols = req.headers['sec-websocket-protocol'];
|
||||||
// The same credential the HTTP leg presents. A managed dashboard's realtime
|
// The same credential the HTTP leg presents. A managed dashboard's realtime
|
||||||
// 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. A managed tab is trusted, so
|
||||||
const cookie =
|
// the browser's other cookies ride along behind it — filtered like the HTTP
|
||||||
(await managedDashboardCookie(webview, upstream)) ??
|
// leg, which never forwards Codeman's own session cookie upstream.
|
||||||
(webview.trusted && req.headers.cookie ? String(req.headers.cookie) : undefined);
|
const injectedCookie = await managedDashboardCookie(webview, upstream);
|
||||||
|
const browserCookie = webview.trusted && req.headers.cookie ? String(req.headers.cookie) : undefined;
|
||||||
|
const cookie = injectedCookie
|
||||||
|
? mergeCookieHeader(filterCookieHeader(browserCookie, [AUTH_COOKIE_NAME]), injectedCookie)
|
||||||
|
: browserCookie;
|
||||||
// `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
|
||||||
// address is judged (see webview-egress.ts).
|
// address is judged (see webview-egress.ts).
|
||||||
|
|||||||
+25
-12
@@ -363,6 +363,20 @@ export function rewriteSetCookie(cookie: string, capability: string, secureConte
|
|||||||
return out.join('; ');
|
return out.join('; ');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Put a server-held credential in front of the cookies the browser sent.
|
||||||
|
*
|
||||||
|
* Order matters: a `Cookie` header can name the same cookie twice, and parsers
|
||||||
|
* that collapse it into a map keep the FIRST value (RFC 6265 §5.4 leaves the
|
||||||
|
* choice open; the common Node parsers take the first). The browser may still
|
||||||
|
* hold a stale copy of the same dsh cookie from an earlier proxied response, so
|
||||||
|
* the credential minted by the running process must lead, with everything else
|
||||||
|
* preserved behind it.
|
||||||
|
*/
|
||||||
|
export function mergeCookieHeader(browserCookie: string | undefined, injectedCookie: string): string {
|
||||||
|
return browserCookie ? `${injectedCookie}; ${browserCookie}` : injectedCookie;
|
||||||
|
}
|
||||||
|
|
||||||
/** Drop named cookies from a `Cookie` request header, returning undefined if none remain. */
|
/** Drop named cookies from a `Cookie` request header, returning undefined if none remain. */
|
||||||
export function filterCookieHeader(cookie: string | undefined, drop: string[]): string | undefined {
|
export function filterCookieHeader(cookie: string | undefined, drop: string[]): string | undefined {
|
||||||
if (!cookie) return undefined;
|
if (!cookie) return undefined;
|
||||||
@@ -384,12 +398,12 @@ export function buildUpstreamRequestHeaders(
|
|||||||
refererPath?: string;
|
refererPath?: string;
|
||||||
relayBodyLength?: boolean;
|
relayBodyLength?: boolean;
|
||||||
/**
|
/**
|
||||||
* A credential the SERVER holds for this dashboard, appended to whatever
|
* A credential the SERVER holds for this dashboard, put in front of whatever
|
||||||
* browser cookies were forwarded. `dsh web` mints its session cookie for a
|
* browser cookies were forwarded (see `mergeCookieHeader` for why the order
|
||||||
* loopback authority the browser never visits, so the proxy is the only party
|
* matters). `dsh web` mints its session cookie for a loopback authority the
|
||||||
* that can present it (see `deepseek-web-server.ts`); the managed tab is
|
* browser never visits, so the proxy is the only party that can present it
|
||||||
* trusted, which means the browser may also carry other cookies dsh set, and
|
* (see `deepseek-web-server.ts`); the managed tab is trusted, which means the
|
||||||
* those must survive.
|
* browser may also carry other cookies dsh set, and those must survive.
|
||||||
*/
|
*/
|
||||||
injectedCookie?: string;
|
injectedCookie?: string;
|
||||||
}
|
}
|
||||||
@@ -424,13 +438,12 @@ export function buildUpstreamRequestHeaders(
|
|||||||
if (cookie) headers['cookie'] = cookie;
|
if (cookie) headers['cookie'] = cookie;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Appended after the relay above, so a browser copy can never shadow it: this
|
// In front of the relayed cookies rather than after them, so a stale browser
|
||||||
// cookie is scoped to the authority the request is for, one the browser has
|
// copy of the same cookie cannot shadow the one minted by the running process
|
||||||
// never been able to store anything against. Other cookies are kept: a managed
|
// (the parser keeps the first value). Other cookies are kept: a managed dsh tab
|
||||||
// dsh tab is trusted, so dsh's own non-auth cookies may legitimately be there.
|
// is trusted, so dsh's own non-auth cookies may legitimately be there.
|
||||||
if (opts.injectedCookie) {
|
if (opts.injectedCookie) {
|
||||||
const existing = headers['cookie'];
|
headers['cookie'] = mergeCookieHeader(headers['cookie'], opts.injectedCookie);
|
||||||
headers['cookie'] = existing ? `${existing}; ${opts.injectedCookie}` : opts.injectedCookie;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Present as if the browser were talking to the dashboard directly. Apps that
|
// Present as if the browser were talking to the dashboard directly. Apps that
|
||||||
|
|||||||
@@ -9,6 +9,9 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
|||||||
import Fastify, { type FastifyInstance } from 'fastify';
|
import Fastify, { type FastifyInstance } from 'fastify';
|
||||||
import fastifyCookie from '@fastify/cookie';
|
import fastifyCookie from '@fastify/cookie';
|
||||||
import fastifyWebsocket from '@fastify/websocket';
|
import fastifyWebsocket from '@fastify/websocket';
|
||||||
|
import WebSocket, { WebSocketServer } from 'ws';
|
||||||
|
import { once } from 'node:events';
|
||||||
|
import type { AddressInfo } from 'node:net';
|
||||||
import fs from 'node:fs/promises';
|
import fs from 'node:fs/promises';
|
||||||
import http from 'node:http';
|
import http from 'node:http';
|
||||||
import os from 'node:os';
|
import os from 'node:os';
|
||||||
@@ -83,6 +86,15 @@ afterEach(async () => {
|
|||||||
|
|
||||||
const create = (payload: Record<string, unknown>) => app.inject({ method: 'POST', url: '/api/webviews', payload });
|
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', () => {
|
describe('GET /api/webviews', () => {
|
||||||
it('starts empty and reports the frame budget the client must honour', async () => {
|
it('starts empty and reports the frame budget the client must honour', async () => {
|
||||||
const res = await app.inject({ method: 'GET', url: '/api/webviews' });
|
const res = await app.inject({ method: 'GET', url: '/api/webviews' });
|
||||||
@@ -415,6 +427,55 @@ describe('managed DeepSeek web cookie', () => {
|
|||||||
expect(upstream.cookies).toEqual([COOKIE]);
|
expect(upstream.cookies).toEqual([COOKIE]);
|
||||||
expect(getDeepSeekWebCookie).toHaveBeenCalledWith(upstream.port, 'carol');
|
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', () => {
|
describe('proxy HTML rewrite', () => {
|
||||||
|
|||||||
@@ -243,13 +243,13 @@ describe('buildUpstreamRequestHeaders', () => {
|
|||||||
// dials, which the browser has never visited and cannot store anything for.
|
// 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
|
// 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.
|
// other dsh cookies are still present and must be kept alongside it.
|
||||||
it('appends the server-held credential to the filtered browser cookies', () => {
|
it('puts the server-held credential ahead of the filtered browser cookies', () => {
|
||||||
const headers = buildUpstreamRequestHeaders({ cookie: 'codeman_session=SECRET; dash=1' }, upstream, {
|
const headers = buildUpstreamRequestHeaders({ cookie: 'codeman_session=SECRET; dash=1' }, upstream, {
|
||||||
forwardCookies: true,
|
forwardCookies: true,
|
||||||
sessionCookieName: 'codeman_session',
|
sessionCookieName: 'codeman_session',
|
||||||
injectedCookie: 'dsh-auth-p=v1.payload.sig',
|
injectedCookie: 'dsh-auth-p=v1.payload.sig',
|
||||||
});
|
});
|
||||||
expect(headers.cookie).toBe('dash=1; 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', () => {
|
it('keeps every non-Codeman browser cookie when injecting the server credential', () => {
|
||||||
@@ -262,7 +262,22 @@ describe('buildUpstreamRequestHeaders', () => {
|
|||||||
injectedCookie: 'dsh-auth-p=v1.payload.sig',
|
injectedCookie: 'dsh-auth-p=v1.payload.sig',
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
expect(headers.cookie).toBe('dsh-ui=dark; dsh-settings=z; 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', () => {
|
it('sends the server-held credential even when browser cookies are not forwarded', () => {
|
||||||
|
|||||||
Reference in new issue
Block a user