A desktop coding agent with free access to frontier models.
TypeScript
fix(account): keep the device session when both holders rotate the refresh token
ogsamrat7ead509481d2
diff --git a/apps/desktop/electron/omnirush-account.mjs b/apps/desktop/electron/omnirush-account.mjsindex aeb7b34d..0ca5b1e8 100644--- a/apps/desktop/electron/omnirush-account.mjs+++ b/apps/desktop/electron/omnirush-account.mjs@@ -24,6 +24,12 @@ const LOOPBACK_HOSTNAMES = ["localhost", "127.0.0.1", "::1", "[::1]"];const SECURITY_TOOL = "/usr/bin/security";/** Upper bound on duplicate keychain items removed per service during sign-out. */const MAX_KEYCHAIN_DELETES = 8;+/**+ * How long a rejected refresh waits for the embedded broker's persist before+ * the store concludes the session is gone. The broker's rotation can reach+ * the server before this store's, while its persist is still on its way.+ */+const ROTATION_GRACE_MS = 250;function normalizeCredential(value) {return typeof value === "string" && value.trim() ? value.trim() : null;@@ -93,13 +99,20 @@ async function responseDetail(response) {}}+/**+ * A credential bundle as persisted and handed to the embedded broker. The+ * `rotation` counter says how often the device session was refreshed, by+ * either holder; a bundle written before the counter existed loads as 0.+ * @returns {{ gatewayUrl: string, accessToken: string, refreshToken: string, rotation: number } | null}+ */function validCredentials(value) {if (!value || typeof value !== "object") return null;const gatewayUrl = normalizeGatewayUrl(value.gatewayUrl);const accessToken = normalizeCredential(value.accessToken);const refreshToken = normalizeCredential(value.refreshToken);if (!gatewayUrl || !accessToken || !refreshToken) return null;- return { gatewayUrl, accessToken, refreshToken };+ const rotation = Number.isSafeInteger(value.rotation) && value.rotation >= 0 ? value.rotation : 0;+ return { gatewayUrl, accessToken, refreshToken, rotation };}function controlPlaneBase(gatewayUrl) {@@ -184,10 +197,34 @@ export function createDesktopOmniRushAccountStore({sleep = (milliseconds) => new Promise((resolvePromise) => setTimeout(resolvePromise, milliseconds)),}) {let cached = null;+ // The embedded broker shares this store (persist/latest/invalidate) and+ // rotates the same device session. Every writer is tracked so a reader,+ // the broker's latest() in particular, observes a settled store rather+ // than the pair a rotation is about to replace.let refreshInFlight = null;+ let saveInFlight = null;+ let clearInFlight = null;+ /** Whether the sign-out in flight revokes the session (see save()). */+ let clearRevokesRemote = false;const signedOutPath = `${filePath}.signed-out`;const runSecurity = (args) => execFileImpl(SECURITY_TOOL, args, { timeout: 5_000, maxBuffer: 64 * 1024 });+ /**+ * Resolves once every in-flight refresh, save and sign-out has finished.+ * A refresh ends in a save and a save may queue behind another, so this+ * re-checks a bounded number of times instead of trusting one snapshot.+ * @param {{ includeRefresh?: boolean, includeClear?: boolean }} [options]+ * `refresh()` and `clear()` must not wait for their own promise; a refresh+ * also never waits for a sign-out (which waits for the refresh).+ */+ async function settle({ includeRefresh = true, includeClear = true } = {}) {+ for (let round = 0; round < 8; round += 1) {+ const pending = [includeRefresh ? refreshInFlight : null, saveInFlight, includeClear ? clearInFlight : null].filter(Boolean);+ if (!pending.length) return;+ await Promise.allSettled(pending);+ }+ }+async function safeStorage() {const storage = loadSafeStorage();if (!storage || !(await storage.isAsyncEncryptionAvailable())) return null;@@ -202,14 +239,24 @@ export function createDesktopOmniRushAccountStore({const encrypted = await readFile(filePath);const decrypted = await storage.decryptStringAsync(encrypted);const credentials = validCredentials(JSON.parse(decrypted.result));- if (credentials && decrypted.shouldReEncrypt) await save(credentials);+ if (credentials && decrypted.shouldReEncrypt) await enqueueWrite(credentials);return credentials;} catch {return null;}}+ /**+ * The stored credentials once the store is settled. This is also the+ * broker's `latest()`: it must never answer with a pair that an in-flight+ * refresh, save or sign-out is about to replace.+ */async function load() {+ await settle();+ return readCredentials();+ }++ async function readCredentials() {if (cached) return cached;const stored = await loadFile();if (stored) {@@ -229,14 +276,47 @@ export function createDesktopOmniRushAccountStore({});if (imported) {cached = imported;- await save(imported);+ await enqueueWrite(imported);}return imported;}+ /**+ * Persist a bundle: this store's own rotation, a sign-in, or the embedded+ * broker's rotation (its `persist`). A save that arrives while the user is+ * signing out is dropped, that session is being revoked; one that arrives+ * during a server-driven sign-out lands afterwards, because a broker that+ * just rotated successfully proves the session is alive.+ */async function save(credentials) {const normalized = validCredentials(credentials);if (!normalized) throw new Error("Invalid OmniRush account credential bundle");+ if (clearInFlight) {+ const revoked = clearRevokesRemote;+ await clearInFlight;+ if (revoked) return;+ }+ await enqueueWrite(normalized);+ }++ /**+ * Serialized writer: the broker's persist and this store's own refresh+ * share one temporary file. Internal writes (legacy import, re-encryption)+ * use this directly since they can run inside a sign-out.+ */+ function enqueueWrite(normalized) {+ const previous = saveInFlight;+ const write = (async () => {+ if (previous) await previous.catch(() => undefined);+ await writeCredentials(normalized);+ })();+ saveInFlight = write;+ return write.finally(() => {+ if (saveInFlight === write) saveInFlight = null;+ });+ }++ async function writeCredentials(normalized) {const storage = await safeStorage();if (!storage) throw new Error("Secure desktop credential storage is unavailable");const encrypted = await storage.encryptStringAsync(JSON.stringify(normalized));@@ -261,9 +341,30 @@ export function createDesktopOmniRushAccountStore({?? (localApiSelected ? DEV_GATEWAY_URL : DEFAULT_GATEWAY_URL);}+ /**+ * The pair the store holds now when it differs from the one a caller is+ * about to spend: the embedded broker rotated the session and persisted+ * the result while the caller's profile request was in flight. Spending+ * the caller's pair would be answered 401 (the server retires a refresh+ * token on rotation) and read as a revoked session. Waits for a persist+ * that is still landing before answering.+ * @returns {Promise<typeof cached>} null when the store still agrees with the caller.+ */+ async function rotatedElsewhere(credentials) {+ await settle({ includeRefresh: false, includeClear: false });+ return cached && cached.refreshToken !== credentials.refreshToken ? cached : null;+ }++ /**+ * Rotate the device session, or return the pair another holder rotated to.+ * Resolves null only when the server retired the token and the store+ * agrees nobody rotated it, which is the sign-out signal.+ */async function refresh(credentials) {if (refreshInFlight) return refreshInFlight;refreshInFlight = (async () => {+ const adopted = await rotatedElsewhere(credentials);+ if (adopted) return adopted;const refreshUrl = controlPlaneBase(credentials.gatewayUrl);refreshUrl.pathname += "/device/refresh";const response = await fetchImpl(refreshUrl, {@@ -272,16 +373,32 @@ export function createDesktopOmniRushAccountStore({body: JSON.stringify({ refresh_token: credentials.refreshToken }),signal: AbortSignal.timeout(20_000),});- if (response.status === 401 || response.status === 403) return null;+ if (response.status === 401 || response.status === 403) {+ // The broker's rotation may have reached the server first while its+ // persist is still on its way here: give it a moment to land.+ await sleep(ROTATION_GRACE_MS);+ return rotatedElsewhere(credentials);+ }+ if (response.status === 409) {+ // refresh_token_already_used: the broker is rotating this very token+ // right now. Its persist lands shortly; until then the account is+ // merely unverified, never signed out.+ const rotated = await rotatedElsewhere(credentials);+ if (rotated) return rotated;+ throw new Error("Account refresh in progress elsewhere (409)");+ }if (!response.ok) throw new Error(`Account refresh unavailable (${response.status})`);const payload = await response.json();const refreshed = validCredentials({gatewayUrl: payload.gateway_url ?? credentials.gatewayUrl,accessToken: payload.access_token,refreshToken: payload.refresh_token,+ rotation: credentials.rotation + 1,});if (!refreshed) throw new Error("Account service returned invalid credentials");- await save(refreshed);+ // Not save(): a sign-out waiting for this refresh must see the pair+ // it has to revoke, so this write never queues behind the sign-out.+ await enqueueWrite(refreshed);return refreshed;})().finally(() => {refreshInFlight = null;@@ -312,17 +429,22 @@ export function createDesktopOmniRushAccountStore({return classifyRemoteLogout(response.status, detail);}- async function fetchProfile(credentials, allowRefresh = true) {+ /**+ * @param {number} refreshesLeft Bounded: one refresh may only adopt the+ * broker's pair, whose access token can itself have expired while the app+ * was idle, so a second one is allowed before the session counts as gone.+ */+ async function fetchProfile(credentials, refreshesLeft = 2) {const profileUrl = controlPlaneBase(credentials.gatewayUrl);profileUrl.pathname += "/device/me";const response = await fetchImpl(profileUrl, {headers: { Authorization: `Bearer ${credentials.accessToken}` },signal: AbortSignal.timeout(20_000),});- if (response.status === 401 && allowRefresh) {+ if (response.status === 401 && refreshesLeft > 0) {const refreshed = await refresh(credentials);if (!refreshed) throw new InvalidAccountCredentialsError("Device session expired");- return fetchProfile(refreshed, false);+ return fetchProfile(refreshed, refreshesLeft - 1);}if (response.status === 401 || response.status === 403) {throw new InvalidAccountCredentialsError("Device session expired");@@ -370,7 +492,8 @@ export function createDesktopOmniRushAccountStore({refreshToken: payload.refresh_token,});if (!credentials) throw new Error("Account service returned invalid credentials");- await save(credentials);+ // A brand-new session always lands, even next to a sign-out of the old one.+ await enqueueWrite(credentials);return /** @type {const} */ ({ connected: true, userCode: String(issued.user_code ?? "") });}throw new Error("Account link expired before it was approved");@@ -434,17 +557,36 @@ export function createDesktopOmniRushAccountStore({* @returns {Promise<SignOutOutcome>}*/async function clear({ revokeRemote = true } = {}) {- const credentials = cached ?? await load();- /** @type {SignOutOutcome} */- const outcome = credentials && revokeRemote- ? await remoteLogout(credentials)- : { remoteRevoked: true, reason: "already_revoked" };- cached = null;- await rm(filePath, { force: true });- await mkdir(path.dirname(signedOutPath), { recursive: true });- await writeFile(signedOutPath, "signed-out\n", { mode: 0o600 });- if (revokeRemote) await deleteMacKeychain(KEYCHAIN_SERVICES.gatewayUrl, platform, runSecurity);- return outcome;+ // Claim the gate first (synchronously, so no persist slips in), then wait+ // for a rotation still in flight: signing out under it would revoke a+ // retired token (the live session survives) or let its persist land+ // right over the sign-out. A second sign-out waits for the first.+ /** @type {(value?: unknown) => void} */+ let release = () => {};+ const signOut = new Promise((resolvePromise) => { release = resolvePromise; });+ const previous = clearInFlight;+ clearInFlight = signOut;+ clearRevokesRemote = revokeRemote;+ try {+ if (previous) await previous;+ await settle({ includeClear: false });+ const credentials = cached ?? await readCredentials();+ /** @type {SignOutOutcome} */+ const outcome = credentials && revokeRemote+ ? await remoteLogout(credentials)+ : { remoteRevoked: true, reason: "already_revoked" };+ cached = null;+ // Sentinel first: a reader that slips in between never sees the file+ // without the sentinel and resurrects the account from disk.+ await mkdir(path.dirname(signedOutPath), { recursive: true });+ await writeFile(signedOutPath, "signed-out\n", { mode: 0o600 });+ await rm(filePath, { force: true });+ if (revokeRemote) await deleteMacKeychain(KEYCHAIN_SERVICES.gatewayUrl, platform, runSecurity);+ return outcome;+ } finally {+ if (clearInFlight === signOut) clearInFlight = null;+ release();+ }}return { load, save, authorize, status, clear };diff --git a/apps/desktop/electron/omnirush-account.test.mjs b/apps/desktop/electron/omnirush-account.test.mjsindex 46628e1d..7b8a45aa 100644--- a/apps/desktop/electron/omnirush-account.test.mjs+++ b/apps/desktop/electron/omnirush-account.test.mjs@@ -1,5 +1,5 @@import assert from "node:assert/strict";-import { mkdtemp, readFile } from "node:fs/promises";+import { mkdtemp, readFile, writeFile } from "node:fs/promises";import os from "node:os";import path from "node:path";import test from "node:test";@@ -490,3 +490,211 @@ test("accountServerLabel marks loopback servers as the local API", () => {assert.equal(accountServerLabel(""), null);assert.equal(accountServerLabel(null), null);});++// The embedded broker shares this store and rotates the same device session+// (its persist() is store.save(), its latest() is store.load()). The server+// retires a refresh token on rotation, so whichever holder spends a token+// the other one already rotated is answered 401.++const SHARED_GATEWAY_URL = "https://gateway.example/omnirush/v1";++/** Fake account server: one live pair; a rotation retires the refresh token it spent. */+function fakeAccountServer() {+ const server = {+ access: "access-1",+ refresh: "refresh-1",+ generation: 1,+ expired: new Set(),+ refreshCalls: [],+ holdProfile: null,+ holdRefresh: null,+ holdLogout: null,+ contendNext: false,+ };+ const fetchImpl = async (url, init = {}) => {+ const pathname = new URL(url).pathname;+ const bearer = new Headers(init.headers).get("authorization")?.slice(7) ?? "";+ if (pathname.endsWith("/device/me")) {+ if (server.holdProfile) await server.holdProfile;+ return bearer === server.access && !server.expired.has(bearer)+ ? Response.json({ email: "[email protected]", status: "active" })+ : Response.json({ detail: "device_token_invalid" }, { status: 401 });+ }+ if (pathname.endsWith("/device/refresh")) {+ const token = JSON.parse(init.body).refresh_token;+ server.refreshCalls.push(token);+ // Held before the check, so the other holder can retire the token meanwhile.+ const hold = server.holdRefresh;+ server.holdRefresh = null;+ if (hold) await hold;+ if (server.contendNext) {+ server.contendNext = false;+ return Response.json({ detail: "refresh_token_already_used" }, { status: 409 });+ }+ if (token !== server.refresh) return Response.json({ detail: "refresh_token_invalid_or_expired" }, { status: 401 });+ server.generation += 1;+ server.access = `access-${server.generation}`;+ server.refresh = `refresh-${server.generation}`;+ return Response.json({ access_token: server.access, refresh_token: server.refresh });+ }+ if (pathname.endsWith("/device/logout")) {+ if (server.holdLogout) await server.holdLogout;+ return new Response(null, { status: 204 });+ }+ throw new Error(`Unexpected request ${pathname}`);+ };+ return { server, fetchImpl };+}++function deferred() {+ /** @type {(value?: unknown) => void} */+ let resolve = () => {};+ const promise = new Promise((resolvePromise) => { resolve = resolvePromise; });+ return { promise, resolve };+}++const tick = (milliseconds = 5) => new Promise((resolvePromise) => setTimeout(resolvePromise, milliseconds));++async function connectedStore(fetchImpl, overrides = {}) {+ const options = await storeOptions({ fetchImpl, ...overrides });+ const store = createDesktopOmniRushAccountStore(options);+ await store.save({ gatewayUrl: SHARED_GATEWAY_URL, accessToken: "access-1", refreshToken: "refresh-1" });+ return { store, options };+}++/** What the embedded broker does on a 401: rotate through the same server and persist the result. */+async function brokerRotates(store, fetchImpl, current) {+ const response = await fetchImpl(`${SHARED_GATEWAY_URL.replace(/\/v1$/, "")}/device/refresh`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ refresh_token: current.refreshToken }),+ });+ assert.equal(response.status, 200);+ const payload = await response.json();+ await store.save({+ gatewayUrl: SHARED_GATEWAY_URL,+ accessToken: payload.access_token,+ refreshToken: payload.refresh_token,+ rotation: current.rotation + 1,+ });+}++test("profile check adopts the pair the embedded broker persisted while it was in flight", async () => {+ const { server, fetchImpl } = fakeAccountServer();+ const { store } = await connectedStore(fetchImpl);+ server.expired.add("access-1");+ const profile = deferred();+ server.holdProfile = profile.promise;+ const status = store.status(); // GET /device/me with the expired token is now in flight+ await tick();+ await brokerRotates(store, fetchImpl, { refreshToken: "refresh-1", rotation: 0 }); // 1 -> 2, persisted+ server.holdProfile = null;+ profile.resolve();+ const result = await status; // 401: the closure's refresh-1 is retired and is never spent+ assert.equal(result.connected, true);+ assert.equal(result.email, "[email protected]");+ assert.equal(result.reauthorizationRequired, undefined);+ assert.deepEqual(server.refreshCalls, ["refresh-1"]);+ assert.deepEqual(await store.load(), { gatewayUrl: SHARED_GATEWAY_URL, accessToken: "access-2", refreshToken: "refresh-2", rotation: 1 });+});++test("a refresh rejected because the broker rotated first adopts the persisted pair instead of signing out", async () => {+ const { server, fetchImpl } = fakeAccountServer();+ const { store } = await connectedStore(fetchImpl);+ server.expired.add("access-1");+ const refresh = deferred();+ server.holdRefresh = refresh.promise;+ const status = store.status(); // 401 -> POST /device/refresh with refresh-1, held inside the handler+ await tick();+ await brokerRotates(store, fetchImpl, { refreshToken: "refresh-1", rotation: 0 }); // retires refresh-1+ refresh.resolve();+ const result = await status; // the held refresh is answered 401+ assert.equal(result.connected, true);+ assert.equal(result.email, "[email protected]");+ assert.deepEqual(server.refreshCalls, ["refresh-1", "refresh-1"]);+ assert.equal((await store.load()).refreshToken, "refresh-2");+});++test("load() waits for a rotation in flight so the broker reads the settled pair", async () => {+ const { server, fetchImpl } = fakeAccountServer();+ const slowStorage = {+ ...testStorage(),+ encryptStringAsync: async (value) => {+ await tick(20);+ return Buffer.from(value, "utf8");+ },+ };+ const { store } = await connectedStore(fetchImpl, { loadSafeStorage: () => slowStorage });+ server.expired.add("access-1");+ const refresh = deferred();+ server.holdRefresh = refresh.promise;+ const status = store.status();+ await tick();+ const latest = store.load(); // the broker's latest(), asked mid-rotation+ refresh.resolve();+ assert.deepEqual(await latest, { gatewayUrl: SHARED_GATEWAY_URL, accessToken: "access-2", refreshToken: "refresh-2", rotation: 1 });+ assert.equal((await status).connected, true);+});++test("a contended refresh (409) leaves the account connected until the other holder's pair lands", async () => {+ const { server, fetchImpl } = fakeAccountServer();+ const { store } = await connectedStore(fetchImpl);+ server.expired.add("access-1");+ server.contendNext = true;+ const unverified = await store.status();+ assert.equal(unverified.connected, true);+ assert.equal(unverified.reauthorizationRequired, undefined);+ assert.equal(unverified.email, null);+ assert.equal((await store.load()).refreshToken, "refresh-1");+ await brokerRotates(store, fetchImpl, { refreshToken: "refresh-1", rotation: 0 });+ const verified = await store.status();+ assert.equal(verified.email, "[email protected]");+ assert.deepEqual(server.refreshCalls, ["refresh-1", "refresh-1"]);+});++test("a reader that races the sign-out cannot resurrect the cleared account", async () => {+ const { server, fetchImpl } = fakeAccountServer();+ const { store, options } = await connectedStore(fetchImpl);+ const logout = deferred();+ server.holdLogout = logout.promise;+ const clearing = store.clear();+ await tick();+ const read = store.load(); // the broker's latest(), asked mid-sign-out+ logout.resolve();+ assert.deepEqual(await clearing, { remoteRevoked: true, reason: "revoked" });+ assert.equal(await read, null);+ assert.equal(await store.load(), null);+ assert.equal((await createDesktopOmniRushAccountStore(options).status()).connected, false);+});++test("a broker persist during a user sign-out is dropped; during a server-driven sign-out it lands", async () => {+ const { server, fetchImpl } = fakeAccountServer();+ const { store } = await connectedStore(fetchImpl);+ const logout = deferred();+ server.holdLogout = logout.promise;+ const clearing = store.clear();+ await tick();+ const dropped = store.save({ gatewayUrl: SHARED_GATEWAY_URL, accessToken: "access-2", refreshToken: "refresh-2", rotation: 1 });+ logout.resolve();+ await clearing;+ await dropped;+ assert.equal(await store.load(), null);++ const { store: invalidated } = await connectedStore(fetchImpl);+ const clearingServerDriven = invalidated.clear({ revokeRemote: false });+ const landed = invalidated.save({ gatewayUrl: SHARED_GATEWAY_URL, accessToken: "access-2", refreshToken: "refresh-2", rotation: 1 });+ await clearingServerDriven;+ await landed;+ assert.deepEqual(await invalidated.load(), { gatewayUrl: SHARED_GATEWAY_URL, accessToken: "access-2", refreshToken: "refresh-2", rotation: 1 });+});++test("a bundle persisted before the rotation counter loads as rotation 0 and counts from there", async () => {+ const { server, fetchImpl } = fakeAccountServer();+ const options = await storeOptions({ fetchImpl });+ await writeFile(options.filePath, JSON.stringify({ gatewayUrl: SHARED_GATEWAY_URL, accessToken: "access-1", refreshToken: "refresh-1" }));+ const store = createDesktopOmniRushAccountStore(options);+ assert.deepEqual(await store.load(), { gatewayUrl: SHARED_GATEWAY_URL, accessToken: "access-1", refreshToken: "refresh-1", rotation: 0 });+ server.expired.add("access-1");+ assert.equal((await store.status()).email, "[email protected]");+ assert.equal(JSON.parse(await readFile(options.filePath, "utf8")).rotation, 1);+});diff --git a/apps/desktop/electron/runtime.mjs b/apps/desktop/electron/runtime.mjsindex 667822b5..2a959c5e 100644--- a/apps/desktop/electron/runtime.mjs+++ b/apps/desktop/electron/runtime.mjs@@ -2005,6 +2005,10 @@ export function createRuntimeManager({...gatewayCredentials,persist: (credentials) => omnirushGatewayCredentials.save(credentials),invalidate: () => omnirushGatewayCredentials.clear({ revokeRemote: false }),+ // The account store rotates on its own when it checks the profile;+ // the broker reads it back before treating a dead refresh token as+ // a revoked device.+ latest: () => omnirushGatewayCredentials.load(),// Name and email for the git commit identity default; the account// store owns the profile lookup and its token refresh.profile: async () => {diff --git a/apps/server/src/omnirush-gateway-broker.test.ts b/apps/server/src/omnirush-gateway-broker.test.tsindex 57ebcaf2..fd1b35e0 100644--- a/apps/server/src/omnirush-gateway-broker.test.ts+++ b/apps/server/src/omnirush-gateway-broker.test.ts@@ -1,8 +1,12 @@import { describe, expect, test } from "bun:test";+import { mkdtemp } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { fileURLToPath } from "node:url";import { OmniRushGatewayBroker, guardEventStream } from "./omnirush-gateway-broker.js";import { OmniRushReasoningEffort } from "./opencode-plugins/omnirush-reasoning-effort.js";-import type { OmniRushGatewayCredentials } from "./types.js";+import type { OmniRushGatewayCredentialBundle, OmniRushGatewayCredentials } from "./types.js";type UpstreamCall = { body: Record<string, unknown>; headers: Headers };@@ -270,3 +274,354 @@ describe("upstream stream guard with realistic frame sizes", () => {expect(body).not.toContain("upstream_stream_interrupted");});});++describe("OmniRush gateway broker credential adoption", () => {+ const gatewayUrl = "https://gateway.example/omnirush/v1";+ /** The pair after n-1 rotations of one device session. */+ const bundle = (n: number) => ({ gatewayUrl, accessToken: `access-${n}`, refreshToken: `refresh-${n}`, rotation: n - 1 });++ /** Upstream accepts only `validAccess`; the refresh endpoint retires `deadRefresh` and rotates anything else to 3. */+ function rotatingFetcher(validAccess: string, deadRefresh: string, refreshCalls: string[]) {+ return async (input: string | URL | Request, init?: RequestInit) => {+ const url = new URL(String(input));+ if (url.pathname.endsWith("/device/refresh")) {+ const body = JSON.parse(String(init?.body)) as { refresh_token: string };+ refreshCalls.push(body.refresh_token);+ return body.refresh_token === deadRefresh+ ? Response.json({ detail: "refresh_token_invalid_or_expired" }, { status: 401 })+ : Response.json({ access_token: "access-3", refresh_token: "refresh-3", gateway_url: gatewayUrl });+ }+ const authorization = new Headers(init?.headers).get("authorization");+ return authorization === `Bearer ${validAccess}`+ ? Response.json({ output: [] })+ : Response.json({ error: "expired" }, { status: 401 });+ };+ }++ function adoptingBroker(latest: () => Promise<ReturnType<typeof bundle> | null>, refreshCalls: string[], onInvalidate: () => void) {+ return new OmniRushGatewayBroker({+ credentials: { ...bundle(1), latest, invalidate: async () => onInvalidate() },+ engineToken: "local-engine-token",+ fetch: rotatingFetcher("access-2", "refresh-1", refreshCalls),+ });+ }++ test("adopts credentials the desktop rotated instead of signing the device out", async () => {+ const refreshCalls: string[] = [];+ let invalidated = 0;+ const broker = adoptingBroker(async () => bundle(2), refreshCalls, () => { invalidated += 1; });+ const response = await broker.handle(gatewayRequest({ model: "gpt-6-astra", input: "test" }), "responses");+ expect(response.status).toBe(200);+ expect(refreshCalls).toEqual([]);+ expect(invalidated).toBe(0);+ // A later refresh spends the adopted token, not the retired one.+ expect(await broker.refreshAccessToken()).toBe("access-3");+ expect(refreshCalls).toEqual(["refresh-2"]);+ });++ test("adopts a rotation that landed while its own refresh was in flight", async () => {+ const refreshCalls: string[] = [];+ let invalidated = 0;+ let reads = 0;+ const broker = adoptingBroker(async () => (reads++ === 0 ? bundle(1) : bundle(2)), refreshCalls, () => { invalidated += 1; });+ const response = await broker.collect("session-1234", new Uint8Array([1, 2, 3]));+ expect(response.status).toBe(200);+ expect(refreshCalls).toEqual(["refresh-1"]);+ expect(invalidated).toBe(0);+ });++ test("still signs the device out when the store agrees the session is gone", async () => {+ const refreshCalls: string[] = [];+ let invalidated = 0;+ const broker = adoptingBroker(async () => bundle(1), refreshCalls, () => { invalidated += 1; });+ const response = await broker.handle(gatewayRequest({ model: "gpt-6-astra", input: "test" }), "responses");+ expect(response.status).toBe(401);+ expect(await response.text()).toContain("omnirush_account_required");+ expect(refreshCalls).toEqual(["refresh-1"]);+ await Bun.sleep(1);+ expect(invalidated).toBe(1);+ });++ test("keeps its own pair when the store still holds the one it rotated away from", async () => {+ // The broker rotated 1 -> 2 but its persist failed, so the store is behind, not ahead.+ const refreshCalls: string[] = [];+ let invalidated = 0;+ const broker = new OmniRushGatewayBroker({+ credentials: { ...bundle(2), latest: async () => bundle(1), invalidate: async () => { invalidated += 1; } },+ engineToken: "local-engine-token",+ fetch: rotatingFetcher("access-3", "refresh-1", refreshCalls),+ });+ const response = await broker.handle(gatewayRequest({ model: "gpt-6-astra", input: "test" }), "responses");+ expect(response.status).toBe(200);+ expect(refreshCalls).toEqual(["refresh-2"]);+ expect(invalidated).toBe(0);+ });++ test("never signs out on a contended refresh (409) and adopts the rotation that won it", async () => {+ const refreshCalls: string[] = [];+ let invalidated = 0;+ let stored = bundle(1);+ const broker = new OmniRushGatewayBroker({+ credentials: { ...bundle(1), latest: async () => stored, invalidate: async () => { invalidated += 1; } },+ engineToken: "local-engine-token",+ fetch: async (input, init) => {+ if (new URL(String(input)).pathname.endsWith("/device/refresh")) {+ refreshCalls.push((JSON.parse(String(init?.body)) as { refresh_token: string }).refresh_token);+ return Response.json({ detail: "refresh_token_already_used" }, { status: 409 });+ }+ return new Headers(init?.headers).get("authorization") === "Bearer access-2"+ ? Response.json({ output: [] })+ : Response.json({ error: "expired" }, { status: 401 });+ },+ });+ // Nothing has landed in the store yet: the request fails without a sign-out.+ const contended = await broker.handle(gatewayRequest({ model: "gpt-6-astra", input: "test" }), "responses");+ expect(contended.status).toBe(401);+ expect(await contended.text()).not.toContain("omnirush_account_required");+ expect(refreshCalls).toEqual(["refresh-1"]);+ expect(invalidated).toBe(0);+ // The other holder's rotation lands; the next request adopts it without spending anything.+ stored = bundle(2);+ const adopted = await broker.handle(gatewayRequest({ model: "gpt-6-astra", input: "test" }), "responses");+ expect(adopted.status).toBe(200);+ expect(refreshCalls).toEqual(["refresh-1"]);+ expect(invalidated).toBe(0);+ });++ test("falls back to the pair it held before adopting when the adopted pair is dead too", async () => {+ const refreshCalls: string[] = [];+ let invalidated = 0;+ // The store claims a newer pair the server does not know; the broker's own still rotates.+ const broker = new OmniRushGatewayBroker({+ credentials: { ...bundle(1), latest: async () => bundle(2), invalidate: async () => { invalidated += 1; } },+ engineToken: "local-engine-token",+ fetch: rotatingFetcher("access-3", "refresh-2", refreshCalls),+ });+ const response = await broker.handle(gatewayRequest({ model: "gpt-6-astra", input: "test" }), "responses");+ expect(response.status).toBe(200);+ expect(refreshCalls).toEqual(["refresh-2", "refresh-1"]);+ expect(invalidated).toBe(0);+ });++ test("signs out promptly when the adopted pair and its own are both dead", async () => {+ const refreshCalls: string[] = [];+ let invalidated = 0;+ const broker = new OmniRushGatewayBroker({+ credentials: { ...bundle(1), latest: async () => bundle(2), invalidate: async () => { invalidated += 1; } },+ engineToken: "local-engine-token",+ fetch: async (input, init) => {+ if (new URL(String(input)).pathname.endsWith("/device/refresh")) {+ refreshCalls.push((JSON.parse(String(init?.body)) as { refresh_token: string }).refresh_token);+ return Response.json({ detail: "refresh_token_invalid_or_expired" }, { status: 401 });+ }+ return Response.json({ error: "expired" }, { status: 401 });+ },+ });+ const response = await broker.handle(gatewayRequest({ model: "gpt-6-astra", input: "test" }), "responses");+ expect(response.status).toBe(401);+ expect(await response.text()).toContain("omnirush_account_required");+ expect(refreshCalls).toEqual(["refresh-2", "refresh-1"]);+ await Bun.sleep(1);+ expect(invalidated).toBe(1);+ });+});++/**+ * The embedded broker and the desktop account store share one device+ * session: whichever holder gets a 401 first rotates the refresh token, and+ * the server retires the token it spent. These run the real store against+ * the real broker, wired as apps/desktop/electron/runtime.mjs wires them.+ */+describe("OmniRush gateway broker sharing a device session with the desktop account store", () => {+ const gatewayUrl = "https://gateway.example/omnirush/v1";+ type StoredBundle = OmniRushGatewayCredentialBundle & { rotation: number };+ type AccountStore = {+ load: () => Promise<StoredBundle | null>;+ save: (credentials: OmniRushGatewayCredentialBundle) => Promise<void>;+ status: () => Promise<{ connected: boolean; reauthorizationRequired?: boolean; email?: string | null }>;+ clear: (options?: { revokeRemote?: boolean }) => Promise<unknown>;+ };+ type Fetcher = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;++ /** The account server: one live pair per session; a rotation retires the refresh token it spent. */+ function accountServer() {+ const server = {+ access: "access-1",+ refresh: "refresh-1",+ generation: 1,+ expired: new Set<string>(),+ refreshCalls: [] as string[],+ holdProfile: null as Promise<void> | null,+ contendNext: false,+ onRotate: () => {},+ };+ const fetcher: Fetcher = async (input, init) => {+ const url = new URL(String(input));+ const bearer = new Headers(init?.headers).get("authorization")?.slice(7) ?? "";+ if (url.pathname.endsWith("/device/me")) {+ if (server.holdProfile) await server.holdProfile;+ return bearer === server.access && !server.expired.has(bearer)+ ? Response.json({ email: "[email protected]", status: "active" })+ : Response.json({ detail: "device_token_invalid" }, { status: 401 });+ }+ if (url.pathname.endsWith("/device/refresh")) {+ const { refresh_token: token } = JSON.parse(String(init?.body)) as { refresh_token: string };+ server.refreshCalls.push(token);+ if (server.contendNext) {+ server.contendNext = false;+ return Response.json({ detail: "refresh_token_already_used" }, { status: 409 });+ }+ if (token !== server.refresh) return Response.json({ detail: "refresh_token_invalid_or_expired" }, { status: 401 });+ server.generation += 1;+ server.access = `access-${server.generation}`;+ server.refresh = `refresh-${server.generation}`;+ server.onRotate();+ return Response.json({ access_token: server.access, refresh_token: server.refresh, gateway_url: gatewayUrl });+ }+ return bearer === server.access && !server.expired.has(bearer)+ ? Response.json({ output: [] })+ : Response.json({ error: "expired" }, { status: 401 });+ };+ return { server, fetcher };+ }++ const storeModule = fileURLToPath(new URL("../../desktop/electron/omnirush-account.mjs", import.meta.url));++ async function desktopStore(fetcher: Fetcher, options: { encryptDelayMs?: number; saveFails?: { value: boolean } } = {}): Promise<AccountStore> {+ const { createDesktopOmniRushAccountStore } = await import(storeModule) as {+ createDesktopOmniRushAccountStore: (options: Record<string, unknown>) => AccountStore;+ };+ const directory = await mkdtemp(path.join(os.tmpdir(), "omnirush-shared-session-"));+ const storage = {+ isAsyncEncryptionAvailable: async () => true,+ getSelectedStorageBackend: () => "keychain",+ encryptStringAsync: async (value: string) => {+ if (options.encryptDelayMs) await Bun.sleep(options.encryptDelayMs);+ if (options.saveFails?.value) throw new Error("secure storage unavailable");+ return Buffer.from(value, "utf8");+ },+ decryptStringAsync: async (value: Buffer) => ({ result: value.toString("utf8"), shouldReEncrypt: false }),+ };+ const store = createDesktopOmniRushAccountStore({+ filePath: path.join(directory, "account.bin"),+ loadSafeStorage: () => storage,+ platform: "linux",+ env: { OMNIRUSH_DEV_MODE: "1" },+ fetchImpl: fetcher,+ sleep: async () => undefined,+ execFileImpl: async () => { throw new Error("no keychain"); },+ });+ await store.save({ gatewayUrl, accessToken: "access-1", refreshToken: "refresh-1" });+ return store;+ }++ async function brokerFor(store: AccountStore, fetcher: Fetcher) {+ const credentials = await store.load();+ if (!credentials) throw new Error("store is signed out");+ return new OmniRushGatewayBroker({+ credentials: {+ ...credentials,+ persist: (rotated) => store.save(rotated),+ invalidate: () => store.clear({ revokeRemote: false }).then(() => undefined),+ latest: () => store.load(),+ },+ engineToken: "local-engine-token",+ fetch: fetcher,+ });+ }++ const prompt = () => gatewayRequest({ model: "gpt-6-astra", input: "test" });++ test("the desktop keeps the session the broker rotated while its profile check was in flight", async () => {+ const { server, fetcher } = accountServer();+ const store = await desktopStore(fetcher);+ const broker = await brokerFor(store, fetcher);+ server.expired.add("access-1");+ let releaseProfile = () => {};+ server.holdProfile = new Promise<void>((resolve) => { releaseProfile = resolve; });+ const status = store.status(); // GET /device/me with the expired token is now in flight+ await Bun.sleep(5);+ expect((await broker.handle(prompt(), "responses")).status).toBe(200); // rotates 1 -> 2 and persists+ await Bun.sleep(5);+ expect((await store.load())?.refreshToken).toBe("refresh-2");+ server.holdProfile = null;+ releaseProfile();+ const result = await status; // 401: the closure's refresh-1 is retired; the store's refresh-2 is used instead+ expect(result.connected).toBe(true);+ expect(result.email).toBe("[email protected]");+ expect(result.reauthorizationRequired).toBeUndefined();+ expect(server.refreshCalls).toEqual(["refresh-1"]);+ expect(await store.load()).toMatchObject({ refreshToken: "refresh-2", rotation: 1 });+ });++ test("the broker adopts the desktop's rotation while its save is still landing", async () => {+ const { server, fetcher } = accountServer();+ const store = await desktopStore(fetcher, { encryptDelayMs: 30 });+ const broker = await brokerFor(store, fetcher);+ server.expired.add("access-1");+ const rotated = new Promise<void>((resolve) => { server.onRotate = resolve; });+ const status = store.status(); // 401 -> refresh -> (access-2, refresh-2) -> slow save()+ await rotated;+ const response = await broker.handle(prompt(), "responses"); // its own refresh-1 is retired by now+ expect(response.status).toBe(200);+ expect(server.refreshCalls).toEqual(["refresh-1"]);+ expect((await status).connected).toBe(true);+ expect(await store.load()).toMatchObject({ refreshToken: "refresh-2", rotation: 1 });+ });++ test("the broker spends its own valid pair when its persist failed and the store is behind", async () => {+ const { server, fetcher } = accountServer();+ const saveFails = { value: false };+ const store = await desktopStore(fetcher, { saveFails });+ const broker = await brokerFor(store, fetcher);+ saveFails.value = true; // secure storage is unavailable from now on+ server.expired.add("access-1");+ expect((await broker.handle(prompt(), "responses")).status).toBe(200); // 1 -> 2 in memory only+ await Bun.sleep(5);+ expect(await store.load()).toMatchObject({ refreshToken: "refresh-1", rotation: 0 });+ server.expired.add("access-2"); // an hour later+ expect((await broker.handle(prompt(), "responses")).status).toBe(200); // spends refresh-2, not the store's retired refresh-1+ expect((await broker.handle(prompt(), "responses")).status).toBe(200);+ expect(server.refreshCalls).toEqual(["refresh-1", "refresh-2"]);+ expect(await store.load()).toMatchObject({ refreshToken: "refresh-1" });+ // Once storage is back, the next rotation catches the store up.+ saveFails.value = false;+ server.expired.add("access-3");+ expect((await broker.handle(prompt(), "responses")).status).toBe(200);+ await Bun.sleep(5);+ expect(await store.load()).toMatchObject({ refreshToken: "refresh-4", rotation: 3 });+ });++ test("a contended refresh (409) never signs the device out; the next request adopts the rotation that won", async () => {+ const { server, fetcher } = accountServer();+ const store = await desktopStore(fetcher);+ const broker = await brokerFor(store, fetcher);+ server.expired.add("access-1");+ server.contendNext = true;+ const contended = await broker.handle(prompt(), "responses");+ expect(contended.status).toBe(401);+ expect(await contended.text()).not.toContain("omnirush_account_required");+ expect(await store.load()).toMatchObject({ refreshToken: "refresh-1" });+ // The desktop's rotation lands in the store...+ expect((await store.status()).connected).toBe(true);+ expect(await store.load()).toMatchObject({ refreshToken: "refresh-2", rotation: 1 });+ // ...and the broker adopts it without spending anything.+ expect((await broker.handle(prompt(), "responses")).status).toBe(200);+ expect(server.refreshCalls).toEqual(["refresh-1", "refresh-1"]);+ });++ test("a revoked session the store agrees on still signs the device out promptly", async () => {+ const { server, fetcher } = accountServer();+ const store = await desktopStore(fetcher);+ const broker = await brokerFor(store, fetcher);+ server.expired.add("access-1");+ server.refresh = "revoked-elsewhere"; // the server no longer knows refresh-1+ const response = await broker.handle(prompt(), "responses");+ expect(response.status).toBe(401);+ expect(await response.text()).toContain("omnirush_account_required");+ expect(server.refreshCalls).toEqual(["refresh-1"]);+ await Bun.sleep(5);+ expect(await store.load()).toBeNull();+ expect((await store.status()).connected).toBe(false);+ });+});diff --git a/apps/server/src/omnirush-gateway-broker.ts b/apps/server/src/omnirush-gateway-broker.tsindex 5fbd4e7a..480e9047 100644--- a/apps/server/src/omnirush-gateway-broker.ts+++ b/apps/server/src/omnirush-gateway-broker.ts@@ -89,8 +89,24 @@ type CredentialState = {gatewayUrl: string;accessToken: string;refreshToken: string;+ /** See OmniRushGatewayCredentialBundle.rotation; always known in memory. */+ rotation: number;};+function rotationOf(value: unknown): number {+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0;+}++/** What the refresh endpoint said about the token that was spent. */+type RefreshOutcome =+ | { kind: "rotated" }+ /** 401/403: the server retired or revoked the token. */+ | { kind: "retired" }+ /** 409 refresh_token_already_used: another holder is rotating this very token right now. */+ | { kind: "contended" }+ /** Anything else (5xx, malformed payload): nothing is known about the session. */+ | { kind: "unavailable" };+function normalizedGatewayUrl(value: string): string | null {try {const url = new URL(value.trim());@@ -190,9 +206,16 @@ export class OmniRushGatewayBroker {private readonly engineToken: string;private readonly persist?: OmniRushGatewayCredentials["persist"];private readonly invalidate?: OmniRushGatewayCredentials["invalidate"];+ private readonly latest?: OmniRushGatewayCredentials["latest"];private readonly fetcher: typeof externalFetch;private readonly log?: BrokerOptions["log"];private refreshInFlight: Promise<boolean> | null = null;+ /**+ * The pair this broker held before it adopted one from the store. Spent as+ * a last resort when the adopted pair turns out to be dead too, so a stale+ * store entry cannot sign out a session this broker still holds.+ */+ private previous: CredentialState | null = null;constructor(options: BrokerOptions) {const gatewayUrl = options.credentials ? normalizedGatewayUrl(options.credentials.gatewayUrl) : null;@@ -201,11 +224,13 @@ export class OmniRushGatewayBroker {gatewayUrl,accessToken: options.credentials.accessToken,refreshToken: options.credentials.refreshToken,+ rotation: rotationOf(options.credentials.rotation),}: null;this.engineToken = options.engineToken?.trim() ?? "";this.persist = options.credentials?.persist;this.invalidate = options.credentials?.invalidate;+ this.latest = options.credentials?.latest;this.fetcher = options.fetch ?? externalFetch;this.log = options.log;}@@ -227,12 +252,17 @@ export class OmniRushGatewayBroker {const body = request.method === "GET"? undefined: await this.requestBody(request, normalizedPath);- const tokenUsed = this.state.accessToken;- let response = await this.forward(request, normalizedPath, body, tokenUsed);- const credentialAlreadyRotated = this.state?.accessToken !== tokenUsed;- if (response.status === 401 && this.state && (credentialAlreadyRotated || await this.refresh(tokenUsed))) {+ let spent = this.state.accessToken;+ let response = await this.forward(request, normalizedPath, body, spent);+ // Two rounds at most: the first may only adopt a pair the desktop rotated,+ // whose own access token can have expired while the app was idle.+ for (let round = 0; round < 2 && response.status === 401 && this.state; round += 1) {+ const credentialAlreadyRotated = this.state.accessToken !== spent;+ if (!credentialAlreadyRotated && !(await this.refresh(spent))) break;+ if (!this.state) break;await response.body?.cancel().catch(() => undefined);- response = await this.forward(request, normalizedPath, body);+ spent = this.state.accessToken;+ response = await this.forward(request, normalizedPath, body, spent);}if (response.status === 401 && !this.state) {await response.body?.cancel().catch(() => undefined);@@ -272,9 +302,14 @@ export class OmniRushGatewayBroker {signal: AbortSignal.timeout(30_000),});let response = await send();- const credentialAlreadyRotated = this.state?.accessToken !== tokenUsed;- if (response.status === 401 && this.state && (credentialAlreadyRotated || await this.refresh(tokenUsed))) {+ let spent = tokenUsed;+ // Bounded like handle(): adopt, then spend the adopted refresh token.+ for (let round = 0; round < 2 && response.status === 401 && this.state; round += 1) {+ const credentialAlreadyRotated = this.state.accessToken !== spent;+ if (!credentialAlreadyRotated && !(await this.refresh(spent))) break;+ if (!this.state) break;await response.body?.cancel().catch(() => undefined);+ spent = this.state.accessToken;response = await send();}return response;@@ -325,32 +360,104 @@ export class OmniRushGatewayBroker {return this.refreshInFlight;}+ /**+ * Adopts a rotation performed by another holder of the same device session+ * (the desktop account store refreshes on its own when it checks the+ * profile). The server retires the previous refresh token on rotation and+ * answers it with 401, which this broker would otherwise read as a revoked+ * device and sign the user out. Only a pair rotated more often than this+ * broker's own is newer: a store that still holds the pair this broker+ * already rotated away from (its persist failed) must not win, or the+ * broker would spend a retired token while its own live one goes unused.+ * True when the state changed.+ */+ private async adoptRotatedCredentials(): Promise<boolean> {+ const current = this.state;+ if (!this.latest || !current) return false;+ let stored: OmniRushGatewayCredentialBundle | null;+ try {+ stored = await this.latest();+ } catch {+ return false;+ }+ if (this.state !== current || !stored?.accessToken || !stored.refreshToken) return false;+ if (stored.refreshToken === current.refreshToken) return false;+ const rotation = rotationOf(stored.rotation);+ if (rotation <= current.rotation) return false;+ this.previous = current;+ this.state = {+ gatewayUrl: normalizedGatewayUrl(stored.gatewayUrl) ?? current.gatewayUrl,+ accessToken: stored.accessToken,+ refreshToken: stored.refreshToken,+ rotation,+ };+ this.log?.("info", "omnirush.ai device credentials adopted from the account store", { rotation });+ return true;+ }++ /**+ * One refresh round trip, bounded: adopt a newer stored pair, otherwise+ * spend our own; on rejection adopt again (the store may have settled in+ * the meantime), then fall back once to the pair held before an adoption,+ * and sign out only when every holder agrees the session is gone.+ */private async performRefresh(expectedAccessToken: string): Promise<boolean> {if (!this.state) return false;if (this.state.accessToken !== expectedAccessToken) return true;- const response = await this.fetcher(refreshUrl(this.state.gatewayUrl), {+ if (await this.adoptRotatedCredentials()) return true;+ const spent = this.state;+ const outcome = await this.rotate(spent);+ if (outcome.kind === "rotated") return true;+ if (outcome.kind === "unavailable") return false;+ if (this.state !== spent) return Boolean(this.state);+ // The token may have been spent elsewhere while this call was in flight;+ // a 409 means it is being spent right now. The store settles before it+ // answers, so a rotation that landed there is adopted instead.+ if (await this.adoptRotatedCredentials()) return true;+ if (outcome.kind === "contended") {+ this.log?.("warn", "omnirush.ai device refresh contended; keeping the session for the next attempt");+ return false;+ }+ const previous = this.previous;+ this.previous = null;+ if (previous && previous.refreshToken !== spent.refreshToken) {+ this.log?.("info", "omnirush.ai adopted device credentials rejected; trying the pair held before");+ const fallback = await this.rotate({ ...previous, rotation: Math.max(previous.rotation, spent.rotation) });+ if (fallback.kind === "rotated") return true;+ if (fallback.kind !== "retired") return false;+ if (this.state !== spent) return Boolean(this.state);+ }+ this.state = null;+ void this.invalidate?.().catch(() => undefined);+ return false;+ }++ /** Spends `from.refreshToken`; on success the state is the rotated pair. */+ private async rotate(from: CredentialState): Promise<RefreshOutcome> {+ const response = await this.fetcher(refreshUrl(from.gatewayUrl), {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ refresh_token: this.state.refreshToken }),+ body: JSON.stringify({ refresh_token: from.refreshToken }),signal: AbortSignal.timeout(20_000),});if (!response.ok) {await response.body?.cancel().catch(() => undefined);- if (response.status === 401 || response.status === 403) {- this.state = null;- void this.invalidate?.().catch(() => undefined);- }- return false;+ if (response.status === 401 || response.status === 403) return { kind: "retired" };+ if (response.status === 409) return { kind: "contended" };+ return { kind: "unavailable" };}const payload: unknown = await response.json();- if (!payload || typeof payload !== "object") return false;+ if (!payload || typeof payload !== "object") return { kind: "unavailable" };const accessToken = Reflect.get(payload, "access_token");const refreshToken = Reflect.get(payload, "refresh_token");- const gatewayUrl = normalizedGatewayUrl(String(Reflect.get(payload, "gateway_url") ?? this.state.gatewayUrl));- if (typeof accessToken !== "string" || typeof refreshToken !== "string" || !gatewayUrl) return false;- this.state = { accessToken, refreshToken, gatewayUrl };- void this.persistLatest({ accessToken, refreshToken, gatewayUrl });- return true;+ const gatewayUrl = normalizedGatewayUrl(String(Reflect.get(payload, "gateway_url") ?? from.gatewayUrl));+ if (typeof accessToken !== "string" || typeof refreshToken !== "string" || !gatewayUrl) return { kind: "unavailable" };+ if (!this.state) return { kind: "unavailable" };+ const rotated = { accessToken, refreshToken, gatewayUrl, rotation: from.rotation + 1 };+ this.state = rotated;+ this.previous = null;+ void this.persistLatest(rotated);+ return { kind: "rotated" };}private async persistLatest(credentials: OmniRushGatewayCredentialBundle, attempt = 0): Promise<void> {diff --git a/apps/server/src/types.ts b/apps/server/src/types.tsindex af5a1445..cc542ef3 100644--- a/apps/server/src/types.ts+++ b/apps/server/src/types.ts@@ -87,11 +87,26 @@ export type OmniRushGatewayCredentialBundle = {gatewayUrl: string;accessToken: string;refreshToken: string;+ /**+ * How many times this device session has been rotated, counted by whichever+ * holder performed the rotation. Two holders (the embedded broker and the+ * desktop account store) share one session and only adopt a stored pair+ * that is newer than their own; missing means 0 (bundles persisted before+ * the counter existed, or read from the environment).+ */+ rotation?: number;};export type OmniRushGatewayCredentials = OmniRushGatewayCredentialBundle & {persist?: (credentials: OmniRushGatewayCredentialBundle) => Promise<void>;invalidate?: () => Promise<void>;+ /**+ * The credentials as currently stored. Another holder (the desktop account+ * store checking the profile) may have rotated them since this bundle was+ * read; the broker adopts that rotation instead of spending a refresh token+ * the server already retired, which would look like a revoked device.+ */+ latest?: () => Promise<OmniRushGatewayCredentialBundle | null>;/** Connected account's profile (name and email for the git commit identity default); null when signed out or offline. */profile?: () => Promise<{ email: string | null; displayName: string | null } | null>;};