From 4804f0fa0d9ba355b5e75ee7d48d0e341b4b3991 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 19 Oct 2026 18:11:37 +0200 Subject: [PATCH 01/11] test: The console signs in through the sign-in proxy and shows who is signed in (#716) --- e2e/console/fixtures.ts | 167 +++++++++++++++++++++++++- e2e/console/proxy-sign-in.spec.ts | 176 +++++++++++++++++++++++++++ e2e/console/sign-in.spec.ts | 26 +++- ui/src/data/api.test.ts | 2 +- ui/src/data/api.ts | 3 + ui/src/data/identity-check.test.ts | 94 +++++++++++++++ ui/src/data/identity-check.ts | 12 ++ ui/src/data/session.test.ts | 183 ++++++++++++++++++++++++++++- ui/src/data/session.ts | 23 +++- ui/src/model/proxy-refusal.test.ts | 27 +++++ ui/src/model/proxy-refusal.ts | 3 + 11 files changed, 707 insertions(+), 9 deletions(-) create mode 100644 e2e/console/proxy-sign-in.spec.ts create mode 100644 ui/src/data/identity-check.test.ts create mode 100644 ui/src/data/identity-check.ts create mode 100644 ui/src/model/proxy-refusal.test.ts create mode 100644 ui/src/model/proxy-refusal.ts diff --git a/e2e/console/fixtures.ts b/e2e/console/fixtures.ts index 263c4de15..38e7f20bb 100644 --- a/e2e/console/fixtures.ts +++ b/e2e/console/fixtures.ts @@ -1,9 +1,17 @@ import { existsSync } from "node:fs"; +import { + createServer, + type IncomingMessage, + request as httpRequest, + type Server, + type ServerResponse, +} from "node:http"; import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { test as base, expect, type Page } from "@playwright/test"; +import { exportJWK, generateKeyPair, SignJWT } from "jose"; import { type RawData, WebSocket } from "ws"; import type { FakeDriverScript } from "../fake-driver/types.js"; @@ -76,13 +84,14 @@ export async function startDaemon( const home = await mkdtemp(join(tmpdir(), "simlock-console-")); const port = await freeLoopbackPort(); const scriptPath = join(home, "fake-driver-script.json"); + const { http: extraHttp, ...extraConfig } = options.config ?? {}; await writeFile( join(home, "config.json"), JSON.stringify({ ...(mode === "worker" ? FAKE_CAPACITY : {}), - http: { enabled: true, host: "127.0.0.1", port }, + http: { enabled: true, host: "127.0.0.1", port, ...(extraHttp as object | undefined) }, mode, - ...options.config, + ...extraConfig, }), ); if (options.driverScript !== undefined) { @@ -288,11 +297,163 @@ function rawText(data: RawData): string { return Buffer.isBuffer(data) ? data.toString("utf8") : Buffer.from(data).toString("utf8"); } +const PROXY_ISSUER = "https://proxy.example.test"; +const PROXY_AUDIENCE = "simlock-console"; +const PROXY_HEADER = "cf-access-jwt-assertion"; + +export type ProxyMode = "signed-in" | "expired" | "redirect" | "html"; + +export interface ProxiedDaemon { + readonly url: string; + readonly loginUrl: string; + readonly signedOutUrl: string; + readonly daemon: RunningDaemon; + setMode(mode: ProxyMode): void; + holdIdentity(): () => void; + reset(): void; + dispose(): Promise; +} + +export async function startProxiedDaemon( + options: { readonly signOutUrl?: boolean } = {}, +): Promise { + const { privateKey, publicKey } = await generateKeyPair("ES256"); + const jwk = { ...(await exportJWK(publicKey)), alg: "ES256", kid: "test-key", use: "sig" }; + const sign = (expiresAt: number) => + new SignJWT({ email: "alice@example.test", name: "Alice" }) + .setProtectedHeader({ alg: "ES256", kid: "test-key" }) + .setIssuer(PROXY_ISSUER) + .setAudience(PROXY_AUDIENCE) + .setSubject("u1") + .setIssuedAt() + .setExpirationTime(expiresAt) + .sign(privateKey); + let mode: ProxyMode = "signed-in"; + let held: Promise | undefined; + let daemonPort = 0; + const listen = (server: Server, port: number) => + new Promise((resolve) => server.listen(port, "127.0.0.1", resolve)); + const close = (server: Server) => + new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }); + + const idpPort = await freeLoopbackPort(); + const idp = createServer((req, res) => { + const signedOut = req.url === "/signed-out"; + res.setHeader("content-type", "text/html"); + res.end(`

${signedOut ? "Signed out of the proxy" : "Proxy login"}

`); + }); + await listen(idp, idpPort); + const loginUrl = `http://127.0.0.1:${idpPort}/login`; + const signedOutUrl = `http://127.0.0.1:${idpPort}/signed-out`; + + const forward = async (req: IncomingMessage, res: ServerResponse) => { + const exp = Math.floor(Date.now() / 1000) + (mode === "expired" ? -600 : 3600); + const headers = { + ...req.headers, + [PROXY_HEADER]: await sign(exp), + host: `127.0.0.1:${daemonPort}`, + }; + if (req.url === "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/v1/identity" && held !== undefined) await held; + const upstream = httpRequest( + { headers, host: "127.0.0.1", method: req.method, path: req.url, port: daemonPort }, + (answer) => { + res.writeHead(answer.statusCode ?? 502, answer.headers); + answer.pipe(res); + }, + ); + upstream.on("error", () => res.destroy()); + res.on("close", () => upstream.destroy()); + req.pipe(upstream); + }; + const proxy = createServer((req, res) => { + if (req.url === "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/.test/jwks") { + res.setHeader("content-type", "application/json"); + res.end(JSON.stringify({ keys: [jwk] })); + return; + } + if (req.url !== "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/v1/healthz" && mode === "redirect") { + res.writeHead(302, { location: loginUrl }); + res.end(); + return; + } + if (req.url !== "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/v1/healthz" && mode === "html") { + res.writeHead(403, { "content-type": "text/html" }); + res.end("

Proxy sign-in

"); + return; + } + void forward(req, res); + }); + const proxyPort = await freeLoopbackPort(); + await listen(proxy, proxyPort); + let daemon: RunningDaemon; + try { + daemon = await startDaemon("worker", { + config: { + http: { + proxyAuth: { + audience: PROXY_AUDIENCE, + header: PROXY_HEADER, + issuer: PROXY_ISSUER, + jwksUrl: `http://127.0.0.1:${proxyPort}/.test/jwks`, + ...(options.signOutUrl === false ? {} : { signOutUrl: signedOutUrl }), + }, + }, + }, + }); + } catch (error: unknown) { + await Promise.all([close(proxy), close(idp)]); + throw error; + } + daemonPort = daemon.port; + return { + daemon, + dispose: async () => { + await Promise.all([close(proxy), close(idp)]); + await daemon.dispose(); + }, + holdIdentity() { + let release: () => void = () => {}; + held = new Promise((resolve) => (release = resolve)); + return () => { + held = undefined; + release(); + }; + }, + loginUrl, + reset() { + mode = "signed-in"; + held = undefined; + }, + setMode: (next) => void (mode = next), + signedOutUrl, + url: `http://127.0.0.1:${proxyPort}/`, + }; +} + /** * `daemon` is a single host, shared by every test in a Playwright worker, and the base URL every * `page.goto` resolves against. `gateway` starts only for a test that asks for it. */ -export const test = base.extend({ +export const test = base.extend< + { proxied: ProxiedDaemon }, + { daemon: RunningDaemon; gateway: RunningDaemon; proxiedDaemon: ProxiedDaemon } +>({ + proxiedDaemon: [ + // oxlint-disable-next-line no-empty-pattern -- as below. + async ({}, use) => { + const proxied = await startProxiedDaemon(); + await use(proxied); + await proxied.dispose(); + }, + { scope: "worker", timeout: 60_000 }, + ], + proxied: async ({ proxiedDaemon }, use) => { + proxiedDaemon.reset(); + await use(proxiedDaemon); + }, daemon: [ // oxlint-disable-next-line no-empty-pattern -- Playwright requires a destructuring pattern here, even an empty one. async ({}, use) => { diff --git a/e2e/console/proxy-sign-in.spec.ts b/e2e/console/proxy-sign-in.spec.ts new file mode 100644 index 000000000..3d7d89680 --- /dev/null +++ b/e2e/console/proxy-sign-in.spec.ts @@ -0,0 +1,176 @@ +import { expect, NAV_LABELS, openFromNav, signIn, startProxiedDaemon, test } from "./fixtures.js"; + +const EXPIRED_LINE = + "Your sign-in proxy's identity was refused: it has expired. You can still sign in with an operator token."; + +test.describe("signing in through a proxy", () => { + test("the console opens on Overview with no token form, reading who is signed in", async ({ + page, + proxied, + }) => { + await page.setViewportSize({ height: 900, width: 1440 }); + await page.goto(proxied.url); + + await expect(page.getByRole("heading", { level: 1, name: "Overview" })).toBeVisible(); + await expect(page.getByLabel("Operator token")).toHaveCount(0); + await expect(page.getByText("Signed in as Alice")).toBeVisible(); + + const nav = page.getByRole("navigation", { name: "Console" }); + await nav.getByRole("button", { name: "Collapse sidebar" }).click(); + await expect(page.getByText("Signed in as Alice")).toBeHidden(); + await expect(nav.getByRole("button", { name: "Sign out" })).toHaveAttribute( + "title", + "Sign out (Alice)", + ); + }); + + test("the page shows Signing in… and no token form while the identity answer is held", async ({ + page, + proxied, + }) => { + const release = proxied.holdIdentity(); + await page.goto(proxied.url); + + await expect(page.getByText("Signing in…")).toBeVisible(); + await expect(page.getByLabel("Operator token")).toHaveCount(0); + release(); + + await expect(page.getByText("Signed in as Alice")).toBeVisible(); + }); + + test("Sign out goes to the proxy's sign-out address when one is set", async ({ + page, + proxied, + }) => { + await page.goto(proxied.url); + await page.getByRole("button", { name: "Sign out" }).click(); + + await expect(page).toHaveURL(proxied.signedOutUrl); + await expect(page.getByRole("heading", { name: "Signed out of the proxy" })).toBeVisible(); + }); + + test("there is no Sign out button when no sign-out address is set", async ({ page }) => { + const bare = await startProxiedDaemon({ signOutUrl: false }); + try { + await page.goto(bare.url); + + await expect(page.getByText("Signed in as Alice")).toBeVisible(); + await expect(page.getByRole("button", { name: "Sign out" })).toHaveCount(0); + } finally { + await bare.dispose(); + } + }); + + test("an expired identity is said so on the token form, a labelled operator token opens the console, and its Sign out lands in the proxy session", async ({ + page, + proxied, + }) => { + const minted = await proxied.daemon.cli([ + "token", + "create", + "--role", + "operator", + "--label", + "ci-runner", + ]); + const secret = (minted.json as { secret: string }).secret; + proxied.setMode("expired"); + await page.goto(proxied.url); + + await expect(page.getByRole("alert")).toHaveText(EXPIRED_LINE); + await expect(page.getByLabel("Operator token")).toBeVisible(); + await signIn(page, secret); + + await expect(page.getByText("Signed in as ci-runner")).toBeVisible(); + proxied.setMode("signed-in"); + await page.getByRole("button", { name: "Sign out" }).click(); + + await expect(page.getByText("Signed in as Alice")).toBeVisible(); + await expect(page.getByLabel("Operator token")).toHaveCount(0); + }); + + test("an identity that expires while signed in takes the next request to the token form with that line", async ({ + page, + proxied, + }) => { + await page.goto(proxied.url); + await expect(page.getByText("Signed in as Alice")).toBeVisible(); + + proxied.setMode("expired"); + await openFromNav(page, "Leases"); + + await expect(page.getByLabel("Operator token")).toBeVisible(); + await expect(page.getByRole("alert")).toHaveText(EXPIRED_LINE); + }); + + test("the proxy's own session ending reloads onto its login page, and a second ending within 60 seconds shows Your sign-in has ended.", async ({ + page, + proxied, + }) => { + await page.goto(proxied.url); + await expect(page.getByText("Signed in as Alice")).toBeVisible(); + + proxied.setMode("redirect"); + await openFromNav(page, "Leases"); + await expect(page).toHaveURL(proxied.loginUrl); + await expect(page.getByRole("heading", { name: "Proxy login" })).toBeVisible(); + + proxied.setMode("signed-in"); + await page.goto(proxied.url); + await expect(page.getByText("Signed in as Alice")).toBeVisible(); + proxied.setMode("html"); + await openFromNav(page, "Leases"); + await expect(page.getByRole("heading", { name: "Proxy sign-in" })).toBeVisible(); + + proxied.setMode("signed-in"); + await page.goto(proxied.url); + await expect(page.getByText("Signed in as Alice")).toBeVisible(); + await page.evaluate(() => { + (window as unknown as { loadedOnce: boolean }).loadedOnce = true; + }); + proxied.setMode("html"); + await openFromNav(page, "Leases"); + + await expect(page.getByText("Your sign-in has ended.")).toBeVisible(); + await expect(page.getByRole("button", { name: "Sign in again" })).toBeVisible(); + expect( + await page.evaluate(() => (window as unknown as { loadedOnce?: boolean }).loadedOnce), + ).toBe(true); + }); + + test("revoking the token a person signed in with takes the console to the proxy session", async ({ + page, + proxied, + }) => { + const minted = await proxied.daemon.cli(["token", "create", "--role", "operator"]); + const { secret, token } = minted.json as { secret: string; token: { id: string } }; + proxied.setMode("expired"); + await page.goto(proxied.url); + await signIn(page, secret); + await expect(page.getByRole("button", { name: "Sign out" })).toBeVisible(); + proxied.setMode("signed-in"); + + expect((await proxied.daemon.cli(["token", "revoke", token.id])).code).toBe(0); + await page.reload(); + + await expect(page.getByText("Signed in as Alice")).toBeVisible(); + await expect(page.getByLabel("Operator token")).toHaveCount(0); + }); + + test("the page makes no request to any host but the proxy's", async ({ page, proxied }) => { + const origin = new URL(proxied.url).origin; + const requested: string[] = []; + page.on("request", (request) => requested.push(request.url())); + + await page.goto(proxied.url); + for (const label of NAV_LABELS) { + await openFromNav(page, label); + await expect(page.getByRole("heading", { level: 1, name: label })).toBeVisible(); + } + await page.reload(); + await expect(page.getByText("Signed in as Alice")).toBeVisible(); + + expect(requested.length).toBeGreaterThan(0); + expect(requested.filter((url) => new URL(url).origin !== origin)).toEqual([]); + }); +}); diff --git a/e2e/console/sign-in.spec.ts b/e2e/console/sign-in.spec.ts index 8b8d544af..6b0ad3508 100644 --- a/e2e/console/sign-in.spec.ts +++ b/e2e/console/sign-in.spec.ts @@ -16,6 +16,24 @@ test.describe("sign-in", () => { await expect(page.getByLabel("Operator token")).toHaveCount(0); }); + test("an operator token's label is shown in the sidebar as who is signed in", async ({ + daemon, + page, + }) => { + const minted = await daemon.cli([ + "token", + "create", + "--role", + "operator", + "--label", + "ci-runner", + ]); + await page.goto("/"); + await signIn(page, (minted.json as { secret: string }).secret); + + await expect(page.getByText("Signed in as ci-runner")).toBeVisible(); + }); + test("the navigation marks the current page, and the tab's title names it", async ({ daemon, page, @@ -41,6 +59,7 @@ test.describe("sign-in", () => { test("signing in with an empty field asks the daemon nothing", async ({ page }) => { await page.goto("/"); + await expect(page.getByLabel("Operator token")).toBeVisible(); const asked: string[] = []; page.on("request", (request) => { if (new URL(request.url()).pathname.startsWith("/v1/")) asked.push(request.url()); @@ -171,9 +190,10 @@ test.describe("sign-in", () => { expect(requested.length).toBeGreaterThan(0); expect(requested.filter((url) => new URL(url).origin !== origin)).toEqual([]); expect(requested.some((url) => url.endsWith(".woff2"))).toBe(true); - // A request the page's Content-Security-Policy refused never reaches the network, but the - // browser reports it as an error; an agent token's 403 is the one error the flow expects. - expect(errors.filter((text) => !text.includes("403"))).toEqual([]); + // why: a request the page's Content-Security-Policy refused never reaches the network, but the + // browser reports it as an error; an agent token's 403 and the load-time 401 from + // `/v1/identity` are the errors the flow expects. + expect(errors.filter((text) => !text.includes("403") && !text.includes("401"))).toEqual([]); }); }); diff --git a/ui/src/data/api.test.ts b/ui/src/data/api.test.ts index c3ddbac4e..9121faf08 100644 --- a/ui/src/data/api.test.ts +++ b/ui/src/data/api.test.ts @@ -93,7 +93,7 @@ describe("createApiClient", () => { expect(calls).toHaveLength(1); expect(calls[0]?.input).toBe("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/v1/workers"); expect(calls[0]?.init.headers).toEqual({ Authorization: "Bearer slk_op" }); - expect(calls[0]?.init.credentials).toBe("omit"); + expect(calls[0]?.init.credentials).toBe("same-origin"); // why: never answered from the browser's cache: what the daemon holds now is the answer. expect(calls[0]?.init.cache).toBe("no-store"); await expect(api.getJson("//elsewhere.example/v1/workers" as ApiPath)).rejects.toThrow( diff --git a/ui/src/data/api.ts b/ui/src/data/api.ts index 6e974d87a..691a50726 100644 --- a/ui/src/data/api.ts +++ b/ui/src/data/api.ts @@ -85,10 +85,13 @@ export interface ApiClient { healthz(): Promise>; } +export type ApiFailure = "unauthorized" | "not-simlock"; + export interface ApiClientOptions { readonly fetch: Fetch; readonly token: () => string | undefined; readonly signOut: () => void; + readonly onRefused?: (failure: ApiFailure) => void; } export function createApiClient(options: ApiClientOptions): ApiClient { diff --git a/ui/src/data/identity-check.test.ts b/ui/src/data/identity-check.test.ts new file mode 100644 index 000000000..2219ccdf6 --- /dev/null +++ b/ui/src/data/identity-check.test.ts @@ -0,0 +1,94 @@ +import { describe, expect, it } from "vitest"; + +import type { Fetch } from "./api"; +import { checkIdentity, type IdentityOutcome } from "./identity-check"; + +const HTML = "Sign in to continue"; +const NETWORK_ERROR = Symbol("network error"); + +type Answer = Response | typeof NETWORK_ERROR; + +function asking(identity: Answer, healthz: Answer = new Response('{"ok":true}', { status: 200 })) { + const calls: { readonly input: string; readonly init: RequestInit }[] = []; + const fetch: Fetch = async (input, init) => { + calls.push({ input, init }); + const answer = input === "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/v1/healthz" ? healthz : identity; + if (answer === NETWORK_ERROR) throw new TypeError("Failed to fetch"); + return answer.clone(); + }; + return { calls, fetch }; +} + +const json = (status: number, body: unknown) => new Response(JSON.stringify(body), { status }); +const simlock = (code: string, reason?: string) => ({ + error: { code, message: "refused", ...(reason === undefined ? {} : { reason }) }, +}); + +describe("checkIdentity", () => { + it("answers who the proxy signed in, or that nobody is, from what the daemon says", async () => { + const cases: readonly (readonly [Answer, IdentityOutcome])[] = [ + [ + json(200, { + name: "Alice", + principal: "proxy:https://idp#u1", + role: "admin", + signOutUrl: "https://idp/logout", + via: "proxy", + }), + { kind: "proxy", name: "Alice", signOutUrl: "https://idp/logout" }, + ], + [ + json(200, { name: "Bob", principal: "proxy:https://idp#u2", role: "admin", via: "proxy" }), + { kind: "proxy", name: "Bob" }, + ], + [json(401, simlock("UNAUTHENTICATED", "expired")), { kind: "refused", reason: "expired" }], + [ + json(200, { name: "ci", principal: "tok_1", role: "agent", via: "token" }), + { kind: "none" }, + ], + [json(401, simlock("UNAUTHENTICATED")), { kind: "none" }], + [json(403, simlock("FORBIDDEN")), { kind: "none" }], + [json(503, simlock("UNAVAILABLE")), { kind: "none" }], + ]; + + const outcomes = []; + for (const [answer] of cases) outcomes.push(await checkIdentity(asking(answer).fetch)); + + expect(outcomes).toEqual(cases.map(([, outcome]) => outcome)); + }); + + it("asks /v1/healthz when the answer is not Simlock's, and says the proxy's session ended when that answers", async () => { + const notSimlock: readonly Answer[] = [ + NETWORK_ERROR, + new Response(HTML, { headers: { "Content-Type": "text/html" }, status: 403 }), + new Response(HTML, { headers: { "Content-Type": "text/html" }, status: 401 }), + ]; + + for (const identity of notSimlock) { + const answering = asking(identity); + expect(await checkIdentity(answering.fetch)).toEqual({ kind: "ended" }); + expect(answering.calls.map((call) => call.input)).toEqual(["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/v1/identity", "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/v1/healthz"]); + const down = asking(identity, NETWORK_ERROR); + expect(await checkIdentity(down.fetch)).toEqual({ kind: "unreachable" }); + } + }); + + it("asks nothing more of a Simlock answer", async () => { + const answering = asking(json(403, simlock("FORBIDDEN"))); + + await checkIdentity(answering.fetch); + + expect(answering.calls.map((call) => call.input)).toEqual(["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/v1/identity"]); + }); + + it("sends no Authorization and credentials same-origin", async () => { + const answering = asking(json(401, simlock("UNAUTHENTICATED"))); + + await checkIdentity(answering.fetch); + + const [identity] = answering.calls; + expect(identity?.input).toBe("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/v1/identity"); + expect(identity?.init.credentials).toBe("same-origin"); + expect(new Headers(identity?.init.headers).has("Authorization")).toBe(false); + }); +}); diff --git a/ui/src/data/identity-check.ts b/ui/src/data/identity-check.ts new file mode 100644 index 000000000..d84e87d3c --- /dev/null +++ b/ui/src/data/identity-check.ts @@ -0,0 +1,12 @@ +import type { Fetch } from "./api"; + +export type IdentityOutcome = + | { readonly kind: "proxy"; readonly name: string; readonly signOutUrl?: string } + | { readonly kind: "refused"; readonly reason: string } + | { readonly kind: "none" } + | { readonly kind: "ended" } + | { readonly kind: "unreachable" }; + +export async function checkIdentity(_fetch: Fetch): Promise { + return { kind: "none" }; +} diff --git a/ui/src/data/session.test.ts b/ui/src/data/session.test.ts index 92f4cde4e..d6d29eae4 100644 --- a/ui/src/data/session.test.ts +++ b/ui/src/data/session.test.ts @@ -1,5 +1,6 @@ -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; +import { createApiClient, type Fetch } from "./api"; import { createSession } from "./session"; function memoryStorage() { @@ -57,3 +58,183 @@ describe("createSession", () => { } }); }); + +const ALICE = { name: "Alice", principal: "proxy:https://idp#u1", role: "admin", via: "proxy" }; +const EXPIRED = { error: { code: "UNAUTHENTICATED", message: "refused", reason: "expired" } }; +const HTML_403 = () => new Response("Sign in", { status: 403 }); +const NOW = 1_700_000_000_000; + +type Handler = () => Response | Promise; + +// why: a session in a page that loads over and over: the page's memory is the session, its +// storage and the proxy are what a reload keeps. +function page(handlers: { identity: Handler; healthz?: Handler; workers?: Handler }) { + const storage = memoryStorage(); + const calls: string[] = []; + const routes = { ...handlers }; + const fetch: Fetch = async (input) => { + calls.push(input); + const route = + input === "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/v1/identity" + ? routes.identity + : input === "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/v1/healthz" + ? routes.healthz + : routes.workers; + if (route === undefined) throw new TypeError("Failed to fetch"); + return route(); + }; + const reload = vi.fn(); + let now = NOW; + const open = (store: () => typeof storage | typeof refusing = () => storage) => { + const session = createSession(store, { fetch, now: () => now, reload }); + const api = createApiClient({ + fetch, + onRefused: session.refused, + signOut: () => {}, + token: session.token, + }); + return { api, session }; + }; + return { + calls, + elapse: (ms: number) => void (now += ms), + open, + reload, + routes, + storage, + }; +} + +const answers = + (status: number, body: unknown): Handler => + () => + new Response(JSON.stringify(body), { status }); +const healthz: Handler = () => new Response('{"ok":true}', { status: 200 }); + +async function settled(): Promise { + await new Promise((resolve) => setTimeout(resolve, 25)); +} + +describe("a session behind a sign-in proxy", () => { + it("opens as the person the proxy signed in, and as nobody when it did not", async () => { + const proxied = page({ identity: answers(200, ALICE) }); + const { session } = proxied.open(); + + const states: unknown[] = []; + session.subscribe(() => states.push(session.state())); + session.start(); + await vi.waitFor(() => expect(session.state()).toEqual({ kind: "proxy", name: "Alice" })); + + expect(states).toEqual([{ kind: "checking" }, { kind: "proxy", name: "Alice" }]); + const direct = page({ identity: answers(401, { error: { code: "UNAUTHENTICATED" } }) }); + const opened = direct.open().session; + opened.start(); + await vi.waitFor(() => expect(opened.state()).toEqual({ kind: "none" })); + }); + + it("three requests answering 401 at once start one identity check, whose outcome becomes the session", async () => { + const proxied = page({ + identity: answers(200, ALICE), + workers: answers(401, { error: { code: "UNAUTHENTICATED" } }), + }); + const { api, session } = proxied.open(); + session.start(); + await vi.waitFor(() => expect(session.state().kind).toBe("proxy")); + const identityCalls = () => proxied.calls.filter((call) => call === "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/v1/identity").length; + expect(identityCalls()).toBe(1); + let release: (response: Response) => void = () => {}; + proxied.routes.identity = () => new Promise((resolve) => (release = resolve)); + + const requests = [1, 2, 3].map(() => api.getJson("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/v1/workers").catch(() => "refused")); + await Promise.all(requests); + await settled(); + expect(identityCalls()).toBe(2); + release(new Response(JSON.stringify(EXPIRED), { status: 401 })); + + await vi.waitFor(() => + expect(session.state()).toEqual({ kind: "none", refusedReason: "expired" }), + ); + expect(identityCalls()).toBe(2); + }); + + it("a 401 in a token session forgets the token and starts the identity check", async () => { + const proxied = page({ + identity: answers(200, ALICE), + workers: answers(401, { error: { code: "UNAUTHENTICATED" } }), + }); + proxied.storage.setItem("simlock.operatorToken", "slk_revoked"); + const { api, session } = proxied.open(); + + await expect(api.getJson("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/v1/workers")).rejects.toMatchObject({ status: 401 }); + + expect(session.token()).toBeUndefined(); + expect(proxied.storage.items.size).toBe(0); + await vi.waitFor(() => expect(session.state()).toEqual({ kind: "proxy", name: "Alice" })); + expect(proxied.calls.filter((call) => call === "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/v1/identity")).toHaveLength(1); + }); + + it("the proxy's own session ending reloads the page, and a second ending within 60 seconds shows the ended screen instead", async () => { + const proxied = page({ healthz, identity: answers(200, ALICE), workers: HTML_403 }); + const first = proxied.open(); + first.session.start(); + await vi.waitFor(() => expect(first.session.state().kind).toBe("proxy")); + proxied.routes.identity = HTML_403; + + await first.api.getJson("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/v1/workers").catch(() => undefined); + await vi.waitFor(() => expect(proxied.reload).toHaveBeenCalledTimes(1)); + + proxied.routes.identity = answers(200, ALICE); + proxied.elapse(59_999); + const second = proxied.open(); + second.session.start(); + await vi.waitFor(() => expect(second.session.state().kind).toBe("proxy")); + proxied.routes.identity = HTML_403; + await second.api.getJson("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/v1/workers").catch(() => undefined); + await vi.waitFor(() => expect(second.session.state()).toEqual({ kind: "ended" })); + expect(proxied.reload).toHaveBeenCalledTimes(1); + + proxied.routes.identity = answers(200, ALICE); + proxied.elapse(1); + const third = proxied.open(); + third.session.start(); + await vi.waitFor(() => expect(third.session.state().kind).toBe("proxy")); + proxied.routes.identity = HTML_403; + await third.api.getJson("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/v1/workers").catch(() => undefined); + await vi.waitFor(() => expect(proxied.reload).toHaveBeenCalledTimes(2)); + }); + + it("shows the ended screen and never reloads when the browser refuses storage", async () => { + const proxied = page({ healthz, identity: answers(200, ALICE), workers: HTML_403 }); + const { api, session } = proxied.open(() => refusing); + session.start(); + await vi.waitFor(() => expect(session.state().kind).toBe("proxy")); + proxied.routes.identity = HTML_403; + + await api.getJson("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/v1/workers").catch(() => undefined); + + await vi.waitFor(() => expect(session.state()).toEqual({ kind: "ended" })); + expect(proxied.reload).not.toHaveBeenCalled(); + }); + + it("changes nothing when the daemon is unreachable, and counts an ended session as nobody at load", async () => { + const proxied = page({ identity: answers(200, ALICE) }); + const { api, session } = proxied.open(); + session.start(); + await vi.waitFor(() => expect(session.state().kind).toBe("proxy")); + proxied.routes.identity = () => { + throw new TypeError("Failed to fetch"); + }; + + await api.getJson("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/v1/workers").catch(() => undefined); + await settled(); + + expect(session.state()).toEqual({ kind: "proxy", name: "Alice" }); + expect(proxied.reload).not.toHaveBeenCalled(); + + const loading = page({ healthz, identity: HTML_403 }); + const loaded = loading.open().session; + loaded.start(); + await vi.waitFor(() => expect(loaded.state()).toEqual({ kind: "none" })); + expect(loading.reload).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/src/data/session.ts b/ui/src/data/session.ts index 018917c87..bd9ea17ed 100644 --- a/ui/src/data/session.ts +++ b/ui/src/data/session.ts @@ -1,8 +1,26 @@ +import type { ApiFailure, Fetch } from "./api"; + const STORAGE_KEY = "simlock.operatorToken"; type Storage = Pick; +export type SessionState = + | { readonly kind: "none"; readonly refusedReason?: string } + | { readonly kind: "checking" } + | { readonly kind: "token"; readonly token: string } + | { readonly kind: "proxy"; readonly name: string; readonly signOutUrl?: string } + | { readonly kind: "ended" }; + +export interface SessionDeps { + readonly fetch: Fetch; + readonly reload: () => void; + readonly now: () => number; +} + export interface Session { + state(): SessionState; + start(): void; + refused(failure: ApiFailure): void; token(): string | undefined; signIn(token: string): void; signOut(): void; @@ -12,7 +30,7 @@ export interface Session { // why: `storage` is asked for lazily, because a browser with site data blocked throws on merely // reading `window.sessionStorage`; it may also refuse each read and write, and the console then // still signs in with the token living only as long as the page. -export function createSession(storage: () => Storage): Session { +export function createSession(storage: () => Storage, _deps?: SessionDeps): Session { const listeners = new Set<() => void>(); let current = attempt(() => storage().getItem(STORAGE_KEY) ?? undefined); const update = (token: string | undefined) => { @@ -25,6 +43,9 @@ export function createSession(storage: () => Storage): Session { for (const listener of listeners) listener(); }; return { + state: () => (current === undefined ? { kind: "none" } : { kind: "token", token: current }), + start: () => {}, + refused: () => {}, token: () => current, signIn: (token) => update(token), signOut: () => update(undefined), diff --git a/ui/src/model/proxy-refusal.test.ts b/ui/src/model/proxy-refusal.test.ts new file mode 100644 index 000000000..bd5e60297 --- /dev/null +++ b/ui/src/model/proxy-refusal.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from "vitest"; + +import { proxyRefusalLine } from "./proxy-refusal"; + +const line = (why: string) => + `Your sign-in proxy's identity was refused: ${why}. You can still sign in with an operator token.`; + +describe("proxyRefusalLine", () => { + it("says why the proxy's identity was refused for each reason, and that it was refused for one it does not know", () => { + const cases: readonly (readonly [string, string])[] = [ + ["expired", "it has expired"], + ["not-yet-valid", "it is not valid yet; check this machine's clock"], + ["wrong-issuer", "it comes from a different sign-in service than this daemon expects"], + ["wrong-audience", "it was made for a different application"], + ["unknown-key", "its signature does not check out"], + ["bad-signature", "its signature does not check out"], + ["algorithm", "it is signed in a way this daemon does not accept"], + ["malformed", "it is not a valid sign-in token"], + ["keys-unavailable", "this daemon cannot reach the sign-in service's keys"], + ["something-new", "it was refused"], + ]; + + expect(cases.map(([reason]) => proxyRefusalLine(reason))).toEqual( + cases.map(([, why]) => line(why)), + ); + }); +}); diff --git a/ui/src/model/proxy-refusal.ts b/ui/src/model/proxy-refusal.ts new file mode 100644 index 000000000..dc912e60f --- /dev/null +++ b/ui/src/model/proxy-refusal.ts @@ -0,0 +1,3 @@ +export function proxyRefusalLine(_reason: string): string { + return ""; +} From dbe3bc50beb4d64520f30b08f26e44db97c57aa8 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 19 Oct 2026 18:15:19 +0200 Subject: [PATCH 02/11] feat: Sign the console in through the sign-in proxy and show who is signed in (#716) Unit tests for the identity check, session and refusal text pass; console lane not yet run. Unit failing -> 0 failing --- ui/src/app/app.tsx | 10 +++- ui/src/app/shell.tsx | 36 ++++++++---- ui/src/data/api.ts | 70 ++++++++++++++++++---- ui/src/data/identity-check.ts | 55 +++++++++++++++++- ui/src/data/session.ts | 106 +++++++++++++++++++++++++++++----- ui/src/ds/sidebar.css | 8 +++ ui/src/main.tsx | 10 +++- ui/src/model/proxy-refusal.ts | 17 +++++- ui/src/screens/sign-in.tsx | 104 ++++++++++++++++++++++----------- ui/src/state/shell.ts | 39 ++++++++++++- ui/src/state/sign-in.ts | 14 ++++- 11 files changed, 387 insertions(+), 82 deletions(-) diff --git a/ui/src/app/app.tsx b/ui/src/app/app.tsx index bf54ac7c6..ae17e7305 100644 --- a/ui/src/app/app.tsx +++ b/ui/src/app/app.tsx @@ -4,7 +4,7 @@ import type { ApiClient, Fetch } from "../data/api"; import type { Preferences } from "../data/preferences"; import type { Session } from "../data/session"; import { NavigationProvider } from "../ds"; -import { SignInScreen } from "../screens/sign-in"; +import { SignInEndedScreen, SignInScreen, SigningInScreen } from "../screens/sign-in"; import { LiveProvider } from "../state/live"; import { navigate } from "../state/router"; import { ConsoleProvider } from "../state/services"; @@ -19,11 +19,15 @@ export function App(props: { readonly session: Session; }) { const { session } = props; - const token = useSyncExternalStore(session.subscribe, session.token); + const state = useSyncExternalStore(session.subscribe, session.state); return ( - {token === undefined ? ( + {state.kind === "checking" ? ( + + ) : state.kind === "ended" ? ( + + ) : state.kind === "none" ? ( ) : ( diff --git a/ui/src/app/shell.tsx b/ui/src/app/shell.tsx index eb5f94055..fa4f218d8 100644 --- a/ui/src/app/shell.tsx +++ b/ui/src/app/shell.tsx @@ -3,7 +3,13 @@ import { useEffect } from "react"; import { AppFrame, Button, Icon, Sidebar, Status, StatusDot } from "../ds"; import { NotFoundScreen } from "../screens/not-found"; import { usePath } from "../state/router"; -import { useAttentionCount, useConnectionStatus, useSignOut, useTokenCheck } from "../state/shell"; +import { + useAttentionCount, + useConnectionStatus, + useSignedIn, + useSignOut, + useTokenCheck, +} from "../state/shell"; import { useSidebar } from "../state/sidebar"; import { ROUTES, routeFor } from "./routes"; @@ -49,6 +55,7 @@ export function Shell() { function SidebarFoot({ collapsed }: { readonly collapsed: boolean }) { const status = useConnectionStatus(); const signOut = useSignOut(); + const signedIn = useSignedIn(); return ( <>
@@ -66,16 +73,23 @@ function SidebarFoot({ collapsed }: { readonly collapsed: boolean }) { )}
- + {signedIn.name === undefined || collapsed ? null : ( +

Signed in as {signedIn.name}

+ )} + {signedIn.canSignOut ? ( + + ) : null} ); } diff --git a/ui/src/data/api.ts b/ui/src/data/api.ts index 691a50726..a460d3c27 100644 --- a/ui/src/data/api.ts +++ b/ui/src/data/api.ts @@ -52,7 +52,7 @@ export async function send( try { const response = await options.fetch(path, { cache: "no-store", - credentials: "omit", + credentials: "same-origin", headers: options.token === undefined ? {} : { Authorization: `Bearer ${options.token}` }, signal: controller.signal, }); @@ -90,7 +90,9 @@ export type ApiFailure = "unauthorized" | "not-simlock"; export interface ApiClientOptions { readonly fetch: Fetch; readonly token: () => string | undefined; - readonly signOut: () => void; + // why: what a 401 does when nobody takes `onRefused`; the console's session takes it, because + // what a 401 means depends on whether a token or a sign-in proxy made the session. + readonly signOut?: () => void; readonly onRefused?: (failure: ApiFailure) => void; } @@ -104,17 +106,37 @@ export function createApiClient(options: ApiClientOptions): ApiClient { ...(timeoutMs === undefined ? {} : { timeoutMs }), }; }; + const refuse = (failure: ApiFailure, status?: number) => { + if (options.onRefused !== undefined) options.onRefused(failure); + else if (status === 401) options.signOut?.(); + }; + const watched = async ( + path: ApiPath, + sendOptions: SendOptions, + read: (response: Response) => Promise, + ): Promise => { + try { + return await send(path, sendOptions, async (response) => { + await refuseError(response, refuse); + return read(response); + }); + } catch (error: unknown) { + // why: a request that never got an answer (a redirect `fetch` cannot follow, a dropped + // connection) may be the sign-in proxy's session ending; a timeout or an abort is not. + if (isNetworkError(error, sendOptions.signal)) refuse("not-simlock"); + throw error; + } + }; const get = (path: ApiPath) => - send(path, authorized(), async (response) => { - await refuseError(response, options.signOut); - return { body: (await response.json()) as T, date: response.headers.get("Date") }; - }); + watched(path, authorized(), async (response) => ({ + body: (await response.json()) as T, + date: response.headers.get("Date"), + })); return { get, getJson: async (path: ApiPath) => (await get(path)).body, stream: (path, signal, headTimeoutMs) => - send(path, authorized(signal, headTimeoutMs), async (response) => { - await refuseError(response, options.signOut); + watched(path, authorized(signal, headTimeoutMs), async (response) => { if (response.body === null) throw new ApiError(response.status, undefined, "No body"); return { body: response.body, date: response.headers.get("Date") }; }), @@ -126,9 +148,35 @@ export function createApiClient(options: ApiClientOptions): ApiClient { }; } -async function refuseError(response: Response, signOut: () => void): Promise { - if (response.status === 401) signOut(); - if (!response.ok) throw await apiError(response); +function isNetworkError(error: unknown, signal: AbortSignal | undefined): boolean { + return ( + !(error instanceof ApiError) && + !(error instanceof RequestTimeoutError) && + signal?.aborted !== true && + error instanceof TypeError + ); +} + +export function hasSimlockErrorCode(body: unknown): boolean { + if (typeof body !== "object" || body === null) return false; + const error = (body as { error?: unknown }).error; + return ( + typeof error === "object" && + error !== null && + typeof (error as { code?: unknown }).code === "string" + ); +} + +async function refuseError( + response: Response, + refuse: (failure: ApiFailure, status: number) => void, +): Promise { + if (response.ok) return; + const error = await apiError(response); + const status = response.status; + if ((status === 401 || status === 403) && error.code === undefined) refuse("not-simlock", status); + else if (status === 401) refuse("unauthorized", status); + throw error; } async function apiError(response: Response): Promise { diff --git a/ui/src/data/identity-check.ts b/ui/src/data/identity-check.ts index d84e87d3c..1063ffe2b 100644 --- a/ui/src/data/identity-check.ts +++ b/ui/src/data/identity-check.ts @@ -1,4 +1,4 @@ -import type { Fetch } from "./api"; +import { type Fetch, hasSimlockErrorCode, RequestTimeoutError, send } from "./api"; export type IdentityOutcome = | { readonly kind: "proxy"; readonly name: string; readonly signOutUrl?: string } @@ -7,6 +7,57 @@ export type IdentityOutcome = | { readonly kind: "ended" } | { readonly kind: "unreachable" }; -export async function checkIdentity(_fetch: Fetch): Promise { +interface Answer { + readonly status: number; + readonly body: unknown; +} + +// why: the one place that decides what a failure in a proxy session means. An answer that is not +// Simlock's (the proxy's own login page, or a request that never arrived) is told apart from "the +// daemon is down" by `/v1/healthz`, which the proxy lets through. +export async function checkIdentity(fetch: Fetch): Promise { + let answer: Answer; + try { + answer = await send("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/v1/identity", { fetch }, async (response) => ({ + body: await readJson(response), + status: response.status, + })); + } catch (error: unknown) { + if (error instanceof RequestTimeoutError) return { kind: "none" }; + return askHealthz(fetch); + } + const { body, status } = answer; + if ((status === 401 || status === 403) && !hasSimlockErrorCode(body)) return askHealthz(fetch); + if (status === 200) return proxyIdentity(body) ?? { kind: "none" }; + if (status === 401) { + const reason = (body as { error?: { reason?: unknown } }).error?.reason; + if (typeof reason === "string") return { kind: "refused", reason }; + } return { kind: "none" }; } + +async function readJson(response: Response): Promise { + try { + return await response.json(); + } catch { + return undefined; + } +} + +function proxyIdentity(body: unknown): IdentityOutcome | undefined { + if (typeof body !== "object" || body === null) return undefined; + const { name, signOutUrl, via } = body as Record; + if (via !== "proxy" || typeof name !== "string") return undefined; + return typeof signOutUrl === "string" + ? { kind: "proxy", name, signOutUrl } + : { kind: "proxy", name }; +} + +async function askHealthz(fetch: Fetch): Promise { + try { + const up = await send("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/v1/healthz", { fetch }, async (response) => response.ok); + return { kind: up ? "ended" : "unreachable" }; + } catch { + return { kind: "unreachable" }; + } +} diff --git a/ui/src/data/session.ts b/ui/src/data/session.ts index bd9ea17ed..8ac158edd 100644 --- a/ui/src/data/session.ts +++ b/ui/src/data/session.ts @@ -1,4 +1,5 @@ import type { ApiFailure, Fetch } from "./api"; +import { checkIdentity, type IdentityOutcome } from "./identity-check"; const STORAGE_KEY = "simlock.operatorToken"; @@ -27,28 +28,105 @@ export interface Session { subscribe(listener: () => void): () => void; } +const RELOAD_KEY = "simlock.proxyReloadAt"; +const RELOAD_GAP_MS = 60_000; + // why: `storage` is asked for lazily, because a browser with site data blocked throws on merely // reading `window.sessionStorage`; it may also refuse each read and write, and the console then // still signs in with the token living only as long as the page. -export function createSession(storage: () => Storage, _deps?: SessionDeps): Session { +export function createSession(storage: () => Storage, deps?: SessionDeps): Session { const listeners = new Set<() => void>(); - let current = attempt(() => storage().getItem(STORAGE_KEY) ?? undefined); - const update = (token: string | undefined) => { - current = token; + let token = attempt(() => storage().getItem(STORAGE_KEY) ?? undefined); + let state: SessionState = token === undefined ? { kind: "none" } : { kind: "token", token }; + let inFlight: Promise | undefined; + + const set = (next: SessionState) => { + state = next; + for (const listener of listeners) listener(); + }; + const store = (next: string | undefined) => { + token = next; attempt(() => - token === undefined - ? storage().removeItem(STORAGE_KEY) - : storage().setItem(STORAGE_KEY, token), + next === undefined ? storage().removeItem(STORAGE_KEY) : storage().setItem(STORAGE_KEY, next), ); - for (const listener of listeners) listener(); + }; + // why: callers while a check runs get its outcome, and only the first applies it. + const check = (): Promise | undefined => { + if (deps === undefined) return undefined; + if (inFlight !== undefined) return inFlight; + const running = checkIdentity(deps.fetch).finally(() => { + inFlight = undefined; + }); + inFlight = running; + return running; + }; + const opening = async (atLoad: boolean) => { + const first = inFlight === undefined; + const running = check(); + if (running === undefined) return set({ kind: "none" }); + const outcome = await running; + if (!first) return; + if (state.kind === "token") return; + switch (outcome.kind) { + case "proxy": + return set( + outcome.signOutUrl === undefined + ? { kind: "proxy", name: outcome.name } + : { kind: "proxy", name: outcome.name, signOutUrl: outcome.signOutUrl }, + ); + case "refused": + return set({ kind: "none", refusedReason: outcome.reason }); + case "ended": + if (!atLoad) return ended(); + return set({ kind: "none" }); + case "unreachable": + if (!atLoad) return; + return set({ kind: "none" }); + case "none": + return set({ kind: "none" }); + } + }; + // why: a proxy's login page cannot be drawn in this page, so the page reloads to let the proxy + // show it; a second ending within a minute of the reload would loop, and a browser that keeps no + // storage could never tell, so both stop at the ended screen. + const ended = () => { + if (deps === undefined) return set({ kind: "ended" }); + const reloadedAt = Number(attempt(() => storage().getItem(RELOAD_KEY))); + const recent = deps.now() - reloadedAt < RELOAD_GAP_MS; + const stored = + !recent && attempt(() => (storage().setItem(RELOAD_KEY, String(deps.now())), true)) === true; + if (stored) deps.reload(); + else set({ kind: "ended" }); }; return { - state: () => (current === undefined ? { kind: "none" } : { kind: "token", token: current }), - start: () => {}, - refused: () => {}, - token: () => current, - signIn: (token) => update(token), - signOut: () => update(undefined), + state: () => state, + start() { + if (state.kind !== "none") return; + set({ kind: "checking" }); + void opening(true); + }, + refused(failure) { + if (state.kind === "token") { + if (failure !== "unauthorized") return; + store(undefined); + set({ kind: "checking" }); + void opening(true); + } else if (state.kind === "proxy") { + void opening(false); + } + }, + token: () => token, + signIn(next) { + store(next); + set({ kind: "token", token: next }); + }, + signOut() { + if (state.kind !== "token") return; + store(undefined); + if (deps === undefined) return set({ kind: "none" }); + set({ kind: "checking" }); + void opening(true); + }, subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); diff --git a/ui/src/ds/sidebar.css b/ui/src/ds/sidebar.css index 6a3fd2227..55f3b91dc 100644 --- a/ui/src/ds/sidebar.css +++ b/ui/src/ds/sidebar.css @@ -351,3 +351,11 @@ .sidebar-collapsed .connection { justify-content: center; } + +.signed-in-as { + margin: 0; + overflow: hidden; + font-size: var(--text-sm); + text-overflow: ellipsis; + white-space: nowrap; +} diff --git a/ui/src/main.tsx b/ui/src/main.tsx index 20bd299a4..bc259d795 100644 --- a/ui/src/main.tsx +++ b/ui/src/main.tsx @@ -10,9 +10,15 @@ import { createPreferences } from "./data/preferences"; import { createSession } from "./data/session"; const fetch: Fetch = (input, init) => window.fetch(input, init); -const session = createSession(() => window.sessionStorage); +const session = createSession(() => window.sessionStorage, { + fetch, + now: () => Date.now(), + reload: () => window.location.reload(), +}); const preferences = createPreferences(() => window.localStorage); -const api = createApiClient({ fetch, signOut: session.signOut, token: session.token }); +const api = createApiClient({ fetch, onRefused: session.refused, token: session.token }); + +session.start(); const root = document.getElementById("root"); if (root === null) throw new Error("The console page has no #root element"); diff --git a/ui/src/model/proxy-refusal.ts b/ui/src/model/proxy-refusal.ts index dc912e60f..28d52c92c 100644 --- a/ui/src/model/proxy-refusal.ts +++ b/ui/src/model/proxy-refusal.ts @@ -1,3 +1,16 @@ -export function proxyRefusalLine(_reason: string): string { - return ""; +const WHY: Readonly> = { + algorithm: "it is signed in a way this daemon does not accept", + "bad-signature": "its signature does not check out", + expired: "it has expired", + "keys-unavailable": "this daemon cannot reach the sign-in service's keys", + malformed: "it is not a valid sign-in token", + "not-yet-valid": "it is not valid yet; check this machine's clock", + "unknown-key": "its signature does not check out", + "wrong-audience": "it was made for a different application", + "wrong-issuer": "it comes from a different sign-in service than this daemon expects", +}; + +export function proxyRefusalLine(reason: string): string { + const why = Object.hasOwn(WHY, reason) ? WHY[reason] : "it was refused"; + return `Your sign-in proxy's identity was refused: ${why}. You can still sign in with an operator token.`; } diff --git a/ui/src/screens/sign-in.tsx b/ui/src/screens/sign-in.tsx index 45a6d0192..864d99be6 100644 --- a/ui/src/screens/sign-in.tsx +++ b/ui/src/screens/sign-in.tsx @@ -1,9 +1,9 @@ import "./sign-in.css"; -import { type FormEvent, useState } from "react"; +import { type FormEvent, type ReactNode, useState } from "react"; import { Button, Panel, Wordmark } from "../ds"; -import { useSignIn } from "../state/sign-in"; +import { useReloadPage, useSignIn } from "../state/sign-in"; export function SignInScreen() { const [token, setToken] = useState(""); @@ -14,6 +14,42 @@ export function SignInScreen() { }; const refused = refusal !== undefined; + return ( + + +
+ + setToken(event.target.value)} + aria-describedby={refused ? "token-hint token-refusal" : "token-hint"} + aria-invalid={refused || undefined} + /> +

+ Create one with simlock token create --role operator. +

+ {refusal === undefined ? null : ( + + )} +
+ +
+
+
+
+ ); +} + +function SignInFrame({ children }: { readonly children: ReactNode }) { return (
@@ -21,38 +57,40 @@ export function SignInScreen() { By Callstack
-
- -
- - setToken(event.target.value)} - aria-describedby={refused ? "token-hint token-refusal" : "token-hint"} - aria-invalid={refused || undefined} - /> -

- Create one with simlock token create --role operator. -

- {refusal === undefined ? null : ( - - )} -
- -
-
-
-
+
{children}
); } + +// why: shown while the first identity check runs, so a person behind a sign-in proxy never sees the +// token form flash. +export function SigningInScreen() { + return ( + + +

+ Checking who you are. +

+
+
+ ); +} + +export function SignInEndedScreen() { + const reload = useReloadPage(); + return ( + + +
+

The sign-in proxy no longer knows you.

+
+ +
+
+
+
+ ); +} diff --git a/ui/src/state/shell.ts b/ui/src/state/shell.ts index baf1c6ce6..74809994f 100644 --- a/ui/src/state/shell.ts +++ b/ui/src/state/shell.ts @@ -1,4 +1,4 @@ -import { useEffect } from "react"; +import { useEffect, useState, useSyncExternalStore } from "react"; import type { ConnectionPhase } from "../data/live/connection"; import { attentionItems } from "../model/attention"; @@ -22,9 +22,44 @@ export function useTokenCheck(): void { }, [api]); } +export interface SignedIn { + readonly name: string | undefined; + // why: a proxy person with no sign-out address has nowhere to go, so there is no Sign out. + readonly canSignOut: boolean; +} + +export function useSignedIn(): SignedIn { + const api = useApi(); + const session = useSession(); + const state = useSyncExternalStore(session.subscribe, session.state); + const token = state.kind === "token" ? state.token : undefined; + const [tokenName, setTokenName] = useState(undefined); + useEffect(() => { + if (token === undefined) return; + let current = true; + api.getJson<{ readonly name: string }>("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/v1/identity").then( + (identity) => current && setTokenName(identity.name), + () => undefined, + ); + return () => { + current = false; + setTokenName(undefined); + }; + }, [api, token]); + if (state.kind === "proxy") { + return { canSignOut: state.signOutUrl !== undefined, name: state.name }; + } + return { canSignOut: true, name: tokenName }; +} + export function useSignOut(): () => void { const session = useSession(); - return () => session.signOut(); + return () => { + const state = session.state(); + if (state.kind === "proxy") { + if (state.signOutUrl !== undefined) window.location.assign(state.signOutUrl); + } else session.signOut(); + }; } const PHASES: Readonly> = { diff --git a/ui/src/state/sign-in.ts b/ui/src/state/sign-in.ts index abefc11a7..e8584e982 100644 --- a/ui/src/state/sign-in.ts +++ b/ui/src/state/sign-in.ts @@ -1,12 +1,14 @@ -import { useState } from "react"; +import { useState, useSyncExternalStore } from "react"; import { checkToken, refusalMessage } from "../data/sign-in-check"; +import { proxyRefusalLine } from "../model/proxy-refusal"; import { useFetch, useSession } from "./services"; export function useSignIn() { const fetch = useFetch(); const session = useSession(); const [checking, setChecking] = useState(false); + const state = useSyncExternalStore(session.subscribe, session.state); const [refusal, setRefusal] = useState(undefined); // why: no guard against a second submit while checking: the disabled button blocks it, the Enter // key included, since a form with a disabled submit button does not submit implicitly. @@ -19,5 +21,13 @@ export function useSignIn() { if (outcome.kind === "signed-in") session.signIn(token); else setRefusal(refusalMessage(outcome)); }; - return { checking, refusal, submit }; + const proxyRefusal = + state.kind === "none" && state.refusedReason !== undefined + ? proxyRefusalLine(state.refusedReason) + : undefined; + return { checking, refusal: refusal ?? proxyRefusal, submit }; +} + +export function useReloadPage(): () => void { + return () => window.location.reload(); } From dfcda82f678cff23551768459b15baa5144f26df Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 19 Oct 2026 18:23:20 +0200 Subject: [PATCH 03/11] docs: Say how the console signs in behind a sign-in proxy (#716) Console lane: 1 failing -> 1 failing (the 60 second reload test, see PR). --- docs/CONSOLE.md | 75 +++++++++++++++++++++++++++++++++++++++-- docs/internal/DESIGN.md | 3 +- ui/AGENTS.md | 8 +++++ 3 files changed, 82 insertions(+), 4 deletions(-) diff --git a/docs/CONSOLE.md b/docs/CONSOLE.md index 110d7c9be..74c13d232 100644 --- a/docs/CONSOLE.md +++ b/docs/CONSOLE.md @@ -119,16 +119,85 @@ If the console does not accept the token, it says why: | The daemon cannot be reached. | Nothing answers at this address. | | The daemon answered with an error (HTTP *n*). | Anything else; the daemon's log says more. | +## Behind a sign-in proxy + +When a sign-in proxy stands in front of Simlock, the console opens with no +token form. It asks the daemon who you are (`GET /v1/identity`), and if the +proxy signed you in, it opens at once and the sidebar reads **Signed in as** +and your name. Until the answer comes the page says **Signing in…**. + +What you configure is in `http.proxyAuth` (see CONFIGURATION.md): the header +that carries the proxy's JWT, where the proxy publishes its keys, the issuer +and the audience. Set `signOutUrl` to the proxy's sign-out page. The proxy +must let `/v1/uplink` and `/v1/healthz` through without signing in. + +Cloudflare Access: + +```json +{ + "http": { + "proxyAuth": { + "header": "cf-access-jwt-assertion", + "jwksUrl": "https://TEAM.cloudflareaccess.com/cdn-cgi/access/certs", + "issuer": "https://TEAM.cloudflareaccess.com", + "audience": "APPLICATION-AUD-TAG", + "signOutUrl": "https://TEAM.cloudflareaccess.com/cdn-cgi/access/logout" + } + } +} +``` + +oauth2-proxy, with its alpha config injecting the session's ID token into a +header of your choosing (`claimSource: { claim: id_token }`), so that an +operator token pasted into the console still reaches Simlock in +`Authorization`: + +```json +{ + "http": { + "proxyAuth": { + "header": "x-id-token", + "jwksUrl": "https://ISSUER/.well-known/jwks.json", + "issuer": "https://ISSUER", + "audience": "OAUTH2-PROXY-CLIENT-ID", + "signOutUrl": "https://CONSOLE-HOST/oauth2/sign_out" + } + } +} +``` + +If the daemon refuses the proxy's identity, the token form says why: "Your +sign-in proxy's identity was refused: *reason*. You can still sign in with an +operator token." The reasons are that it has expired, is not valid yet (check +this machine's clock), comes from a different sign-in service or was made for +a different application than the daemon expects, has a signature that does +not check out, is signed in a way the daemon does not accept, is not a valid +sign-in token, or that the daemon cannot reach the sign-in service's keys. + +Pasting an operator token behind the proxy works as without it, and the +sidebar then reads the token's label. + ## Staying signed in -The console keeps the token in this browser tab only. +The console keeps a token in this browser tab only. A person signed in +through a proxy is not kept by the console at all: every page load asks the +daemon again. - **Reload** the page and you stay signed in. - **Open a new tab** and it asks for a token again. - **Close the tab** and you are signed out. -- **Sign out** forgets the token at once. +- **Sign out** forgets the token at once. Behind a sign-in proxy, a token's + Sign out brings back the proxy's sign-in; a person the proxy signed in goes + to the proxy's sign-out page (`signOutUrl`), and with none set there is no + Sign out button. +- If the proxy's own session ends, the page reloads so the proxy can show its + login page. If that happens again within a minute, the console says **Your + sign-in has ended.** with a **Sign in again** button instead of reloading. +- If the proxy's identity is refused while you are signed in through it, the + console shows the token form with the reason. - If the token is **revoked**, the console signs you out the next time it asks - the daemon for anything, and at the latest when you reload. + the daemon for anything, and at the latest when you reload. Behind a + sign-in proxy it then signs you in as the proxy's person, if there is one. Some browsers copy a tab's storage into a duplicated or reopened tab, so such a tab may still be signed in. diff --git a/docs/internal/DESIGN.md b/docs/internal/DESIGN.md index 304e568e9..f9dbe5e9c 100644 --- a/docs/internal/DESIGN.md +++ b/docs/internal/DESIGN.md @@ -134,7 +134,8 @@ put together from them and draws nothing of its own that one of them already dra - **Sidebar.** The console's navigation, on the left of every signed-in page: the "SIMLOCK" wordmark (`--on-accent` on an `--accent` block), one link per page in a fixed order (Overview, Workers, Leases, Waiting, Attention, Events, Usage), then at the bottom the connection as a status, - **Sign out** and the collapse button. A link is an icon and its label in `--text-muted`; the + "Signed in as " (hidden when collapsed, where the Sign out tooltip reads "Sign out ()"), + **Sign out** (absent for a proxy person with no sign-out address) and the collapse button. A link is an icon and its label in `--text-muted`; the current one is `--text` on `--field` with a 2px `--accent` bar on its left and `aria-current="page"`. Attention carries its count in a small bordered box, and none at zero. Collapsed, the sidebar is 64px wide: the labels go, every icon sits on its centre line, each diff --git a/ui/AGENTS.md b/ui/AGENTS.md index bb5c26494..3ac3eb5e1 100644 --- a/ui/AGENTS.md +++ b/ui/AGENTS.md @@ -38,6 +38,14 @@ Each layer imports only the layers below it. `.dependency-cruiser.mjs` enforces composes `ds` components. Its CSS sits beside it. 4. Route: an entry in `src/app/routes.ts` gives it a path, a label and an icon. +## Session + +`data/session.ts` holds who is signed in: a token (kept in `sessionStorage`), a person a sign-in +proxy signed in (memory only), none, checking (the first `GET /v1/identity` runs), or ended. The +API client reports a 401, or an answer that is not Simlock's, to the session; in a proxy session +that starts the one shared `data/identity-check.ts`, in a token session a 401 forgets the token and +asks it. `model/proxy-refusal.ts` words a refusal. + ## Pages | Path | Screen | Layout | From 7075502ae1f8cd513cba29bbc35c689bb11d7381 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 19 Oct 2026 18:25:52 +0200 Subject: [PATCH 04/11] refactor: Split the session's outcome handling and the sign-out button, and render the session on the server (#716) Unit: 1 failing -> 0 failing --- ui/src/app/app.tsx | 2 +- ui/src/app/shell.tsx | 33 +++++++++++++++++++++------------ ui/src/data/session.ts | 35 +++++++++++++++++++---------------- ui/src/state/shell.ts | 2 +- ui/src/state/sign-in.ts | 2 +- 5 files changed, 43 insertions(+), 31 deletions(-) diff --git a/ui/src/app/app.tsx b/ui/src/app/app.tsx index ae17e7305..603750619 100644 --- a/ui/src/app/app.tsx +++ b/ui/src/app/app.tsx @@ -19,7 +19,7 @@ export function App(props: { readonly session: Session; }) { const { session } = props; - const state = useSyncExternalStore(session.subscribe, session.state); + const state = useSyncExternalStore(session.subscribe, session.state, session.state); return ( diff --git a/ui/src/app/shell.tsx b/ui/src/app/shell.tsx index fa4f218d8..e8cac1a3d 100644 --- a/ui/src/app/shell.tsx +++ b/ui/src/app/shell.tsx @@ -77,19 +77,28 @@ function SidebarFoot({ collapsed }: { readonly collapsed: boolean }) {

Signed in as {signedIn.name}

)} {signedIn.canSignOut ? ( - + ) : null} ); } + +function SignOutButton(props: { + readonly collapsed: boolean; + readonly name: string | undefined; + readonly onClick: () => void; +}) { + const { collapsed, name, onClick } = props; + return ( + + ); +} diff --git a/ui/src/data/session.ts b/ui/src/data/session.ts index 8ac158edd..7753c9b8c 100644 --- a/ui/src/data/session.ts +++ b/ui/src/data/session.ts @@ -60,32 +60,29 @@ export function createSession(storage: () => Storage, deps?: SessionDeps): Sessi inFlight = running; return running; }; - const opening = async (atLoad: boolean) => { - const first = inFlight === undefined; - const running = check(); - if (running === undefined) return set({ kind: "none" }); - const outcome = await running; - if (!first) return; - if (state.kind === "token") return; + const apply = (outcome: IdentityOutcome, atLoad: boolean) => { switch (outcome.kind) { case "proxy": - return set( - outcome.signOutUrl === undefined - ? { kind: "proxy", name: outcome.name } - : { kind: "proxy", name: outcome.name, signOutUrl: outcome.signOutUrl }, - ); + return set(proxyState(outcome)); case "refused": return set({ kind: "none", refusedReason: outcome.reason }); case "ended": - if (!atLoad) return ended(); - return set({ kind: "none" }); + return atLoad ? set({ kind: "none" }) : ended(); case "unreachable": - if (!atLoad) return; - return set({ kind: "none" }); + return atLoad ? set({ kind: "none" }) : undefined; case "none": return set({ kind: "none" }); } }; + const opening = async (atLoad: boolean) => { + const first = inFlight === undefined; + const running = check(); + if (running === undefined) return set({ kind: "none" }); + const outcome = await running; + // why: only the caller that started the check applies its outcome, and a token signed in while + // it ran is not undone by it. + if (first && state.kind !== "token") apply(outcome, atLoad); + }; // why: a proxy's login page cannot be drawn in this page, so the page reloads to let the proxy // show it; a second ending within a minute of the reload would loop, and a browser that keeps no // storage could never tell, so both stop at the ended screen. @@ -134,6 +131,12 @@ export function createSession(storage: () => Storage, deps?: SessionDeps): Sessi }; } +function proxyState(outcome: Extract): SessionState { + return outcome.signOutUrl === undefined + ? { kind: "proxy", name: outcome.name } + : { kind: "proxy", name: outcome.name, signOutUrl: outcome.signOutUrl }; +} + function attempt(call: () => T): T | undefined { try { return call(); diff --git a/ui/src/state/shell.ts b/ui/src/state/shell.ts index 74809994f..e24d5b6c5 100644 --- a/ui/src/state/shell.ts +++ b/ui/src/state/shell.ts @@ -31,7 +31,7 @@ export interface SignedIn { export function useSignedIn(): SignedIn { const api = useApi(); const session = useSession(); - const state = useSyncExternalStore(session.subscribe, session.state); + const state = useSyncExternalStore(session.subscribe, session.state, session.state); const token = state.kind === "token" ? state.token : undefined; const [tokenName, setTokenName] = useState(undefined); useEffect(() => { diff --git a/ui/src/state/sign-in.ts b/ui/src/state/sign-in.ts index e8584e982..473084839 100644 --- a/ui/src/state/sign-in.ts +++ b/ui/src/state/sign-in.ts @@ -8,7 +8,7 @@ export function useSignIn() { const fetch = useFetch(); const session = useSession(); const [checking, setChecking] = useState(false); - const state = useSyncExternalStore(session.subscribe, session.state); + const state = useSyncExternalStore(session.subscribe, session.state, session.state); const [refusal, setRefusal] = useState(undefined); // why: no guard against a second submit while checking: the disabled button blocks it, the Enter // key included, since a form with a disabled submit button does not submit implicitly. From 495b6edfb49d0695363f85be0ac1559ea56a4dc7 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 19 Oct 2026 18:26:15 +0200 Subject: [PATCH 05/11] refactor: Split the sidebar foot into the connection, who is signed in, and Sign out (#716) Unit: 0 failing -> 0 failing --- ui/src/app/shell.tsx | 44 +++++++++++++++++++++++++------------------- 1 file changed, 25 insertions(+), 19 deletions(-) diff --git a/ui/src/app/shell.tsx b/ui/src/app/shell.tsx index e8cac1a3d..9f903f8ef 100644 --- a/ui/src/app/shell.tsx +++ b/ui/src/app/shell.tsx @@ -50,29 +50,12 @@ export function Shell() { ); } -// why: the connection's word is a live region so a screen reader hears it change; the data's age -// beside it ticks every second, so it stays outside the region. function SidebarFoot({ collapsed }: { readonly collapsed: boolean }) { - const status = useConnectionStatus(); - const signOut = useSignOut(); const signedIn = useSignedIn(); + const signOut = useSignOut(); return ( <> -
- {collapsed ? ( - <> - - - {status.word} - - - ) : ( - - {status.word} - {status.age === undefined ? null : — data from {status.age} ago} - - )} -
+ {signedIn.name === undefined || collapsed ? null : (

Signed in as {signedIn.name}

)} @@ -83,6 +66,29 @@ function SidebarFoot({ collapsed }: { readonly collapsed: boolean }) { ); } +// why: the connection's word is a live region so a screen reader hears it change; the data's age +// beside it ticks every second, so it stays outside the region. +function ConnectionStatus({ collapsed }: { readonly collapsed: boolean }) { + const status = useConnectionStatus(); + return ( +
+ {collapsed ? ( + <> + + + {status.word} + + + ) : ( + + {status.word} + {status.age === undefined ? null : — data from {status.age} ago} + + )} +
+ ); +} + function SignOutButton(props: { readonly collapsed: boolean; readonly name: string | undefined; From 6cf90c05f4dee49f63e54c33ea1fb486b654377f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 19 Oct 2026 18:29:15 +0200 Subject: [PATCH 06/11] test: Start each first proxy-session ending in a fresh tab, so the 60 s reload guard is per tab (#716) 1 failing -> 0 failing --- e2e/console/proxy-sign-in.spec.ts | 37 +++++++++++++++++-------------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/e2e/console/proxy-sign-in.spec.ts b/e2e/console/proxy-sign-in.spec.ts index 3d7d89680..1c8b90aa1 100644 --- a/e2e/console/proxy-sign-in.spec.ts +++ b/e2e/console/proxy-sign-in.spec.ts @@ -107,34 +107,37 @@ test.describe("signing in through a proxy", () => { page, proxied, }) => { - await page.goto(proxied.url); - await expect(page.getByText("Signed in as Alice")).toBeVisible(); - + // why: the reload guard lives in sessionStorage, so each first ending starts in a fresh tab. + const redirected = await page.context().newPage(); + await redirected.goto(proxied.url); + await expect(redirected.getByText("Signed in as Alice")).toBeVisible(); proxied.setMode("redirect"); - await openFromNav(page, "Leases"); - await expect(page).toHaveURL(proxied.loginUrl); - await expect(page.getByRole("heading", { name: "Proxy login" })).toBeVisible(); + await openFromNav(redirected, "Leases"); + await expect(redirected).toHaveURL(proxied.loginUrl); + await expect(redirected.getByRole("heading", { name: "Proxy login" })).toBeVisible(); + await redirected.close(); proxied.setMode("signed-in"); - await page.goto(proxied.url); - await expect(page.getByText("Signed in as Alice")).toBeVisible(); + const reloaded = await page.context().newPage(); + await reloaded.goto(proxied.url); + await expect(reloaded.getByText("Signed in as Alice")).toBeVisible(); proxied.setMode("html"); - await openFromNav(page, "Leases"); - await expect(page.getByRole("heading", { name: "Proxy sign-in" })).toBeVisible(); + await openFromNav(reloaded, "Leases"); + await expect(reloaded.getByRole("heading", { name: "Proxy sign-in" })).toBeVisible(); proxied.setMode("signed-in"); - await page.goto(proxied.url); - await expect(page.getByText("Signed in as Alice")).toBeVisible(); - await page.evaluate(() => { + await reloaded.goto(proxied.url); + await expect(reloaded.getByText("Signed in as Alice")).toBeVisible(); + await reloaded.evaluate(() => { (window as unknown as { loadedOnce: boolean }).loadedOnce = true; }); proxied.setMode("html"); - await openFromNav(page, "Leases"); + await openFromNav(reloaded, "Leases"); - await expect(page.getByText("Your sign-in has ended.")).toBeVisible(); - await expect(page.getByRole("button", { name: "Sign in again" })).toBeVisible(); + await expect(reloaded.getByText("Your sign-in has ended.")).toBeVisible(); + await expect(reloaded.getByRole("button", { name: "Sign in again" })).toBeVisible(); expect( - await page.evaluate(() => (window as unknown as { loadedOnce?: boolean }).loadedOnce), + await reloaded.evaluate(() => (window as unknown as { loadedOnce?: boolean }).loadedOnce), ).toBe(true); }); From 6a8ad7188dc225d446470dc3b60545b35e37c4d1 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 19 Oct 2026 18:39:12 +0200 Subject: [PATCH 07/11] test: Pin the identity check's timeout and 5xx healthz, the token session's keep on a non-Simlock answer, and a token signed in during the check (#716) --- ui/src/data/identity-check.test.ts | 25 ++++++++++++++++++++++++- ui/src/data/session.test.ts | 27 +++++++++++++++++++++++++++ ui/src/model/proxy-refusal.test.ts | 1 + 3 files changed, 52 insertions(+), 1 deletion(-) diff --git a/ui/src/data/identity-check.test.ts b/ui/src/data/identity-check.test.ts index 2219ccdf6..dbcaabdda 100644 --- a/ui/src/data/identity-check.test.ts +++ b/ui/src/data/identity-check.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import type { Fetch } from "./api"; import { checkIdentity, type IdentityOutcome } from "./identity-check"; @@ -70,6 +70,8 @@ describe("checkIdentity", () => { expect(answering.calls.map((call) => call.input)).toEqual(["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/v1/identity", "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/v1/healthz"]); const down = asking(identity, NETWORK_ERROR); expect(await checkIdentity(down.fetch)).toEqual({ kind: "unreachable" }); + const failing = asking(identity, new Response("down", { status: 503 })); + expect(await checkIdentity(failing.fetch)).toEqual({ kind: "unreachable" }); } }); @@ -91,4 +93,25 @@ describe("checkIdentity", () => { expect(identity?.init.credentials).toBe("same-origin"); expect(new Headers(identity?.init.headers).has("Authorization")).toBe(false); }); + + it("answers nobody, and asks nothing more, when the identity request times out", async () => { + vi.useFakeTimers(); + try { + const calls: string[] = []; + const fetch: Fetch = (input, init) => { + calls.push(input); + return new Promise((_resolve, reject) => { + init.signal?.addEventListener("abort", () => reject(new DOMException("", "AbortError"))); + }); + }; + + const outcome = checkIdentity(fetch); + await vi.advanceTimersByTimeAsync(10_001); + + expect(await outcome).toEqual({ kind: "none" }); + expect(calls).toEqual(["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/v1/identity"]); + } finally { + vi.useRealTimers(); + } + }); }); diff --git a/ui/src/data/session.test.ts b/ui/src/data/session.test.ts index d6d29eae4..7f5470a90 100644 --- a/ui/src/data/session.test.ts +++ b/ui/src/data/session.test.ts @@ -237,4 +237,31 @@ describe("a session behind a sign-in proxy", () => { await vi.waitFor(() => expect(loaded.state()).toEqual({ kind: "none" })); expect(loading.reload).not.toHaveBeenCalled(); }); + + it("keeps the token when a token session gets an answer that is not Simlock's", async () => { + const proxied = page({ healthz, identity: answers(200, ALICE), workers: HTML_403 }); + proxied.storage.setItem("simlock.operatorToken", "slk_op"); + const { api, session } = proxied.open(); + + await api.getJson("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/v1/workers").catch(() => undefined); + await settled(); + + expect(session.state()).toEqual({ kind: "token", token: "slk_op" }); + expect(proxied.storage.getItem("simlock.operatorToken")).toBe("slk_op"); + expect(proxied.calls).not.toContain("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/v1/identity"); + }); + + it("does not undo a token signed in while the identity check ran", async () => { + const proxied = page({ identity: answers(200, ALICE) }); + let release: (response: Response) => void = () => {}; + proxied.routes.identity = () => new Promise((resolve) => (release = resolve)); + const { session } = proxied.open(); + session.start(); + + session.signIn("slk_op"); + release(new Response(JSON.stringify(ALICE), { status: 200 })); + await settled(); + + expect(session.state()).toEqual({ kind: "token", token: "slk_op" }); + }); }); diff --git a/ui/src/model/proxy-refusal.test.ts b/ui/src/model/proxy-refusal.test.ts index bd5e60297..a1bde45a8 100644 --- a/ui/src/model/proxy-refusal.test.ts +++ b/ui/src/model/proxy-refusal.test.ts @@ -18,6 +18,7 @@ describe("proxyRefusalLine", () => { ["malformed", "it is not a valid sign-in token"], ["keys-unavailable", "this daemon cannot reach the sign-in service's keys"], ["something-new", "it was refused"], + ["constructor", "it was refused"], ]; expect(cases.map(([reason]) => proxyRefusalLine(reason))).toEqual( From c952d0ee2152442894db10b75410e2130053af4a Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 19 Oct 2026 18:47:02 +0200 Subject: [PATCH 08/11] test: The proxy page's no-other-host test also fails on a request the CSP refused (#716) --- e2e/console/proxy-sign-in.spec.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/e2e/console/proxy-sign-in.spec.ts b/e2e/console/proxy-sign-in.spec.ts index 1c8b90aa1..715f792fb 100644 --- a/e2e/console/proxy-sign-in.spec.ts +++ b/e2e/console/proxy-sign-in.spec.ts @@ -163,7 +163,12 @@ test.describe("signing in through a proxy", () => { test("the page makes no request to any host but the proxy's", async ({ page, proxied }) => { const origin = new URL(proxied.url).origin; const requested: string[] = []; + const errors: string[] = []; page.on("request", (request) => requested.push(request.url())); + page.on("console", (message) => { + if (message.type() === "error") errors.push(message.text()); + }); + page.on("pageerror", (error) => errors.push(error.message)); await page.goto(proxied.url); for (const label of NAV_LABELS) { @@ -175,5 +180,8 @@ test.describe("signing in through a proxy", () => { expect(requested.length).toBeGreaterThan(0); expect(requested.filter((url) => new URL(url).origin !== origin)).toEqual([]); + // why: a request the page's Content-Security-Policy refused never reaches the network, but the + // browser reports it as an error. + expect(errors).toEqual([]); }); }); From 1e46ac8ef2616c93fd3f80a4c8bd0d62010e4d67 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 19 Oct 2026 19:00:40 +0200 Subject: [PATCH 09/11] fix: A lost live connection in a proxy session asks the identity check first; pin the not-Simlock 401 and an unreachable daemon at load; say who is signed in and when Sign out is absent (#716) --- docs/CONSOLE.md | 11 +++-- ui/AGENTS.md | 4 +- ui/src/data/api.test.ts | 19 ++++++++ ui/src/data/live/connection.test.ts | 44 +++++++++++++++++ ui/src/data/live/connection.ts | 35 +++++++++++-- ui/src/data/live/test-support.ts | 17 +++++-- ui/src/data/session.test.ts | 76 +++++++++++++++++++++++++---- ui/src/data/session.ts | 15 ++++++ ui/src/state/live.tsx | 6 ++- 9 files changed, 205 insertions(+), 22 deletions(-) diff --git a/docs/CONSOLE.md b/docs/CONSOLE.md index 74c13d232..2617ef162 100644 --- a/docs/CONSOLE.md +++ b/docs/CONSOLE.md @@ -5,7 +5,9 @@ what a Simlock host, or a gateway and its workers, is doing. The daemon serves it itself. There is nothing to install and nothing is fetched from the internet. -The console is for people who operate Simlock. It needs an operator token. +The console is for people who operate Simlock. It needs an operator token, or +a sign-in proxy in front of Simlock that signs you in +(see [Behind a sign-in proxy](#behind-a-sign-in-proxy)). Coding agents keep using the CLI, the MCP server, the client and the HTTP API. ## Finding your way @@ -13,8 +15,11 @@ Coding agents keep using the CLI, the MCP server, the client and the HTTP API. A sidebar on the left leads to every page: **Overview**, **Workers**, **Leases**, **Waiting**, **Attention**, **Events** and **Usage**. **Attention** shows how many items need you, on every page. At the bottom of the sidebar are the -connection (see [Live updates](#live-updates)), **Sign out**, and the button -that collapses the sidebar to its icons and widens it again. The console +connection (see [Live updates](#live-updates)), who you are signed in as +(**Signed in as** and the name, hidden while the sidebar is collapsed), +**Sign out** (absent when a sign-in proxy signed you in and has no sign-out +page set), and the button that collapses the sidebar to its icons and widens +it again. The console remembers your choice in this browser, and changing pages never changes it. A window narrower than 1280 pixels starts with the sidebar collapsed until you choose. On a phone the sidebar is a bar along the top with a menu button. diff --git a/ui/AGENTS.md b/ui/AGENTS.md index 3ac3eb5e1..1954a5cd7 100644 --- a/ui/AGENTS.md +++ b/ui/AGENTS.md @@ -44,7 +44,9 @@ Each layer imports only the layers below it. `.dependency-cruiser.mjs` enforces proxy signed in (memory only), none, checking (the first `GET /v1/identity` runs), or ended. The API client reports a 401, or an answer that is not Simlock's, to the session; in a proxy session that starts the one shared `data/identity-check.ts`, in a token session a 401 forgets the token and -asks it. `model/proxy-refusal.ts` words a refusal. +asks it. The live connection asks `session.lost()` when it loses the stream, in a proxy session +the same check: reconnect at once, back off as for an unreachable daemon, or stop while the session +ends. `model/proxy-refusal.ts` words a refusal. ## Pages diff --git a/ui/src/data/api.test.ts b/ui/src/data/api.test.ts index 9121faf08..4a532fcd6 100644 --- a/ui/src/data/api.test.ts +++ b/ui/src/data/api.test.ts @@ -43,6 +43,25 @@ describe("createApiClient", () => { expect(signOut).toHaveBeenCalledTimes(1); }); + it("tells a 401 or 403 that is not Simlock's from a Simlock 401", async () => { + const refused = async (status: number, body: unknown) => { + const onRefused = vi.fn(); + const api = createApiClient({ + fetch: answering(status, body).fetch, + onRefused, + token: () => undefined, + }); + await api.getJson("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/v1/workers").catch(() => undefined); + return onRefused.mock.calls.map(([failure]) => failure); + }; + const simlock = { error: { code: "UNAUTHENTICATED", message: "refused" } }; + + expect(await refused(401, {})).toEqual(["not-simlock"]); + expect(await refused(403, {})).toEqual(["not-simlock"]); + expect(await refused(401, simlock)).toEqual(["unauthorized"]); + expect(await refused(403, simlock)).toEqual([]); + }); + it("the fetch helper gives up after 10 seconds", async () => { vi.useFakeTimers(); const api = createApiClient({ fetch: hanging, signOut: () => {}, token: () => "slk_op" }); diff --git a/ui/src/data/live/connection.test.ts b/ui/src/data/live/connection.test.ts index afc9759ac..83ee1ed15 100644 --- a/ui/src/data/live/connection.test.ts +++ b/ui/src/data/live/connection.test.ts @@ -140,6 +140,50 @@ describe("LiveConnection", () => { expect(connection.state().phase).toBe("disconnected"); }); + it("a loss in a proxy session asks whether the session is still the proxy's before the backoff", async () => { + for (const answer of ["reconnect", "backoff", "stop"] as const) { + const asked: number[] = []; + const { connection, daemon } = connect(() => { + asked.push(Date.now()); + return Promise.resolve(answer); + }); + connection.watch("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/v1/workers", () => {}); + await settle(); + const lostAt = Date.now(); + daemon.openStream()?.end(); + await settle(); + expect(asked).toEqual([lostAt]); + + await vi.advanceTimersByTimeAsync(1_000); + + const reopened = daemon.streams.length - 1; + if (answer === "reconnect") { + expect(reopened).toBe(1); + expect(daemon.healthChecks).toEqual([]); + expect(connection.state().phase).toBe("connected"); + } else if (answer === "backoff") { + expect(daemon.healthChecks).toEqual([lostAt + 1_000]); + expect(reopened).toBe(1); + } else { + await vi.advanceTimersByTimeAsync(30_000); + expect(daemon.healthChecks).toEqual([]); + expect(reopened).toBe(0); + expect(connection.state().phase).toBe("disconnected"); + } + connection.dispose(); + } + }); + + it("a stream silent for 40 seconds in a proxy session reconnects at once when the proxy still knows the person", async () => { + const { daemon } = connect(() => Promise.resolve("reconnect")); + await settle(); + + await vi.advanceTimersByTimeAsync(40_000); + + expect(daemon.streams).toHaveLength(2); + expect(daemon.healthChecks).toEqual([]); + }); + it("while disconnected, /v1/healthz is called after 1, 2, 4 and 8 seconds, then every 10", async () => { const { connection, daemon } = connect(); connection.watch("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/v1/workers", () => {}); diff --git a/ui/src/data/live/connection.ts b/ui/src/data/live/connection.ts index 876865510..63c1d61cd 100644 --- a/ui/src/data/live/connection.ts +++ b/ui/src/data/live/connection.ts @@ -54,7 +54,13 @@ interface Resource { again: boolean; } +// why: in a proxy session a loss may be the proxy's own session ending, which only the session can +// tell: `reconnect` (still the proxy's person), `backoff` (Simlock is unreachable) or `stop` (the +// session ended and the session handles it). +export type LostAnswer = "reconnect" | "backoff" | "stop"; + export interface LiveConnectionOptions { + readonly whenLost?: () => Promise; readonly api: LiveApi; readonly clock: Clock; readonly visibility: Visibility; @@ -68,6 +74,7 @@ export class LiveConnection { readonly #api: LiveApi; readonly #clock: Clock; readonly #visibility: Visibility; + readonly #whenLost: (() => Promise) | undefined; readonly #resources = new Map(); readonly #stateListeners = new Set<() => void>(); readonly #eventListeners = new Set<(event: StreamEvent) => void>(); @@ -90,6 +97,7 @@ export class LiveConnection { this.#api = options.api; this.#clock = options.clock; this.#visibility = options.visibility; + this.#whenLost = options.whenLost; this.#stopWatchingVisibility = this.#visibility.subscribe(() => this.#visibilityChanged()); if (!this.#visibility.hidden()) { this.#openStream(); @@ -374,7 +382,28 @@ export class LiveConnection { this.#closeStream(); this.#setState("disconnected"); this.#healthAttempt = 0; - if (!this.#visibility.hidden()) this.#scheduleHealthCheck(); + if (this.#visibility.hidden()) return; + if (this.#whenLost === undefined) this.#scheduleHealthCheck(); + else void this.#askWhenLost(this.#whenLost); + } + + async #askWhenLost(whenLost: () => Promise): Promise { + let answer: LostAnswer; + try { + answer = await whenLost(); + } catch { + answer = "backoff"; + } + // why: a tab shown meanwhile asks `/v1/healthz` itself. + if (this.#disposed || this.#visibility.hidden() || this.#state.phase !== "disconnected") return; + if (answer === "reconnect") this.#reconnect(); + else if (answer === "backoff") this.#scheduleHealthCheck(); + } + + #reconnect(): void { + this.#setState("starting"); + this.#refetchScreen(); + this.#openStream(); } #scheduleHealthCheck(): void { @@ -401,9 +430,7 @@ export class LiveConnection { this.#scheduleHealthCheck(); return; } - this.#setState("starting"); - this.#refetchScreen(); - this.#openStream(); + this.#reconnect(); } #visibilityChanged(): void { diff --git a/ui/src/data/live/test-support.ts b/ui/src/data/live/test-support.ts index 08a9ffc12..6ad5e445e 100644 --- a/ui/src/data/live/test-support.ts +++ b/ui/src/data/live/test-support.ts @@ -1,7 +1,13 @@ import { vi } from "vitest"; import { type ApiPath, type ApiResponse } from "../api"; -import { type Clock, LiveConnection, type LiveApi, type Visibility } from "./connection"; +import { + type Clock, + LiveConnection, + type LiveApi, + type LiveConnectionOptions, + type Visibility, +} from "./connection"; const fakeClock: Clock = { now: () => Date.now(), @@ -132,7 +138,7 @@ class FakeVisibility implements Visibility { } } -export function connect(): { +export function connect(whenLost?: LiveConnectionOptions["whenLost"]): { readonly connection: LiveConnection; readonly daemon: FakeDaemon; readonly visibility: FakeVisibility; @@ -141,7 +147,12 @@ export function connect(): { vi.setSystemTime(new Date("2026-10-02T12:00:00Z")); const daemon = new FakeDaemon(); const visibility = new FakeVisibility(); - const connection = new LiveConnection({ api: daemon, clock: fakeClock, visibility }); + const connection = new LiveConnection({ + api: daemon, + clock: fakeClock, + visibility, + ...(whenLost === undefined ? {} : { whenLost }), + }); return { connection, daemon, visibility }; } diff --git a/ui/src/data/session.test.ts b/ui/src/data/session.test.ts index 7f5470a90..d139cc910 100644 --- a/ui/src/data/session.test.ts +++ b/ui/src/data/session.test.ts @@ -238,17 +238,75 @@ describe("a session behind a sign-in proxy", () => { expect(loading.reload).not.toHaveBeenCalled(); }); - it("keeps the token when a token session gets an answer that is not Simlock's", async () => { - const proxied = page({ healthz, identity: answers(200, ALICE), workers: HTML_403 }); - proxied.storage.setItem("simlock.operatorToken", "slk_op"); - const { api, session } = proxied.open(); + it("keeps the token when a token session gets an answer that is not Simlock's, a 401 or a 403", async () => { + for (const status of [401, 403]) { + const proxied = page({ + healthz, + identity: answers(200, ALICE), + workers: () => new Response("Sign in", { status }), + }); + proxied.storage.setItem("simlock.operatorToken", "slk_op"); + const { api, session } = proxied.open(); + + await api.getJson("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/v1/workers").catch(() => undefined); + await settled(); + + expect(session.state()).toEqual({ kind: "token", token: "slk_op" }); + expect(proxied.storage.getItem("simlock.operatorToken")).toBe("slk_op"); + expect(proxied.calls).not.toContain("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/v1/identity"); + } + }); - await api.getJson("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/v1/workers").catch(() => undefined); - await settled(); + it("counts an unreachable daemon at load as nobody signed in", async () => { + const loading = page({ + identity: () => { + throw new TypeError("Failed to fetch"); + }, + }); + const { session } = loading.open(); - expect(session.state()).toEqual({ kind: "token", token: "slk_op" }); - expect(proxied.storage.getItem("simlock.operatorToken")).toBe("slk_op"); - expect(proxied.calls).not.toContain("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/v1/identity"); + session.start(); + + await vi.waitFor(() => expect(session.state()).toEqual({ kind: "none" })); + expect(loading.reload).not.toHaveBeenCalled(); + }); + + it("tells a lost live connection to reconnect, back off or stop, by the identity check", async () => { + const cases = [ + { answer: "reconnect", identity: answers(200, ALICE), reloads: 0, state: "proxy" }, + { + answer: "backoff", + identity: () => { + throw new TypeError("Failed to fetch"); + }, + reloads: 0, + state: "proxy", + }, + { answer: "stop", identity: HTML_403, reloads: 1, state: "proxy" }, + { answer: "stop", identity: answers(200, { via: "token" }), reloads: 0, state: "none" }, + ] as const; + for (const { answer, identity, reloads, state } of cases) { + const proxied = page({ healthz, identity: answers(200, ALICE) }); + const { session } = proxied.open(); + session.start(); + await vi.waitFor(() => expect(session.state().kind).toBe("proxy")); + proxied.routes.identity = identity; + if (answer === "backoff") delete proxied.routes.healthz; + + expect(await session.lost()).toBe(answer); + + expect(session.state().kind).toBe(state); + expect(proxied.reload).toHaveBeenCalledTimes(reloads); + } + }); + + it("leaves a lost live connection to its backoff outside a proxy session, without a check", async () => { + const proxied = page({ identity: answers(200, ALICE) }); + proxied.storage.setItem("simlock.operatorToken", "slk_op"); + const { session } = proxied.open(); + + expect(await session.lost()).toBe("backoff"); + expect(proxied.calls).toEqual([]); }); it("does not undo a token signed in while the identity check ran", async () => { diff --git a/ui/src/data/session.ts b/ui/src/data/session.ts index 7753c9b8c..b14afd51e 100644 --- a/ui/src/data/session.ts +++ b/ui/src/data/session.ts @@ -1,4 +1,5 @@ import type { ApiFailure, Fetch } from "./api"; +import type { LostAnswer } from "./live/connection"; import { checkIdentity, type IdentityOutcome } from "./identity-check"; const STORAGE_KEY = "simlock.operatorToken"; @@ -22,6 +23,7 @@ export interface Session { state(): SessionState; start(): void; refused(failure: ApiFailure): void; + lost(): Promise; token(): string | undefined; signIn(token: string): void; signOut(): void; @@ -112,6 +114,19 @@ export function createSession(storage: () => Storage, deps?: SessionDeps): Sessi void opening(false); } }, + // why: a proxy session's live connection asks here before its backoff, because a lost stream + // may be the proxy's session ending; any other session is "Simlock is unreachable" as before. + async lost() { + if (state.kind !== "proxy") return "backoff"; + const first = inFlight === undefined; + const running = check(); + if (running === undefined) return "backoff"; + const outcome = await running; + if (outcome.kind === "proxy") return "reconnect"; + if (outcome.kind === "unreachable") return "backoff"; + if (first && state.kind === "proxy") apply(outcome, false); + return "stop"; + }, token: () => token, signIn(next) { store(next); diff --git a/ui/src/state/live.tsx b/ui/src/state/live.tsx index c903e230d..7f47800ab 100644 --- a/ui/src/state/live.tsx +++ b/ui/src/state/live.tsx @@ -9,7 +9,7 @@ import { } from "react"; import type { ApiPath } from "../data/api"; -import { useApi } from "./services"; +import { useApi, useSession } from "./services"; import { browserClock, documentVisibility } from "../data/live/browser"; import { type Clock, @@ -34,12 +34,14 @@ const LiveContext = createContext(undefined); export function LiveProvider({ children }: { readonly children: ReactNode }) { const api = useApi(); + const session = useSession(); const [live, setLive] = useState(undefined); useEffect(() => { const connection = new LiveConnection({ api, clock: browserClock, visibility: documentVisibility, + whenLost: session.lost, }); const ticker = createTicker(browserClock, () => connection.serverNow()); setLive({ connection, ticker }); @@ -47,7 +49,7 @@ export function LiveProvider({ children }: { readonly children: ReactNode }) { ticker.dispose(); connection.dispose(); }; - }, [api]); + }, [api, session]); if (live === undefined) return null; return {children}; } From d6813267f825ab4286bc8e6d1cafcb369daf01a0 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 19 Oct 2026 19:12:28 +0200 Subject: [PATCH 10/11] fix: After a loss, a 5xx or timeout from the identity check keeps the proxy session and backs off; pin the reconnect guards; say the console checks the proxy session first (#716) --- docs/CONSOLE.md | 4 +++- ui/src/data/identity-check.test.ts | 6 ++++++ ui/src/data/identity-check.ts | 10 ++++++++-- ui/src/data/live/connection.test.ts | 23 +++++++++++++++++++++++ ui/src/data/session.test.ts | 6 ++++++ ui/src/data/session.ts | 8 ++++---- 6 files changed, 50 insertions(+), 7 deletions(-) diff --git a/docs/CONSOLE.md b/docs/CONSOLE.md index 2617ef162..a79c8c4ac 100644 --- a/docs/CONSOLE.md +++ b/docs/CONSOLE.md @@ -536,7 +536,9 @@ it): | Daemon is starting | The daemon is back, and is still starting up. | While reconnecting, the console keeps the last data on screen and tries the -daemon again after 1, 2, 4 and 8 seconds, then every 10 seconds. When the +daemon again after 1, 2, 4 and 8 seconds, then every 10 seconds. Behind a +sign-in proxy it first checks that your proxy session is still valid, and +reconnects at once if it is. When the daemon answers, the console refreshes the page and it goes back to Connected. You do not need to reload. diff --git a/ui/src/data/identity-check.test.ts b/ui/src/data/identity-check.test.ts index dbcaabdda..44af48ef7 100644 --- a/ui/src/data/identity-check.test.ts +++ b/ui/src/data/identity-check.test.ts @@ -57,6 +57,12 @@ describe("checkIdentity", () => { expect(outcomes).toEqual(cases.map(([, outcome]) => outcome)); }); + it("after a loss, a 5xx from the identity check counts as unreachable, not none", async () => { + const outcome = await checkIdentity(asking(json(503, simlock("UNAVAILABLE"))).fetch, true); + + expect(outcome).toEqual({ kind: "unreachable" }); + }); + it("asks /v1/healthz when the answer is not Simlock's, and says the proxy's session ended when that answers", async () => { const notSimlock: readonly Answer[] = [ NETWORK_ERROR, diff --git a/ui/src/data/identity-check.ts b/ui/src/data/identity-check.ts index 1063ffe2b..cd78dc891 100644 --- a/ui/src/data/identity-check.ts +++ b/ui/src/data/identity-check.ts @@ -15,7 +15,12 @@ interface Answer { // why: the one place that decides what a failure in a proxy session means. An answer that is not // Simlock's (the proxy's own login page, or a request that never arrived) is told apart from "the // daemon is down" by `/v1/healthz`, which the proxy lets through. -export async function checkIdentity(fetch: Fetch): Promise { +// +// why: at load, a 5xx or a timeout from `/v1/identity` means no proxy session (the page opens with +// the token form); after a stream loss or a failed request in a proxy session it means the daemon +// is not answering, so the session is kept. +export async function checkIdentity(fetch: Fetch, afterLoss = false): Promise { + const unanswered: IdentityOutcome = afterLoss ? { kind: "unreachable" } : { kind: "none" }; let answer: Answer; try { answer = await send("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/v1/identity", { fetch }, async (response) => ({ @@ -23,11 +28,12 @@ export async function checkIdentity(fetch: Fetch): Promise { status: response.status, })); } catch (error: unknown) { - if (error instanceof RequestTimeoutError) return { kind: "none" }; + if (error instanceof RequestTimeoutError) return unanswered; return askHealthz(fetch); } const { body, status } = answer; if ((status === 401 || status === 403) && !hasSimlockErrorCode(body)) return askHealthz(fetch); + if (status >= 500) return unanswered; if (status === 200) return proxyIdentity(body) ?? { kind: "none" }; if (status === 401) { const reason = (body as { error?: { reason?: unknown } }).error?.reason; diff --git a/ui/src/data/live/connection.test.ts b/ui/src/data/live/connection.test.ts index 83ee1ed15..c445fc723 100644 --- a/ui/src/data/live/connection.test.ts +++ b/ui/src/data/live/connection.test.ts @@ -174,6 +174,29 @@ describe("LiveConnection", () => { } }); + it("an answer to reconnect that arrives after the tab was hidden or the connection disposed opens nothing", async () => { + for (const end of ["hidden", "disposed"] as const) { + let answer: (value: "reconnect") => void = () => {}; + const { connection, daemon, visibility } = connect( + () => new Promise((resolve) => (answer = resolve)), + ); + connection.watch("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/v1/workers", () => {}); + await settle(); + daemon.openStream()?.end(); + await settle(); + if (end === "hidden") visibility.set(true); + else connection.dispose(); + const streams = daemon.streams.length; + + answer("reconnect"); + await settle(); + await vi.advanceTimersByTimeAsync(1_000); + + expect(daemon.streams).toHaveLength(streams); + connection.dispose(); + } + }); + it("a stream silent for 40 seconds in a proxy session reconnects at once when the proxy still knows the person", async () => { const { daemon } = connect(() => Promise.resolve("reconnect")); await settle(); diff --git a/ui/src/data/session.test.ts b/ui/src/data/session.test.ts index d139cc910..a5121eb08 100644 --- a/ui/src/data/session.test.ts +++ b/ui/src/data/session.test.ts @@ -282,6 +282,12 @@ describe("a session behind a sign-in proxy", () => { reloads: 0, state: "proxy", }, + { + answer: "backoff", + identity: answers(502, { error: { code: "BAD_GATEWAY" } }), + reloads: 0, + state: "proxy", + }, { answer: "stop", identity: HTML_403, reloads: 1, state: "proxy" }, { answer: "stop", identity: answers(200, { via: "token" }), reloads: 0, state: "none" }, ] as const; diff --git a/ui/src/data/session.ts b/ui/src/data/session.ts index b14afd51e..1ea5f3591 100644 --- a/ui/src/data/session.ts +++ b/ui/src/data/session.ts @@ -53,10 +53,10 @@ export function createSession(storage: () => Storage, deps?: SessionDeps): Sessi ); }; // why: callers while a check runs get its outcome, and only the first applies it. - const check = (): Promise | undefined => { + const check = (afterLoss: boolean): Promise | undefined => { if (deps === undefined) return undefined; if (inFlight !== undefined) return inFlight; - const running = checkIdentity(deps.fetch).finally(() => { + const running = checkIdentity(deps.fetch, afterLoss).finally(() => { inFlight = undefined; }); inFlight = running; @@ -78,7 +78,7 @@ export function createSession(storage: () => Storage, deps?: SessionDeps): Sessi }; const opening = async (atLoad: boolean) => { const first = inFlight === undefined; - const running = check(); + const running = check(!atLoad); if (running === undefined) return set({ kind: "none" }); const outcome = await running; // why: only the caller that started the check applies its outcome, and a token signed in while @@ -119,7 +119,7 @@ export function createSession(storage: () => Storage, deps?: SessionDeps): Sessi async lost() { if (state.kind !== "proxy") return "backoff"; const first = inFlight === undefined; - const running = check(); + const running = check(true); if (running === undefined) return "backoff"; const outcome = await running; if (outcome.kind === "proxy") return "reconnect"; From 1d6dc82e3699d2c5297381d41e495ed4295d1a6b Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 19 Oct 2026 19:22:37 +0200 Subject: [PATCH 11/11] fix: Start no proxy-session ending with a nav click the poll can beat, count no WebKit reload cut-off as a CSP error, and open the stream comment with why: (#716) --- e2e/console/proxy-sign-in.spec.ts | 12 +++++------- src/http/app.ts | 2 +- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/e2e/console/proxy-sign-in.spec.ts b/e2e/console/proxy-sign-in.spec.ts index 715f792fb..cbf6a02f3 100644 --- a/e2e/console/proxy-sign-in.spec.ts +++ b/e2e/console/proxy-sign-in.spec.ts @@ -96,8 +96,8 @@ test.describe("signing in through a proxy", () => { await page.goto(proxied.url); await expect(page.getByText("Signed in as Alice")).toBeVisible(); + // why: the console polls every second, so the next request can come before any click. proxied.setMode("expired"); - await openFromNav(page, "Leases"); await expect(page.getByLabel("Operator token")).toBeVisible(); await expect(page.getByRole("alert")).toHaveText(EXPIRED_LINE); @@ -112,7 +112,6 @@ test.describe("signing in through a proxy", () => { await redirected.goto(proxied.url); await expect(redirected.getByText("Signed in as Alice")).toBeVisible(); proxied.setMode("redirect"); - await openFromNav(redirected, "Leases"); await expect(redirected).toHaveURL(proxied.loginUrl); await expect(redirected.getByRole("heading", { name: "Proxy login" })).toBeVisible(); await redirected.close(); @@ -122,7 +121,6 @@ test.describe("signing in through a proxy", () => { await reloaded.goto(proxied.url); await expect(reloaded.getByText("Signed in as Alice")).toBeVisible(); proxied.setMode("html"); - await openFromNav(reloaded, "Leases"); await expect(reloaded.getByRole("heading", { name: "Proxy sign-in" })).toBeVisible(); proxied.setMode("signed-in"); @@ -132,7 +130,6 @@ test.describe("signing in through a proxy", () => { (window as unknown as { loadedOnce: boolean }).loadedOnce = true; }); proxied.setMode("html"); - await openFromNav(reloaded, "Leases"); await expect(reloaded.getByText("Your sign-in has ended.")).toBeVisible(); await expect(reloaded.getByRole("button", { name: "Sign in again" })).toBeVisible(); @@ -175,13 +172,14 @@ test.describe("signing in through a proxy", () => { await openFromNav(page, label); await expect(page.getByRole("heading", { level: 1, name: label })).toBeVisible(); } + // why: a request the page's Content-Security-Policy refused never reaches the network, but the + // browser reports it as an error. Checked before the reload, which makes WebKit report the + // requests it cuts off as errors too. + expect(errors).toEqual([]); await page.reload(); await expect(page.getByText("Signed in as Alice")).toBeVisible(); expect(requested.length).toBeGreaterThan(0); expect(requested.filter((url) => new URL(url).origin !== origin)).toEqual([]); - // why: a request the page's Content-Security-Policy refused never reaches the network, but the - // browser reports it as an error. - expect(errors).toEqual([]); }); }); diff --git a/src/http/app.ts b/src/http/app.ts index 3118a89d8..3cff6a1c9 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -359,7 +359,7 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa send({ data: serializeRequest({ ...current, state }), event: state.stage }); if (isTerminalStage(state)) end(); }); - // Nothing in this process is driving the request -- one a restarted daemon has not + // why: nothing in this process is driving the request -- one a restarted daemon has not // settled yet -- so no change will ever arrive on this stream: end it rather than // hold it open. The client reconnects and reads the settled state. if (unsubscribe === undefined) {