A desktop coding agent with free access to frontier models.
TypeScript
fix(desktop): one refresh owner; never present a superseded refresh token
Ramshouriesh Rcbb755279fad
diff --git a/apps/desktop/electron/omnirush-account.mjs b/apps/desktop/electron/omnirush-account.mjsindex 8f36a87b..d8efcd37 100644--- a/apps/desktop/electron/omnirush-account.mjs+++ b/apps/desktop/electron/omnirush-account.mjs@@ -1,5 +1,6 @@import { execFile } from "node:child_process";-import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";+import { createHash } from "node:crypto";+import { access, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";import path from "node:path";import { promisify } from "node:util";@@ -34,11 +35,26 @@ 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.+ * The account server still accepts the refresh token its latest rotation+ * replaced for this long (omnirush_device_rotation_grace_seconds). Any other+ * superseded refresh token it receives reads as a sign-in copied to a second+ * device, so this store never sends one.*/-const ROTATION_GRACE_MS = 250;+const SERVER_ROTATION_GRACE_MS = 120_000;+const REFRESH_TIMEOUT_MS = 20_000;+/**+ * A refresh token that may already have been rotated (the answer was lost)+ * is sent again only while that attempt, timeout included, ends inside the+ * server's grace, counted from the first time it was sent.+ */+const REFRESH_RETRY_WINDOW_MS = SERVER_ROTATION_GRACE_MS - REFRESH_TIMEOUT_MS;+const REFRESH_RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 15_000];+const PERSIST_RETRY_MAX_MS = 60_000;+/**+ * Connection failures that prove a request never reached the account server+ * (Node fetch and Electron net spellings), so nothing was rotated.+ */+const NEVER_SENT = /\b(?:ENOTFOUND|EAI_AGAIN|ECONNREFUSED|ENETUNREACH|EHOSTUNREACH|UND_ERR_CONNECT_TIMEOUT|ERR_NAME_NOT_RESOLVED|ERR_NAME_RESOLUTION_FAILED|ERR_INTERNET_DISCONNECTED|ERR_CONNECTION_REFUSED|ERR_CONNECTION_TIMED_OUT|ERR_ADDRESS_UNREACHABLE|ERR_PROXY_CONNECTION_FAILED|ERR_CERT_\w+|ERR_TLS_CERT_\w+|SELF_SIGNED_CERT_IN_CHAIN|DEPTH_ZERO_SELF_SIGNED_CERT|UNABLE_TO_\w+|CERT_HAS_EXPIRED)\b/;const PLAINTEXT_KIND = "omnirush.ai sign-in";const PLAINTEXT_NOTE = "Unencrypted at rest: this system has no keyring. Owner-only file; signing out deletes it.";@@ -118,8 +134,8 @@ 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.+ * `rotation` counter says how often this store refreshed the device session;+ * a bundle written before the counter existed loads as 0.* @returns {{ gatewayUrl: string, accessToken: string, refreshToken: string, rotation: number } | null}*/function validCredentials(value) {@@ -132,6 +148,24 @@ function validCredentials(value) {return { gatewayUrl, accessToken, refreshToken, rotation };}+function tokenHash(token) {+ return createHash("sha256").update(token).digest("hex");+}++/** Names a failure for the log: its code, name or message, never a URL, header or body. */+function failureLabel(error) {+ const code = error?.cause?.code ?? error?.code;+ if (typeof code === "string") return code;+ if (error?.name && error.name !== "Error" && error.name !== "TypeError") return String(error.name);+ return String(error?.message ?? error).slice(0, 160);+}++function neverSent(error) {+ const cause = error?.cause;+ const text = [error?.code, error?.message, cause?.code, cause?.message].filter((value) => typeof value === "string").join(" ");+ return NEVER_SENT.test(text);+}+function controlPlaneBase(gatewayUrl) {const base = new URL(gatewayUrl);base.pathname = base.pathname.replace(/\/+$/, "").replace(/\/v1$/, "");@@ -238,21 +272,48 @@ export function createDesktopOmniRushAccountStore({// written and read back, so later launches keep that --password-store.onKeyringSealed = null,log = (message) => console.warn(message),+ now = () => Date.now(),+ // First pause before a failed save of a rotated pair is tried again; tests shrink it.+ persistRetryBaseMs = 1_000,}) {+ // This store is the one owner of the device session's refresh token: its+ // own profile check and the embedded broker (runtime.mjs wires the+ // broker's `refresh` to refresh() below) both come here, and only here is+ // a refresh token sent. Both run in the Electron main process.+ /** The current pair: the owner's truth, ahead of the disk while a save of it keeps failing. */let cached = null;+ /** The pair a restart would load (the saved file, or the environment/keychain import). */+ let persisted = null;+ /**+ * The current pair's refresh token was sent at `firstSentAt` and no answer+ * settled it: the rotation may have happened with the answer lost.+ * @type {{ hash: string, firstSentAt: number } | null}+ */+ let inFlight = null;+ /** The store dropped a pair it may not present any more; the user signs in again. */+ let signInRequired = false;+ let persistRetry = null;+ let persistRetryAttempt = 0;+ let loading = null;const fileFallback = platform === "linux" && Boolean(fallbackFilePath);let keyringLossLogged = false;let sealedBackendRecorded = 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.+ // 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`;+ /**+ * Written before a refresh token is sent and removed once the rotated pair+ * is saved: after a crash or quit mid-refresh, the next launch knows the+ * token on disk may have been rotated already. It holds a hash of the+ * token, never the token.+ */+ const refreshingPath = `${filePath}.refreshing`;const runSecurity = (args) => (legacyKeychain? execFileImpl(SECURITY_TOOL, args, { timeout: 5_000, maxBuffer: 64 * 1024 }): Promise.reject(new Error("The legacy keychain entries belong to the default production profile")));@@ -364,35 +425,138 @@ export function createDesktopOmniRushAccountStore({async function readCredentials() {if (cached) return cached;+ loading ??= loadCredentials().finally(() => {+ loading = null;+ });+ return loading;+ }++ async function exists(file) {+ return access(file).then(() => true, () => false);+ }++ async function loadCredentials() {const stored = await loadFile();- if (stored) {- cached = stored;- return stored;+ const imported = stored ? null : await legacyCredentials();+ const credentials = stored ?? imported;+ if (!credentials) return null;+ if (!(await usableAfterRestart(credentials))) {+ return forget("The saved omnirush.ai sign-in was being renewed when the app stopped, longer ago than the account server accepts that token again.");}- try {- await readFile(signedOutPath);- return null;- } catch {- // No sign-out sentinel: legacy credentials may be imported once.+ cached = credentials;+ persisted = credentials;+ // A refresh the last exit cut off is finished now, while the server still+ // accepts its token (its access token may keep working a little longer).+ if (inFlight) void refresh(credentials.accessToken).catch(() => undefined);+ if (imported) {+ await enqueueWrite(imported);+ // Imported once: an old keychain copy must never come back later.+ if (!env.OMNIRUSH_REFRESH_TOKEN) {+ await deleteMacKeychain(KEYCHAIN_SERVICES.accessToken, platform, runSecurity);+ await deleteMacKeychain(KEYCHAIN_SERVICES.refreshToken, platform, runSecurity);+ }}- const imported = validCredentials({+ return credentials;+ }++ /**+ * Environment or legacy keychain credentials, imported only while no+ * sign-in is on disk at all: never over a saved sign-in this launch cannot+ * read (a locked or replaced keyring), whose pair is newer, and never after+ * a sign-out.+ */+ async function legacyCredentials() {+ if (await exists(filePath) || (fileFallback && await exists(fallbackFilePath))) return null;+ if (await exists(signedOutPath)) return null;+ return validCredentials({gatewayUrl: env.OMNIRUSH_GATEWAY_URL ?? await readMacKeychain(KEYCHAIN_SERVICES.gatewayUrl, platform, runSecurity),accessToken: env.OMNIRUSH_ACCESS_TOKEN ?? await readMacKeychain(KEYCHAIN_SERVICES.accessToken, platform, runSecurity),refreshToken: env.OMNIRUSH_REFRESH_TOKEN ?? await readMacKeychain(KEYCHAIN_SERVICES.refreshToken, platform, runSecurity),});- if (imported) {- cached = imported;- await enqueueWrite(imported);+ }++ /** @returns {Promise<{ hash: string, rotation: number, firstSentAt: number } | null>} */+ async function readRefreshing() {+ try {+ const value = JSON.parse(await readFile(refreshingPath, "utf8"));+ const valid = typeof value?.refreshTokenSha256 === "string"+ && Number.isSafeInteger(value.rotation) && value.rotation >= 0+ && Number.isSafeInteger(value.firstSentAt) && value.firstSentAt >= 0;+ return valid ? { hash: value.refreshTokenSha256, rotation: value.rotation, firstSentAt: value.firstSentAt } : null;+ } catch {+ return null;+ }+ }++ /** Atomic (temporary file, then rename). `firstSentAt: 0` marks a token never to be sent again. */+ async function writeRefreshing({ hash, rotation, firstSentAt }) {+ await mkdir(path.dirname(refreshingPath), { recursive: true });+ const temporary = `${refreshingPath}.${process.pid}.tmp`;+ const record = { note: "A device sign-in renewal was in flight. Hash only; no token.", refreshTokenSha256: hash, rotation, firstSentAt };+ await writeFile(temporary, `${JSON.stringify(record)}\n`, { mode: 0o600 });+ await rename(temporary, refreshingPath).catch(async (error) => {+ await rm(temporary, { force: true }).catch(() => undefined);+ throw error;+ });+ }++ function withinRetryWindow(firstSentAt, delay = 0) {+ return firstSentAt > 0 && now() + delay - firstSentAt <= REFRESH_RETRY_WINDOW_MS;+ }++ /**+ * Whether a pair read at launch may be used. A refresh of it that was in+ * flight when the app stopped (crash, quit, update) may have rotated it+ * with the answer lost: it is sent again only inside the server's grace,+ * and a pair behind a rotation that was recorded is never used.+ */+ async function usableAfterRestart(credentials) {+ const record = await readRefreshing();+ if (!record) return true;+ const hash = tokenHash(credentials.refreshToken);+ if (record.hash === hash) {+ if (!withinRetryWindow(record.firstSentAt)) return false;+ inFlight = { hash, firstSentAt: record.firstSentAt };+ return true;}- return imported;+ if (record.rotation > credentials.rotation) return false;+ // Left behind by a pair that has since been saved.+ await rm(refreshingPath, { force: true });+ return true;+ }++ /**+ * Ends the local sign-in without sending its refresh token anywhere, not+ * even to /device/logout: it may be superseded, and a superseded token the+ * server receives reads as a copied sign-in. The user signs in again.+ */+ async function forget(reason) {+ log(`[omnirush] ${reason} Asking to sign in again.`);+ await serialize(removeLocalSignIn);+ signInRequired = true;+ return null;+ }++ async function removeLocalSignIn() {+ cached = null;+ persisted = null;+ inFlight = null;+ stopPersistRetry();+ // 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 (fileFallback) await removePlaintextCredentialFile(fallbackFilePath);+ await rm(refreshingPath, { force: true });}/**- * 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.+ * Persist a bundle (a sign-in; this store's own rotations save themselves).+ * A bundle rotated fewer times than the current pair is older and is never+ * written over it. 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.*/async function save(credentials) {const normalized = validCredentials(credentials);@@ -402,19 +566,24 @@ export function createDesktopOmniRushAccountStore({await clearInFlight;if (revoked) return;}+ const current = cached ?? await loadFile();+ if (current && normalized.rotation < current.rotation) {+ log(`[omnirush] Kept the current omnirush.ai sign-in (rotation ${current.rotation}); an older one (rotation ${normalized.rotation}) was not saved over it.`);+ 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.+ * Serialized disk writer: sign-ins, rotations and the refresh record share+ * one queue (and temporary files). Internal writes (legacy import,+ * re-encryption) use it directly since they can run inside a sign-out.*/- function enqueueWrite(normalized) {+ function serialize(task) {const previous = saveInFlight;const write = (async () => {if (previous) await previous.catch(() => undefined);- await writeCredentials(normalized);+ return task();})();saveInFlight = write;return write.finally(() => {@@ -422,6 +591,10 @@ export function createDesktopOmniRushAccountStore({});}+ function enqueueWrite(normalized) {+ return serialize(() => writeCredentials(normalized));+ }+async function writeCredentials(normalized) {const storage = await safeStorage();if (!storage) {@@ -462,6 +635,8 @@ export function createDesktopOmniRushAccountStore({}await rm(signedOutPath, { force: true });cached = normalized;+ persisted = normalized;+ signInRequired = false;}async function configuredGatewayUrl() {@@ -475,68 +650,190 @@ export function createDesktopOmniRushAccountStore({}/**- * 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.+ * The only place a refresh token is sent. The embedded broker and this+ * store's profile check both come here after a 401, with the access token+ * that was refused. One refresh runs at a time; a caller that arrives+ * during one waits for it, then decides against the pair it left, so a+ * refresh token is never spent twice.+ *+ * Resolves the current pair: the one already past `rejectedAccessToken`+ * (no request), or a new rotation, saved before it is handed out. Resolves+ * null once the session is gone and the user has to sign in again. Rejects+ * when no rotation happened right now (offline, refused); the pair is kept.+ * @param {string} rejectedAccessToken*/- async function rotatedElsewhere(credentials) {- await settle({ includeRefresh: false, includeClear: false });- return cached && cached.refreshToken !== credentials.refreshToken ? cached : null;+ async function refresh(rejectedAccessToken) {+ while (refreshInFlight) await refreshInFlight.catch(() => undefined);+ refreshInFlight = (async () => {+ await settle({ includeRefresh: false, includeClear: false });+ const current = await readCredentials();+ if (!current || current.accessToken !== rejectedAccessToken) return current;+ return rotate(current);+ })().finally(() => {+ refreshInFlight = null;+ });+ return refreshInFlight;}/**- * 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.+ * Sends the current pair's refresh token until an answer settles it. After+ * an answer that was lost the same token is sent again, only while inside+ * the server's grace; past it the token is never sent again.*/- 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, {+ async function rotate(current) {+ const started = await beginRefresh(current);+ if (!started) {+ return forget("Renewing the omnirush.ai sign-in got no answer, longer ago than the account server accepts that token again.");+ }+ // Whether an earlier attempt may have rotated the token with its answer lost.+ let unsettled = !started.fresh;+ for (let attempt = 0; ; attempt += 1) {+ const outcome = await sendRefresh(current);+ if (outcome.kind === "rotated") {+ inFlight = null;+ cached = outcome.credentials;+ await persistCurrent();+ return outcome.credentials;+ }+ if (outcome.kind === "retired") {+ return forget("The account server no longer accepts this device's omnirush.ai sign-in.");+ }+ if (outcome.kind === "unchanged" && !unsettled) {+ await endRefresh(current);+ throw new Error(`Account refresh unavailable (${outcome.detail})`);+ }+ // Lost, or refused after an earlier attempt that may have rotated the+ // token: only another attempt inside the grace can settle it.+ unsettled = true;+ const delay = REFRESH_RETRY_DELAYS_MS[Math.min(attempt, REFRESH_RETRY_DELAYS_MS.length - 1)];+ if (!withinRetryWindow(started.firstSentAt, delay)) {+ return forget(`Renewing the omnirush.ai sign-in got no usable answer (${outcome.detail}) before the account server's grace for sending it again ran out.`);+ }+ log(`[omnirush] Renewing the omnirush.ai sign-in got no usable answer (${outcome.detail}); sending the same token again inside the server's grace.`);+ await sleep(delay);+ // A sign-out is waiting for this refresh; it revokes the pair as it is.+ if (clearInFlight) throw new Error("Account refresh stopped for a sign-out");+ }+ }++ /**+ * Records, on disk before it is sent, that `current`'s refresh token is in+ * flight. Resolves null when it may not be sent any more; `fresh` is false+ * when it is being sent again after an attempt that settled nothing.+ * @returns {Promise<{ fresh: boolean, firstSentAt: number } | null>}+ */+ async function beginRefresh(current) {+ const hash = tokenHash(current.refreshToken);+ if (inFlight?.hash === hash) {+ return withinRetryWindow(inFlight.firstSentAt) ? { fresh: false, firstSentAt: inFlight.firstSentAt } : null;+ }+ const firstSentAt = now();+ try {+ await serialize(() => writeRefreshing(persisted.refreshToken === current.refreshToken+ ? { hash, rotation: current.rotation, firstSentAt }+ // The pair a restart would load is already behind this one (its save+ // keeps failing); after this rotation it is two behind and must never+ // be sent again.+ : { hash: tokenHash(persisted.refreshToken), rotation: persisted.rotation, firstSentAt: 0 }));+ } catch (error) {+ log(`[omnirush] Could not record the omnirush.ai sign-in renewal before sending it (${failureLabel(error)}); not renewing now.`);+ throw error;+ }+ inFlight = { hash, firstSentAt };+ return { fresh: true, firstSentAt };+ }++ /** The token was answered without a rotation, or never reached the server: it stays current. */+ async function endRefresh(current) {+ inFlight = null;+ // Otherwise the record guards an older pair on disk and stays.+ if (persisted?.refreshToken === current.refreshToken) await serialize(() => rm(refreshingPath, { force: true }));+ }++ /**+ * One POST /device/refresh. `rotated` carries the new pair; `retired`: the+ * server does not know the token (401/403); `unchanged`: answered without+ * a rotation, or never reached the server; `unknown`: the rotation may+ * have happened with its answer lost (timeout, reset, 408, 409, 5xx other+ * than 503, an unreadable success).+ */+ async function sendRefresh(credentials) {+ const refreshUrl = controlPlaneBase(credentials.gatewayUrl);+ refreshUrl.pathname += "/device/refresh";+ let response;+ try {+ response = await fetchImpl(refreshUrl, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ refresh_token: credentials.refreshToken }),- signal: AbortSignal.timeout(20_000),+ signal: AbortSignal.timeout(REFRESH_TIMEOUT_MS),});- 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})`);+ } catch (error) {+ return { kind: neverSent(error) ? "unchanged" : "unknown", detail: failureLabel(error) };+ }+ if (response.status === 401 || response.status === 403) return { kind: "retired" };+ if (!response.ok) {+ await response.body?.cancel().catch(() => undefined);+ const lost = (response.status >= 500 && response.status !== 503) || response.status === 408 || response.status === 409;+ return { kind: lost ? "unknown" : "unchanged", detail: `HTTP ${response.status}` };+ }+ try {const payload = await response.json();- const refreshed = validCredentials({+ const rotated = 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");- // 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;- });- return refreshInFlight;+ if (rotated) return { kind: "rotated", credentials: rotated };+ } catch {+ // An answer cut off or unreadable counts as lost.+ }+ return { kind: "unknown", detail: "unreadable answer" };+ }++ /**+ * Saves the pair this store just rotated to. Until a save lands the pair+ * stays the in-memory truth (never swapped back for the pair on disk, which+ * it superseded), the refresh record keeps that older pair from being sent+ * after a restart, and the save is retried.+ */+ async function persistCurrent() {+ const pair = cached;+ if (!pair || persisted === pair) return;+ try {+ await serialize(async () => {+ if (cached !== pair) return;+ // Sent already without an answer: its record moves to this pair before the pair lands on disk.+ const unsettled = inFlight?.hash === tokenHash(pair.refreshToken) ? inFlight : null;+ if (unsettled) await writeRefreshing({ hash: unsettled.hash, rotation: pair.rotation, firstSentAt: unsettled.firstSentAt });+ await writeCredentials(pair);+ if (!unsettled) await rm(refreshingPath, { force: true });+ });+ stopPersistRetry();+ } catch (error) {+ persistRetryAttempt += 1;+ log(`[omnirush] Could not save the renewed omnirush.ai sign-in (${failureLabel(error)}, attempt ${persistRetryAttempt}); keeping it in memory and trying again.`);+ schedulePersistRetry();+ }+ }++ function schedulePersistRetry() {+ if (persistRetry) return;+ const delay = Math.min(PERSIST_RETRY_MAX_MS, persistRetryBaseMs * 2 ** Math.min(persistRetryAttempt - 1, 10));+ persistRetry = setTimeout(() => {+ persistRetry = null;+ // A refresh in flight saves its own result; a sign-out drops the pair.+ if (refreshInFlight || clearInFlight) schedulePersistRetry();+ else void persistCurrent();+ }, delay);+ persistRetry.unref?.();+ }++ function stopPersistRetry() {+ if (persistRetry) clearTimeout(persistRetry);+ persistRetry = null;+ persistRetryAttempt = 0;}/**@@ -563,9 +860,10 @@ export function createDesktopOmniRushAccountStore({}/**- * @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.+ * @param {number} refreshesLeft Bounded: one refresh may only hand back a+ * pair rotated earlier (for the broker), 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);@@ -575,7 +873,7 @@ export function createDesktopOmniRushAccountStore({signal: AbortSignal.timeout(20_000),});if (response.status === 401 && refreshesLeft > 0) {- const refreshed = await refresh(credentials);+ const refreshed = await refresh(credentials.accessToken);if (!refreshed) throw new InvalidAccountCredentialsError("Device session expired");return fetchProfile(refreshed, refreshesLeft - 1);}@@ -626,7 +924,13 @@ export function createDesktopOmniRushAccountStore({});if (!credentials) throw new Error("Account service returned invalid credentials");// A brand-new session always lands, even next to a sign-out of the old one.- await enqueueWrite(credentials);+ await serialize(async () => {+ await writeCredentials(credentials);+ // The refresh record belonged to the session this one replaces.+ inFlight = null;+ stopPersistRetry();+ await rm(refreshingPath, { force: true }).catch(() => undefined);+ });return /** @type {const} */ ({ connected: true, userCode: String(issued.user_code ?? "") });}throw new Error("Account link expired before it was approved");@@ -666,6 +970,7 @@ export function createDesktopOmniRushAccountStore({if (fileBacked && await keyringCopyUnreadable()) {return { connected: false, gatewayConfigured, ...server, ...storage, reauthorizationRequired: true, keyringUnavailable: true };}+ if (signInRequired) return { connected: false, gatewayConfigured, ...server, ...storage, reauthorizationRequired: true };return { connected: false, gatewayConfigured, ...server, ...storage };}try {@@ -696,7 +1001,7 @@ export function createDesktopOmniRushAccountStore({};}// Offline profile lookup must not make a securely stored account look- // signed out. Model requests will still use the broker's refresh path.+ // signed out. The next 401 (here or in the broker) refreshes again.return {connected: true,gatewayConfigured,@@ -737,14 +1042,11 @@ export function createDesktopOmniRushAccountStore({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 (fileFallback) await removePlaintextCredentialFile(fallbackFilePath);- if (revokeRemote) await deleteMacKeychain(KEYCHAIN_SERVICES.gatewayUrl, platform, runSecurity);+ await serialize(removeLocalSignIn);+ if (revokeRemote) {+ signInRequired = false;+ await deleteMacKeychain(KEYCHAIN_SERVICES.gatewayUrl, platform, runSecurity);+ }return outcome;} finally {if (clearInFlight === signOut) clearInFlight = null;@@ -752,5 +1054,5 @@ export function createDesktopOmniRushAccountStore({}}- return { load, save, authorize, status, clear };+ return { load, save, refresh, authorize, status, clear };}diff --git a/apps/desktop/electron/omnirush-account.test.mjs b/apps/desktop/electron/omnirush-account.test.mjsindex 4f000f61..b4d744f9 100644--- a/apps/desktop/electron/omnirush-account.test.mjs+++ b/apps/desktop/electron/omnirush-account.test.mjs@@ -541,25 +541,55 @@ test("accountServerLabel marks loopback servers as the local API", () => {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.+// This store is the one owner of the device session's refresh token: the+// embedded broker asks store.refresh() after a 401 instead of refreshing on+// its own (runtime.mjs). The account server accepts the refresh token its+// latest rotation replaced for 120 s; any other superseded token it receives+// reads as a sign-in copied to another device, so the store never sends one.const SHARED_GATEWAY_URL = "https://gateway.example/omnirush/v1";+const SERVER_GRACE_MS = 120_000;++/** A test clock: the store's `now`, and a `sleep` that moves it forward. */+function testClock(start = 1_700_000_000_000) {+ const clock = {+ t: start,+ now: () => clock.t,+ sleep: async (milliseconds) => { clock.t += milliseconds; },+ };+ return clock;+}-/** Fake account server: one live pair; a rotation retires the refresh token it spent. */-function fakeAccountServer() {+/**+ * Fake account server with the backend's rotation rules: a rotation demotes+ * the token it spent to `previous`, still accepted for 120 s (a grace+ * rotation, from the current token), and retires the one before. A token+ * past its grace (previous, or retired longer than 120 s ago) is refused and+ * recorded in `superseded`: the backend's copied-sign-in signal.+ */+function fakeAccountServer(clock = testClock()) {const server = {access: "access-1",refresh: "refresh-1",+ previous: null,+ previousAt: 0,+ retired: new Map(),generation: 1,expired: new Set(),refreshCalls: [],+ refreshTimes: [],+ superseded: [],holdProfile: null,holdRefresh: null,holdLogout: null,- contendNext: false,+ /** Rotate, then lose the answer this many times (the request times out). */+ loseNext: 0,+ /** Time out this many times before the request is handled (nothing rotates). */+ stallNext: 0,+ /** Answer the next refresh with this status before looking at the token. */+ answerNext: null,+ /** Rotate, then never answer: the app is gone (crash, quit) before the answer. */+ hangNext: false,};const fetchImpl = async (url, init = {}) => {const pathname = new URL(url).pathname;@@ -573,18 +603,42 @@ function fakeAccountServer() {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.+ server.refreshTimes.push(clock.now());+ // Held before the check, so a test can act while the request is in flight.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 (server.stallNext > 0) {+ server.stallNext -= 1;+ clock.t += 20_000;+ throw new DOMException("The operation was aborted due to timeout", "TimeoutError");+ }+ if (server.answerNext) {+ const status = server.answerNext;+ server.answerNext = null;+ return Response.json({ detail: "unavailable" }, { status });+ }+ const inGrace = token === server.previous && clock.now() - server.previousAt <= SERVER_GRACE_MS;+ if (token !== server.refresh && !inGrace) {+ const supersededAt = token === server.previous ? server.previousAt : server.retired.get(token);+ if (supersededAt !== undefined && clock.now() - supersededAt > SERVER_GRACE_MS) server.superseded.push(token);+ return Response.json({ detail: "refresh_token_invalid_or_expired" }, { status: 401 });}- if (token !== server.refresh) return Response.json({ detail: "refresh_token_invalid_or_expired" }, { status: 401 });+ if (server.previous) server.retired.set(server.previous, clock.now());+ server.previous = server.refresh;+ server.previousAt = clock.now();server.generation += 1;server.access = `access-${server.generation}`;server.refresh = `refresh-${server.generation}`;+ if (server.hangNext) {+ server.hangNext = false;+ return new Promise(() => {});+ }+ if (server.loseNext > 0) {+ server.loseNext -= 1;+ clock.t += 20_000;+ throw new DOMException("The operation was aborted due to timeout", "TimeoutError");+ }return Response.json({ access_token: server.access, refresh_token: server.refresh });}if (pathname.endsWith("/device/logout")) {@@ -612,57 +666,50 @@ async function connectedStore(fetchImpl, overrides = {}) {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,- });-}+const refreshingFile = (options) => `${options.filePath}.refreshing`;-test("profile check adopts the pair the embedded broker persisted while it was in flight", async () => {+test("concurrent refreshes spend the refresh token once and all get the rotated pair", 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+ const refresh = deferred();+ server.holdRefresh = refresh.promise;+ // The broker (twice) and the profile check all see access-1 refused at once.+ const callers = [store.refresh("access-1"), store.refresh("access-1"), store.status()];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);+ refresh.resolve();+ const [first, second, status] = await Promise.all(callers);assert.deepEqual(server.refreshCalls, ["refresh-1"]);+ assert.equal(first.accessToken, "access-2");+ assert.deepEqual(second, first);+ assert.equal(status.email, "[email protected]");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 () => {+test("a caller refused with an access token that was already rotated gets the current pair without a request", async () => {+ const { server, fetchImpl } = fakeAccountServer();+ const { store } = await connectedStore(fetchImpl);+ assert.equal((await store.refresh("access-1")).accessToken, "access-2");+ // The broker still held access-1 when it was refused.+ assert.equal((await store.refresh("access-1")).accessToken, "access-2");+ assert.deepEqual(server.refreshCalls, ["refresh-1"]);+});++test("a profile check whose token the broker's refresh replaced meanwhile uses the new pair without a request", 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+ const profile = deferred();+ server.holdProfile = profile.promise;+ const status = store.status(); // GET /device/me with the expired token is now in flightawait 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((await store.refresh("access-1")).accessToken, "access-2"); // the broker's 401+ server.holdProfile = null;+ profile.resolve();+ const result = await status;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");+ assert.deepEqual(server.refreshCalls, ["refresh-1"]);});test("load() waits for a rotation in flight so the broker reads the settled pair", async () => {@@ -686,20 +733,241 @@ test("load() waits for a rotation in flight so the broker reads the settled pairassert.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);+test("a lost refresh answer is sent again with the same token inside the grace and converges", async () => {+ const clock = testClock();+ const { server, fetchImpl } = fakeAccountServer(clock);+ const logs = [];+ const { store, options } = await connectedStore(fetchImpl, { now: clock.now, sleep: clock.sleep, log: (line) => logs.push(line) });+ server.loseNext = 1; // the server rotates, the answer times out+ const rotated = await store.refresh("access-1");+ // refresh-1 again, within the grace: the server rotates once more from the current token.+ assert.deepEqual(server.refreshCalls, ["refresh-1", "refresh-1"]);+ assert.equal(server.refreshTimes[1] - server.refreshTimes[0] <= 100_000, true);+ assert.deepEqual(server.superseded, []);+ assert.equal(rotated.refreshToken, server.refresh);+ assert.deepEqual(await createDesktopOmniRushAccountStore(options).load(), rotated);+ assert.equal(await exists(refreshingFile(options)), false);+ assert.equal(logs.some((line) => /same token again/.test(line)), true);+ assert.equal(logs.some((line) => line.includes("refresh-") || line.includes("access-")), false);+});++test("a 409 while the token is being rotated is sent again inside the grace, never signed out", async () => {+ const clock = testClock();+ const { server, fetchImpl } = fakeAccountServer(clock);+ const { store } = await connectedStore(fetchImpl, { now: clock.now, sleep: clock.sleep });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]");+ server.answerNext = 409;+ const status = await store.status();+ assert.equal(status.connected, true);+ assert.equal(status.email, "[email protected]");+ assert.deepEqual(server.refreshCalls, ["refresh-1", "refresh-1"]);+ assert.deepEqual(server.superseded, []);+});++test("a refresh answer lost past the grace: the token is never sent again and the user signs in again", async () => {+ const clock = testClock();+ const { server, fetchImpl } = fakeAccountServer(clock);+ const logs = [];+ const { store, options } = await connectedStore(fetchImpl, { now: clock.now, sleep: clock.sleep, log: (line) => logs.push(line) });+ server.stallNext = 100; // no answer ever arrives+ assert.equal(await store.refresh("access-1"), null);+ const first = server.refreshTimes[0];+ assert.equal(server.refreshCalls.every((token) => token === "refresh-1"), true);+ // Each attempt starts early enough to end (20 s timeout) inside the server's 120 s grace.+ assert.equal(server.refreshTimes.every((time) => time - first <= 100_000), true);+ assert.deepEqual(server.superseded, []);+ const sent = server.refreshCalls.length;+ const status = await store.status();+ assert.equal(status.connected, false);+ assert.equal(status.reauthorizationRequired, true);+ assert.equal(await store.refresh("access-1"), null);+ assert.equal(server.refreshCalls.length, sent);+ // A restart does not bring it back.+ assert.equal(await createDesktopOmniRushAccountStore(options).load(), null);+ assert.equal(server.refreshCalls.length, sent);+ assert.equal(logs.some((line) => /grace for sending it again ran out/.test(line)), true);+});++/** Starts a refresh whose answer never arrives: the app is gone before it lands. */+async function crashMidRefresh(overrides = {}) {+ const clock = testClock();+ const { server, fetchImpl } = fakeAccountServer(clock);+ const { store, options } = await connectedStore(fetchImpl, { now: clock.now, sleep: clock.sleep, ...overrides });+ server.hangNext = true;+ void store.refresh("access-1");+ while (server.refreshCalls.length === 0) await tick(1);+ // The record was on disk before the token was sent; the server rotated.+ const record = JSON.parse(await readFile(refreshingFile(options), "utf8"));+ assert.equal(record.firstSentAt, clock.t);+ assert.equal(JSON.stringify(record).includes("refresh-1"), false);+ return { clock, server, options };+}++test("a restart after the grace never presents the token a crash left in flight; the user signs in again", async () => {+ const { clock, server, options } = await crashMidRefresh();+ clock.t += SERVER_GRACE_MS + 30_000;+ const restarted = createDesktopOmniRushAccountStore(options);+ assert.equal(await restarted.load(), null);+ const status = await restarted.status();+ assert.equal(status.connected, false);+ assert.equal(status.reauthorizationRequired, true);+ assert.deepEqual(server.refreshCalls, ["refresh-1"]);+ assert.deepEqual(server.superseded, []);+ assert.equal(await exists(options.filePath), false);+ assert.equal(await exists(refreshingFile(options)), false);+});++test("a restart inside the grace finishes the refresh a crash cut off, with the same token", async () => {+ const { clock, server, options } = await crashMidRefresh();+ clock.t += 30_000;+ const restarted = createDesktopOmniRushAccountStore(options);+ assert.equal((await restarted.load()).refreshToken, "refresh-1");+ // Sent again at once, while the server still accepts it.+ const current = await restarted.refresh("access-1");assert.deepEqual(server.refreshCalls, ["refresh-1", "refresh-1"]);+ assert.equal(current.refreshToken, server.refresh);+ assert.deepEqual(server.superseded, []);+ assert.equal(await exists(refreshingFile(options)), false);+});++/** A store whose secure storage fails once `broken.value` is set. */+function breakableStorage(broken) {+ return {+ ...testStorage(),+ encryptStringAsync: async (value) => {+ if (broken.value) throw new Error("Secure desktop credential storage is unavailable");+ return Buffer.from(value, "utf8");+ },+ };+}++test("a failed save keeps the rotated pair in use, retries and logs it, and never sends the pair it replaced", async () => {+ const clock = testClock();+ const { server, fetchImpl } = fakeAccountServer(clock);+ const logs = [];+ const broken = { value: false };+ const { store, options } = await connectedStore(fetchImpl, {+ now: clock.now,+ sleep: clock.sleep,+ loadSafeStorage: () => breakableStorage(broken),+ log: (line) => logs.push(line),+ persistRetryBaseMs: 5,+ });+ broken.value = true;+ server.expired.add("access-1");+ assert.equal((await store.status()).email, "[email protected]");+ // The new pair is the truth in memory; the disk still has the old one.+ assert.equal((await store.load()).refreshToken, "refresh-2");+ assert.match(await readFile(options.filePath, "utf8"), /refresh-1/);+ await tick(40);+ assert.equal(logs.filter((line) => /Could not save the renewed omnirush\.ai sign-in/.test(line)).length > 1, true);++ // An hour later the next rotation spends refresh-2, never refresh-1.+ clock.t += 3_600_000;+ server.expired.add("access-2");+ assert.equal((await store.refresh("access-2")).refreshToken, "refresh-3");+ assert.deepEqual(server.refreshCalls, ["refresh-1", "refresh-2"]);+ assert.deepEqual(server.superseded, []);+ // The pair on disk is two rotations behind now: no restart may send it.+ assert.equal(JSON.parse(await readFile(refreshingFile(options), "utf8")).firstSentAt, 0);++ // Storage comes back: the retry saves the current pair and drops the record.+ broken.value = false;+ for (let waited = 0; waited < 200 && await exists(refreshingFile(options)); waited += 1) await tick(5);+ assert.match(await readFile(options.filePath, "utf8"), /refresh-3/);+ assert.equal(await exists(refreshingFile(options)), false);+ assert.equal((await createDesktopOmniRushAccountStore(options).load()).refreshToken, "refresh-3");+});++test("a quit or crash between a rotation and its save never presents the replaced token after the grace", async () => {+ const clock = testClock();+ const { server, fetchImpl } = fakeAccountServer(clock);+ const broken = { value: false };+ const { store, options } = await connectedStore(fetchImpl, { now: clock.now, sleep: clock.sleep, loadSafeStorage: () => breakableStorage(broken) });+ broken.value = true;+ server.expired.add("access-1");+ assert.equal((await store.status()).connected, true); // rotated to refresh-2, saved nowhere+ // The app is gone; it starts again later with working storage.+ clock.t += SERVER_GRACE_MS + 1;+ const restarted = createDesktopOmniRushAccountStore({ ...options, loadSafeStorage: () => testStorage() });+ assert.equal(await restarted.load(), null);+ const status = await restarted.status();+ assert.equal(status.connected, false);+ assert.equal(status.reauthorizationRequired, true);+ assert.deepEqual(server.refreshCalls, ["refresh-1"]);+ assert.deepEqual(server.superseded, []);+});++test("a refresh that never reached the server keeps the pair and leaves nothing to guard", async () => {+ const clock = testClock();+ const { server, fetchImpl } = fakeAccountServer(clock);+ let offline = true;+ const { store, options } = await connectedStore(async (url, init) => {+ if (offline && new URL(url).pathname.endsWith("/device/refresh")) {+ throw new TypeError("fetch failed", { cause: Object.assign(new Error("getaddrinfo ENOTFOUND gateway.example"), { code: "ENOTFOUND" }) });+ }+ return fetchImpl(url, init);+ }, { now: clock.now, sleep: clock.sleep });+ await assert.rejects(store.refresh("access-1"), /Account refresh unavailable \(ENOTFOUND\)/);+ assert.equal((await store.load()).refreshToken, "refresh-1");+ assert.equal(await exists(refreshingFile(options)), false);+ // Back online much later: refresh-1 was never spent, so it is sent as usual.+ offline = false;+ clock.t += 3_600_000;+ assert.equal((await store.refresh("access-1")).refreshToken, "refresh-2");+ assert.deepEqual(server.refreshCalls, ["refresh-1"]);+});++test("save() never writes a pair rotated fewer times over the current one", async () => {+ const { fetchImpl } = fakeAccountServer();+ const logs = [];+ const { store, options } = await connectedStore(fetchImpl, { log: (line) => logs.push(line) });+ await store.refresh("access-1");+ await store.refresh("access-2");+ assert.equal((await store.load()).rotation, 2);+ await store.save({ gatewayUrl: SHARED_GATEWAY_URL, accessToken: "access-2", refreshToken: "refresh-2", rotation: 1 });+ assert.deepEqual(await store.load(), { gatewayUrl: SHARED_GATEWAY_URL, accessToken: "access-3", refreshToken: "refresh-3", rotation: 2 });+ // A fresh process reading the file first refuses it as well.+ const restarted = createDesktopOmniRushAccountStore(options);+ await restarted.save({ gatewayUrl: SHARED_GATEWAY_URL, accessToken: "access-1", refreshToken: "refresh-1" });+ assert.equal((await restarted.load()).refreshToken, "refresh-3");+ assert.equal(logs.some((line) => /was not saved over it/.test(line)), true);+});++test("a saved sign-in this launch cannot read is never replaced by environment or keychain credentials", async () => {+ const requests = [];+ const options = await storeOptions({+ env: LEGACY_ENV,+ fetchImpl: async (url) => {+ requests.push(new URL(url).pathname);+ return Response.json({ email: "[email protected]", status: "active" });+ },+ // The keyring that sealed the file is not the one this launch has.+ loadSafeStorage: () => ({ ...testStorage(), decryptStringAsync: async () => { throw new Error("cannot decrypt"); } }),+ });+ await writeFile(options.filePath, "sealed by another keyring");+ const store = createDesktopOmniRushAccountStore(options);+ assert.equal(await store.load(), null);+ assert.equal((await store.status()).connected, false);+ assert.deepEqual(requests, []);+ assert.equal(await readFile(options.filePath, "utf8"), "sealed by another keyring");+});++test("the legacy keychain pair is imported once and removed, so it can never come back", async () => {+ const keychain = fakeMacKeychain({+ [KEYCHAIN_SERVICES.gatewayUrl]: "https://omnirush.ai/omnirush/v1",+ [KEYCHAIN_SERVICES.accessToken]: "old-access",+ [KEYCHAIN_SERVICES.refreshToken]: "old-refresh",+ });+ const options = await storeOptions({+ platform: "darwin",+ env: {},+ legacyKeychain: true,+ execFileImpl: keychain.execFileImpl,+ fetchImpl: async () => Response.json({ email: "[email protected]", status: "active" }),+ });+ assert.equal((await createDesktopOmniRushAccountStore(options).load()).refreshToken, "old-refresh");+ assert.deepEqual([...keychain.items.keys()], [KEYCHAIN_SERVICES.gatewayUrl]);});test("a reader that races the sign-out cannot resurrect the cleared account", async () => {@@ -717,7 +985,7 @@ test("a reader that races the sign-out cannot resurrect the cleared account", asassert.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 () => {+test("a save 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();diff --git a/apps/desktop/electron/runtime.mjs b/apps/desktop/electron/runtime.mjsindex 6bc4a24c..6eabcde3 100644--- a/apps/desktop/electron/runtime.mjs+++ b/apps/desktop/electron/runtime.mjs@@ -2227,11 +2227,11 @@ export function createRuntimeManager({omnirushGatewayCredentials: gatewayCredentials? {...gatewayCredentials,- persist: (credentials) => omnirushGatewayCredentials.save(credentials),+ // The account store is the one owner of the refresh token: the+ // broker asks it after a 401 and never refreshes on its own, so+ // no superseded refresh token is ever sent.+ refresh: (rejectedAccessToken) => omnirushGatewayCredentials.refresh(rejectedAccessToken),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.diff --git a/apps/server/src/omnirush-gateway-broker.test.ts b/apps/server/src/omnirush-gateway-broker.test.tsindex 8cb5e23b..f3eff598 100644--- a/apps/server/src/omnirush-gateway-broker.test.ts+++ b/apps/server/src/omnirush-gateway-broker.test.ts@@ -6,7 +6,7 @@ import { fileURLToPath } from "node:url";import { OmniRushGatewayBroker, guardEventStream } from "./omnirush-gateway-broker.js";import { OmniRushReasoningEffort } from "./opencode-plugins/omnirush-reasoning-effort.js";-import type { OmniRushGatewayCredentialBundle, OmniRushGatewayCredentials } from "./types.js";+import type { OmniRushGatewayCredentialBundle } from "./types.js";type UpstreamCall = { body: Record<string, unknown>; headers: Headers };@@ -39,7 +39,6 @@ function gatewayRequest(body: Record<string, unknown>, headers: Record<string, sdescribe("OmniRush gateway broker", () => {test("refreshes one expired credential and retries concurrent requests with the rotated token", async () => {let refreshCalls = 0;- const persisted: Array<Omit<OmniRushGatewayCredentials, "persist">> = [];const fetcher = async (input: string | URL | Request, init?: RequestInit) => {const url = new URL(String(input));if (url.pathname.endsWith("/device/refresh")) {@@ -61,7 +60,6 @@ describe("OmniRush gateway broker", () => {gatewayUrl: "https://gateway.example/omnirush/v1",accessToken: "expired-access",refreshToken: "old-refresh",- persist: async (credentials) => { persisted.push(credentials); },},engineToken: "local-engine-token",fetch: fetcher,@@ -75,8 +73,6 @@ describe("OmniRush gateway broker", () => {const responses = await Promise.all([request(), request()]);expect(responses.map((response) => response.status)).toEqual([200, 200]);expect(refreshCalls).toBe(1);- await Bun.sleep(1);- expect(persisted.at(-1)?.refreshToken).toBe("new-refresh");expect(responses[0]?.headers.get("x-omnirush-model")).toBe("gpt-6-astra");});@@ -306,163 +302,106 @@ describe("upstream stream guard with realistic frame sizes", () => {});});-describe("OmniRush gateway broker credential adoption", () => {+describe("OmniRush gateway broker with a refresh owner", () => {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[]) {+ /** Upstream accepts only the access tokens in `valid`; a refresh request fails the test. */+ function upstream(valid: Set<string>, bearers: 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 });+ if (new URL(String(input)).pathname.endsWith("/device/refresh")) throw new Error("the broker sent a refresh token");+ const bearer = new Headers(init?.headers).get("authorization")?.slice(7) ?? "";+ bearers.push(bearer);+ return valid.has(bearer) ? Response.json({ output: [] }) : Response.json({ error: "expired" }, { status: 401 });};}- function adoptingBroker(latest: () => Promise<ReturnType<typeof bundle> | null>, refreshCalls: string[], onInvalidate: () => void) {+ function ownedBroker(owner: (rejected: string) => Promise<ReturnType<typeof bundle> | null>, valid: Set<string>, bearers: string[], onInvalidate = () => {}) {return new OmniRushGatewayBroker({- credentials: { ...bundle(1), latest, invalidate: async () => onInvalidate() },+ credentials: { ...bundle(1), refresh: owner, invalidate: async () => onInvalidate() },engineToken: "local-engine-token",- fetch: rotatingFetcher("access-2", "refresh-1", refreshCalls),+ fetch: upstream(valid, bearers),});}- 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; });+ test("asks the owner after a 401 and never sends a refresh token itself", async () => {+ const asked: string[] = [];+ const bearers: string[] = [];+ const broker = ownedBroker(async (rejected) => {+ asked.push(rejected);+ return bundle(2);+ }, new Set(["access-2"]), bearers);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"]);+ expect(asked).toEqual(["access-1"]);+ expect(bearers).toEqual(["access-1", "access-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.uploadSession("session-1234", new Uint8Array([1, 2, 3]));- expect(response.status).toBe(200);- expect(refreshCalls).toEqual(["refresh-1"]);- expect(invalidated).toBe(0);+ test("a later 401 hands the owner the pair it gave last, so only the current pair is ever rotated", async () => {+ const asked: string[] = [];+ const valid = new Set(["access-2"]);+ const broker = ownedBroker(async (rejected) => {+ asked.push(rejected);+ return bundle(Number(rejected.slice("access-".length)) + 1);+ }, valid, []);+ expect((await broker.handle(gatewayRequest({ model: "gpt-6-astra", input: "test" }), "responses")).status).toBe(200);+ valid.delete("access-2");+ valid.add("access-3");+ expect((await broker.modelCatalog()).status).toBe(200);+ expect(await broker.refreshAccessToken()).toBe("access-4");+ expect(asked).toEqual(["access-1", "access-2", "access-3"]);});- test("still signs the device out when the store agrees the session is gone", async () => {- const refreshCalls: string[] = [];+ test("concurrent 401s ask the owner once", async () => {+ let asked = 0;+ const broker = ownedBroker(async () => {+ asked += 1;+ await Bun.sleep(10);+ return bundle(2);+ }, new Set(["access-2"]), []);+ const responses = await Promise.all([+ broker.handle(gatewayRequest({ model: "gpt-6-astra", input: "one" }), "responses"),+ broker.handle(gatewayRequest({ model: "gpt-6-astra", input: "two" }), "responses"),+ broker.uploadSession("session-1234", new Uint8Array([1, 2, 3])),+ ]);+ expect(responses.map((response) => response.status)).toEqual([200, 200, 200]);+ expect(asked).toBe(1);+ });++ test("signs the device out when the owner reports the session gone", async () => {let invalidated = 0;- const broker = adoptingBroker(async () => bundle(1), refreshCalls, () => { invalidated += 1; });+ const broker = ownedBroker(async () => null, new Set(), [], () => { 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");- // A retryable answer, not a sign-in error that would end the turn.- expect(contended.status).toBe(503);- 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[] = [];+ test("an owner that cannot rotate right now keeps the session and answers a retryable 503", async () => {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),- });+ let offline = true;+ const broker = ownedBroker(async () => {+ if (offline) throw new Error("Account refresh unavailable (ENOTFOUND)");+ return bundle(2);+ }, new Set(["access-2"]), [], () => { invalidated += 1; });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(response.status).toBe(503);+ expect(await response.text()).toContain("device_refresh_unavailable");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);+ offline = false;+ expect((await broker.handle(gatewayRequest({ model: "gpt-6-astra", input: "test" }), "responses")).status).toBe(200);});});/*** 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.+ * session. The store is its one refresh owner: the broker asks it after a+ * 401 and never refreshes on its own. These run the real store against the+ * real broker, wired as apps/desktop/electron/runtime.mjs wires them. The+ * account server accepts the refresh token its latest rotation replaced for+ * 120 s; any other superseded token it receives reads as a copied sign-in.*/describe("OmniRush gateway broker sharing a device session with the desktop account store", () => {const gatewayUrl = "https://gateway.example/omnirush/v1";@@ -470,28 +409,29 @@ describe("OmniRush gateway broker sharing a device session with the desktop accotype AccountStore = {load: () => Promise<StoredBundle | null>;save: (credentials: OmniRushGatewayCredentialBundle) => Promise<void>;+ refresh: (rejectedAccessToken: string) => Promise<StoredBundle | null>;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. */+ /** The account server: a rotation demotes the spent token to `previous` (120 s grace) and retires the one before. */function accountServer() {const server = {access: "access-1",refresh: "refresh-1",+ previous: null as string | null,generation: 1,expired: new Set<string>(),refreshCalls: [] as string[],- holdProfile: null as Promise<void> | null,- contendNext: false,- onRotate: () => {},+ /** Superseded refresh tokens presented outside the grace: the backend's copied-sign-in signal. */+ superseded: [] as string[],+ holdRefresh: null as Promise<void> | null,};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 });@@ -499,15 +439,18 @@ describe("OmniRush gateway broker sharing a device session with the desktop accoif (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 });+ const hold = server.holdRefresh;+ server.holdRefresh = null;+ if (hold) await hold;+ // Every call here happens well inside the 120 s grace.+ if (token !== server.refresh && token !== server.previous) {+ if (/^refresh-\d+$/.test(token)) server.superseded.push(token);+ return Response.json({ detail: "refresh_token_invalid_or_expired" }, { status: 401 });}- if (token !== server.refresh) return Response.json({ detail: "refresh_token_invalid_or_expired" }, { status: 401 });+ server.previous = server.refresh;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)@@ -517,19 +460,27 @@ describe("OmniRush gateway broker sharing a device session with the desktop accoreturn { server, fetcher };}+ /** The broker's own fetch: model and API calls only; it must never reach the refresh endpoint. */+ function brokerFetch(fetcher: Fetcher): Fetcher {+ return async (input, init) => {+ if (new URL(String(input)).pathname.endsWith("/device/refresh")) throw new Error("the broker sent a refresh token");+ return fetcher(input, init);+ };+ }+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> {+ async function desktopStore(fetcher: Fetcher, options: { saveFails?: { value: boolean }; logs?: string[]; where?: { filePath: string } } = {}): 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-"));+ if (options.where) options.where.filePath = path.join(directory, "account.bin");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");+ if (options.saveFails?.value) throw new Error("Secure desktop credential storage is unavailable");return Buffer.from(value, "utf8");},decryptStringAsync: async (value: Buffer) => ({ result: value.toString("utf8"), shouldReEncrypt: false }),@@ -542,6 +493,8 @@ describe("OmniRush gateway broker sharing a device session with the desktop accofetchImpl: fetcher,sleep: async () => undefined,execFileImpl: async () => { throw new Error("no keychain"); },+ log: (line: string) => options.logs?.push(line),+ persistRetryBaseMs: 5,});await store.save({ gatewayUrl, accessToken: "access-1", refreshToken: "refresh-1" });return store;@@ -553,93 +506,71 @@ describe("OmniRush gateway broker sharing a device session with the desktop accoreturn new OmniRushGatewayBroker({credentials: {...credentials,- persist: (rotated) => store.save(rotated),+ refresh: (rejectedAccessToken) => store.refresh(rejectedAccessToken),invalidate: () => store.clear({ revokeRemote: false }).then(() => undefined),latest: () => store.load(),},engineToken: "local-engine-token",- fetch: fetcher,+ fetch: brokerFetch(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 () => {+ test("the store and the broker racing a refresh spend the token once and end on the same pair", 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();+ let release = () => {};+ server.holdRefresh = new Promise<void>((resolve) => { release = resolve; });+ // The profile check and two model requests all see access-1 refused at once.+ const racing = Promise.all([store.status(), broker.handle(prompt(), "responses"), broker.handle(prompt(), "responses")]);+ await Bun.sleep(10);+ release();+ const [status, first, second] = await racing;+ expect(status.email).toBe("[email protected]");+ expect([first.status, second.status]).toEqual([200, 200]);expect(server.refreshCalls).toEqual(["refresh-1"]);- expect(await store.load()).toMatchObject({ refreshToken: "refresh-2", rotation: 1 });+ expect(await store.load()).toMatchObject({ accessToken: "access-2", refreshToken: "refresh-2", rotation: 1 });+ expect(await broker.refreshAccessToken()).toBe("access-3"); // the broker holds the store's pair: it rotates refresh-2+ expect(server.refreshCalls).toEqual(["refresh-1", "refresh-2"]);+ expect(server.superseded).toEqual([]);});- test("the broker adopts the desktop's rotation while its save is still landing", async () => {+ test("a broker 401 after the store rotated uses the store's pair; the old refresh token is never sent", async () => {const { server, fetcher } = accountServer();- const store = await desktopStore(fetcher, { encryptDelayMs: 30 });+ const store = await desktopStore(fetcher);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((await store.status()).email).toBe("[email protected]"); // the store rotates 1 -> 2+ expect((await broker.handle(prompt(), "responses")).status).toBe(200); // access-1 refused, access-2 used+ expect((await broker.modelCatalog()).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 });+ expect(server.superseded).toEqual([]);});- test("the broker spends its own valid pair when its persist failed and the store is behind", async () => {+ test("a failed save keeps the rotated pair in use by both and retries it; the pair it replaced is never sent", async () => {const { server, fetcher } = accountServer();const saveFails = { value: false };- const store = await desktopStore(fetcher, { saveFails });+ const logs: string[] = [];+ const where = { filePath: "" };+ const store = await desktopStore(fetcher, { saveFails, logs, where });const broker = await brokerFor(store, fetcher);saveFails.value = true; // secure storage is unavailable from now onserver.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 });+ expect((await broker.handle(prompt(), "responses")).status).toBe(200); // 1 -> 2, kept in memory+ expect((await store.status()).email).toBe("[email protected]");+ expect(logs.some((line) => line.includes("Could not save the renewed omnirush.ai sign-in"))).toBe(true);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((await broker.handle(prompt(), "responses")).status).toBe(200); // spends refresh-2, not refresh-1expect(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.+ // Once storage is back, the retry saves the current pair.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(503);- 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"]);+ for (let waited = 0; waited < 200 && !(await readFile(where.filePath, "utf8")).includes("refresh-3"); waited += 1) await Bun.sleep(5);+ expect(JSON.parse(await readFile(where.filePath, "utf8"))).toMatchObject({ refreshToken: "refresh-3", rotation: 2 });+ expect(server.superseded).toEqual([]);+ expect(logs.some((line) => /(access|refresh)-\d/.test(line))).toBe(false);});test("a revoked session the store agrees on still signs the device out promptly", async () => {@@ -654,7 +585,9 @@ describe("OmniRush gateway broker sharing a device session with the desktop accoexpect(server.refreshCalls).toEqual(["refresh-1"]);await Bun.sleep(5);expect(await store.load()).toBeNull();- expect((await store.status()).connected).toBe(false);+ const status = await store.status();+ expect(status.connected).toBe(false);+ expect(status.reauthorizationRequired).toBe(true);});});diff --git a/apps/server/src/omnirush-gateway-broker.ts b/apps/server/src/omnirush-gateway-broker.tsindex b72007d4..cfc11b76 100644--- a/apps/server/src/omnirush-gateway-broker.ts+++ b/apps/server/src/omnirush-gateway-broker.ts@@ -2,7 +2,7 @@ import { timingSafeEqual } from "node:crypto";import { SESSION_UPLOAD_BUDGET, SESSION_UPLOAD_ENDPOINT_PATH, sessionUploadTimeoutMs, type SessionUploadBudget } from "./session-upload-budget.js";import { externalFetch } from "./server-fetch.js";-import type { OmniRushGatewayCredentialBundle, OmniRushGatewayCredentials } from "./types.js";+import type { OmniRushGatewayCredentials } from "./types.js";import {SUBAGENT_FALLBACK_EFFORT_HEADER,SUBAGENT_FALLBACK_MODEL_HEADER,@@ -434,21 +434,16 @@ async function readableErrorResponse(response: Response): Promise<Response> {type CredentialState = {gatewayUrl: string;accessToken: string;+ /** Spent only without a refresh owner (see OmniRushGatewayCredentials.refresh). */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. */+ /** 409 refresh_token_already_used: this very token is being rotated right now. */| { kind: "contended" }/** Anything else (5xx, malformed payload): nothing is known about the session. */| { kind: "unavailable" };@@ -719,9 +714,8 @@ function responseHeaders(headers: Headers): Headers {export class OmniRushGatewayBroker {private state: CredentialState | null;private readonly engineToken: string;- private readonly persist?: OmniRushGatewayCredentials["persist"];private readonly invalidate?: OmniRushGatewayCredentials["invalidate"];- private readonly latest?: OmniRushGatewayCredentials["latest"];+ private readonly refreshOwner?: OmniRushGatewayCredentials["refresh"];private readonly fetcher: typeof externalFetch;private readonly log?: BrokerOptions["log"];private readonly sessionUploadBudget: SessionUploadBudget;@@ -731,12 +725,6 @@ export class OmniRushGatewayBroker {private refreshInFlight: Promise<boolean> | null = null;/** Whether the last failed refresh left the session as it was (unreachable, 5xx, contended). */private lastRefreshTransient = false;- /**- * 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;@@ -745,13 +733,11 @@ 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.refreshOwner = options.credentials?.refresh;this.fetcher = options.fetch ?? externalFetch;this.log = options.log;this.sessionUploadBudget = options.sessionUploadBudget ?? SESSION_UPLOAD_BUDGET;@@ -1098,7 +1084,9 @@ export class OmniRushGatewayBroker {private refresh(expectedAccessToken: string): Promise<boolean> {if (this.state?.accessToken !== expectedAccessToken) return Promise.resolve(true);- this.refreshInFlight ??= this.performRefresh(expectedAccessToken)+ this.refreshInFlight ??= (this.refreshOwner+ ? this.refreshFromOwner(this.refreshOwner, expectedAccessToken)+ : this.performRefresh(expectedAccessToken)).then((rotated) => {if (rotated) this.lastRefreshTransient = false;return rotated;@@ -1117,73 +1105,50 @@ export class OmniRushGatewayBroker {}/**- * 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.+ * The desktop account store owns the device session: it alone spends the+ * refresh token, one rotation at a time, and saves the result before it+ * answers. After a 401 the broker hands it the access token that was+ * refused and takes the pair it gets back (one it rotated earlier, or a new+ * rotation): the broker never sends a refresh token, and never acts on a+ * pair of its own that can go stale. A rejection leaves the session as it+ * is (the owner could not rotate right now); null means the session is gone.*/- 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 {+ private async refreshFromOwner(owner: NonNullable<OmniRushGatewayCredentials["refresh"]>, rejectedAccessToken: string): Promise<boolean> {+ const asked = this.state;+ if (!asked) return false;+ const current = await owner(rejectedAccessToken);+ if (this.state !== asked) return Boolean(this.state);+ if (!current) {+ this.state = null;+ void this.invalidate?.().catch(() => undefined);+ return false;+ }+ if (current.accessToken === rejectedAccessToken) {+ this.lastRefreshTransient = true;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,+ gatewayUrl: normalizedGatewayUrl(current.gatewayUrl) ?? asked.gatewayUrl,+ accessToken: current.accessToken,+ refreshToken: current.refreshToken,};- 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.+ * One refresh round trip of a broker that holds its credentials alone (the+ * standalone server with credentials from the environment): sign out only+ * when the server retired the token.*/private async performRefresh(expectedAccessToken: string): Promise<boolean> {if (!this.state) return false;if (this.state.accessToken !== expectedAccessToken) return true;- if (await this.adoptRotatedCredentials()) return true;const spent = this.state;const outcome = await this.rotate(spent);if (outcome.kind === "rotated") return true;this.lastRefreshTransient = outcome.kind === "unavailable" || outcome.kind === "contended";- if (outcome.kind === "unavailable") return false;+ if (outcome.kind !== "retired") 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;@@ -1210,23 +1175,7 @@ export class OmniRushGatewayBroker {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);+ this.state = { accessToken, refreshToken, gatewayUrl };return { kind: "rotated" };}-- private async persistLatest(credentials: OmniRushGatewayCredentialBundle, attempt = 0): Promise<void> {- if (!this.persist) return;- try {- await this.persist(credentials);- } catch {- if (attempt >= 5 || this.state?.refreshToken !== credentials.refreshToken) return;- const timer = setTimeout(() => {- void this.persistLatest(credentials, attempt + 1);- }, Math.min(30_000, 1_000 * 2 ** attempt));- timer.unref?.();- }- }}diff --git a/apps/server/src/types.ts b/apps/server/src/types.tsindex 9488011b..8e6afe4c 100644--- a/apps/server/src/types.ts+++ b/apps/server/src/types.ts@@ -88,24 +88,28 @@ export type OmniRushGatewayCredentialBundle = {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).+ * How many times the desktop account store has rotated this device session;+ * it never saves a bundle with a lower count over a higher one. 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.+ * The one owner of the device session's refresh token (the desktop account+ * store). With it the broker never sends a refresh token: after a 401 it+ * passes the refused access token here and uses the pair it gets back,+ * either one the owner already rotated to or a new rotation (the owner runs+ * one at a time and saves it before answering). Null means the session is+ * gone; a rejection means no rotation was possible right now. The server+ * treats a superseded refresh token as a sign-in copied to another device,+ * so two holders must never both spend one.*/+ refresh?: (rejectedAccessToken: string) => Promise<OmniRushGatewayCredentialBundle | null>;+ /** The credentials as currently stored; null after a sign-out. */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>;