fix(deepseek): restart a server whose token exchange failed

Reuse returned the running server whenever it answered HTTP and matched
the authority, including one whose launch token could not be exchanged
for a cookie. That server answered 401 forever, so the restart the
warning asks for could never happen. Track the failed exchange and skip
reuse, which makes the next start request stop and respawn it.
This commit is contained in:
ArizeSky committed 2026-11-16 16:09:16 +08:00
1 parent 4ce9abde7d
commit b1bcd1e3af
4 files changed
+103 -14

No files matched your search

+1 -1
View File
@@ -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. 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 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. 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. 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.
+4 -1
View File
@@ -301,7 +301,10 @@ elsewhere. The reader scans every `dsh web:` line (dsh prints diagnostics such a
`dsh web: loading profiles` under the same prefix before the banner) and only
complete lines, so a banner split across two output chunks is waited for rather
than parsed truncated. A dsh without the gate prints a token-less banner and
keeps working unchanged.
keeps working unchanged. If a token is printed but the exchange still fails, the
server keeps running (its page serves, just 401) and is marked unusable for
reuse: the next start request stops and respawns it, which is the "restart `dsh
web`" the warning asks the user to perform.
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
+30 -11
View File
@@ -108,6 +108,13 @@ interface RunningServer {
* token, which is why "no cookie" is not a startup failure.
*/
cookie: string | null;
/**
* True when a token-bearing banner was found but the exchange produced no
* cookie. Such a server cannot authenticate its tab and must not be reused: the
* warning tells the user to restart `dsh web`, and the next start request is
* what performs that restart.
*/
cookieFailed: boolean;
}
let current: RunningServer | null = null;
@@ -237,9 +244,10 @@ async function exchangeLaunchToken(launchUrl: string): Promise<string | null> {
* failure.
*
* @param running - the just-started server, read for its captured output.
* @returns the cookie to hand the proxy, or null.
* @returns the cookie to hand the proxy (null when there is none) and whether a
* token was printed but could not be exchanged.
*/
async function captureSessionCookie(running: RunningServer): Promise<string | null> {
async function captureSessionCookie(running: RunningServer): Promise<{ cookie: string | null; failed: boolean }> {
const deadline = Date.now() + LAUNCH_URL_WAIT_MS;
while (Date.now() < deadline) {
// Only COMPLETE lines: a chunk boundary can cut the token in half, and
@@ -254,18 +262,19 @@ async function captureSessionCookie(running: RunningServer): Promise<string | nu
if (!cookie) {
console.warn(
'[DeepSeek web] the launch token was printed but could not be exchanged for a session cookie; ' +
"the tab will show dsh's 401 page until `dsh web` is restarted"
'the next start request will restart `dsh web` so it can retry'
);
return { cookie: null, failed: true };
}
return cookie;
return { cookie, failed: false };
}
// Only a printed http(s) URL settles this: it is the older dsh, which needs
// no cookie. Any other line carrying the prefix (a diagnostic, a truncated
// write) is not a banner, so the wait continues instead of giving up early.
if (firstLaunchBannerUrl(complete)) return null;
if (firstLaunchBannerUrl(complete)) return { cookie: null, failed: false };
await new Promise((resolve) => setTimeout(resolve, 100));
}
return null;
return { cookie: null, failed: false };
}
/**
@@ -376,11 +385,18 @@ async function startDeepSeekWebLocked(
starter: string | undefined
): Promise<StartResult> {
// Reuse only when the running server is BOTH healthy and fenced for the
// 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.
// authority now asking, it was started by this identity, and its credential
// works: 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, and a server whose token exchange failed would keep answering 401
// forever because reuse never gave anyone a chance to restart it.
if (current) {
if (current.authority === authority && current.starter === starter && (await answersHttp(current.port))) {
if (
!current.cookieFailed &&
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();
@@ -443,6 +459,7 @@ async function startDeepSeekWebLocked(
output: () => output,
banner: () => banner,
cookie: null,
cookieFailed: false,
};
current = running;
@@ -460,7 +477,9 @@ async function startDeepSeekWebLocked(
// Bought before this call resolves, so the first proxied page load
// already carries a credential — a tab opened a moment earlier would
// otherwise get the 401 this whole module exists to prevent.
running.cookie = await captureSessionCookie(running);
const captured = await captureSessionCookie(running);
running.cookie = captured.cookie;
running.cookieFailed = captured.failed;
return { ok: true, port, url: `http://127.0.0.1:${port}`, reused: false };
}
await new Promise((r) => setTimeout(r, READY_POLL_MS));
+68 -1
View File
@@ -16,7 +16,7 @@
* 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, afterEach } 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';
@@ -202,6 +202,73 @@ http
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);
it('leaves the old, ungated dsh working: no token means no cookie, not a failure', async () => {
writeFileSync(
join(dir, 'dsh'),