From 9311635102799968e70c498c6567f5b60c5d8827 Mon Sep 17 00:00:00 2001 From: Pragati Agrawal Date: Thu, 23 Jul 2026 18:05:26 +0530 Subject: [PATCH 01/10] [Plugin] Fix intermittent re-auth from cross-process refresh-token rotation MCP servers are spawned per session, and the OAuth provider reads credentials from disk once at startup, then serves tokens from that in-memory snapshot. With Ory single-use refresh-token rotation, when one process refreshes it persists a new refresh token and invalidates the old one that every other live process still holds in memory. The next process to hit a 401 refreshes with its now-dead token -> invalid_grant -> full re-auth -> [SETUP_REQUIRED]. This is the intermittent "why is it asking me to auth again", not the (intentional, unchanged) 7-day access-token TTL. Two fixes, both independent of the PLUGIN_DATA_DIR store split: 1. tokens() re-reads the credentials file when its mtime advances, so a process picks up a sibling's freshly-rotated grant before the SDK's auth flow reads tokens and attempts a refresh. mtime-guarded so the steady state is a single stat(). Conservative on removal: a missing file or a tokens-less rewrite does not evict the in-memory token. 2. createRemoteClient retries connect once when, after an auth failure, a newer access token has appeared on disk (sibling refresh) -- turning the rotation race into a silent reconnect instead of a re-auth. Bounded to a single retry. Tests: provider adopts a sibling's newer token, keeps its token when the file vanishes, ignores a tokens-less rewrite; credentialsMtimeMs probe; connect retry fires only when the on-disk token changed. Follow-ups (not in this PR): collapse the PLUGIN_DATA_DIR / ~/.glean store split to one canonical path so surfaces share one DCR client; reuse the DCR client across re-auths to stop orphaned-token pile-up. Co-Authored-By: Claude Opus 4.8 (1M context) --- plugins/glean/.claude-plugin/plugin.json | 2 +- plugins/glean/.codex-plugin/plugin.json | 2 +- plugins/glean/.cursor-plugin/plugin.json | 2 +- plugins/glean/dist/index.js | 65 +++++++++++++++-- src/auth-provider.ts | 53 +++++++++++++- src/remote-client.ts | 30 +++++++- src/token-store.ts | 16 +++++ tests/auth-provider.test.ts | 65 +++++++++++++++++ tests/remote-client-auth-retry.test.ts | 91 ++++++++++++++++++++++++ tests/token-store.test.ts | 24 ++++++- 10 files changed, 336 insertions(+), 14 deletions(-) create mode 100644 tests/remote-client-auth-retry.test.ts diff --git a/plugins/glean/.claude-plugin/plugin.json b/plugins/glean/.claude-plugin/plugin.json index d918a2c..2b79653 100644 --- a/plugins/glean/.claude-plugin/plugin.json +++ b/plugins/glean/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "glean-vnext", - "version": "0.2.42", + "version": "0.2.43", "description": "Glean plugin for discovering skills and running tools.", "author": { "name": "Glean" diff --git a/plugins/glean/.codex-plugin/plugin.json b/plugins/glean/.codex-plugin/plugin.json index a7bf7fd..724f092 100644 --- a/plugins/glean/.codex-plugin/plugin.json +++ b/plugins/glean/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "glean-vnext", - "version": "0.2.42", + "version": "0.2.43", "description": "Glean Codex plugin for discovering skills and running tools.", "author": { "name": "Glean" diff --git a/plugins/glean/.cursor-plugin/plugin.json b/plugins/glean/.cursor-plugin/plugin.json index eb42ee7..c9ac74b 100644 --- a/plugins/glean/.cursor-plugin/plugin.json +++ b/plugins/glean/.cursor-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "glean-vnext", "displayName": "Glean vNext", - "version": "0.2.42", + "version": "0.2.43", "description": "Search and act across your company's apps — Jira, Slack, Salesforce, Google Workspace, and more — without leaving Cursor.", "author": { "name": "Glean" diff --git a/plugins/glean/dist/index.js b/plugins/glean/dist/index.js index 5b6789d..27ad711 100644 --- a/plugins/glean/dist/index.js +++ b/plugins/glean/dist/index.js @@ -25216,7 +25216,7 @@ function buildTransport(serverUrl, opts, chatSessionId) { } return new StreamableHTTPClientTransport(parsedUrl, transportOpts); } -async function createRemoteClient(serverUrl, opts, chatSessionId) { +async function createRemoteClient(serverUrl, opts, chatSessionId, authRetry = false) { const authProvider = opts.authProvider; if (authProvider?.pendingAuthCode) { const transportForAuth = pendingTransport ?? buildTransport(serverUrl, opts, chatSessionId); @@ -25244,13 +25244,23 @@ async function createRemoteClient(serverUrl, opts, chatSessionId) { { name: "glean", version: "1.0.0" }, { capabilities: {} } ); + const accessTokenAtConnect = authProvider?.tokens()?.access_token; const transport = buildTransport(serverUrl, opts, chatSessionId); try { await client.connect(transport); } catch (error2) { - if (error2 instanceof UnauthorizedError && authProvider?.authorizationUrl) { - pendingTransport = transport; - throw new AuthRequiredError(authProvider.authorizationUrl); + if (error2 instanceof UnauthorizedError && authProvider) { + const refreshedAccessToken = authProvider.tokens()?.access_token; + if (!authRetry && refreshedAccessToken && refreshedAccessToken !== accessTokenAtConnect) { + console.error( + "[auth] Auth failed but a newer token is on disk (sibling refresh) \u2014 retrying once" + ); + return createRemoteClient(serverUrl, opts, chatSessionId, true); + } + if (authProvider.authorizationUrl) { + pendingTransport = transport; + throw new AuthRequiredError(authProvider.authorizationUrl); + } } throw error2; } @@ -25371,6 +25381,13 @@ function loadCredentials() { return void 0; } } +function credentialsMtimeMs() { + try { + return fs.statSync(credentialsFile()).mtimeMs; + } catch { + return void 0; + } +} function saveCredentials(tokens, clientInfo) { try { const filePath = credentialsFile(); @@ -25419,6 +25436,10 @@ var GleanOAuthClientProvider = class { // explicitly invalidating. Used to detect when a previous auth URL didn't // complete — likely because the server rejected the (stale) client_id. _authUrlPending = false; + // mtime (epoch ms) of the credentials file at the point our in-memory + // _tokens/_clientInfo snapshot was last taken from disk. Undefined until the + // first successful read. Used to detect sibling rewrites — see syncFromDisk. + _credentialsMtimeMs; authorizationUrl; /** * Optional hook invoked whenever the in-memory token state changes — @@ -25433,6 +25454,39 @@ var GleanOAuthClientProvider = class { this._tokens = stored.tokens; this._clientInfo = stored.clientInfo; } + this._credentialsMtimeMs = credentialsMtimeMs(); + } + // Re-read the credentials file if it has changed on disk since we last read + // it. MCP servers are spawned per session, so several of our processes can be + // alive at once sharing one credentials file. When one process refreshes an + // (Ory-rotated, single-use) refresh token, it persists the new grant and + // silently invalidates the old refresh token that every other process still + // holds in memory. Without this, the next process to hit a 401 would refresh + // with its now-dead token, get invalid_grant, and force a full re-auth + // ([SETUP_REQUIRED]). Syncing here — right before the SDK reads tokens() at + // the start of its auth flow — lets us pick up the sibling's fresh grant + // instead. Guarded by mtime so the steady state is one stat(), not a re-parse. + // + // Conservative on removal: if the file is gone (undefined mtime) or has no + // tokens, we keep our in-memory snapshot rather than logging ourselves out — + // a transient stat failure or another process's explicit logout shouldn't + // drop a token that still works for us; a genuinely revoked token self-heals + // through the normal 401 path. + syncFromDisk() { + const mtimeMs = credentialsMtimeMs(); + if (mtimeMs === void 0) return; + if (this._credentialsMtimeMs !== void 0 && mtimeMs <= this._credentialsMtimeMs) { + return; + } + const stored = loadCredentials(); + this._credentialsMtimeMs = mtimeMs; + if (!stored) return; + if (stored.tokens) { + this._tokens = stored.tokens; + } + if (stored.clientInfo) { + this._clientInfo = stored.clientInfo; + } } get redirectUrl() { return getCallbackUrl(); @@ -25449,14 +25503,17 @@ var GleanOAuthClientProvider = class { saveClientInformation(info) { this._clientInfo = info; saveCredentials(this._tokens, this._clientInfo); + this._credentialsMtimeMs = credentialsMtimeMs(); } tokens() { + this.syncFromDisk(); return this._tokens; } saveTokens(tokens) { this._tokens = tokens; this._authUrlPending = false; saveCredentials(this._tokens, this._clientInfo); + this._credentialsMtimeMs = credentialsMtimeMs(); this.onTokensChanged?.(tokens); } async invalidateCredentials(scope) { diff --git a/src/auth-provider.ts b/src/auth-provider.ts index 4c47d0b..6abbd89 100644 --- a/src/auth-provider.ts +++ b/src/auth-provider.ts @@ -7,7 +7,12 @@ import type { import { execFile, spawn } from "node:child_process"; import { platform } from "node:os"; import { getCallbackUrl, setExpectedState } from "./auth-callback-server.js"; -import { clearCredentials, loadCredentials, saveCredentials } from "./token-store.js"; +import { + clearCredentials, + credentialsMtimeMs, + loadCredentials, + saveCredentials, +} from "./token-store.js"; export type InvalidationScope = "all" | "client" | "tokens" | "verifier"; @@ -47,6 +52,10 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { // explicitly invalidating. Used to detect when a previous auth URL didn't // complete — likely because the server rejected the (stale) client_id. private _authUrlPending = false; + // mtime (epoch ms) of the credentials file at the point our in-memory + // _tokens/_clientInfo snapshot was last taken from disk. Undefined until the + // first successful read. Used to detect sibling rewrites — see syncFromDisk. + private _credentialsMtimeMs: number | undefined; authorizationUrl: string | undefined; @@ -64,6 +73,43 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { this._tokens = stored.tokens as OAuthTokens | undefined; this._clientInfo = stored.clientInfo as OAuthClientInformationMixed | undefined; } + this._credentialsMtimeMs = credentialsMtimeMs(); + } + + // Re-read the credentials file if it has changed on disk since we last read + // it. MCP servers are spawned per session, so several of our processes can be + // alive at once sharing one credentials file. When one process refreshes an + // (Ory-rotated, single-use) refresh token, it persists the new grant and + // silently invalidates the old refresh token that every other process still + // holds in memory. Without this, the next process to hit a 401 would refresh + // with its now-dead token, get invalid_grant, and force a full re-auth + // ([SETUP_REQUIRED]). Syncing here — right before the SDK reads tokens() at + // the start of its auth flow — lets us pick up the sibling's fresh grant + // instead. Guarded by mtime so the steady state is one stat(), not a re-parse. + // + // Conservative on removal: if the file is gone (undefined mtime) or has no + // tokens, we keep our in-memory snapshot rather than logging ourselves out — + // a transient stat failure or another process's explicit logout shouldn't + // drop a token that still works for us; a genuinely revoked token self-heals + // through the normal 401 path. + private syncFromDisk(): void { + const mtimeMs = credentialsMtimeMs(); + if (mtimeMs === undefined) return; + if ( + this._credentialsMtimeMs !== undefined && + mtimeMs <= this._credentialsMtimeMs + ) { + return; + } + const stored = loadCredentials(); + this._credentialsMtimeMs = mtimeMs; + if (!stored) return; + if (stored.tokens) { + this._tokens = stored.tokens as OAuthTokens; + } + if (stored.clientInfo) { + this._clientInfo = stored.clientInfo as OAuthClientInformationMixed; + } } get redirectUrl(): string { @@ -84,9 +130,11 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { saveClientInformation(info: OAuthClientInformationMixed): void { this._clientInfo = info; saveCredentials(this._tokens, this._clientInfo); + this._credentialsMtimeMs = credentialsMtimeMs(); } tokens(): OAuthTokens | undefined { + this.syncFromDisk(); return this._tokens; } @@ -94,6 +142,9 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { this._tokens = tokens; this._authUrlPending = false; saveCredentials(this._tokens, this._clientInfo); + // Record the mtime of the file we just wrote so our own write doesn't look + // like a sibling change on the next syncFromDisk. + this._credentialsMtimeMs = credentialsMtimeMs(); this.onTokensChanged?.(tokens); } diff --git a/src/remote-client.ts b/src/remote-client.ts index 954cf52..d7c1366 100644 --- a/src/remote-client.ts +++ b/src/remote-client.ts @@ -144,6 +144,7 @@ export async function createRemoteClient( serverUrl: string, opts: RemoteClientOptions, chatSessionId?: string, + authRetry = false, ): Promise { const authProvider = opts.authProvider; @@ -189,14 +190,37 @@ export async function createRemoteClient( { capabilities: {} }, ); + // Snapshot the access token we're about to connect with. Between now and a + // possible 401, a sibling per-session server can rotate the (single-use) + // refresh token and persist a newer grant. authProvider.tokens() re-reads the + // store when it changed on disk, so on auth failure we can tell whether a + // fresher token has since appeared and retry once with it — turning a + // cross-process rotation race into a silent reconnect instead of a full + // re-auth. Bounded to a single retry via authRetry so it can't spin. + const accessTokenAtConnect = authProvider?.tokens()?.access_token; + const transport = buildTransport(serverUrl, opts, chatSessionId); try { await client.connect(transport); } catch (error) { - if (error instanceof UnauthorizedError && authProvider?.authorizationUrl) { - pendingTransport = transport; - throw new AuthRequiredError(authProvider.authorizationUrl); + if (error instanceof UnauthorizedError && authProvider) { + const refreshedAccessToken = authProvider.tokens()?.access_token; + if ( + !authRetry && + refreshedAccessToken && + refreshedAccessToken !== accessTokenAtConnect + ) { + console.error( + "[auth] Auth failed but a newer token is on disk " + + "(sibling refresh) — retrying once", + ); + return createRemoteClient(serverUrl, opts, chatSessionId, true); + } + if (authProvider.authorizationUrl) { + pendingTransport = transport; + throw new AuthRequiredError(authProvider.authorizationUrl); + } } throw error; } diff --git a/src/token-store.ts b/src/token-store.ts index e41c2fa..028cd15 100644 --- a/src/token-store.ts +++ b/src/token-store.ts @@ -28,6 +28,22 @@ export function loadCredentials(): StoredCredentials | undefined { } } +/** + * Last-modified time (epoch ms) of the credentials file, or undefined if it + * doesn't exist / can't be stat'd. Used as a cheap change-detection probe so a + * long-lived provider can notice when a sibling process has rewritten the + * shared store (e.g. after a refresh-token rotation) and re-read it, instead of + * serving a stale in-memory snapshot. Kept separate from loadCredentials so the + * common "nothing changed" path is a single stat, not a full read + parse. + */ +export function credentialsMtimeMs(): number | undefined { + try { + return fs.statSync(credentialsFile()).mtimeMs; + } catch { + return undefined; + } +} + export function saveCredentials(tokens: unknown, clientInfo: unknown): void { try { const filePath = credentialsFile(); diff --git a/tests/auth-provider.test.ts b/tests/auth-provider.test.ts index ba181f0..1ecfcfb 100644 --- a/tests/auth-provider.test.ts +++ b/tests/auth-provider.test.ts @@ -74,6 +74,71 @@ describe("GleanOAuthClientProvider", () => { expect(raw.tokens.access_token).toBe("new_tok"); }); + // --- Cross-process sync: a per-session sibling server may rotate the + // refresh token and rewrite the shared store; tokens() must pick that up + // instead of serving the stale startup snapshot. --- + + const credFile = path.join(gleanDir, "mcp-credentials.json"); + + function writeCredFileNewer(tokens: unknown, clientInfo?: unknown): void { + fs.mkdirSync(gleanDir, { recursive: true }); + fs.writeFileSync(credFile, JSON.stringify({ tokens, clientInfo })); + // Guarantee a strictly-newer mtime than any prior read, independent of + // filesystem timestamp resolution. + const future = new Date(Date.now() + 10_000); + fs.utimesSync(credFile, future, future); + } + + it("tokens() adopts a newer token written by another process", () => { + fs.mkdirSync(gleanDir, { recursive: true }); + fs.writeFileSync( + credFile, + JSON.stringify({ + tokens: { access_token: "T0", refresh_token: "R0" }, + clientInfo: { client_id: "cid" }, + }), + ); + const provider = new GleanOAuthClientProvider(); + expect(provider.tokens()?.access_token).toBe("T0"); + + // Sibling refreshes: new access + rotated refresh token on disk. + writeCredFileNewer( + { access_token: "T1", refresh_token: "R1" }, + { client_id: "cid" }, + ); + + expect(provider.tokens()?.access_token).toBe("T1"); + expect(provider.tokens()?.refresh_token).toBe("R1"); + }); + + it("tokens() keeps the in-memory token when the file is deleted", () => { + fs.mkdirSync(gleanDir, { recursive: true }); + fs.writeFileSync( + credFile, + JSON.stringify({ tokens: { access_token: "T0" }, clientInfo: {} }), + ); + const provider = new GleanOAuthClientProvider(); + expect(provider.tokens()?.access_token).toBe("T0"); + + // Transient disappearance / another process mid-write — don't self-evict. + fs.rmSync(credFile, { force: true }); + expect(provider.tokens()?.access_token).toBe("T0"); + }); + + it("tokens() does not adopt a rewrite that carries no tokens", () => { + fs.mkdirSync(gleanDir, { recursive: true }); + fs.writeFileSync( + credFile, + JSON.stringify({ tokens: { access_token: "T0" }, clientInfo: {} }), + ); + const provider = new GleanOAuthClientProvider(); + expect(provider.tokens()?.access_token).toBe("T0"); + + // A client-only rewrite (tokens dropped) must not log us out in-memory. + writeCredFileNewer(undefined, { client_id: "cid" }); + expect(provider.tokens()?.access_token).toBe("T0"); + }); + it("saveClientInformation persists to disk", () => { const provider = new GleanOAuthClientProvider(); const info = { client_id: "cid", client_secret: "sec" } as any; diff --git a/tests/remote-client-auth-retry.test.ts b/tests/remote-client-auth-retry.test.ts new file mode 100644 index 0000000..3afce9c --- /dev/null +++ b/tests/remote-client-auth-retry.test.ts @@ -0,0 +1,91 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js"; + +// Control client.connect() across (re)tries. +const { connectMock } = vi.hoisted(() => ({ connectMock: vi.fn() })); + +vi.mock("@modelcontextprotocol/sdk/client/index.js", () => ({ + Client: class { + async connect(...args: unknown[]) { + return connectMock(...args); + } + }, +})); + +// Keep buildTransport cheap and side-effect free. +vi.mock("@modelcontextprotocol/sdk/client/streamableHttp.js", () => ({ + StreamableHTTPClientTransport: class { + constructor() {} + async close() {} + }, +})); + +const { createRemoteClient, AuthRequiredError } = await import( + "../src/remote-client.js" +); + +/** + * Minimal OAuthClientProvider stand-in. tokens() returns the next value in + * `seq` on each call, mirroring how the real provider re-reads disk: the + * pre-connect snapshot, then the value after a sibling may have rewritten it. + */ +function makeProvider(seq: Array<{ access_token?: string } | undefined>) { + let i = 0; + return { + tokens() { + const t = seq[Math.min(i, seq.length - 1)]; + i += 1; + return t; + }, + authorizationUrl: "https://example.com/oauth/authorize?state=s1", + pendingAuthCode: undefined, + needsFreshClient: () => false, + } as any; +} + +describe("createRemoteClient sibling-refresh retry", () => { + beforeEach(() => { + connectMock.mockReset(); + }); + + it("retries once and succeeds when a newer token appears on disk", async () => { + connectMock + .mockRejectedValueOnce(new UnauthorizedError("401")) + .mockResolvedValueOnce(undefined); + + // pre-connect snapshot T0, post-failure re-read T1 (rotated), retry snapshot T1. + const provider = makeProvider([ + { access_token: "T0" }, + { access_token: "T1" }, + { access_token: "T1" }, + ]); + + const client = await createRemoteClient( + "https://acme-be.glean.com/mcp/gateway/proxy", + { authProvider: provider }, + "sess-1", + ); + + expect(client).toBeTruthy(); + expect(connectMock).toHaveBeenCalledTimes(2); + }); + + it("does not retry when the on-disk token is unchanged", async () => { + connectMock.mockRejectedValue(new UnauthorizedError("401")); + + const provider = makeProvider([ + { access_token: "T0" }, + { access_token: "T0" }, + ]); + + await expect( + createRemoteClient( + "https://acme-be.glean.com/mcp/gateway/proxy", + { authProvider: provider }, + "sess-2", + ), + ).rejects.toBeInstanceOf(AuthRequiredError); + + expect(connectMock).toHaveBeenCalledTimes(1); + }); +}); diff --git a/tests/token-store.test.ts b/tests/token-store.test.ts index 14fd6cc..88685ad 100644 --- a/tests/token-store.test.ts +++ b/tests/token-store.test.ts @@ -10,9 +10,8 @@ vi.mock("node:os", async () => { return { ...actual, homedir: () => tmpDir }; }); -const { clearCredentials, loadCredentials, saveCredentials } = await import( - "../src/token-store.js" -); +const { clearCredentials, credentialsMtimeMs, loadCredentials, saveCredentials } = + await import("../src/token-store.js"); describe("token-store", () => { const gleanDir = path.join(tmpDir, ".glean"); @@ -88,4 +87,23 @@ describe("token-store", () => { expect(fs.existsSync(credFile)).toBe(false); expect(() => clearCredentials()).not.toThrow(); }); + + it("credentialsMtimeMs returns undefined when file does not exist", () => { + expect(credentialsMtimeMs()).toBeUndefined(); + }); + + it("credentialsMtimeMs returns a number once credentials are saved", () => { + saveCredentials({ access_token: "x" }, undefined); + expect(typeof credentialsMtimeMs()).toBe("number"); + }); + + it("credentialsMtimeMs advances when the file is rewritten", () => { + saveCredentials({ access_token: "x" }, undefined); + const first = credentialsMtimeMs()!; + // Force a strictly-newer mtime rather than relying on filesystem timer + // resolution between two quick writes. + const future = new Date(Date.now() + 10_000); + fs.utimesSync(credFile, future, future); + expect(credentialsMtimeMs()!).toBeGreaterThan(first); + }); }); From 86c95ecc946052fb0e97910c5aa951167606fc1b Mon Sep 17 00:00:00 2001 From: Pragati Agrawal Date: Mon, 27 Jul 2026 18:06:29 +0530 Subject: [PATCH 02/10] [Plugin] Complete rotation fix: don't wipe a sibling's fresh token on invalid_grant The SDK's auth() calls invalidateCredentials("tokens") when a refresh returns invalid_grant, which wrote {tokens: undefined} to the SHARED credentials file. But the plugin's OAuth server (legacy /oauth, fosite) rotates refresh tokens with NO grace period (RevokeRefreshTokenMaybeGracePeriod -> immediate delete), so invalid_grant is exactly what a sibling's rotation looks like: the sibling already minted a fresh grant and persisted it, and we only failed because we refreshed with the now-revoked old token. Blindly clearing then (a) forced a needless re-auth and (b) clobbered the fresh token every other session on that store depends on -- one stale session poisoned the well for all of them. syncFromDisk alone couldn't cover this: the wipe runs inside connect() (SDK auth() catch), before the connect-retry could re-read. Now invalidateCredentials("tokens") first checks whether disk holds a token newer than the one we failed with (mtime-guarded, access_token differs). If so it adopts that token and keeps it on disk instead of clearing; the SDK's own post-invalidation retry (authInternal -> refreshAuthorization) then refreshes with the fresh token and succeeds -- no re-auth, no poisoning. A genuine invalidation (nothing newer on disk) still clears as before. Tests: adopt-newer-token-instead-of-wipe (store preserved); clear-when-nothing- newer. Full suite green, typecheck clean. Co-Authored-By: Claude Opus 4.8 (1M context) --- plugins/glean/dist/index.js | 32 +++++++++++++++++++++++++++ src/auth-provider.ts | 43 +++++++++++++++++++++++++++++++++++++ tests/auth-provider.test.ts | 41 +++++++++++++++++++++++++++++++++++ 3 files changed, 116 insertions(+) diff --git a/plugins/glean/dist/index.js b/plugins/glean/dist/index.js index 27ad711..b4ce685 100644 --- a/plugins/glean/dist/index.js +++ b/plugins/glean/dist/index.js @@ -25488,6 +25488,37 @@ var GleanOAuthClientProvider = class { this._clientInfo = stored.clientInfo; } } + // On a refresh failure the SDK calls invalidateCredentials("tokens"), which + // would clear our tokens AND overwrite the shared store with an empty set. + // But invalid_grant is exactly what a sibling's refresh-token rotation looks + // like: the sibling already minted a fresh grant and wrote it to disk, and we + // only failed because we refreshed with the now-revoked old token. In that + // case, blindly wiping would (a) force a needless re-auth and (b) poison the + // fresh token other sessions depend on. So: if disk holds a token newer than + // the one we just failed with, adopt it and return true — the caller keeps it + // on disk instead of clearing, and the SDK's post-invalidation retry refreshes + // with the fresh token and succeeds. Returns false when there's genuinely + // nothing newer to adopt (real invalidation → clear as normal). + adoptNewerTokenFromDisk() { + const diskMtime = credentialsMtimeMs(); + if (diskMtime === void 0 || this._credentialsMtimeMs === void 0 || diskMtime <= this._credentialsMtimeMs) { + return false; + } + const stored = loadCredentials(); + const diskTokens = stored?.tokens; + if (!diskTokens?.access_token || diskTokens.access_token === this._tokens?.access_token) { + return false; + } + this._tokens = diskTokens; + this._credentialsMtimeMs = diskMtime; + if (stored?.clientInfo) { + this._clientInfo = stored.clientInfo; + } + console.error( + "[auth] invalid_grant, but a newer token is on disk (sibling refresh) \u2014 adopting it instead of clearing" + ); + return true; + } get redirectUrl() { return getCallbackUrl(); } @@ -25532,6 +25563,7 @@ var GleanOAuthClientProvider = class { saveCredentials(this._tokens, void 0); break; case "tokens": + if (this.adoptNewerTokenFromDisk()) return; this._tokens = void 0; saveCredentials(void 0, this._clientInfo); break; diff --git a/src/auth-provider.ts b/src/auth-provider.ts index 6abbd89..f87f151 100644 --- a/src/auth-provider.ts +++ b/src/auth-provider.ts @@ -112,6 +112,46 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { } } + // On a refresh failure the SDK calls invalidateCredentials("tokens"), which + // would clear our tokens AND overwrite the shared store with an empty set. + // But invalid_grant is exactly what a sibling's refresh-token rotation looks + // like: the sibling already minted a fresh grant and wrote it to disk, and we + // only failed because we refreshed with the now-revoked old token. In that + // case, blindly wiping would (a) force a needless re-auth and (b) poison the + // fresh token other sessions depend on. So: if disk holds a token newer than + // the one we just failed with, adopt it and return true — the caller keeps it + // on disk instead of clearing, and the SDK's post-invalidation retry refreshes + // with the fresh token and succeeds. Returns false when there's genuinely + // nothing newer to adopt (real invalidation → clear as normal). + private adoptNewerTokenFromDisk(): boolean { + const diskMtime = credentialsMtimeMs(); + if ( + diskMtime === undefined || + this._credentialsMtimeMs === undefined || + diskMtime <= this._credentialsMtimeMs + ) { + return false; + } + const stored = loadCredentials(); + const diskTokens = stored?.tokens as OAuthTokens | undefined; + if ( + !diskTokens?.access_token || + diskTokens.access_token === this._tokens?.access_token + ) { + return false; + } + this._tokens = diskTokens; + this._credentialsMtimeMs = diskMtime; + if (stored?.clientInfo) { + this._clientInfo = stored.clientInfo as OAuthClientInformationMixed; + } + console.error( + "[auth] invalid_grant, but a newer token is on disk " + + "(sibling refresh) — adopting it instead of clearing", + ); + return true; + } + get redirectUrl(): string { return getCallbackUrl(); } @@ -164,6 +204,9 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { saveCredentials(this._tokens, undefined); break; case "tokens": + // A refresh failure is usually a sibling's rotation, not a dead session + // — adopt any newer on-disk token instead of wiping the shared store. + if (this.adoptNewerTokenFromDisk()) return; this._tokens = undefined; saveCredentials(undefined, this._clientInfo); break; diff --git a/tests/auth-provider.test.ts b/tests/auth-provider.test.ts index 1ecfcfb..8450512 100644 --- a/tests/auth-provider.test.ts +++ b/tests/auth-provider.test.ts @@ -139,6 +139,47 @@ describe("GleanOAuthClientProvider", () => { expect(provider.tokens()?.access_token).toBe("T0"); }); + it("invalidateCredentials('tokens') adopts a sibling's newer token instead of wiping the store", async () => { + fs.mkdirSync(gleanDir, { recursive: true }); + fs.writeFileSync( + credFile, + JSON.stringify({ + tokens: { access_token: "T0", refresh_token: "R0" }, + clientInfo: { client_id: "cid" }, + }), + ); + const provider = new GleanOAuthClientProvider(); + expect(provider.tokens()?.access_token).toBe("T0"); + + // A sibling refreshed + rotated: fresh grant now on disk with a newer mtime. + writeCredFileNewer( + { access_token: "T1", refresh_token: "R1" }, + { client_id: "cid" }, + ); + + // The SDK calls this on invalid_grant. It must NOT clear — the failure was + // just our stale token; adopt the sibling's fresh one and leave it on disk. + await provider.invalidateCredentials("tokens"); + + expect(provider.tokens()?.access_token).toBe("T1"); + expect(provider.tokens()?.refresh_token).toBe("R1"); + const raw = JSON.parse(fs.readFileSync(credFile, "utf-8")); + expect(raw.tokens.access_token).toBe("T1"); // not clobbered with undefined + }); + + it("invalidateCredentials('tokens') clears when there is no newer token on disk", async () => { + const provider = new GleanOAuthClientProvider(); + provider.saveTokens({ access_token: "T0", refresh_token: "R0" } as any); + expect(provider.tokens()?.access_token).toBe("T0"); + + // No sibling write since our snapshot → a genuine invalidation → clear. + await provider.invalidateCredentials("tokens"); + + expect(provider.tokens()).toBeUndefined(); + const raw = JSON.parse(fs.readFileSync(credFile, "utf-8")); + expect(raw.tokens).toBeUndefined(); + }); + it("saveClientInformation persists to disk", () => { const provider = new GleanOAuthClientProvider(); const info = { client_id: "cid", client_secret: "sec" } as any; From 02407b22666bc7390380087b1a317aa63d4d83df Mon Sep 17 00:00:00 2001 From: Pragati Agrawal Date: Tue, 28 Jul 2026 11:03:25 +0530 Subject: [PATCH 03/10] Trim token-rotation fix comments to just the rationale Cut the comments added for the cross-process rotation fix down to the reason/use-case, dropping restatements of what the code already shows. No behavior change. Co-Authored-By: Claude Opus 4.8 --- plugins/glean/dist/index.js | 43 +++++++++++----------------------- src/auth-provider.ts | 46 +++++++++++-------------------------- src/remote-client.ts | 11 ++++----- 3 files changed, 31 insertions(+), 69 deletions(-) diff --git a/plugins/glean/dist/index.js b/plugins/glean/dist/index.js index b4ce685..2d74399 100644 --- a/plugins/glean/dist/index.js +++ b/plugins/glean/dist/index.js @@ -25436,9 +25436,8 @@ var GleanOAuthClientProvider = class { // explicitly invalidating. Used to detect when a previous auth URL didn't // complete — likely because the server rejected the (stale) client_id. _authUrlPending = false; - // mtime (epoch ms) of the credentials file at the point our in-memory - // _tokens/_clientInfo snapshot was last taken from disk. Undefined until the - // first successful read. Used to detect sibling rewrites — see syncFromDisk. + // mtime of the creds file when we last read it — lets us spot a sibling + // process rewriting the shared store. See syncFromDisk. _credentialsMtimeMs; authorizationUrl; /** @@ -25456,22 +25455,12 @@ var GleanOAuthClientProvider = class { } this._credentialsMtimeMs = credentialsMtimeMs(); } - // Re-read the credentials file if it has changed on disk since we last read - // it. MCP servers are spawned per session, so several of our processes can be - // alive at once sharing one credentials file. When one process refreshes an - // (Ory-rotated, single-use) refresh token, it persists the new grant and - // silently invalidates the old refresh token that every other process still - // holds in memory. Without this, the next process to hit a 401 would refresh - // with its now-dead token, get invalid_grant, and force a full re-auth - // ([SETUP_REQUIRED]). Syncing here — right before the SDK reads tokens() at - // the start of its auth flow — lets us pick up the sibling's fresh grant - // instead. Guarded by mtime so the steady state is one stat(), not a re-parse. - // - // Conservative on removal: if the file is gone (undefined mtime) or has no - // tokens, we keep our in-memory snapshot rather than logging ourselves out — - // a transient stat failure or another process's explicit logout shouldn't - // drop a token that still works for us; a genuinely revoked token self-heals - // through the normal 401 path. + // Per-session sibling processes share one creds file. When one refreshes, the + // rotated single-use refresh token it persists kills the copy every other + // process holds in memory. Re-read before the SDK reads tokens() so we use the + // sibling's fresh grant, not a dead token that would force re-auth. Stay + // conservative on a missing/token-less file — don't evict a token that still + // works for us. syncFromDisk() { const mtimeMs = credentialsMtimeMs(); if (mtimeMs === void 0) return; @@ -25488,17 +25477,11 @@ var GleanOAuthClientProvider = class { this._clientInfo = stored.clientInfo; } } - // On a refresh failure the SDK calls invalidateCredentials("tokens"), which - // would clear our tokens AND overwrite the shared store with an empty set. - // But invalid_grant is exactly what a sibling's refresh-token rotation looks - // like: the sibling already minted a fresh grant and wrote it to disk, and we - // only failed because we refreshed with the now-revoked old token. In that - // case, blindly wiping would (a) force a needless re-auth and (b) poison the - // fresh token other sessions depend on. So: if disk holds a token newer than - // the one we just failed with, adopt it and return true — the caller keeps it - // on disk instead of clearing, and the SDK's post-invalidation retry refreshes - // with the fresh token and succeeds. Returns false when there's genuinely - // nothing newer to adopt (real invalidation → clear as normal). + // invalid_grant is what a sibling's rotation looks like: it already wrote a + // fresh grant to disk and we only failed because we used the revoked old + // token. Wiping would force a needless re-auth and poison the shared token + // other sessions depend on, so adopt a newer on-disk token instead. Returns + // false when nothing newer exists (a real invalidation → clear as normal). adoptNewerTokenFromDisk() { const diskMtime = credentialsMtimeMs(); if (diskMtime === void 0 || this._credentialsMtimeMs === void 0 || diskMtime <= this._credentialsMtimeMs) { diff --git a/src/auth-provider.ts b/src/auth-provider.ts index f87f151..667f66f 100644 --- a/src/auth-provider.ts +++ b/src/auth-provider.ts @@ -52,9 +52,8 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { // explicitly invalidating. Used to detect when a previous auth URL didn't // complete — likely because the server rejected the (stale) client_id. private _authUrlPending = false; - // mtime (epoch ms) of the credentials file at the point our in-memory - // _tokens/_clientInfo snapshot was last taken from disk. Undefined until the - // first successful read. Used to detect sibling rewrites — see syncFromDisk. + // mtime of the creds file when we last read it — lets us spot a sibling + // process rewriting the shared store. See syncFromDisk. private _credentialsMtimeMs: number | undefined; authorizationUrl: string | undefined; @@ -76,22 +75,12 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { this._credentialsMtimeMs = credentialsMtimeMs(); } - // Re-read the credentials file if it has changed on disk since we last read - // it. MCP servers are spawned per session, so several of our processes can be - // alive at once sharing one credentials file. When one process refreshes an - // (Ory-rotated, single-use) refresh token, it persists the new grant and - // silently invalidates the old refresh token that every other process still - // holds in memory. Without this, the next process to hit a 401 would refresh - // with its now-dead token, get invalid_grant, and force a full re-auth - // ([SETUP_REQUIRED]). Syncing here — right before the SDK reads tokens() at - // the start of its auth flow — lets us pick up the sibling's fresh grant - // instead. Guarded by mtime so the steady state is one stat(), not a re-parse. - // - // Conservative on removal: if the file is gone (undefined mtime) or has no - // tokens, we keep our in-memory snapshot rather than logging ourselves out — - // a transient stat failure or another process's explicit logout shouldn't - // drop a token that still works for us; a genuinely revoked token self-heals - // through the normal 401 path. + // Per-session sibling processes share one creds file. When one refreshes, the + // rotated single-use refresh token it persists kills the copy every other + // process holds in memory. Re-read before the SDK reads tokens() so we use the + // sibling's fresh grant, not a dead token that would force re-auth. Stay + // conservative on a missing/token-less file — don't evict a token that still + // works for us. private syncFromDisk(): void { const mtimeMs = credentialsMtimeMs(); if (mtimeMs === undefined) return; @@ -112,17 +101,11 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { } } - // On a refresh failure the SDK calls invalidateCredentials("tokens"), which - // would clear our tokens AND overwrite the shared store with an empty set. - // But invalid_grant is exactly what a sibling's refresh-token rotation looks - // like: the sibling already minted a fresh grant and wrote it to disk, and we - // only failed because we refreshed with the now-revoked old token. In that - // case, blindly wiping would (a) force a needless re-auth and (b) poison the - // fresh token other sessions depend on. So: if disk holds a token newer than - // the one we just failed with, adopt it and return true — the caller keeps it - // on disk instead of clearing, and the SDK's post-invalidation retry refreshes - // with the fresh token and succeeds. Returns false when there's genuinely - // nothing newer to adopt (real invalidation → clear as normal). + // invalid_grant is what a sibling's rotation looks like: it already wrote a + // fresh grant to disk and we only failed because we used the revoked old + // token. Wiping would force a needless re-auth and poison the shared token + // other sessions depend on, so adopt a newer on-disk token instead. Returns + // false when nothing newer exists (a real invalidation → clear as normal). private adoptNewerTokenFromDisk(): boolean { const diskMtime = credentialsMtimeMs(); if ( @@ -204,8 +187,7 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { saveCredentials(this._tokens, undefined); break; case "tokens": - // A refresh failure is usually a sibling's rotation, not a dead session - // — adopt any newer on-disk token instead of wiping the shared store. + // Usually a sibling's rotation, not a dead session — see helper. if (this.adoptNewerTokenFromDisk()) return; this._tokens = undefined; saveCredentials(undefined, this._clientInfo); diff --git a/src/remote-client.ts b/src/remote-client.ts index d7c1366..a3aeeed 100644 --- a/src/remote-client.ts +++ b/src/remote-client.ts @@ -190,13 +190,10 @@ export async function createRemoteClient( { capabilities: {} }, ); - // Snapshot the access token we're about to connect with. Between now and a - // possible 401, a sibling per-session server can rotate the (single-use) - // refresh token and persist a newer grant. authProvider.tokens() re-reads the - // store when it changed on disk, so on auth failure we can tell whether a - // fresher token has since appeared and retry once with it — turning a - // cross-process rotation race into a silent reconnect instead of a full - // re-auth. Bounded to a single retry via authRetry so it can't spin. + // Snapshot the token we connect with. A sibling may rotate and persist a newer + // grant before we hit a 401; comparing against this on failure lets us retry + // once with the fresh token (silent reconnect) instead of forcing re-auth. + // authRetry bounds it to one retry. const accessTokenAtConnect = authProvider?.tokens()?.access_token; const transport = buildTransport(serverUrl, opts, chatSessionId); From fd2c095842ca3bd725693a9fe94de67a48a4ccb0 Mon Sep 17 00:00:00 2001 From: Pragati Agrawal Date: Wed, 29 Jul 2026 13:03:00 +0530 Subject: [PATCH 04/10] [Plugin] Close the tight rotation race: grace-window adopt, collision retry, atomic writes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit E2E-verified on an experimental pod against the real prod /oauth (3-min token-age gate; two plugin sessions sharing one store): - OLD build: the session losing a refresh race gets 400, wipes the shared store, and surfaces [SETUP_REQUIRED] — reproduced on demand. - With these changes: the loser recovers silently in both race shapes. Three additions on top of the existing rails: 1. invalidateCredentials('tokens') now polls the store briefly (2s, GLEAN_ROTATION_GRACE_MS) before the destructive clear — the loser's invalid_grant usually arrives milliseconds BEFORE the winner's write lands, and clearing immediately poisons the shared store for every session. Skipped when no refresh token was held (no race possible). 2. Connect-level sibling-refresh retry: when two sessions refresh the same grant simultaneously, fosite fails the loser with invalid_request (NOT invalid_grant — observed live), which the SDK rethrows raw without touching invalidateCredentials. createRemoteClient now recognizes refresh-shaped failures, waits out the same grace window for the sibling's token, and retries once. 3. saveCredentials writes temp-file + rename so concurrent sibling writers can never leave a torn store that parses as wiped. Co-Authored-By: Claude Opus 4.8 --- plugins/glean/dist/index.js | 61 +++++++++++++++++++-- src/auth-provider.ts | 61 ++++++++++++++++++++- src/remote-client.ts | 24 +++++++++ src/token-store.ts | 9 +++- tests/auth-provider.test.ts | 39 ++++++++++++++ tests/remote-client-auth-retry.test.ts | 73 ++++++++++++++++++++++++++ 6 files changed, 260 insertions(+), 7 deletions(-) diff --git a/plugins/glean/dist/index.js b/plugins/glean/dist/index.js index 2d74399..edf831e 100644 --- a/plugins/glean/dist/index.js +++ b/plugins/glean/dist/index.js @@ -25262,10 +25262,20 @@ async function createRemoteClient(serverUrl, opts, chatSessionId, authRetry = fa throw new AuthRequiredError(authProvider.authorizationUrl); } } + if (authProvider && !authRetry && isLikelyRefreshFailure(error2) && await authProvider.waitForSiblingRefresh(accessTokenAtConnect)) { + console.error( + "[auth] Refresh failed but a sibling refreshed \u2014 retrying with its token" + ); + return createRemoteClient(serverUrl, opts, chatSessionId, true); + } throw error2; } return client; } +function isLikelyRefreshFailure(error2) { + const msg = error2 instanceof Error ? error2.message : String(error2); + return /refresh|invalid_grant|invalid_request|oauth/i.test(msg); +} async function callRemoteTool(client, name, args) { const result = await client.callTool({ name, arguments: args }, void 0, { timeout: remoteToolTimeoutMs() @@ -25395,11 +25405,12 @@ function saveCredentials(tokens, clientInfo) { fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE }); fs.chmodSync(dir, DIR_MODE); const data = { tokens, clientInfo }; - fs.writeFileSync(filePath, JSON.stringify(data, null, 2), { + const tmpPath = `${filePath}.${process.pid}.tmp`; + fs.writeFileSync(tmpPath, JSON.stringify(data, null, 2), { encoding: "utf-8", mode: FILE_MODE }); - fs.chmodSync(filePath, FILE_MODE); + fs.renameSync(tmpPath, filePath); } catch (err) { const msg = err instanceof Error ? err.message : String(err); console.error(`[auth] Failed to persist credentials: ${msg}`); @@ -25415,6 +25426,19 @@ function clearCredentials() { } // src/auth-provider.ts +var ROTATION_GRACE_MS_DEFAULT = 2e3; +var ROTATION_POLL_MS = 100; +function rotationGraceMs() { + const raw = process.env.GLEAN_ROTATION_GRACE_MS; + if (raw !== void 0) { + const parsed = Number.parseInt(raw, 10); + if (Number.isFinite(parsed) && parsed >= 0) return parsed; + } + return ROTATION_GRACE_MS_DEFAULT; +} +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} function openBrowser(url2) { if (platform() === "win32") { spawn("cmd", ["/c", "start", '""', "/b", url2.replace(/&/g, "^&")], { @@ -25502,6 +25526,37 @@ var GleanOAuthClientProvider = class { ); return true; } + // The losing side of a refresh race often sees invalid_grant milliseconds + // BEFORE the winner's write lands on disk. Poll briefly for it instead of + // clearing right away — the clear writes {tokens: undefined} to the shared + // store, which would poison the winner's fresh grant for every session. + // Skipped when we held no refresh token: no refresh was possible, so + // there's no race to wait out. + async adoptNewerTokenWithGrace() { + if (this.adoptNewerTokenFromDisk()) return true; + if (!this._tokens?.refresh_token) return false; + const deadline = Date.now() + rotationGraceMs(); + while (Date.now() < deadline) { + await sleep(ROTATION_POLL_MS); + if (this.adoptNewerTokenFromDisk()) return true; + } + return false; + } + // Grace-bounded wait for a sibling's refresh to land on disk. Covers the + // collision shapes the SDK does NOT route through invalidateCredentials — + // observed live: two concurrent refreshes of the same grant make fosite + // return invalid_request (not invalid_grant) to the loser, which surfaces + // as a raw connect error. Returns true once a token differing from + // `previousAccessToken` is available to retry with. + async waitForSiblingRefresh(previousAccessToken) { + const deadline = Date.now() + rotationGraceMs(); + for (; ; ) { + const current = this.tokens()?.access_token; + if (current && current !== previousAccessToken) return true; + if (Date.now() >= deadline) return false; + await sleep(ROTATION_POLL_MS); + } + } get redirectUrl() { return getCallbackUrl(); } @@ -25546,7 +25601,7 @@ var GleanOAuthClientProvider = class { saveCredentials(this._tokens, void 0); break; case "tokens": - if (this.adoptNewerTokenFromDisk()) return; + if (await this.adoptNewerTokenWithGrace()) return; this._tokens = void 0; saveCredentials(void 0, this._clientInfo); break; diff --git a/src/auth-provider.ts b/src/auth-provider.ts index 667f66f..d7ed522 100644 --- a/src/auth-provider.ts +++ b/src/auth-provider.ts @@ -16,6 +16,26 @@ import { export type InvalidationScope = "all" | "client" | "tokens" | "verifier"; +// How long to wait for a sibling's in-flight refresh to land on disk before +// treating invalid_grant as a real invalidation. The losing side of a +// rotation race usually sees invalid_grant milliseconds before the winner's +// write arrives; clearing immediately would poison the shared store. +const ROTATION_GRACE_MS_DEFAULT = 2000; +const ROTATION_POLL_MS = 100; + +function rotationGraceMs(): number { + const raw = process.env.GLEAN_ROTATION_GRACE_MS; + if (raw !== undefined) { + const parsed = Number.parseInt(raw, 10); + if (Number.isFinite(parsed) && parsed >= 0) return parsed; + } + return ROTATION_GRACE_MS_DEFAULT; +} + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + /** * Open `url` in the user's default browser. Used for the self-open sign-in * path when the client does not support URL-mode elicitation (where the client @@ -135,6 +155,41 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { return true; } + // The losing side of a refresh race often sees invalid_grant milliseconds + // BEFORE the winner's write lands on disk. Poll briefly for it instead of + // clearing right away — the clear writes {tokens: undefined} to the shared + // store, which would poison the winner's fresh grant for every session. + // Skipped when we held no refresh token: no refresh was possible, so + // there's no race to wait out. + private async adoptNewerTokenWithGrace(): Promise { + if (this.adoptNewerTokenFromDisk()) return true; + if (!this._tokens?.refresh_token) return false; + const deadline = Date.now() + rotationGraceMs(); + while (Date.now() < deadline) { + await sleep(ROTATION_POLL_MS); + if (this.adoptNewerTokenFromDisk()) return true; + } + return false; + } + + // Grace-bounded wait for a sibling's refresh to land on disk. Covers the + // collision shapes the SDK does NOT route through invalidateCredentials — + // observed live: two concurrent refreshes of the same grant make fosite + // return invalid_request (not invalid_grant) to the loser, which surfaces + // as a raw connect error. Returns true once a token differing from + // `previousAccessToken` is available to retry with. + async waitForSiblingRefresh( + previousAccessToken: string | undefined, + ): Promise { + const deadline = Date.now() + rotationGraceMs(); + for (;;) { + const current = this.tokens()?.access_token; + if (current && current !== previousAccessToken) return true; + if (Date.now() >= deadline) return false; + await sleep(ROTATION_POLL_MS); + } + } + get redirectUrl(): string { return getCallbackUrl(); } @@ -187,8 +242,10 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { saveCredentials(this._tokens, undefined); break; case "tokens": - // Usually a sibling's rotation, not a dead session — see helper. - if (this.adoptNewerTokenFromDisk()) return; + // Usually a sibling's rotation, not a dead session — see helpers. + // Waits out an in-flight sibling refresh before the destructive + // clear. + if (await this.adoptNewerTokenWithGrace()) return; this._tokens = undefined; saveCredentials(undefined, this._clientInfo); break; diff --git a/src/remote-client.ts b/src/remote-client.ts index a3aeeed..f078d32 100644 --- a/src/remote-client.ts +++ b/src/remote-client.ts @@ -219,12 +219,36 @@ export async function createRemoteClient( throw new AuthRequiredError(authProvider.authorizationUrl); } } + // Concurrent refreshes of the same grant: fosite fails the loser with + // invalid_request (observed live), which the SDK rethrows as a raw error + // without touching invalidateCredentials. If a sibling's fresh grant + // lands on disk within the grace window, retry with it instead of + // surfacing the error. + if ( + authProvider && + !authRetry && + isLikelyRefreshFailure(error) && + (await authProvider.waitForSiblingRefresh(accessTokenAtConnect)) + ) { + console.error( + "[auth] Refresh failed but a sibling refreshed — retrying with its token", + ); + return createRemoteClient(serverUrl, opts, chatSessionId, true); + } throw error; } return client; } +// Token-refresh failures reach us as OAuth protocol errors whose shapes vary +// by server and race timing — match broadly; the disk re-check in the caller +// is what actually gates the retry. +function isLikelyRefreshFailure(error: unknown): boolean { + const msg = error instanceof Error ? error.message : String(error); + return /refresh|invalid_grant|invalid_request|oauth/i.test(msg); +} + export async function callRemoteTool( client: Client, name: string, diff --git a/src/token-store.ts b/src/token-store.ts index 028cd15..491c786 100644 --- a/src/token-store.ts +++ b/src/token-store.ts @@ -51,11 +51,16 @@ export function saveCredentials(tokens: unknown, clientInfo: unknown): void { fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE }); fs.chmodSync(dir, DIR_MODE); const data: StoredCredentials = { tokens, clientInfo }; - fs.writeFileSync(filePath, JSON.stringify(data, null, 2), { + // Write-temp-then-rename: the store is shared by concurrent sibling + // processes, and an in-place write could be read half-written — a parse + // failure that masquerades as a wiped store. Rename is atomic, so readers + // only ever see a complete old or complete new file. + const tmpPath = `${filePath}.${process.pid}.tmp`; + fs.writeFileSync(tmpPath, JSON.stringify(data, null, 2), { encoding: "utf-8", mode: FILE_MODE, }); - fs.chmodSync(filePath, FILE_MODE); + fs.renameSync(tmpPath, filePath); } catch (err) { const msg = err instanceof Error ? err.message : String(err); console.error(`[auth] Failed to persist credentials: ${msg}`); diff --git a/tests/auth-provider.test.ts b/tests/auth-provider.test.ts index 8450512..d7ad36c 100644 --- a/tests/auth-provider.test.ts +++ b/tests/auth-provider.test.ts @@ -28,11 +28,15 @@ describe("GleanOAuthClientProvider", () => { beforeEach(() => { delete process.env.PLUGIN_DATA_DIR; + // Skip the rotation grace window by default so invalidation tests don't + // wait out the real 2s poll; the grace test overrides this explicitly. + process.env.GLEAN_ROTATION_GRACE_MS = "0"; fs.rmSync(gleanDir, { recursive: true, force: true }); vi.clearAllMocks(); }); afterEach(() => { + delete process.env.GLEAN_ROTATION_GRACE_MS; fs.rmSync(gleanDir, { recursive: true, force: true }); }); @@ -180,6 +184,41 @@ describe("GleanOAuthClientProvider", () => { expect(raw.tokens).toBeUndefined(); }); + it("invalidateCredentials('tokens') adopts a token that lands during the grace window", async () => { + // The losing side of a rotation race sees invalid_grant milliseconds + // BEFORE the winner writes its fresh grant — the grace poll must catch + // the late write instead of clearing the shared store. + process.env.GLEAN_ROTATION_GRACE_MS = "2000"; + const provider = new GleanOAuthClientProvider(); + provider.saveTokens({ access_token: "T0", refresh_token: "R0" } as any); + + const invalidation = provider.invalidateCredentials("tokens"); + // Sibling's write lands mid-window. + setTimeout(() => { + writeCredFileNewer( + { access_token: "T1", refresh_token: "R1" }, + { client_id: "cid" }, + ); + }, 150); + await invalidation; + + expect(provider.tokens()?.access_token).toBe("T1"); + const raw = JSON.parse(fs.readFileSync(credFile, "utf-8")); + expect(raw.tokens.access_token).toBe("T1"); // not clobbered with undefined + }); + + it("skips the grace window when no refresh token was held (no race possible)", async () => { + process.env.GLEAN_ROTATION_GRACE_MS = "5000"; + const provider = new GleanOAuthClientProvider(); + provider.saveTokens({ access_token: "T0" } as any); // no refresh_token + + const start = Date.now(); + await provider.invalidateCredentials("tokens"); + + expect(Date.now() - start).toBeLessThan(1000); // no 5s poll + expect(provider.tokens()).toBeUndefined(); + }); + it("saveClientInformation persists to disk", () => { const provider = new GleanOAuthClientProvider(); const info = { client_id: "cid", client_secret: "sec" } as any; diff --git a/tests/remote-client-auth-retry.test.ts b/tests/remote-client-auth-retry.test.ts index 3afce9c..6f6a598 100644 --- a/tests/remote-client-auth-retry.test.ts +++ b/tests/remote-client-auth-retry.test.ts @@ -89,3 +89,76 @@ describe("createRemoteClient sibling-refresh retry", () => { expect(connectMock).toHaveBeenCalledTimes(1); }); }); + +describe("createRemoteClient refresh-collision retry", () => { + beforeEach(() => { + connectMock.mockReset(); + }); + + // The tight race: fosite fails the losing refresh with invalid_request, + // which the SDK rethrows as a raw error (never touching + // invalidateCredentials). Verified live on prod /oauth (2026-07-29). + const collisionError = new Error( + "The request is missing a required parameter, includes an invalid " + + "parameter value, includes a parameter more than once, or is " + + "otherwise malformed. Failed to refresh token", + ); + + function makeCollisionProvider(siblingRefreshed: boolean) { + return { + tokens: () => ({ access_token: "T0" }), + authorizationUrl: undefined, + pendingAuthCode: undefined, + needsFreshClient: () => false, + waitForSiblingRefresh: vi.fn(async () => siblingRefreshed), + invalidateCredentials: vi.fn(), + } as any; + } + + it("retries once when a sibling's refresh lands during the grace wait", async () => { + connectMock + .mockRejectedValueOnce(collisionError) + .mockResolvedValueOnce(undefined); + const provider = makeCollisionProvider(true /*siblingRefreshed*/); + + const client = await createRemoteClient( + "https://acme-be.glean.com/mcp/gateway/proxy", + { authProvider: provider }, + "sess-5", + ); + + expect(client).toBeTruthy(); + expect(connectMock).toHaveBeenCalledTimes(2); + expect(provider.waitForSiblingRefresh).toHaveBeenCalledWith("T0"); + }); + + it("rethrows when no sibling token appears within the grace window", async () => { + connectMock.mockRejectedValue(collisionError); + const provider = makeCollisionProvider(false /*siblingRefreshed*/); + + await expect( + createRemoteClient( + "https://acme-be.glean.com/mcp/gateway/proxy", + { authProvider: provider }, + "sess-6", + ), + ).rejects.toBe(collisionError); + + expect(connectMock).toHaveBeenCalledTimes(1); + }); + + it("does not treat unrelated connect errors as refresh failures", async () => { + connectMock.mockRejectedValue(new Error("socket hang up")); + const provider = makeCollisionProvider(true /*siblingRefreshed*/); + + await expect( + createRemoteClient( + "https://acme-be.glean.com/mcp/gateway/proxy", + { authProvider: provider }, + "sess-7", + ), + ).rejects.toThrow("socket hang up"); + + expect(provider.waitForSiblingRefresh).not.toHaveBeenCalled(); + }); +}); From d97069c26cd3ff49b9b42863059c8d1cbd4c04be Mon Sep 17 00:00:00 2001 From: Pragati Agrawal Date: Wed, 29 Jul 2026 13:21:17 +0530 Subject: [PATCH 05/10] Rename syncFromDisk to syncTokensFromDisk (review feedback) Co-Authored-By: Claude Opus 4.8 --- plugins/glean/dist/index.js | 6 +++--- src/auth-provider.ts | 8 ++++---- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/plugins/glean/dist/index.js b/plugins/glean/dist/index.js index edf831e..8604edb 100644 --- a/plugins/glean/dist/index.js +++ b/plugins/glean/dist/index.js @@ -25461,7 +25461,7 @@ var GleanOAuthClientProvider = class { // complete — likely because the server rejected the (stale) client_id. _authUrlPending = false; // mtime of the creds file when we last read it — lets us spot a sibling - // process rewriting the shared store. See syncFromDisk. + // process rewriting the shared store. See syncTokensFromDisk. _credentialsMtimeMs; authorizationUrl; /** @@ -25485,7 +25485,7 @@ var GleanOAuthClientProvider = class { // sibling's fresh grant, not a dead token that would force re-auth. Stay // conservative on a missing/token-less file — don't evict a token that still // works for us. - syncFromDisk() { + syncTokensFromDisk() { const mtimeMs = credentialsMtimeMs(); if (mtimeMs === void 0) return; if (this._credentialsMtimeMs !== void 0 && mtimeMs <= this._credentialsMtimeMs) { @@ -25575,7 +25575,7 @@ var GleanOAuthClientProvider = class { this._credentialsMtimeMs = credentialsMtimeMs(); } tokens() { - this.syncFromDisk(); + this.syncTokensFromDisk(); return this._tokens; } saveTokens(tokens) { diff --git a/src/auth-provider.ts b/src/auth-provider.ts index d7ed522..135556e 100644 --- a/src/auth-provider.ts +++ b/src/auth-provider.ts @@ -73,7 +73,7 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { // complete — likely because the server rejected the (stale) client_id. private _authUrlPending = false; // mtime of the creds file when we last read it — lets us spot a sibling - // process rewriting the shared store. See syncFromDisk. + // process rewriting the shared store. See syncTokensFromDisk. private _credentialsMtimeMs: number | undefined; authorizationUrl: string | undefined; @@ -101,7 +101,7 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { // sibling's fresh grant, not a dead token that would force re-auth. Stay // conservative on a missing/token-less file — don't evict a token that still // works for us. - private syncFromDisk(): void { + private syncTokensFromDisk(): void { const mtimeMs = credentialsMtimeMs(); if (mtimeMs === undefined) return; if ( @@ -212,7 +212,7 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { } tokens(): OAuthTokens | undefined { - this.syncFromDisk(); + this.syncTokensFromDisk(); return this._tokens; } @@ -221,7 +221,7 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { this._authUrlPending = false; saveCredentials(this._tokens, this._clientInfo); // Record the mtime of the file we just wrote so our own write doesn't look - // like a sibling change on the next syncFromDisk. + // like a sibling change on the next syncTokensFromDisk. this._credentialsMtimeMs = credentialsMtimeMs(); this.onTokensChanged?.(tokens); } From 65c90a982e3846cdfe820ef9be7385954ad37f22 Mon Sep 17 00:00:00 2001 From: Pragati Agrawal Date: Thu, 30 Jul 2026 16:10:20 +0530 Subject: [PATCH 06/10] Shorten comments to one-line purpose statements Co-Authored-By: Claude Opus 4.8 --- plugins/glean/dist/index.js | 34 +++++-------------- src/auth-provider.ts | 46 +++++++------------------- src/remote-client.ts | 16 +++------ src/token-store.ts | 13 ++------ tests/auth-provider.test.ts | 8 ++--- tests/remote-client-auth-retry.test.ts | 4 +-- 6 files changed, 31 insertions(+), 90 deletions(-) diff --git a/plugins/glean/dist/index.js b/plugins/glean/dist/index.js index 8604edb..ddb1b3e 100644 --- a/plugins/glean/dist/index.js +++ b/plugins/glean/dist/index.js @@ -25460,8 +25460,7 @@ var GleanOAuthClientProvider = class { // explicitly invalidating. Used to detect when a previous auth URL didn't // complete — likely because the server rejected the (stale) client_id. _authUrlPending = false; - // mtime of the creds file when we last read it — lets us spot a sibling - // process rewriting the shared store. See syncTokensFromDisk. + // mtime at last read; detects sibling rewrites of the shared store. _credentialsMtimeMs; authorizationUrl; /** @@ -25479,12 +25478,8 @@ var GleanOAuthClientProvider = class { } this._credentialsMtimeMs = credentialsMtimeMs(); } - // Per-session sibling processes share one creds file. When one refreshes, the - // rotated single-use refresh token it persists kills the copy every other - // process holds in memory. Re-read before the SDK reads tokens() so we use the - // sibling's fresh grant, not a dead token that would force re-auth. Stay - // conservative on a missing/token-less file — don't evict a token that still - // works for us. + // Re-read the shared store after a sibling process rewrites it, so we use + // the rotated grant instead of a stale in-memory copy. syncTokensFromDisk() { const mtimeMs = credentialsMtimeMs(); if (mtimeMs === void 0) return; @@ -25501,11 +25496,8 @@ var GleanOAuthClientProvider = class { this._clientInfo = stored.clientInfo; } } - // invalid_grant is what a sibling's rotation looks like: it already wrote a - // fresh grant to disk and we only failed because we used the revoked old - // token. Wiping would force a needless re-auth and poison the shared token - // other sessions depend on, so adopt a newer on-disk token instead. Returns - // false when nothing newer exists (a real invalidation → clear as normal). + // On invalid_grant, adopt a sibling's newer on-disk token instead of + // clearing. Returns false when nothing newer exists. adoptNewerTokenFromDisk() { const diskMtime = credentialsMtimeMs(); if (diskMtime === void 0 || this._credentialsMtimeMs === void 0 || diskMtime <= this._credentialsMtimeMs) { @@ -25526,12 +25518,8 @@ var GleanOAuthClientProvider = class { ); return true; } - // The losing side of a refresh race often sees invalid_grant milliseconds - // BEFORE the winner's write lands on disk. Poll briefly for it instead of - // clearing right away — the clear writes {tokens: undefined} to the shared - // store, which would poison the winner's fresh grant for every session. - // Skipped when we held no refresh token: no refresh was possible, so - // there's no race to wait out. + // Poll briefly for the race winner's write before clearing. Skipped when + // no refresh token was held (no race possible). async adoptNewerTokenWithGrace() { if (this.adoptNewerTokenFromDisk()) return true; if (!this._tokens?.refresh_token) return false; @@ -25542,12 +25530,8 @@ var GleanOAuthClientProvider = class { } return false; } - // Grace-bounded wait for a sibling's refresh to land on disk. Covers the - // collision shapes the SDK does NOT route through invalidateCredentials — - // observed live: two concurrent refreshes of the same grant make fosite - // return invalid_request (not invalid_grant) to the loser, which surfaces - // as a raw connect error. Returns true once a token differing from - // `previousAccessToken` is available to retry with. + // Grace-bounded wait for a sibling's refresh; covers failures the SDK does + // not route through invalidateCredentials (e.g. invalid_request collisions). async waitForSiblingRefresh(previousAccessToken) { const deadline = Date.now() + rotationGraceMs(); for (; ; ) { diff --git a/src/auth-provider.ts b/src/auth-provider.ts index 135556e..cebf440 100644 --- a/src/auth-provider.ts +++ b/src/auth-provider.ts @@ -16,10 +16,7 @@ import { export type InvalidationScope = "all" | "client" | "tokens" | "verifier"; -// How long to wait for a sibling's in-flight refresh to land on disk before -// treating invalid_grant as a real invalidation. The losing side of a -// rotation race usually sees invalid_grant milliseconds before the winner's -// write arrives; clearing immediately would poison the shared store. +// Grace window for a sibling's in-flight refresh to land on disk. const ROTATION_GRACE_MS_DEFAULT = 2000; const ROTATION_POLL_MS = 100; @@ -72,8 +69,7 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { // explicitly invalidating. Used to detect when a previous auth URL didn't // complete — likely because the server rejected the (stale) client_id. private _authUrlPending = false; - // mtime of the creds file when we last read it — lets us spot a sibling - // process rewriting the shared store. See syncTokensFromDisk. + // mtime at last read; detects sibling rewrites of the shared store. private _credentialsMtimeMs: number | undefined; authorizationUrl: string | undefined; @@ -95,12 +91,8 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { this._credentialsMtimeMs = credentialsMtimeMs(); } - // Per-session sibling processes share one creds file. When one refreshes, the - // rotated single-use refresh token it persists kills the copy every other - // process holds in memory. Re-read before the SDK reads tokens() so we use the - // sibling's fresh grant, not a dead token that would force re-auth. Stay - // conservative on a missing/token-less file — don't evict a token that still - // works for us. + // Re-read the shared store after a sibling process rewrites it, so we use + // the rotated grant instead of a stale in-memory copy. private syncTokensFromDisk(): void { const mtimeMs = credentialsMtimeMs(); if (mtimeMs === undefined) return; @@ -121,11 +113,8 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { } } - // invalid_grant is what a sibling's rotation looks like: it already wrote a - // fresh grant to disk and we only failed because we used the revoked old - // token. Wiping would force a needless re-auth and poison the shared token - // other sessions depend on, so adopt a newer on-disk token instead. Returns - // false when nothing newer exists (a real invalidation → clear as normal). + // On invalid_grant, adopt a sibling's newer on-disk token instead of + // clearing. Returns false when nothing newer exists. private adoptNewerTokenFromDisk(): boolean { const diskMtime = credentialsMtimeMs(); if ( @@ -155,12 +144,8 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { return true; } - // The losing side of a refresh race often sees invalid_grant milliseconds - // BEFORE the winner's write lands on disk. Poll briefly for it instead of - // clearing right away — the clear writes {tokens: undefined} to the shared - // store, which would poison the winner's fresh grant for every session. - // Skipped when we held no refresh token: no refresh was possible, so - // there's no race to wait out. + // Poll briefly for the race winner's write before clearing. Skipped when + // no refresh token was held (no race possible). private async adoptNewerTokenWithGrace(): Promise { if (this.adoptNewerTokenFromDisk()) return true; if (!this._tokens?.refresh_token) return false; @@ -172,12 +157,8 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { return false; } - // Grace-bounded wait for a sibling's refresh to land on disk. Covers the - // collision shapes the SDK does NOT route through invalidateCredentials — - // observed live: two concurrent refreshes of the same grant make fosite - // return invalid_request (not invalid_grant) to the loser, which surfaces - // as a raw connect error. Returns true once a token differing from - // `previousAccessToken` is available to retry with. + // Grace-bounded wait for a sibling's refresh; covers failures the SDK does + // not route through invalidateCredentials (e.g. invalid_request collisions). async waitForSiblingRefresh( previousAccessToken: string | undefined, ): Promise { @@ -220,8 +201,7 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { this._tokens = tokens; this._authUrlPending = false; saveCredentials(this._tokens, this._clientInfo); - // Record the mtime of the file we just wrote so our own write doesn't look - // like a sibling change on the next syncTokensFromDisk. + // Own write must not look like a sibling change. this._credentialsMtimeMs = credentialsMtimeMs(); this.onTokensChanged?.(tokens); } @@ -242,9 +222,7 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { saveCredentials(this._tokens, undefined); break; case "tokens": - // Usually a sibling's rotation, not a dead session — see helpers. - // Waits out an in-flight sibling refresh before the destructive - // clear. + // Usually a sibling's rotation — try adopting before clearing. if (await this.adoptNewerTokenWithGrace()) return; this._tokens = undefined; saveCredentials(undefined, this._clientInfo); diff --git a/src/remote-client.ts b/src/remote-client.ts index f078d32..d825947 100644 --- a/src/remote-client.ts +++ b/src/remote-client.ts @@ -190,10 +190,7 @@ export async function createRemoteClient( { capabilities: {} }, ); - // Snapshot the token we connect with. A sibling may rotate and persist a newer - // grant before we hit a 401; comparing against this on failure lets us retry - // once with the fresh token (silent reconnect) instead of forcing re-auth. - // authRetry bounds it to one retry. + // Snapshot to detect a sibling's refresh between connect and failure. const accessTokenAtConnect = authProvider?.tokens()?.access_token; const transport = buildTransport(serverUrl, opts, chatSessionId); @@ -219,11 +216,8 @@ export async function createRemoteClient( throw new AuthRequiredError(authProvider.authorizationUrl); } } - // Concurrent refreshes of the same grant: fosite fails the loser with - // invalid_request (observed live), which the SDK rethrows as a raw error - // without touching invalidateCredentials. If a sibling's fresh grant - // lands on disk within the grace window, retry with it instead of - // surfacing the error. + // Concurrent-refresh losers get errors the SDK rethrows raw (e.g. fosite + // invalid_request); retry once if a sibling's grant lands in the grace window. if ( authProvider && !authRetry && @@ -241,9 +235,7 @@ export async function createRemoteClient( return client; } -// Token-refresh failures reach us as OAuth protocol errors whose shapes vary -// by server and race timing — match broadly; the disk re-check in the caller -// is what actually gates the retry. +// Match broadly; the caller's disk re-check gates the actual retry. function isLikelyRefreshFailure(error: unknown): boolean { const msg = error instanceof Error ? error.message : String(error); return /refresh|invalid_grant|invalid_request|oauth/i.test(msg); diff --git a/src/token-store.ts b/src/token-store.ts index 491c786..535a07d 100644 --- a/src/token-store.ts +++ b/src/token-store.ts @@ -29,12 +29,8 @@ export function loadCredentials(): StoredCredentials | undefined { } /** - * Last-modified time (epoch ms) of the credentials file, or undefined if it - * doesn't exist / can't be stat'd. Used as a cheap change-detection probe so a - * long-lived provider can notice when a sibling process has rewritten the - * shared store (e.g. after a refresh-token rotation) and re-read it, instead of - * serving a stale in-memory snapshot. Kept separate from loadCredentials so the - * common "nothing changed" path is a single stat, not a full read + parse. + * mtime of the credentials file (epoch ms), or undefined if unreadable. + * Cheap change probe: a single stat, no read + parse. */ export function credentialsMtimeMs(): number | undefined { try { @@ -51,10 +47,7 @@ export function saveCredentials(tokens: unknown, clientInfo: unknown): void { fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE }); fs.chmodSync(dir, DIR_MODE); const data: StoredCredentials = { tokens, clientInfo }; - // Write-temp-then-rename: the store is shared by concurrent sibling - // processes, and an in-place write could be read half-written — a parse - // failure that masquerades as a wiped store. Rename is atomic, so readers - // only ever see a complete old or complete new file. + // Temp-file + rename: concurrent readers never see a half-written store. const tmpPath = `${filePath}.${process.pid}.tmp`; fs.writeFileSync(tmpPath, JSON.stringify(data, null, 2), { encoding: "utf-8", diff --git a/tests/auth-provider.test.ts b/tests/auth-provider.test.ts index d7ad36c..3e4e032 100644 --- a/tests/auth-provider.test.ts +++ b/tests/auth-provider.test.ts @@ -78,9 +78,7 @@ describe("GleanOAuthClientProvider", () => { expect(raw.tokens.access_token).toBe("new_tok"); }); - // --- Cross-process sync: a per-session sibling server may rotate the - // refresh token and rewrite the shared store; tokens() must pick that up - // instead of serving the stale startup snapshot. --- + // --- Cross-process sync: tokens() must pick up a sibling's rewrite. --- const credFile = path.join(gleanDir, "mcp-credentials.json"); @@ -185,9 +183,7 @@ describe("GleanOAuthClientProvider", () => { }); it("invalidateCredentials('tokens') adopts a token that lands during the grace window", async () => { - // The losing side of a rotation race sees invalid_grant milliseconds - // BEFORE the winner writes its fresh grant — the grace poll must catch - // the late write instead of clearing the shared store. + // The winner's write lands just after the loser's invalid_grant. process.env.GLEAN_ROTATION_GRACE_MS = "2000"; const provider = new GleanOAuthClientProvider(); provider.saveTokens({ access_token: "T0", refresh_token: "R0" } as any); diff --git a/tests/remote-client-auth-retry.test.ts b/tests/remote-client-auth-retry.test.ts index 6f6a598..f730cc7 100644 --- a/tests/remote-client-auth-retry.test.ts +++ b/tests/remote-client-auth-retry.test.ts @@ -95,9 +95,7 @@ describe("createRemoteClient refresh-collision retry", () => { connectMock.mockReset(); }); - // The tight race: fosite fails the losing refresh with invalid_request, - // which the SDK rethrows as a raw error (never touching - // invalidateCredentials). Verified live on prod /oauth (2026-07-29). + // Fosite fails concurrent-refresh losers with invalid_request (SDK rethrows raw). const collisionError = new Error( "The request is missing a required parameter, includes an invalid " + "parameter value, includes a parameter more than once, or is " + From fc6b0f39ea9e511dbd8e656baf2b62285aec557b Mon Sep 17 00:00:00 2001 From: Pragati Agrawal Date: Wed, 29 Jul 2026 13:03:40 +0530 Subject: [PATCH 07/10] [Plugin] Reuse the DCR client instead of re-registering on setup and abandoned sign-ins MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One user accumulated 34 'Glean Claude Code Plugin' clients in their authorized-apps list. The server never dedupes registrations (the DCR endpoint has no user identity in scope), and a 7-day sweeper deletes never-used clients — so every needless client-side re-registration either piles up as a UI row or becomes a future invalid_client. Log correlation showed every setup.configured/setup.reset was followed by a fresh registration 6-9s later. Client-side causes fixed: 1. setup({email}/{server_url}) wiped credentials (including clientInfo) even when the resolved URL was IDENTICAL to the configured one — the dominant trigger, one client per call. Now only an actual URL change clears auth state. 2. An abandoned sign-in (browser closed, elicitation timeout) forced invalidateCredentials('all') → fresh DCR. Now the existing registration is retried first (abandonPendingSignIn budget); a fresh DCR is the escalation path after two consecutive failures with the same client — the pattern of a client actually rejected server-side. 3. clientInformation() now syncs from the shared store, so two sessions starting concurrently no longer both register (the SDK registers whenever it returns undefined). 4. Every registration is now logged ([auth] Registered OAuth client) — previously invisible. E2E note: one client survived a full day of race testing on an exp pod — sign-in, a bug-induced token wipe, re-sign-in, and six refresh rotations — with zero new registrations. Co-Authored-By: Claude Opus 4.8 --- plugins/glean/dist/index.js | 43 +++++++++++++++---- src/auth-provider.ts | 19 +++++++++ src/index.ts | 16 +++---- src/remote-client.ts | 25 +++++++---- tests/auth-provider.test.ts | 58 ++++++++++++++++++++++++++ tests/remote-client-auth-retry.test.ts | 45 ++++++++++++++++++++ 6 files changed, 184 insertions(+), 22 deletions(-) diff --git a/plugins/glean/dist/index.js b/plugins/glean/dist/index.js index ddb1b3e..bc1d1e1 100644 --- a/plugins/glean/dist/index.js +++ b/plugins/glean/dist/index.js @@ -25230,15 +25230,24 @@ async function createRemoteClient(serverUrl, opts, chatSessionId, authRetry = fa } catch (err) { const msg = err instanceof Error ? err.message : String(err); console.error(`[auth] Code exchange failed: ${msg} \u2014 discarding stale auth state`); - authProvider.clearPendingAuth(); pendingTransport = void 0; - await authProvider.invalidateCredentials("all"); + if (!authProvider.abandonPendingSignIn()) { + await authProvider.invalidateCredentials("all"); + } return createRemoteClient(serverUrl, opts, chatSessionId); } } if (authProvider?.needsFreshClient()) { - console.error("[auth] Previous auth URL didn't complete \u2014 forcing fresh DCR"); - await authProvider.invalidateCredentials("all"); + if (authProvider.abandonPendingSignIn()) { + console.error( + "[auth] Previous sign-in didn't complete \u2014 retrying with the existing client" + ); + } else { + console.error( + "[auth] Sign-in failed twice with this client \u2014 forcing fresh DCR" + ); + await authProvider.invalidateCredentials("all"); + } } const client = new Client( { name: "glean", version: "1.0.0" }, @@ -25462,6 +25471,8 @@ var GleanOAuthClientProvider = class { _authUrlPending = false; // mtime at last read; detects sibling rewrites of the shared store. _credentialsMtimeMs; + // Consecutive abandoned sign-ins with the current client. + _abandonedSignIns = 0; authorizationUrl; /** * Optional hook invoked whenever the in-memory token state changes — @@ -25551,9 +25562,11 @@ var GleanOAuthClientProvider = class { }; } clientInformation() { + this.syncTokensFromDisk(); return this._clientInfo; } saveClientInformation(info) { + console.error(`[auth] Registered OAuth client: ${info.client_id}`); this._clientInfo = info; saveCredentials(this._tokens, this._clientInfo); this._credentialsMtimeMs = credentialsMtimeMs(); @@ -25565,6 +25578,7 @@ var GleanOAuthClientProvider = class { saveTokens(tokens) { this._tokens = tokens; this._authUrlPending = false; + this._abandonedSignIns = 0; saveCredentials(this._tokens, this._clientInfo); this._credentialsMtimeMs = credentialsMtimeMs(); this.onTokensChanged?.(tokens); @@ -25578,6 +25592,7 @@ var GleanOAuthClientProvider = class { this._clientInfo = void 0; this._codeVerifier = ""; this._authUrlPending = false; + this._abandonedSignIns = 0; clearCredentials(); break; case "client": @@ -25602,6 +25617,16 @@ var GleanOAuthClientProvider = class { needsFreshClient() { return this._authUrlPending && !this._tokens?.access_token && this._pendingAuthCode === void 0; } + // Abandoned sign-in: keep the client and clear the pending flow. Returns + // false after two consecutive failures (client likely dead → re-register). + abandonPendingSignIn() { + this._abandonedSignIns += 1; + this._codeVerifier = ""; + this._pendingAuthCode = void 0; + this.authorizationUrl = void 0; + this._authUrlPending = false; + return this._abandonedSignIns < 2; + } get pendingAuthCode() { return this._pendingAuthCode; } @@ -26943,6 +26968,7 @@ ${EMAIL_RESOLVE_FAILED_TEXT}` isError: true }; } + const previousUrl = loadServerUrl(); try { saveServerUrl(normalized); } catch (err) { @@ -26954,10 +26980,13 @@ ${EMAIL_RESOLVE_FAILED_TEXT}` isError: true }; } - clearCredentials(); - oauthProvider = void 0; + const urlChanged = previousUrl !== normalized; + if (urlChanged) { + clearCredentials(); + oauthProvider = void 0; + } cachedRemoteTools = loadRemoteTools(normalized); - logLine("setup.configured", { serverUrl: normalized }); + logLine("setup.configured", { serverUrl: normalized, urlChanged }); } return await advanceSetup(); } diff --git a/src/auth-provider.ts b/src/auth-provider.ts index cebf440..d3345d9 100644 --- a/src/auth-provider.ts +++ b/src/auth-provider.ts @@ -71,6 +71,8 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { private _authUrlPending = false; // mtime at last read; detects sibling rewrites of the shared store. private _credentialsMtimeMs: number | undefined; + // Consecutive abandoned sign-ins with the current client. + private _abandonedSignIns = 0; authorizationUrl: string | undefined; @@ -183,10 +185,13 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { } clientInformation(): OAuthClientInformationMixed | undefined { + // Pick up a sibling's registration; the SDK registers whenever this is undefined. + this.syncTokensFromDisk(); return this._clientInfo; } saveClientInformation(info: OAuthClientInformationMixed): void { + console.error(`[auth] Registered OAuth client: ${info.client_id}`); this._clientInfo = info; saveCredentials(this._tokens, this._clientInfo); this._credentialsMtimeMs = credentialsMtimeMs(); @@ -200,6 +205,7 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { saveTokens(tokens: OAuthTokens): void { this._tokens = tokens; this._authUrlPending = false; + this._abandonedSignIns = 0; saveCredentials(this._tokens, this._clientInfo); // Own write must not look like a sibling change. this._credentialsMtimeMs = credentialsMtimeMs(); @@ -215,6 +221,8 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { this._clientInfo = undefined; this._codeVerifier = ""; this._authUrlPending = false; + // Fresh client → fresh retry budget. + this._abandonedSignIns = 0; clearCredentials(); break; case "client": @@ -249,6 +257,17 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { ); } + // Abandoned sign-in: keep the client and clear the pending flow. Returns + // false after two consecutive failures (client likely dead → re-register). + abandonPendingSignIn(): boolean { + this._abandonedSignIns += 1; + this._codeVerifier = ""; + this._pendingAuthCode = undefined; + this.authorizationUrl = undefined; + this._authUrlPending = false; + return this._abandonedSignIns < 2; + } + get pendingAuthCode(): string | undefined { return this._pendingAuthCode; } diff --git a/src/index.ts b/src/index.ts index aa07a4e..bf87b6d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -795,6 +795,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => { }; } + const previousUrl = loadServerUrl(); try { saveServerUrl(normalized); } catch (err) { @@ -807,14 +808,15 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => { }; } - // New instance — clear stale auth state. The on-disk remote-tool - // cache for the previous URL is left intact (so switching back is - // instant); we just rehydrate from whatever cache exists for the - // newly configured URL — empty for a first-time server. - clearCredentials(); - oauthProvider = undefined; + // Only wipe auth state when actually switching instances — a same-URL + // re-setup must keep the DCR client. Old URL's tool cache is kept. + const urlChanged = previousUrl !== normalized; + if (urlChanged) { + clearCredentials(); + oauthProvider = undefined; + } cachedRemoteTools = loadRemoteTools(normalized); - logLine("setup.configured", { serverUrl: normalized }); + logLine("setup.configured", { serverUrl: normalized, urlChanged }); // Fall through to advanceSetup, which will now find URL ✓ and try // to drive auth + tool fetch in the same call. } diff --git a/src/remote-client.ts b/src/remote-client.ts index d825947..d718bf4 100644 --- a/src/remote-client.ts +++ b/src/remote-client.ts @@ -169,20 +169,29 @@ export async function createRemoteClient( } catch (err) { const msg = err instanceof Error ? err.message : String(err); console.error(`[auth] Code exchange failed: ${msg} — discarding stale auth state`); - authProvider.clearPendingAuth(); pendingTransport = undefined; - await authProvider.invalidateCredentials("all"); + // Exchange failures are about the code/verifier, not the client — keep + // the registration; repeat failure escalates to a fresh DCR. + if (!authProvider.abandonPendingSignIn()) { + await authProvider.invalidateCredentials("all"); + } return createRemoteClient(serverUrl, opts, chatSessionId); } } - // DCR recovery: we previously issued an authorize URL but never received - // tokens. The URL was likely rejected by the server (most commonly: the - // cached DCR client was deleted server-side). Force a fresh DCR so the next - // URL we generate uses a valid, server-known client_id. + // Unfinished sign-in: reuse the existing registration first; fresh DCR is + // the escalation path. if (authProvider?.needsFreshClient()) { - console.error("[auth] Previous auth URL didn't complete — forcing fresh DCR"); - await authProvider.invalidateCredentials("all"); + if (authProvider.abandonPendingSignIn()) { + console.error( + "[auth] Previous sign-in didn't complete — retrying with the existing client", + ); + } else { + console.error( + "[auth] Sign-in failed twice with this client — forcing fresh DCR", + ); + await authProvider.invalidateCredentials("all"); + } } const client = new Client( diff --git a/tests/auth-provider.test.ts b/tests/auth-provider.test.ts index 3e4e032..b73a1c5 100644 --- a/tests/auth-provider.test.ts +++ b/tests/auth-provider.test.ts @@ -215,6 +215,64 @@ describe("GleanOAuthClientProvider", () => { expect(provider.tokens()).toBeUndefined(); }); + // --- Client reuse: an abandoned sign-in must not burn the DCR client. + // Every registration permanently adds a client server-side, so the + // existing one is retried first and a fresh DCR is the escalation path. --- + + it("clientInformation() adopts a sibling's registration from disk", () => { + // Constructed with no credentials — this process would otherwise register. + const provider = new GleanOAuthClientProvider(); + expect(provider.clientInformation()).toBeUndefined(); + + // Sibling process wins the registration race and persists its client. + writeCredFileNewer(undefined, { client_id: "cid_sibling" }); + + expect(provider.clientInformation()).toEqual({ client_id: "cid_sibling" }); + }); + + it("abandonPendingSignIn keeps the registered client and clears the pending flow", async () => { + const provider = new GleanOAuthClientProvider(); + provider.saveClientInformation({ client_id: "cid" } as any); + provider.saveCodeVerifier("v1"); + await provider.redirectToAuthorization( + new URL("https://example.com/oauth/authorize?state=s1"), + ); + expect(provider.needsFreshClient()).toBe(true); + + expect(provider.abandonPendingSignIn()).toBe(true); + + expect(provider.clientInformation()).toEqual({ client_id: "cid" }); + expect(provider.codeVerifier()).toBe(""); + expect(provider.authorizationUrl).toBeUndefined(); + expect(provider.needsFreshClient()).toBe(false); + // Registration untouched on disk — nothing was wiped. + const raw = JSON.parse(fs.readFileSync(credFile, "utf-8")); + expect(raw.clientInfo.client_id).toBe("cid"); + }); + + it("abandonPendingSignIn exhausts after two consecutive abandonments", () => { + const provider = new GleanOAuthClientProvider(); + expect(provider.abandonPendingSignIn()).toBe(true); + expect(provider.abandonPendingSignIn()).toBe(false); + }); + + it("a completed sign-in resets the abandonment budget", () => { + const provider = new GleanOAuthClientProvider(); + expect(provider.abandonPendingSignIn()).toBe(true); + provider.saveTokens({ access_token: "tok" } as any); + // Fresh budget: the next abandonment retries the client again. + expect(provider.abandonPendingSignIn()).toBe(true); + }); + + it("invalidateCredentials('all') resets the budget for the next registration", async () => { + const provider = new GleanOAuthClientProvider(); + expect(provider.abandonPendingSignIn()).toBe(true); + expect(provider.abandonPendingSignIn()).toBe(false); + await provider.invalidateCredentials("all"); + // A freshly registered client gets a fresh retry budget. + expect(provider.abandonPendingSignIn()).toBe(true); + }); + it("saveClientInformation persists to disk", () => { const provider = new GleanOAuthClientProvider(); const info = { client_id: "cid", client_secret: "sec" } as any; diff --git a/tests/remote-client-auth-retry.test.ts b/tests/remote-client-auth-retry.test.ts index f730cc7..2508234 100644 --- a/tests/remote-client-auth-retry.test.ts +++ b/tests/remote-client-auth-retry.test.ts @@ -90,6 +90,51 @@ describe("createRemoteClient sibling-refresh retry", () => { }); }); +describe("createRemoteClient abandoned sign-in client reuse", () => { + beforeEach(() => { + connectMock.mockReset(); + }); + + function makeAbandonedProvider(budgetLeft: boolean) { + return { + tokens: () => ({ access_token: "T0" }), + authorizationUrl: undefined, + pendingAuthCode: undefined, + needsFreshClient: () => true, + abandonPendingSignIn: vi.fn(() => budgetLeft), + invalidateCredentials: vi.fn(), + } as any; + } + + it("reuses the existing client on the first abandoned sign-in", async () => { + connectMock.mockResolvedValueOnce(undefined); + const provider = makeAbandonedProvider(true); + + await createRemoteClient( + "https://acme-be.glean.com/mcp/gateway/proxy", + { authProvider: provider }, + "sess-3", + ); + + expect(provider.abandonPendingSignIn).toHaveBeenCalledTimes(1); + // The registration survives — no wipe, no fresh DCR. + expect(provider.invalidateCredentials).not.toHaveBeenCalled(); + }); + + it("falls back to a fresh DCR once the retry budget is exhausted", async () => { + connectMock.mockResolvedValueOnce(undefined); + const provider = makeAbandonedProvider(false); + + await createRemoteClient( + "https://acme-be.glean.com/mcp/gateway/proxy", + { authProvider: provider }, + "sess-4", + ); + + expect(provider.invalidateCredentials).toHaveBeenCalledWith("all"); + }); +}); + describe("createRemoteClient refresh-collision retry", () => { beforeEach(() => { connectMock.mockReset(); From 3ac82cb4a805fac0a68ccea548392758f0ffdb1f Mon Sep 17 00:00:00 2001 From: Pragati Agrawal Date: Mon, 3 Aug 2026 01:38:35 +0530 Subject: [PATCH 08/10] [Plugin] Harden auth store and DCR recovery --- README.md | 13 +- plugins/glean/dist/index.js | 808 ++++++++++++++++++------- plugins/glean/start.mjs | 4 +- src/auth-provider.ts | 176 +++++- src/data-dir.ts | 249 ++++++++ src/index.ts | 109 +++- src/remote-client.ts | 57 +- src/remote-tools-cache-store.ts | 13 +- src/token-store.ts | 117 +++- src/url-config-store.ts | 14 +- tests/auth-provider.test.ts | 41 ++ tests/remote-client-auth-retry.test.ts | 54 ++ tests/remote-tools-cache-store.test.ts | 2 +- tests/token-store.test.ts | 76 ++- tests/url-config-store.test.ts | 2 +- 15 files changed, 1464 insertions(+), 271 deletions(-) create mode 100644 src/data-dir.ts diff --git a/README.md b/README.md index f320098..9e78c32 100644 --- a/README.md +++ b/README.md @@ -121,8 +121,11 @@ The launcher (`plugins/glean/start.mjs`) also derives and **exports** three more variables the bundle reads, so these are internal — start.mjs overwrites them on every launch and setting them yourself has no effect: -- `PLUGIN_DATA_DIR` — directory for credentials, caches, the saved server URL, - and `glean-server.log`. Defaults to `~/.glean`, or the host's +- `PLUGIN_DATA_DIR` — host-managed directory used for skills/cache compatibility. + Auth credentials, server configuration, remote-tool cache, and logs use the + stable canonical `~/.glean` directory so terminal and plugin launches share + state. Legacy files in host-managed plugin directories are migrated once into + `~/.glean`. The launcher still defaults this variable to `~/.glean`, or the host's `CLAUDE_PLUGIN_DATA` dir when provided. - `SKILLS_BASE_DIR` — where discovered skill files are written; defaults to `/glean-skills-cache`, or redirected under the launch @@ -134,8 +137,10 @@ every launch and setting them yourself has no effect: - **Sign-in loop or stale auth** — prompt the agent to reset and sign in again (e.g. "reset the Glean setup"). It calls the `setup` tool with `reset=true` to - clear the saved configuration and credentials, then runs `setup` again to - re-authenticate. + clear the saved configuration and grant, while retaining the registered OAuth + client when it belongs to the same server. Use `fresh_client=true` with + `reset=true` only when the server explicitly rejects the client or a genuinely + new registration is required. - **Tools return `[SETUP_REQUIRED]`** — the plugin isn't configured or authenticated yet. Prompt the agent to set up Glean (e.g. "set up Glean"). The `setup` tool, called with no arguments, advances through the next missing diff --git a/plugins/glean/dist/index.js b/plugins/glean/dist/index.js index bc1d1e1..777eb4d 100644 --- a/plugins/glean/dist/index.js +++ b/plugins/glean/dist/index.js @@ -3236,8 +3236,8 @@ var require_utils = __commonJS({ } return ind; } - function removeDotSegments(path8) { - let input = path8; + function removeDotSegments(path9) { + let input = path9; const output = []; let nextSlash = -1; let len = 0; @@ -3489,8 +3489,8 @@ var require_schemes = __commonJS({ wsComponent.secure = void 0; } if (wsComponent.resourceName) { - const [path8, query] = wsComponent.resourceName.split("?"); - wsComponent.path = path8 && path8 !== "/" ? path8 : void 0; + const [path9, query] = wsComponent.resourceName.split("?"); + wsComponent.path = path9 && path9 !== "/" ? path9 : void 0; wsComponent.query = query; wsComponent.resourceName = void 0; } @@ -6883,12 +6883,12 @@ var require_dist = __commonJS({ throw new Error(`Unknown format "${name}"`); return f; }; - function addFormats(ajv, list, fs8, exportName) { + function addFormats(ajv, list, fs9, exportName) { var _a3; var _b; (_a3 = (_b = ajv.opts.code).formats) !== null && _a3 !== void 0 ? _a3 : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`; for (const f of list) - ajv.addFormat(f, fs8[f]); + ajv.addFormat(f, fs9[f]); } module.exports = exports = formatsPlugin; Object.defineProperty(exports, "__esModule", { value: true }); @@ -6973,17 +6973,17 @@ var require_visit = __commonJS({ visit.BREAK = BREAK; visit.SKIP = SKIP; visit.REMOVE = REMOVE; - function visit_(key, node, visitor, path8) { - const ctrl = callVisitor(key, node, visitor, path8); + function visit_(key, node, visitor, path9) { + const ctrl = callVisitor(key, node, visitor, path9); if (identity.isNode(ctrl) || identity.isPair(ctrl)) { - replaceNode(key, path8, ctrl); - return visit_(key, ctrl, visitor, path8); + replaceNode(key, path9, ctrl); + return visit_(key, ctrl, visitor, path9); } if (typeof ctrl !== "symbol") { if (identity.isCollection(node)) { - path8 = Object.freeze(path8.concat(node)); + path9 = Object.freeze(path9.concat(node)); for (let i = 0; i < node.items.length; ++i) { - const ci = visit_(i, node.items[i], visitor, path8); + const ci = visit_(i, node.items[i], visitor, path9); if (typeof ci === "number") i = ci - 1; else if (ci === BREAK) @@ -6994,13 +6994,13 @@ var require_visit = __commonJS({ } } } else if (identity.isPair(node)) { - path8 = Object.freeze(path8.concat(node)); - const ck = visit_("key", node.key, visitor, path8); + path9 = Object.freeze(path9.concat(node)); + const ck = visit_("key", node.key, visitor, path9); if (ck === BREAK) return BREAK; else if (ck === REMOVE) node.key = null; - const cv = visit_("value", node.value, visitor, path8); + const cv = visit_("value", node.value, visitor, path9); if (cv === BREAK) return BREAK; else if (cv === REMOVE) @@ -7021,17 +7021,17 @@ var require_visit = __commonJS({ visitAsync.BREAK = BREAK; visitAsync.SKIP = SKIP; visitAsync.REMOVE = REMOVE; - async function visitAsync_(key, node, visitor, path8) { - const ctrl = await callVisitor(key, node, visitor, path8); + async function visitAsync_(key, node, visitor, path9) { + const ctrl = await callVisitor(key, node, visitor, path9); if (identity.isNode(ctrl) || identity.isPair(ctrl)) { - replaceNode(key, path8, ctrl); - return visitAsync_(key, ctrl, visitor, path8); + replaceNode(key, path9, ctrl); + return visitAsync_(key, ctrl, visitor, path9); } if (typeof ctrl !== "symbol") { if (identity.isCollection(node)) { - path8 = Object.freeze(path8.concat(node)); + path9 = Object.freeze(path9.concat(node)); for (let i = 0; i < node.items.length; ++i) { - const ci = await visitAsync_(i, node.items[i], visitor, path8); + const ci = await visitAsync_(i, node.items[i], visitor, path9); if (typeof ci === "number") i = ci - 1; else if (ci === BREAK) @@ -7042,13 +7042,13 @@ var require_visit = __commonJS({ } } } else if (identity.isPair(node)) { - path8 = Object.freeze(path8.concat(node)); - const ck = await visitAsync_("key", node.key, visitor, path8); + path9 = Object.freeze(path9.concat(node)); + const ck = await visitAsync_("key", node.key, visitor, path9); if (ck === BREAK) return BREAK; else if (ck === REMOVE) node.key = null; - const cv = await visitAsync_("value", node.value, visitor, path8); + const cv = await visitAsync_("value", node.value, visitor, path9); if (cv === BREAK) return BREAK; else if (cv === REMOVE) @@ -7075,23 +7075,23 @@ var require_visit = __commonJS({ } return visitor; } - function callVisitor(key, node, visitor, path8) { + function callVisitor(key, node, visitor, path9) { if (typeof visitor === "function") - return visitor(key, node, path8); + return visitor(key, node, path9); if (identity.isMap(node)) - return visitor.Map?.(key, node, path8); + return visitor.Map?.(key, node, path9); if (identity.isSeq(node)) - return visitor.Seq?.(key, node, path8); + return visitor.Seq?.(key, node, path9); if (identity.isPair(node)) - return visitor.Pair?.(key, node, path8); + return visitor.Pair?.(key, node, path9); if (identity.isScalar(node)) - return visitor.Scalar?.(key, node, path8); + return visitor.Scalar?.(key, node, path9); if (identity.isAlias(node)) - return visitor.Alias?.(key, node, path8); + return visitor.Alias?.(key, node, path9); return void 0; } - function replaceNode(key, path8, node) { - const parent = path8[path8.length - 1]; + function replaceNode(key, path9, node) { + const parent = path9[path9.length - 1]; if (identity.isCollection(parent)) { parent.items[key] = node; } else if (identity.isPair(parent)) { @@ -7701,10 +7701,10 @@ var require_Collection = __commonJS({ var createNode = require_createNode(); var identity = require_identity(); var Node = require_Node(); - function collectionFromPath(schema, path8, value) { + function collectionFromPath(schema, path9, value) { let v = value; - for (let i = path8.length - 1; i >= 0; --i) { - const k = path8[i]; + for (let i = path9.length - 1; i >= 0; --i) { + const k = path9[i]; if (typeof k === "number" && Number.isInteger(k) && k >= 0) { const a = []; a[k] = v; @@ -7723,7 +7723,7 @@ var require_Collection = __commonJS({ sourceObjects: /* @__PURE__ */ new Map() }); } - var isEmptyPath = (path8) => path8 == null || typeof path8 === "object" && !!path8[Symbol.iterator]().next().done; + var isEmptyPath = (path9) => path9 == null || typeof path9 === "object" && !!path9[Symbol.iterator]().next().done; var Collection = class extends Node.NodeBase { constructor(type, schema) { super(type); @@ -7753,11 +7753,11 @@ var require_Collection = __commonJS({ * be a Pair instance or a `{ key, value }` object, which may not have a key * that already exists in the map. */ - addIn(path8, value) { - if (isEmptyPath(path8)) + addIn(path9, value) { + if (isEmptyPath(path9)) this.add(value); else { - const [key, ...rest] = path8; + const [key, ...rest] = path9; const node = this.get(key, true); if (identity.isCollection(node)) node.addIn(rest, value); @@ -7771,8 +7771,8 @@ var require_Collection = __commonJS({ * Removes a value from the collection. * @returns `true` if the item was found and removed. */ - deleteIn(path8) { - const [key, ...rest] = path8; + deleteIn(path9) { + const [key, ...rest] = path9; if (rest.length === 0) return this.delete(key); const node = this.get(key, true); @@ -7786,8 +7786,8 @@ var require_Collection = __commonJS({ * scalar values from their surrounding node; to disable set `keepScalar` to * `true` (collections are always returned intact). */ - getIn(path8, keepScalar) { - const [key, ...rest] = path8; + getIn(path9, keepScalar) { + const [key, ...rest] = path9; const node = this.get(key, true); if (rest.length === 0) return !keepScalar && identity.isScalar(node) ? node.value : node; @@ -7805,8 +7805,8 @@ var require_Collection = __commonJS({ /** * Checks if the collection includes a value with the key `key`. */ - hasIn(path8) { - const [key, ...rest] = path8; + hasIn(path9) { + const [key, ...rest] = path9; if (rest.length === 0) return this.has(key); const node = this.get(key, true); @@ -7816,8 +7816,8 @@ var require_Collection = __commonJS({ * Sets a value in this collection. For `!!set`, `value` needs to be a * boolean to add/remove the item from the set. */ - setIn(path8, value) { - const [key, ...rest] = path8; + setIn(path9, value) { + const [key, ...rest] = path9; if (rest.length === 0) { this.set(key, value); } else { @@ -10332,9 +10332,9 @@ var require_Document = __commonJS({ this.contents.add(value); } /** Adds a value to the document. */ - addIn(path8, value) { + addIn(path9, value) { if (assertCollection(this.contents)) - this.contents.addIn(path8, value); + this.contents.addIn(path9, value); } /** * Create a new `Alias` node, ensuring that the target `node` has the required anchor. @@ -10409,14 +10409,14 @@ var require_Document = __commonJS({ * Removes a value from the document. * @returns `true` if the item was found and removed. */ - deleteIn(path8) { - if (Collection.isEmptyPath(path8)) { + deleteIn(path9) { + if (Collection.isEmptyPath(path9)) { if (this.contents == null) return false; this.contents = null; return true; } - return assertCollection(this.contents) ? this.contents.deleteIn(path8) : false; + return assertCollection(this.contents) ? this.contents.deleteIn(path9) : false; } /** * Returns item at `key`, or `undefined` if not found. By default unwraps @@ -10431,10 +10431,10 @@ var require_Document = __commonJS({ * scalar values from their surrounding node; to disable set `keepScalar` to * `true` (collections are always returned intact). */ - getIn(path8, keepScalar) { - if (Collection.isEmptyPath(path8)) + getIn(path9, keepScalar) { + if (Collection.isEmptyPath(path9)) return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents; - return identity.isCollection(this.contents) ? this.contents.getIn(path8, keepScalar) : void 0; + return identity.isCollection(this.contents) ? this.contents.getIn(path9, keepScalar) : void 0; } /** * Checks if the document includes a value with the key `key`. @@ -10445,10 +10445,10 @@ var require_Document = __commonJS({ /** * Checks if the document includes a value at `path`. */ - hasIn(path8) { - if (Collection.isEmptyPath(path8)) + hasIn(path9) { + if (Collection.isEmptyPath(path9)) return this.contents !== void 0; - return identity.isCollection(this.contents) ? this.contents.hasIn(path8) : false; + return identity.isCollection(this.contents) ? this.contents.hasIn(path9) : false; } /** * Sets a value in this document. For `!!set`, `value` needs to be a @@ -10465,13 +10465,13 @@ var require_Document = __commonJS({ * Sets a value in this document. For `!!set`, `value` needs to be a * boolean to add/remove the item from the set. */ - setIn(path8, value) { - if (Collection.isEmptyPath(path8)) { + setIn(path9, value) { + if (Collection.isEmptyPath(path9)) { this.contents = value; } else if (this.contents == null) { - this.contents = Collection.collectionFromPath(this.schema, Array.from(path8), value); + this.contents = Collection.collectionFromPath(this.schema, Array.from(path9), value); } else if (assertCollection(this.contents)) { - this.contents.setIn(path8, value); + this.contents.setIn(path9, value); } } /** @@ -12431,9 +12431,9 @@ var require_cst_visit = __commonJS({ visit.BREAK = BREAK; visit.SKIP = SKIP; visit.REMOVE = REMOVE; - visit.itemAtPath = (cst, path8) => { + visit.itemAtPath = (cst, path9) => { let item = cst; - for (const [field, index] of path8) { + for (const [field, index] of path9) { const tok = item?.[field]; if (tok && "items" in tok) { item = tok.items[index]; @@ -12442,23 +12442,23 @@ var require_cst_visit = __commonJS({ } return item; }; - visit.parentCollection = (cst, path8) => { - const parent = visit.itemAtPath(cst, path8.slice(0, -1)); - const field = path8[path8.length - 1][0]; + visit.parentCollection = (cst, path9) => { + const parent = visit.itemAtPath(cst, path9.slice(0, -1)); + const field = path9[path9.length - 1][0]; const coll = parent?.[field]; if (coll && "items" in coll) return coll; throw new Error("Parent collection not found"); }; - function _visit(path8, item, visitor) { - let ctrl = visitor(item, path8); + function _visit(path9, item, visitor) { + let ctrl = visitor(item, path9); if (typeof ctrl === "symbol") return ctrl; for (const field of ["key", "value"]) { const token = item[field]; if (token && "items" in token) { for (let i = 0; i < token.items.length; ++i) { - const ci = _visit(Object.freeze(path8.concat([[field, i]])), token.items[i], visitor); + const ci = _visit(Object.freeze(path9.concat([[field, i]])), token.items[i], visitor); if (typeof ci === "number") i = ci - 1; else if (ci === BREAK) @@ -12469,10 +12469,10 @@ var require_cst_visit = __commonJS({ } } if (typeof ctrl === "function" && field === "key") - ctrl = ctrl(item, path8); + ctrl = ctrl(item, path9); } } - return typeof ctrl === "function" ? ctrl(item, path8) : ctrl; + return typeof ctrl === "function" ? ctrl(item, path9) : ctrl; } exports.visit = visit; } @@ -13774,14 +13774,14 @@ var require_parser = __commonJS({ case "scalar": case "single-quoted-scalar": case "double-quoted-scalar": { - const fs8 = this.flowScalar(this.type); + const fs9 = this.flowScalar(this.type); if (atNextItem || it.value) { - map.items.push({ start, key: fs8, sep: [] }); + map.items.push({ start, key: fs9, sep: [] }); this.onKeyLine = true; } else if (it.sep) { - this.stack.push(fs8); + this.stack.push(fs9); } else { - Object.assign(it, { key: fs8, sep: [] }); + Object.assign(it, { key: fs9, sep: [] }); this.onKeyLine = true; } return; @@ -13909,13 +13909,13 @@ var require_parser = __commonJS({ case "scalar": case "single-quoted-scalar": case "double-quoted-scalar": { - const fs8 = this.flowScalar(this.type); + const fs9 = this.flowScalar(this.type); if (!it || it.value) - fc.items.push({ start: [], key: fs8, sep: [] }); + fc.items.push({ start: [], key: fs9, sep: [] }); else if (it.sep) - this.stack.push(fs8); + this.stack.push(fs9); else - Object.assign(it, { key: fs8, sep: [] }); + Object.assign(it, { key: fs9, sep: [] }); return; } case "flow-map-end": @@ -14466,10 +14466,10 @@ function mergeDefs(...defs) { function cloneDef(schema) { return mergeDefs(schema._zod.def); } -function getElementAtPath(obj, path8) { - if (!path8) +function getElementAtPath(obj, path9) { + if (!path9) return obj; - return path8.reduce((acc, key) => acc?.[key], obj); + return path9.reduce((acc, key) => acc?.[key], obj); } function promiseAllObject(promisesObj) { const keys = Object.keys(promisesObj); @@ -14878,11 +14878,11 @@ function explicitlyAborted(x, startIndex = 0) { } return false; } -function prefixIssues(path8, issues) { +function prefixIssues(path9, issues) { return issues.map((iss) => { var _a3; (_a3 = iss).path ?? (_a3.path = []); - iss.path.unshift(path8); + iss.path.unshift(path9); return iss; }); } @@ -15029,16 +15029,16 @@ function flattenError(error2, mapper = (issue2) => issue2.message) { } function formatError(error2, mapper = (issue2) => issue2.message) { const fieldErrors = { _errors: [] }; - const processError = (error3, path8 = []) => { + const processError = (error3, path9 = []) => { for (const issue2 of error3.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { - issue2.errors.map((issues) => processError({ issues }, [...path8, ...issue2.path])); + issue2.errors.map((issues) => processError({ issues }, [...path9, ...issue2.path])); } else if (issue2.code === "invalid_key") { - processError({ issues: issue2.issues }, [...path8, ...issue2.path]); + processError({ issues: issue2.issues }, [...path9, ...issue2.path]); } else if (issue2.code === "invalid_element") { - processError({ issues: issue2.issues }, [...path8, ...issue2.path]); + processError({ issues: issue2.issues }, [...path9, ...issue2.path]); } else { - const fullpath = [...path8, ...issue2.path]; + const fullpath = [...path9, ...issue2.path]; if (fullpath.length === 0) { fieldErrors._errors.push(mapper(issue2)); } else { @@ -22982,9 +22982,9 @@ var StdioServerTransport = class { }; // src/index.ts -import path7 from "node:path"; -import fs7 from "node:fs"; -import { homedir as homedir4, tmpdir } from "node:os"; +import path8 from "node:path"; +import fs8 from "node:fs"; +import { tmpdir } from "node:os"; // node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js var ExperimentalClientTasks = class { @@ -25197,6 +25197,7 @@ var AuthRequiredError = class extends Error { authUrl; }; var pendingTransport; +var pendingRegistrations = /* @__PURE__ */ new WeakMap(); function buildTransport(serverUrl, opts, chatSessionId) { const parsedUrl = new URL(serverUrl); const headers = { @@ -25231,7 +25232,7 @@ async function createRemoteClient(serverUrl, opts, chatSessionId, authRetry = fa const msg = err instanceof Error ? err.message : String(err); console.error(`[auth] Code exchange failed: ${msg} \u2014 discarding stale auth state`); pendingTransport = void 0; - if (!authProvider.abandonPendingSignIn()) { + if (!authProvider.abandonPendingSignIn(isInvalidClientError(err))) { await authProvider.invalidateCredentials("all"); } return createRemoteClient(serverUrl, opts, chatSessionId); @@ -25249,15 +25250,39 @@ async function createRemoteClient(serverUrl, opts, chatSessionId, authRetry = fa await authProvider.invalidateCredentials("all"); } } + let registrationNeeded = false; + if (authProvider?.clientInformation) { + registrationNeeded = !authProvider.clientInformation(); + if (registrationNeeded) { + const pending = pendingRegistrations.get(authProvider); + if (pending) { + await pending; + registrationNeeded = !authProvider.clientInformation(); + } + } + } const client = new Client( { name: "glean", version: "1.0.0" }, { capabilities: {} } ); const accessTokenAtConnect = authProvider?.tokens()?.access_token; const transport = buildTransport(serverUrl, opts, chatSessionId); + let trackedRegistration; + let connectPromise; + if (registrationNeeded && authProvider) { + connectPromise = client.connect(transport); + trackedRegistration = connectPromise.then( + () => void 0, + () => void 0 + ); + pendingRegistrations.set(authProvider, trackedRegistration); + } else { + connectPromise = client.connect(transport); + } try { - await client.connect(transport); + await connectPromise; } catch (error2) { + authProvider?.releaseClientRegistrationLock?.(); if (error2 instanceof UnauthorizedError && authProvider) { const refreshedAccessToken = authProvider.tokens()?.access_token; if (!authRetry && refreshedAccessToken && refreshedAccessToken !== accessTokenAtConnect) { @@ -25278,9 +25303,17 @@ async function createRemoteClient(serverUrl, opts, chatSessionId, authRetry = fa return createRemoteClient(serverUrl, opts, chatSessionId, true); } throw error2; + } finally { + if (trackedRegistration && authProvider && pendingRegistrations.get(authProvider) === trackedRegistration) { + pendingRegistrations.delete(authProvider); + } } return client; } +function isInvalidClientError(error2) { + const msg = error2 instanceof Error ? error2.message : String(error2); + return /invalid[_ -]?client|unknown client|client authentication failed/i.test(msg); +} function isLikelyRefreshFailure(error2) { const msg = error2 instanceof Error ? error2.message : String(error2); return /refresh|invalid_grant|invalid_request|oauth/i.test(msg); @@ -25379,47 +25412,247 @@ function closeCallbackServer() { expectedState = void 0; } -// src/token-store.ts +// src/data-dir.ts import fs from "node:fs"; import path from "node:path"; +import { randomUUID } from "node:crypto"; import { homedir } from "node:os"; -var CREDENTIALS_FILENAME = "mcp-credentials.json"; var DIR_MODE = 448; var FILE_MODE = 384; -function resolveCredentialsDir() { - return process.env.PLUGIN_DATA_DIR || path.join(homedir(), ".glean"); +var MIGRATION_MARKER = ".legacy-store-migrated-v1"; +var MIGRATION_LOCK = ".legacy-store-migration.lock"; +var MIGRATED_FILES = [ + "mcp-credentials.json", + "mcp-server-url.json", + "remote-tools-cache.json", + "glean-server.log" +]; +function envValue(name) { + const value = process.env[name]?.trim(); + if (!value || value.startsWith("${")) return void 0; + return value; +} +function resolveDataDir() { + return envValue("GLEAN_AUTH_DATA_DIR") ?? path.join(homedir() || process.env.TMPDIR || "/tmp", ".glean"); +} +function legacyDataDirs() { + const canonical = path.resolve(resolveDataDir()); + const candidates = [envValue("PLUGIN_DATA_DIR"), envValue("CLAUDE_PLUGIN_DATA")]; + return [...new Set(candidates.filter((dir) => !!dir))].map((dir) => path.resolve(dir)).filter((dir) => dir !== canonical); } +function sleepSync(ms) { + const signal = new Int32Array(new SharedArrayBuffer(4)); + Atomics.wait(signal, 0, 0, ms); +} +function lockPath(name) { + return path.join(resolveDataDir(), `.${name}.lock`); +} +function isStale(lockFile, staleMs) { + try { + return Date.now() - fs.statSync(lockFile).mtimeMs > staleMs; + } catch { + return false; + } +} +function acquireDataFileLockSync(name, options = {}) { + const waitMs = options.waitMs ?? 3e4; + const staleMs = options.staleMs ?? 12e4; + const filePath = lockPath(name); + const dir = path.dirname(filePath); + try { + fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE }); + fs.chmodSync(dir, DIR_MODE); + } catch { + return void 0; + } + const deadline = Date.now() + Math.max(0, waitMs); + do { + try { + const token = randomUUID(); + const fd = fs.openSync(filePath, "wx", FILE_MODE); + try { + fs.writeFileSync( + fd, + JSON.stringify({ + pid: process.pid, + token, + createdAt: (/* @__PURE__ */ new Date()).toISOString() + }), + { encoding: "utf-8" } + ); + } finally { + fs.closeSync(fd); + } + return { path: filePath, token }; + } catch (err) { + const code = err && typeof err === "object" && "code" in err ? err.code : void 0; + if (code !== "EEXIST") return void 0; + if (isStale(filePath, staleMs)) { + try { + fs.rmSync(filePath, { force: true }); + } catch { + } + continue; + } + if (Date.now() >= deadline) return void 0; + sleepSync(Math.min(25, Math.max(1, deadline - Date.now()))); + } + } while (Date.now() <= deadline); + return void 0; +} +function releaseDataFileLock(lock) { + if (!lock) return; + try { + const contents = JSON.parse(fs.readFileSync(lock.path, "utf-8")); + if (contents.token !== lock.token) return; + fs.rmSync(lock.path, { force: true }); + } catch { + } +} +function copyFileAtomically(source, target) { + const dir = path.dirname(target); + fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE }); + fs.chmodSync(dir, DIR_MODE); + const tmp = `${target}.${process.pid}.migration.tmp`; + try { + fs.copyFileSync(source, tmp); + fs.chmodSync(tmp, FILE_MODE); + fs.renameSync(tmp, target); + fs.chmodSync(target, FILE_MODE); + } finally { + try { + fs.rmSync(tmp, { force: true }); + } catch { + } + } +} +function migrateLegacyData() { + const canonical = resolveDataDir(); + const sources = legacyDataDirs(); + if (sources.length === 0) return; + const marker = path.join(canonical, MIGRATION_MARKER); + try { + if (fs.existsSync(marker)) return; + } catch { + return; + } + const lock = acquireDataFileLockSync( + MIGRATION_LOCK.slice(1), + { waitMs: 5e3, staleMs: 6e4 } + ); + if (!lock) return; + try { + if (fs.existsSync(marker)) return; + fs.mkdirSync(canonical, { recursive: true, mode: DIR_MODE }); + fs.chmodSync(canonical, DIR_MODE); + for (const filename of MIGRATED_FILES) { + const candidates = sources.map((dir) => path.join(dir, filename)).filter((file) => { + try { + return fs.statSync(file).isFile(); + } catch { + return false; + } + }).sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs); + if (candidates.length === 0) continue; + const target = path.join(canonical, filename); + const newestSource = candidates[0]; + let targetIsOlder = true; + try { + targetIsOlder = fs.statSync(target).mtimeMs < fs.statSync(newestSource).mtimeMs; + } catch { + } + if (!fs.existsSync(target) || targetIsOlder) { + copyFileAtomically(newestSource, target); + console.error(`[auth] Migrated legacy data: ${filename}`); + } + } + fs.writeFileSync( + marker, + JSON.stringify({ migratedAt: (/* @__PURE__ */ new Date()).toISOString(), sources }), + { encoding: "utf-8", mode: FILE_MODE } + ); + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + console.error(`[auth] Failed to migrate legacy data: ${msg}`); + } finally { + releaseDataFileLock(lock); + } +} +function ensureDataDir() { + const dir = resolveDataDir(); + fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE }); + fs.chmodSync(dir, DIR_MODE); + return dir; +} + +// src/token-store.ts +import fs2 from "node:fs"; +import path2 from "node:path"; +var CREDENTIALS_FILENAME = "mcp-credentials.json"; +var DIR_MODE2 = 448; +var FILE_MODE2 = 384; +var CLIENT_REGISTRATION_LOCK = "mcp-client-registration"; function credentialsFile() { - return path.join(resolveCredentialsDir(), CREDENTIALS_FILENAME); + return path2.join(resolveDataDir(), CREDENTIALS_FILENAME); } -function loadCredentials() { +function readCredentialsFile(filePath) { try { - const raw = fs.readFileSync(credentialsFile(), "utf-8"); + const raw = fs2.readFileSync(filePath, "utf-8"); return JSON.parse(raw); } catch { return void 0; } } +function loadCredentials() { + migrateLegacyData(); + return readCredentialsFile(credentialsFile()); +} function credentialsMtimeMs() { + migrateLegacyData(); try { - return fs.statSync(credentialsFile()).mtimeMs; + return fs2.statSync(credentialsFile()).mtimeMs; } catch { return void 0; } } -function saveCredentials(tokens, clientInfo) { +function acquireClientRegistrationLock() { + return acquireDataFileLockSync(CLIENT_REGISTRATION_LOCK, { + waitMs: 3e4, + staleMs: 12e4 + }); +} +function releaseClientRegistrationLock(lock) { + releaseDataFileLock(lock); +} +function saveCredentials(tokens, clientInfo, metadata = {}, options = {}) { try { + migrateLegacyData(); const filePath = credentialsFile(); - const dir = path.dirname(filePath); - fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE }); - fs.chmodSync(dir, DIR_MODE); - const data = { tokens, clientInfo }; + const dir = ensureDataDir(); + const existing = readCredentialsFile(filePath); + const incomingTokenTime = metadata.tokenUpdatedAt ?? void 0; + const existingTokenTime = existing?.tokenUpdatedAt ?? void 0; + const existingTokenIsNewer = !options.forceTokenUpdate && existing?.tokens !== void 0 && (tokens === void 0 || existingTokenTime !== void 0 && (incomingTokenTime === void 0 || existingTokenTime > incomingTokenTime)); + const effectiveTokens = existingTokenIsNewer ? existing?.tokens : tokens; + const effectiveTokenTime = existingTokenIsNewer ? existingTokenTime : metadata.tokenUpdatedAt !== void 0 ? metadata.tokenUpdatedAt : existing?.tokenUpdatedAt; + const effectiveClientInfo = !options.forceClientUpdate && clientInfo === void 0 ? existing?.clientInfo : clientInfo; + const data = { + tokens: effectiveTokens, + clientInfo: effectiveClientInfo, + // Omitted metadata means preserve it; null explicitly clears it. + accountEmail: metadata.accountEmail !== void 0 ? metadata.accountEmail : existing?.accountEmail, + clientServerUrl: metadata.clientServerUrl !== void 0 ? metadata.clientServerUrl : existing?.clientServerUrl, + abandonedSignIns: metadata.abandonedSignIns !== void 0 ? metadata.abandonedSignIns : existing?.abandonedSignIns, + tokenUpdatedAt: effectiveTokenTime + }; const tmpPath = `${filePath}.${process.pid}.tmp`; - fs.writeFileSync(tmpPath, JSON.stringify(data, null, 2), { + fs2.writeFileSync(tmpPath, JSON.stringify(data, null, 2), { encoding: "utf-8", - mode: FILE_MODE + mode: FILE_MODE2 }); - fs.renameSync(tmpPath, filePath); + fs2.renameSync(tmpPath, filePath); + fs2.chmodSync(dir, DIR_MODE2); + fs2.chmodSync(filePath, FILE_MODE2); } catch (err) { const msg = err instanceof Error ? err.message : String(err); console.error(`[auth] Failed to persist credentials: ${msg}`); @@ -25427,7 +25660,8 @@ function saveCredentials(tokens, clientInfo) { } function clearCredentials() { try { - fs.rmSync(credentialsFile(), { force: true }); + migrateLegacyData(); + fs2.rmSync(credentialsFile(), { force: true }); } catch (err) { const msg = err instanceof Error ? err.message : String(err); console.error(`[auth] Failed to clear credentials: ${msg}`); @@ -25448,6 +25682,10 @@ function rotationGraceMs() { function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } +function normalizeAccountEmail(email2) { + const normalized = email2?.trim().toLowerCase(); + return normalized || void 0; +} function openBrowser(url2) { if (platform() === "win32") { spawn("cmd", ["/c", "start", '""', "/b", url2.replace(/&/g, "^&")], { @@ -25473,6 +25711,12 @@ var GleanOAuthClientProvider = class { _credentialsMtimeMs; // Consecutive abandoned sign-ins with the current client. _abandonedSignIns = 0; + // Held from clientInformation() returning undefined until the SDK either + // persists the registration or the connection attempt fails. + _clientRegistrationLock; + _accountEmail; + _clientServerUrl; + _tokenUpdatedAt; authorizationUrl; /** * Optional hook invoked whenever the in-memory token state changes — @@ -25484,8 +25728,12 @@ var GleanOAuthClientProvider = class { constructor() { const stored = loadCredentials(); if (stored) { - this._tokens = stored.tokens; - this._clientInfo = stored.clientInfo; + this._tokens = stored.tokens ?? void 0; + this._clientInfo = stored.clientInfo ?? void 0; + this._accountEmail = stored.accountEmail ?? void 0; + this._clientServerUrl = stored.clientServerUrl ?? void 0; + this._abandonedSignIns = stored.abandonedSignIns ?? 0; + this._tokenUpdatedAt = stored.tokenUpdatedAt ?? void 0; } this._credentialsMtimeMs = credentialsMtimeMs(); } @@ -25502,9 +25750,27 @@ var GleanOAuthClientProvider = class { if (!stored) return; if (stored.tokens) { this._tokens = stored.tokens; + } else if (stored.tokenUpdatedAt !== void 0 && stored.tokenUpdatedAt !== null && (this._tokenUpdatedAt === void 0 || stored.tokenUpdatedAt > this._tokenUpdatedAt)) { + this._tokens = void 0; } if (stored.clientInfo) { this._clientInfo = stored.clientInfo; + if (this._clientRegistrationLock) { + releaseClientRegistrationLock(this._clientRegistrationLock); + this._clientRegistrationLock = void 0; + } + } + if (stored.accountEmail !== void 0) { + this._accountEmail = stored.accountEmail ?? void 0; + } + if (stored.clientServerUrl !== void 0) { + this._clientServerUrl = stored.clientServerUrl ?? void 0; + } + if (stored.abandonedSignIns !== void 0) { + this._abandonedSignIns = stored.abandonedSignIns ?? 0; + } + if (stored.tokenUpdatedAt !== void 0) { + this._tokenUpdatedAt = stored.tokenUpdatedAt ?? void 0; } } // On invalid_grant, adopt a sibling's newer on-disk token instead of @@ -25520,6 +25786,7 @@ var GleanOAuthClientProvider = class { return false; } this._tokens = diskTokens; + this._tokenUpdatedAt = stored?.tokenUpdatedAt ?? Date.now(); this._credentialsMtimeMs = diskMtime; if (stored?.clientInfo) { this._clientInfo = stored.clientInfo; @@ -25563,13 +25830,25 @@ var GleanOAuthClientProvider = class { } clientInformation() { this.syncTokensFromDisk(); + if (this._clientInfo) return this._clientInfo; + if (!this._clientRegistrationLock) { + this._clientRegistrationLock = acquireClientRegistrationLock(); + this._credentialsMtimeMs = void 0; + this.syncTokensFromDisk(); + if (this._clientInfo) { + releaseClientRegistrationLock(this._clientRegistrationLock); + this._clientRegistrationLock = void 0; + } + } return this._clientInfo; } saveClientInformation(info) { console.error(`[auth] Registered OAuth client: ${info.client_id}`); this._clientInfo = info; - saveCredentials(this._tokens, this._clientInfo); + saveCredentials(this._tokens, this._clientInfo, this.credentialMetadata()); this._credentialsMtimeMs = credentialsMtimeMs(); + releaseClientRegistrationLock(this._clientRegistrationLock); + this._clientRegistrationLock = void 0; } tokens() { this.syncTokensFromDisk(); @@ -25577,32 +25856,88 @@ var GleanOAuthClientProvider = class { } saveTokens(tokens) { this._tokens = tokens; + this._tokenUpdatedAt = Date.now(); this._authUrlPending = false; this._abandonedSignIns = 0; - saveCredentials(this._tokens, this._clientInfo); + saveCredentials(this._tokens, this._clientInfo, this.credentialMetadata()); this._credentialsMtimeMs = credentialsMtimeMs(); this.onTokensChanged?.(tokens); } + /** Persist the account/server context without changing the grant. */ + setAccountContext(accountEmail, serverUrl) { + this._accountEmail = normalizeAccountEmail(accountEmail); + this._clientServerUrl = serverUrl; + saveCredentials(this._tokens, this._clientInfo, this.credentialMetadata()); + this._credentialsMtimeMs = credentialsMtimeMs(); + } + /** The account associated with the currently cached grant, if known. */ + accountEmail() { + return this._accountEmail; + } + /** The server for which the cached DCR client was registered, if known. */ + clientServerUrl() { + return this._clientServerUrl; + } + /** + * Force a new user sign-in while retaining a client registered for the same + * server. This is used for account switching and normal reset. A fresh DCR + * is only required when the server changes or the caller explicitly asks + * for a fresh client. + */ + resetAuthentication(accountEmail, serverUrl) { + const hadTokens = this._tokens !== void 0; + this._tokens = void 0; + this._tokenUpdatedAt = Date.now(); + this._accountEmail = normalizeAccountEmail(accountEmail); + this._clientServerUrl = serverUrl; + this._codeVerifier = ""; + this._pendingAuthCode = void 0; + this.authorizationUrl = void 0; + this._authUrlPending = false; + this._abandonedSignIns = 0; + saveCredentials(void 0, this._clientInfo, this.credentialMetadata(), { + forceTokenUpdate: true + }); + this._credentialsMtimeMs = credentialsMtimeMs(); + if (hadTokens) this.onTokensChanged?.(void 0); + } + credentialMetadata() { + return { + accountEmail: this._accountEmail ?? null, + clientServerUrl: this._clientServerUrl ?? null, + abandonedSignIns: this._abandonedSignIns, + tokenUpdatedAt: this._tokenUpdatedAt ?? null + }; + } async invalidateCredentials(scope) { console.error(`[auth] Invalidating credentials: scope=${scope}`); const tokensClearedBefore = this._tokens === void 0; switch (scope) { case "all": + this.releaseClientRegistrationLock(); this._tokens = void 0; this._clientInfo = void 0; + this._accountEmail = void 0; + this._clientServerUrl = void 0; this._codeVerifier = ""; this._authUrlPending = false; this._abandonedSignIns = 0; clearCredentials(); break; case "client": + this.releaseClientRegistrationLock(); this._clientInfo = void 0; - saveCredentials(this._tokens, void 0); + saveCredentials(this._tokens, void 0, this.credentialMetadata(), { + forceClientUpdate: true + }); break; case "tokens": if (await this.adoptNewerTokenWithGrace()) return; this._tokens = void 0; - saveCredentials(void 0, this._clientInfo); + this._tokenUpdatedAt = Date.now(); + saveCredentials(void 0, this._clientInfo, this.credentialMetadata(), { + forceTokenUpdate: true + }); break; case "verifier": this._codeVerifier = ""; @@ -25612,6 +25947,10 @@ var GleanOAuthClientProvider = class { this.onTokensChanged?.(void 0); } } + releaseClientRegistrationLock() { + releaseClientRegistrationLock(this._clientRegistrationLock); + this._clientRegistrationLock = void 0; + } // True if we previously issued an authorize URL but never received tokens — // implying the URL was likely rejected by the server (e.g. stale client_id). needsFreshClient() { @@ -25619,13 +25958,24 @@ var GleanOAuthClientProvider = class { } // Abandoned sign-in: keep the client and clear the pending flow. Returns // false after two consecutive failures (client likely dead → re-register). - abandonPendingSignIn() { - this._abandonedSignIns += 1; - this._codeVerifier = ""; - this._pendingAuthCode = void 0; - this.authorizationUrl = void 0; - this._authUrlPending = false; - return this._abandonedSignIns < 2; + abandonPendingSignIn(clientRejected = false) { + const lock = acquireDataFileLockSync("mcp-auth-recovery", { + waitMs: 5e3, + staleMs: 3e4 + }); + try { + this.syncTokensFromDisk(); + this._abandonedSignIns = clientRejected ? 2 : this._abandonedSignIns + 1; + this._codeVerifier = ""; + this._pendingAuthCode = void 0; + this.authorizationUrl = void 0; + this._authUrlPending = false; + saveCredentials(this._tokens, this._clientInfo, this.credentialMetadata()); + this._credentialsMtimeMs = credentialsMtimeMs(); + return !clientRejected && this._abandonedSignIns < 2; + } finally { + releaseDataFileLock(lock); + } } get pendingAuthCode() { return this._pendingAuthCode; @@ -25664,11 +26014,11 @@ var GleanOAuthClientProvider = class { // src/skill-writer.ts var import_yaml = __toESM(require_dist2(), 1); -import fs2 from "node:fs/promises"; -import path2 from "node:path"; +import fs3 from "node:fs/promises"; +import path3 from "node:path"; function isInsideDir(filePath, dir) { - const resolved = path2.resolve(filePath); - return resolved.startsWith(path2.resolve(dir) + path2.sep); + const resolved = path3.resolve(filePath); + return resolved.startsWith(path3.resolve(dir) + path3.sep); } function parseFrontmatter(content) { const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---/); @@ -25693,7 +26043,7 @@ function parseFrontmatter(content) { async function evictStaleSkills(baseDir, maxAgeMs, log, now = Date.now()) { let entries; try { - entries = await fs2.readdir(baseDir, { withFileTypes: true }); + entries = await fs3.readdir(baseDir, { withFileTypes: true }); } catch { return; } @@ -25701,12 +26051,12 @@ async function evictStaleSkills(baseDir, maxAgeMs, log, now = Date.now()) { await Promise.all( entries.map(async (entry) => { if (!entry.isDirectory()) return; - const skillDir = path2.resolve(baseDir, entry.name); + const skillDir = path3.resolve(baseDir, entry.name); if (!isInsideDir(skillDir, baseDir)) return; try { - const stat = await fs2.stat(skillDir); + const stat = await fs3.stat(skillDir); if (stat.mtimeMs < cutoff) { - await fs2.rm(skillDir, { recursive: true, force: true }); + await fs3.rm(skillDir, { recursive: true, force: true }); log?.("evict-stale-skill", { skill: entry.name }); } } catch (err) { @@ -25719,21 +26069,21 @@ async function evictStaleSkills(baseDir, maxAgeMs, log, now = Date.now()) { async function writeSkillsToDisk(skills, baseDir) { const index = []; for (const [skillName, fileMap] of Object.entries(skills)) { - const skillDir = path2.resolve(baseDir, skillName); + const skillDir = path3.resolve(baseDir, skillName); if (!isInsideDir(skillDir, baseDir)) { continue; } - await fs2.rm(skillDir, { recursive: true, force: true }); - await fs2.mkdir(skillDir, { recursive: true }); + await fs3.rm(skillDir, { recursive: true, force: true }); + await fs3.mkdir(skillDir, { recursive: true }); const writtenFiles = []; for (const [filePath, content] of Object.entries(fileMap)) { - const fullPath = path2.resolve(skillDir, filePath); + const fullPath = path3.resolve(skillDir, filePath); if (!isInsideDir(fullPath, skillDir)) { continue; } - await fs2.mkdir(path2.dirname(fullPath), { recursive: true }); + await fs3.mkdir(path3.dirname(fullPath), { recursive: true }); const text = typeof content === "string" ? content : JSON.stringify(content); - await fs2.writeFile(fullPath, text, "utf-8"); + await fs3.writeFile(fullPath, text, "utf-8"); writtenFiles.push(fullPath); } const rawSkillMd = fileMap["SKILL.md"] ?? ""; @@ -25801,17 +26151,17 @@ async function handleFindSkills(remoteClient, skillsBaseDir, args) { } // src/tools/run-tool.ts -import fs4 from "node:fs/promises"; +import fs5 from "node:fs/promises"; import os2 from "node:os"; -import path4 from "node:path"; +import path5 from "node:path"; // src/tools/approval-args.ts -import fs3 from "node:fs/promises"; -import path3 from "node:path"; +import fs4 from "node:fs/promises"; +import path4 from "node:path"; import os from "node:os"; // src/session-id.ts -import { randomUUID } from "node:crypto"; +import { randomUUID as randomUUID2 } from "node:crypto"; var fallbackSessionId; function resolveSessionId() { const fromHost = process.env.GLEAN_SESSION_ID?.trim(); @@ -25819,7 +26169,7 @@ function resolveSessionId() { return fromHost; } if (!fallbackSessionId) { - fallbackSessionId = randomUUID(); + fallbackSessionId = randomUUID2(); } return fallbackSessionId; } @@ -25898,10 +26248,10 @@ function formatArgumentsForFile(toolName, args) { async function writeApprovalArgsFile(toolName, args) { const base = process.env.PLUGIN_DATA_DIR || process.env.CLAUDE_PLUGIN_DATA || os.tmpdir(); const sessionId = resolveSessionId().replace(/[^a-zA-Z0-9_-]/g, "-").slice(0, 64); - const dir = path3.join(base, "glean-approvals", sessionId); - await fs3.mkdir(dir, { recursive: true }); - const file = path3.join(dir, "glean-approval-args.md"); - await fs3.writeFile(file, formatArgumentsForFile(toolName, args), "utf-8"); + const dir = path4.join(base, "glean-approvals", sessionId); + await fs4.mkdir(dir, { recursive: true }); + const file = path4.join(dir, "glean-approval-args.md"); + await fs4.writeFile(file, formatArgumentsForFile(toolName, args), "utf-8"); return file; } @@ -25951,7 +26301,7 @@ async function resolveFileArgs(fileArgs, baseArgs, inputSchema) { `file_args.${argName} must be a non-empty string path` ); } - if (!path4.isAbsolute(filePathRaw)) { + if (!path5.isAbsolute(filePathRaw)) { throw new FileArgsError( `file_args.${argName} must be an absolute path; got "${filePathRaw}"` ); @@ -25963,7 +26313,7 @@ async function resolveFileArgs(fileArgs, baseArgs, inputSchema) { } let stat; try { - stat = await fs4.stat(filePathRaw); + stat = await fs5.stat(filePathRaw); } catch (err) { const msg = err instanceof Error ? err.message : String(err); throw new FileArgsError( @@ -25980,7 +26330,7 @@ async function resolveFileArgs(fileArgs, baseArgs, inputSchema) { `file_args.${argName}: "${filePathRaw}" is ${stat.size} bytes, exceeds ${maxBytes} byte limit (set GLEAN_FILE_ARG_MAX_BYTES to override)` ); } - const content = await fs4.readFile(filePathRaw, "utf-8"); + const content = await fs5.readFile(filePathRaw, "utf-8"); const types = declaredParamTypes(inputSchema, argName); if (types.has("object") || types.has("array")) { try { @@ -26003,12 +26353,12 @@ async function resolveFileArgs(fileArgs, baseArgs, inputSchema) { } async function findToolJson(skillsBaseDir, toolName) { try { - const skillDirs = await fs4.readdir(skillsBaseDir, { withFileTypes: true }); + const skillDirs = await fs5.readdir(skillsBaseDir, { withFileTypes: true }); for (const dir of skillDirs) { if (!dir.isDirectory()) continue; - const toolPath = path4.join(skillsBaseDir, dir.name, "tools", `${toolName}.json`); + const toolPath = path5.join(skillsBaseDir, dir.name, "tools", `${toolName}.json`); try { - const content = await fs4.readFile(toolPath, "utf-8"); + const content = await fs5.readFile(toolPath, "utf-8"); return JSON.parse(content); } catch { continue; @@ -26049,13 +26399,13 @@ function primeElicitationCancellation(mcpServer) { }); } function permissionModeMarkerPath() { - const base = process.env.CLAUDE_PLUGIN_DATA || path4.join(os2.homedir(), ".glean"); + const base = process.env.CLAUDE_PLUGIN_DATA || path5.join(os2.homedir(), ".glean"); const sessionId = resolveSessionId().replace(/[^a-zA-Z0-9_-]/g, "-").slice(0, 64); - return path4.join(base, "glean-hitl-mode", `${sessionId}.json`); + return path5.join(base, "glean-hitl-mode", `${sessionId}.json`); } async function currentPermissionMode() { try { - const raw = await fs4.readFile(permissionModeMarkerPath(), "utf-8"); + const raw = await fs5.readFile(permissionModeMarkerPath(), "utf-8"); const parsed = JSON.parse(raw); return typeof parsed.permission_mode === "string" ? parsed.permission_mode : null; } catch { @@ -26152,21 +26502,21 @@ function runToolAnnotations(enableHitl, clientSupportsElicitation, isCursor) { } // src/url-config-store.ts -import fs5 from "node:fs"; -import path5 from "node:path"; -import { homedir as homedir2 } from "node:os"; +import fs6 from "node:fs"; +import path6 from "node:path"; var CONFIG_FILENAME = "mcp-server-url.json"; -var DIR_MODE2 = 448; -var FILE_MODE2 = 384; +var DIR_MODE3 = 448; +var FILE_MODE3 = 384; function resolveConfigDir() { - return process.env.PLUGIN_DATA_DIR || path5.join(homedir2(), ".glean"); + return resolveDataDir(); } function configFile() { - return path5.join(resolveConfigDir(), CONFIG_FILENAME); + return path6.join(resolveConfigDir(), CONFIG_FILENAME); } function loadServerUrl() { + migrateLegacyData(); try { - const raw = fs5.readFileSync(configFile(), "utf-8"); + const raw = fs6.readFileSync(configFile(), "utf-8"); const data = JSON.parse(raw); if (typeof data.serverUrl !== "string" || !data.serverUrl) return void 0; return data.serverUrl; @@ -26175,40 +26525,41 @@ function loadServerUrl() { } } function saveServerUrl(url2) { + migrateLegacyData(); const filePath = configFile(); - const dir = path5.dirname(filePath); - fs5.mkdirSync(dir, { recursive: true, mode: DIR_MODE2 }); - fs5.chmodSync(dir, DIR_MODE2); + const dir = ensureDataDir(); + fs6.chmodSync(dir, DIR_MODE3); const data = { serverUrl: url2 }; - fs5.writeFileSync(filePath, JSON.stringify(data, null, 2), { + fs6.writeFileSync(filePath, JSON.stringify(data, null, 2), { encoding: "utf-8", - mode: FILE_MODE2 + mode: FILE_MODE3 }); - fs5.chmodSync(filePath, FILE_MODE2); + fs6.chmodSync(filePath, FILE_MODE3); } function clearServerUrl() { + migrateLegacyData(); try { - fs5.rmSync(configFile(), { force: true }); + fs6.rmSync(configFile(), { force: true }); } catch { } } // src/remote-tools-cache-store.ts -import fs6 from "node:fs"; -import path6 from "node:path"; -import { homedir as homedir3 } from "node:os"; +import fs7 from "node:fs"; +import path7 from "node:path"; var CACHE_FILENAME = "remote-tools-cache.json"; -var DIR_MODE3 = 448; -var FILE_MODE3 = 384; +var DIR_MODE4 = 448; +var FILE_MODE4 = 384; function resolveCacheDir() { - return process.env.PLUGIN_DATA_DIR || path6.join(homedir3(), ".glean"); + return resolveDataDir(); } function cacheFile() { - return path6.join(resolveCacheDir(), CACHE_FILENAME); + return path7.join(resolveCacheDir(), CACHE_FILENAME); } function readStore() { + migrateLegacyData(); try { - const raw = fs6.readFileSync(cacheFile(), "utf-8"); + const raw = fs7.readFileSync(cacheFile(), "utf-8"); const data = JSON.parse(raw); if (data && typeof data === "object" && !Array.isArray(data)) { return data; @@ -26220,14 +26571,13 @@ function readStore() { } function writeStore(store) { const filePath = cacheFile(); - const dir = path6.dirname(filePath); - fs6.mkdirSync(dir, { recursive: true, mode: DIR_MODE3 }); - fs6.chmodSync(dir, DIR_MODE3); - fs6.writeFileSync(filePath, JSON.stringify(store, null, 2), { + const dir = ensureDataDir(); + fs7.chmodSync(dir, DIR_MODE4); + fs7.writeFileSync(filePath, JSON.stringify(store, null, 2), { encoding: "utf-8", - mode: FILE_MODE3 + mode: FILE_MODE4 }); - fs6.chmodSync(filePath, FILE_MODE3); + fs7.chmodSync(filePath, FILE_MODE4); } function loadRemoteTools(serverUrl) { if (!serverUrl) return []; @@ -26248,16 +26598,17 @@ function saveRemoteTools(serverUrl, tools) { } } function clearRemoteTools(serverUrl) { + migrateLegacyData(); try { if (!serverUrl) { - fs6.rmSync(cacheFile(), { force: true }); + fs7.rmSync(cacheFile(), { force: true }); return; } const store = readStore(); if (store[serverUrl] !== void 0) { delete store[serverUrl]; if (Object.keys(store).length === 0) { - fs6.rmSync(cacheFile(), { force: true }); + fs7.rmSync(cacheFile(), { force: true }); } else { writeStore(store); } @@ -26446,14 +26797,13 @@ var EMAIL_RESOLVE_FAILED_TEXT = `Double-check the email for typos and try again var SETUP_NEEDED_ERROR = "Glean is not configured yet. Call the `setup` tool first to provide your Glean Server URL before using find_skills or run_tool."; var AUTH_REDIRECT_TO_SETUP_TEXT = "[SETUP_REQUIRED]\n\nAuthentication is required. Call the `setup` tool (no arguments) to sign in to Glean, then retry this tool."; function resolveLogPath() { - const base = process.env.PLUGIN_DATA_DIR || path7.join(homedir4(), ".glean"); - return path7.join(base, "glean-server.log"); + return path8.join(resolveDataDir(), "glean-server.log"); } var LOG_PATH = resolveLogPath(); try { - const logDir = path7.dirname(LOG_PATH); - fs7.mkdirSync(logDir, { recursive: true, mode: 448 }); - fs7.chmodSync(logDir, 448); + const logDir = path8.dirname(LOG_PATH); + fs8.mkdirSync(logDir, { recursive: true, mode: 448 }); + fs8.chmodSync(logDir, 448); } catch { } function logLine(label, detail) { @@ -26462,8 +26812,8 @@ function logLine(label, detail) { const line = `${ts} ${label}${suffix} `; try { - fs7.appendFileSync(LOG_PATH, line, { mode: 384 }); - fs7.chmodSync(LOG_PATH, 384); + fs8.appendFileSync(LOG_PATH, line, { mode: 384 }); + fs8.chmodSync(LOG_PATH, 384); } catch { } console.error(line.trimEnd()); @@ -26472,7 +26822,7 @@ function resolveSkillsBaseDir() { if (process.env.SKILLS_BASE_DIR) { return process.env.SKILLS_BASE_DIR; } - return path7.join(tmpdir(), "glean-skills-cache"); + return path8.join(tmpdir(), "glean-skills-cache"); } var server = new Server( { name: "glean", version: "1.0.0" }, @@ -26540,7 +26890,7 @@ var RUN_TOOL_TOOL = { var SETUP_TOOL = { name: "setup", annotations: { readOnlyHint: true }, - description: "Check or configure the Glean connection. Setup completes in three stages: (1) resolve and save the Server URL, (2) authenticate, (3) fetch the remote tool catalog. Call with no arguments to advance through the next missing stage. Call with email to look up and (re)configure user's Glean instance. Call with reset=true to clear all configuration.", + description: "Check or configure the Glean connection. Setup completes in three stages: (1) resolve and save the Server URL, (2) authenticate, (3) fetch the remote tool catalog. Call with no arguments to advance through the next missing stage. Call with email to look up and (re)configure user's Glean instance. Call with reset=true to clear the current authentication and setup URL while retaining the DCR client when it can safely be reused. Pass fresh_client=true only when a new OAuth client registration is explicitly required.", inputSchema: { type: "object", properties: { @@ -26554,7 +26904,11 @@ var SETUP_TOOL = { }, reset: { type: "boolean", - description: "Clear cached URL, credentials, and remote tool cache." + description: "Clear the cached URL, authentication, and remote tool cache. The registered OAuth client is retained when possible." + }, + fresh_client: { + type: "boolean", + description: "With reset=true, also discard the registered OAuth client and force a new dynamic client registration." } }, required: [] @@ -26734,6 +27088,10 @@ async function advanceSetup() { if (!serverUrl) { return { content: [{ type: "text", text: SETUP_REQUIRED_TEXT }] }; } + const provider = getOAuthProvider(); + if (provider.clientServerUrl() !== serverUrl) { + provider.setAccountContext(provider.accountEmail(), serverUrl); + } const conn = await connectWithSignIn(serverUrl); if (!conn.ok) return conn.result; const remoteClient = conn.client; @@ -26915,19 +27273,39 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => { clientInfo: server.getClientVersion() ?? null }); if (args.reset === true) { + const freshClient = args.fresh_client === true; + const stored = loadCredentials(); + const previousServerUrl = loadServerUrl(); clearServerUrl(); - clearCredentials(); + if (freshClient) { + clearCredentials(); + } else if (stored) { + saveCredentials( + void 0, + stored.clientInfo, + { + accountEmail: null, + clientServerUrl: stored.clientServerUrl ?? previousServerUrl ?? null, + abandonedSignIns: 0, + tokenUpdatedAt: Date.now() + }, + { forceTokenUpdate: true } + ); + } clearRemoteTools(); oauthProvider = void 0; cachedRemoteTools = []; - logLine("setup.reset"); + logLine("setup.reset", { + freshClient, + retainedClient: !freshClient && !!stored?.clientInfo + }); server.sendToolListChanged().catch(() => { }); return { content: [ { type: "text", - text: "Glean configuration has been reset. Call setup again with your email to reconfigure." + text: "Glean authentication has been reset. Call setup again with your email to sign in. The registered OAuth client will be reused when it belongs to the same server; pass fresh_client=true with reset=true to register a new client." } ] }; @@ -26969,6 +27347,11 @@ ${EMAIL_RESOLVE_FAILED_TEXT}` }; } const previousUrl = loadServerUrl(); + const stored = loadCredentials(); + const requestedEmail = normalizeAccountEmail(email2); + const urlChanged = previousUrl !== normalized; + const reusableClient = !!stored?.clientInfo && stored.clientServerUrl === normalized; + const accountChanged = !!requestedEmail && !!stored?.tokens && stored.accountEmail !== requestedEmail; try { saveServerUrl(normalized); } catch (err) { @@ -26980,13 +27363,26 @@ ${EMAIL_RESOLVE_FAILED_TEXT}` isError: true }; } - const urlChanged = previousUrl !== normalized; - if (urlChanged) { + if (urlChanged && !reusableClient) { clearCredentials(); oauthProvider = void 0; } + const provider = getOAuthProvider(); + if (accountChanged) { + provider.resetAuthentication(requestedEmail, normalized); + } else { + provider.setAccountContext( + requestedEmail ?? provider.accountEmail(), + normalized + ); + } cachedRemoteTools = loadRemoteTools(normalized); - logLine("setup.configured", { serverUrl: normalized, urlChanged }); + logLine("setup.configured", { + serverUrl: normalized, + urlChanged, + reusableClient, + accountChanged + }); } return await advanceSetup(); } diff --git a/plugins/glean/start.mjs b/plugins/glean/start.mjs index 84e549b..2bf85d8 100644 --- a/plugins/glean/start.mjs +++ b/plugins/glean/start.mjs @@ -21,7 +21,9 @@ function val(v) { const launchCwd = process.cwd(); -// Resolve where credentials, caches, and config are stored. +// Resolve the host-managed plugin data directory for skills/cache state. +// Auth credentials and setup state are resolved by the bundle to the stable +// per-user ~/.glean directory, with one-time migration from this legacy path. // CLAUDE_PLUGIN_DATA is the managed lifecycle dir provided by the plugin host. const pluginDataDir = val(process.env.CLAUDE_PLUGIN_DATA) ?? diff --git a/src/auth-provider.ts b/src/auth-provider.ts index d3345d9..0f1425d 100644 --- a/src/auth-provider.ts +++ b/src/auth-provider.ts @@ -8,10 +8,18 @@ import { execFile, spawn } from "node:child_process"; import { platform } from "node:os"; import { getCallbackUrl, setExpectedState } from "./auth-callback-server.js"; import { + acquireDataFileLockSync, + releaseDataFileLock, + type DataLockHandle, +} from "./data-dir.js"; +import { + acquireClientRegistrationLock, clearCredentials, credentialsMtimeMs, loadCredentials, + releaseClientRegistrationLock, saveCredentials, + type CredentialMetadata, } from "./token-store.js"; export type InvalidationScope = "all" | "client" | "tokens" | "verifier"; @@ -33,6 +41,11 @@ function sleep(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } +export function normalizeAccountEmail(email: string | undefined): string | undefined { + const normalized = email?.trim().toLowerCase(); + return normalized || undefined; +} + /** * Open `url` in the user's default browser. Used for the self-open sign-in * path when the client does not support URL-mode elicitation (where the client @@ -73,6 +86,12 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { private _credentialsMtimeMs: number | undefined; // Consecutive abandoned sign-ins with the current client. private _abandonedSignIns = 0; + // Held from clientInformation() returning undefined until the SDK either + // persists the registration or the connection attempt fails. + private _clientRegistrationLock: DataLockHandle | undefined; + private _accountEmail: string | undefined; + private _clientServerUrl: string | undefined; + private _tokenUpdatedAt: number | undefined; authorizationUrl: string | undefined; @@ -87,8 +106,12 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { constructor() { const stored = loadCredentials(); if (stored) { - this._tokens = stored.tokens as OAuthTokens | undefined; - this._clientInfo = stored.clientInfo as OAuthClientInformationMixed | undefined; + this._tokens = (stored.tokens ?? undefined) as OAuthTokens | undefined; + this._clientInfo = (stored.clientInfo ?? undefined) as OAuthClientInformationMixed | undefined; + this._accountEmail = stored.accountEmail ?? undefined; + this._clientServerUrl = stored.clientServerUrl ?? undefined; + this._abandonedSignIns = stored.abandonedSignIns ?? 0; + this._tokenUpdatedAt = stored.tokenUpdatedAt ?? undefined; } this._credentialsMtimeMs = credentialsMtimeMs(); } @@ -109,9 +132,35 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { if (!stored) return; if (stored.tokens) { this._tokens = stored.tokens as OAuthTokens; + } else if ( + stored.tokenUpdatedAt !== undefined && + stored.tokenUpdatedAt !== null && + (this._tokenUpdatedAt === undefined || + stored.tokenUpdatedAt > this._tokenUpdatedAt) + ) { + // A newer explicit reset/invalidation is different from a transient + // missing file or a client-only rewrite; propagate the token tombstone. + this._tokens = undefined; } if (stored.clientInfo) { this._clientInfo = stored.clientInfo as OAuthClientInformationMixed; + // A sibling completed the registration while this process was waiting. + if (this._clientRegistrationLock) { + releaseClientRegistrationLock(this._clientRegistrationLock); + this._clientRegistrationLock = undefined; + } + } + if (stored.accountEmail !== undefined) { + this._accountEmail = stored.accountEmail ?? undefined; + } + if (stored.clientServerUrl !== undefined) { + this._clientServerUrl = stored.clientServerUrl ?? undefined; + } + if (stored.abandonedSignIns !== undefined) { + this._abandonedSignIns = stored.abandonedSignIns ?? 0; + } + if (stored.tokenUpdatedAt !== undefined) { + this._tokenUpdatedAt = stored.tokenUpdatedAt ?? undefined; } } @@ -135,6 +184,7 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { return false; } this._tokens = diskTokens; + this._tokenUpdatedAt = stored?.tokenUpdatedAt ?? Date.now(); this._credentialsMtimeMs = diskMtime; if (stored?.clientInfo) { this._clientInfo = stored.clientInfo as OAuthClientInformationMixed; @@ -187,14 +237,33 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { clientInformation(): OAuthClientInformationMixed | undefined { // Pick up a sibling's registration; the SDK registers whenever this is undefined. this.syncTokensFromDisk(); + if (this._clientInfo) return this._clientInfo; + + // The SDK's provider API is synchronous here. Acquire a lock before + // returning undefined and hold it until saveClientInformation() or the + // connection error path. A second process therefore waits for the first + // registration to land instead of registering a second client. + if (!this._clientRegistrationLock) { + this._clientRegistrationLock = acquireClientRegistrationLock(); + // The lock may have been held by a sibling that just completed DCR. + // Force a post-lock read before deciding that registration is needed. + this._credentialsMtimeMs = undefined; + this.syncTokensFromDisk(); + if (this._clientInfo) { + releaseClientRegistrationLock(this._clientRegistrationLock); + this._clientRegistrationLock = undefined; + } + } return this._clientInfo; } saveClientInformation(info: OAuthClientInformationMixed): void { console.error(`[auth] Registered OAuth client: ${info.client_id}`); this._clientInfo = info; - saveCredentials(this._tokens, this._clientInfo); + saveCredentials(this._tokens, this._clientInfo, this.credentialMetadata()); this._credentialsMtimeMs = credentialsMtimeMs(); + releaseClientRegistrationLock(this._clientRegistrationLock); + this._clientRegistrationLock = undefined; } tokens(): OAuthTokens | undefined { @@ -204,21 +273,76 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { saveTokens(tokens: OAuthTokens): void { this._tokens = tokens; + this._tokenUpdatedAt = Date.now(); this._authUrlPending = false; this._abandonedSignIns = 0; - saveCredentials(this._tokens, this._clientInfo); + saveCredentials(this._tokens, this._clientInfo, this.credentialMetadata()); // Own write must not look like a sibling change. this._credentialsMtimeMs = credentialsMtimeMs(); this.onTokensChanged?.(tokens); } + /** Persist the account/server context without changing the grant. */ + setAccountContext(accountEmail: string | undefined, serverUrl: string): void { + this._accountEmail = normalizeAccountEmail(accountEmail); + this._clientServerUrl = serverUrl; + saveCredentials(this._tokens, this._clientInfo, this.credentialMetadata()); + this._credentialsMtimeMs = credentialsMtimeMs(); + } + + /** The account associated with the currently cached grant, if known. */ + accountEmail(): string | undefined { + return this._accountEmail; + } + + /** The server for which the cached DCR client was registered, if known. */ + clientServerUrl(): string | undefined { + return this._clientServerUrl; + } + + /** + * Force a new user sign-in while retaining a client registered for the same + * server. This is used for account switching and normal reset. A fresh DCR + * is only required when the server changes or the caller explicitly asks + * for a fresh client. + */ + resetAuthentication(accountEmail: string | undefined, serverUrl: string): void { + const hadTokens = this._tokens !== undefined; + this._tokens = undefined; + this._tokenUpdatedAt = Date.now(); + this._accountEmail = normalizeAccountEmail(accountEmail); + this._clientServerUrl = serverUrl; + this._codeVerifier = ""; + this._pendingAuthCode = undefined; + this.authorizationUrl = undefined; + this._authUrlPending = false; + this._abandonedSignIns = 0; + saveCredentials(undefined, this._clientInfo, this.credentialMetadata(), { + forceTokenUpdate: true, + }); + this._credentialsMtimeMs = credentialsMtimeMs(); + if (hadTokens) this.onTokensChanged?.(undefined); + } + + private credentialMetadata(): CredentialMetadata { + return { + accountEmail: this._accountEmail ?? null, + clientServerUrl: this._clientServerUrl ?? null, + abandonedSignIns: this._abandonedSignIns, + tokenUpdatedAt: this._tokenUpdatedAt ?? null, + }; + } + async invalidateCredentials(scope: InvalidationScope): Promise { console.error(`[auth] Invalidating credentials: scope=${scope}`); const tokensClearedBefore = this._tokens === undefined; switch (scope) { case "all": + this.releaseClientRegistrationLock(); this._tokens = undefined; this._clientInfo = undefined; + this._accountEmail = undefined; + this._clientServerUrl = undefined; this._codeVerifier = ""; this._authUrlPending = false; // Fresh client → fresh retry budget. @@ -226,14 +350,20 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { clearCredentials(); break; case "client": + this.releaseClientRegistrationLock(); this._clientInfo = undefined; - saveCredentials(this._tokens, undefined); + saveCredentials(this._tokens, undefined, this.credentialMetadata(), { + forceClientUpdate: true, + }); break; case "tokens": // Usually a sibling's rotation — try adopting before clearing. if (await this.adoptNewerTokenWithGrace()) return; this._tokens = undefined; - saveCredentials(undefined, this._clientInfo); + this._tokenUpdatedAt = Date.now(); + saveCredentials(undefined, this._clientInfo, this.credentialMetadata(), { + forceTokenUpdate: true, + }); break; case "verifier": this._codeVerifier = ""; @@ -247,6 +377,11 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { } } + releaseClientRegistrationLock(): void { + releaseClientRegistrationLock(this._clientRegistrationLock); + this._clientRegistrationLock = undefined; + } + // True if we previously issued an authorize URL but never received tokens — // implying the URL was likely rejected by the server (e.g. stale client_id). needsFreshClient(): boolean { @@ -259,13 +394,28 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { // Abandoned sign-in: keep the client and clear the pending flow. Returns // false after two consecutive failures (client likely dead → re-register). - abandonPendingSignIn(): boolean { - this._abandonedSignIns += 1; - this._codeVerifier = ""; - this._pendingAuthCode = undefined; - this.authorizationUrl = undefined; - this._authUrlPending = false; - return this._abandonedSignIns < 2; + abandonPendingSignIn(clientRejected = false): boolean { + const lock = acquireDataFileLockSync("mcp-auth-recovery", { + waitMs: 5_000, + staleMs: 30_000, + }); + try { + // Re-read first so a sibling's token/client metadata is not clobbered by + // this process's recovery bookkeeping. + this.syncTokensFromDisk(); + this._abandonedSignIns = clientRejected + ? 2 + : this._abandonedSignIns + 1; + this._codeVerifier = ""; + this._pendingAuthCode = undefined; + this.authorizationUrl = undefined; + this._authUrlPending = false; + saveCredentials(this._tokens, this._clientInfo, this.credentialMetadata()); + this._credentialsMtimeMs = credentialsMtimeMs(); + return !clientRejected && this._abandonedSignIns < 2; + } finally { + releaseDataFileLock(lock); + } } get pendingAuthCode(): string | undefined { diff --git a/src/data-dir.ts b/src/data-dir.ts new file mode 100644 index 0000000..b872934 --- /dev/null +++ b/src/data-dir.ts @@ -0,0 +1,249 @@ +import fs from "node:fs"; +import path from "node:path"; +import { randomUUID } from "node:crypto"; +import { homedir } from "node:os"; + +const DIR_MODE = 0o700; +const FILE_MODE = 0o600; +const MIGRATION_MARKER = ".legacy-store-migrated-v1"; +const MIGRATION_LOCK = ".legacy-store-migration.lock"; + +// These are the files that historically followed PLUGIN_DATA_DIR. Auth and +// setup state now live in the stable per-user directory so terminal, VS Code, +// Cursor, and managed plugin launches share one state store. +const MIGRATED_FILES = [ + "mcp-credentials.json", + "mcp-server-url.json", + "remote-tools-cache.json", + "glean-server.log", +]; + +export interface DataLockOptions { + waitMs?: number; + staleMs?: number; +} + +export interface DataLockHandle { + path: string; + token: string; +} + +function envValue(name: string): string | undefined { + const value = process.env[name]?.trim(); + if (!value || value.startsWith("${")) return undefined; + return value; +} + +/** + * Stable auth/config directory shared by every host and launcher. + * + * GLEAN_AUTH_DATA_DIR is intentionally an explicit escape hatch for tests and + * controlled deployments. PLUGIN_DATA_DIR is deliberately not used here: it + * is host-managed and was the source of the terminal/plugin store split. + */ +export function resolveDataDir(): string { + return ( + envValue("GLEAN_AUTH_DATA_DIR") ?? + path.join(homedir() || process.env.TMPDIR || "/tmp", ".glean") + ); +} + +function legacyDataDirs(): string[] { + const canonical = path.resolve(resolveDataDir()); + const candidates = [envValue("PLUGIN_DATA_DIR"), envValue("CLAUDE_PLUGIN_DATA")]; + return [...new Set(candidates.filter((dir): dir is string => !!dir))] + .map((dir) => path.resolve(dir)) + .filter((dir) => dir !== canonical); +} + +function sleepSync(ms: number): void { + const signal = new Int32Array(new SharedArrayBuffer(4)); + Atomics.wait(signal, 0, 0, ms); +} + +function lockPath(name: string): string { + return path.join(resolveDataDir(), `.${name}.lock`); +} + +function isStale(lockFile: string, staleMs: number): boolean { + try { + return Date.now() - fs.statSync(lockFile).mtimeMs > staleMs; + } catch { + return false; + } +} + +/** + * Acquire a small cross-process lock using O_EXCL semantics. The returned + * path must be released by the caller. Stale locks are recoverable after the + * configured timeout so a crashed plugin cannot permanently block auth. + */ +export function acquireDataFileLockSync( + name: string, + options: DataLockOptions = {}, +): DataLockHandle | undefined { + const waitMs = options.waitMs ?? 30_000; + const staleMs = options.staleMs ?? 120_000; + const filePath = lockPath(name); + const dir = path.dirname(filePath); + + try { + fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE }); + fs.chmodSync(dir, DIR_MODE); + } catch { + return undefined; + } + + const deadline = Date.now() + Math.max(0, waitMs); + do { + try { + const token = randomUUID(); + const fd = fs.openSync(filePath, "wx", FILE_MODE); + try { + fs.writeFileSync( + fd, + JSON.stringify({ + pid: process.pid, + token, + createdAt: new Date().toISOString(), + }), + { encoding: "utf-8" }, + ); + } finally { + fs.closeSync(fd); + } + return { path: filePath, token }; + } catch (err) { + const code = err && typeof err === "object" && "code" in err + ? (err as { code?: string }).code + : undefined; + if (code !== "EEXIST") return undefined; + if (isStale(filePath, staleMs)) { + try { + fs.rmSync(filePath, { force: true }); + } catch { + /* another process may have replaced or removed the lock */ + } + continue; + } + if (Date.now() >= deadline) return undefined; + sleepSync(Math.min(25, Math.max(1, deadline - Date.now()))); + } + } while (Date.now() <= deadline); + + return undefined; +} + +export function releaseDataFileLock(lock: DataLockHandle | undefined): void { + if (!lock) return; + try { + const contents = JSON.parse(fs.readFileSync(lock.path, "utf-8")) as { + token?: string; + }; + if (contents.token !== lock.token) return; + fs.rmSync(lock.path, { force: true }); + } catch { + /* best effort; stale-lock recovery handles a crashed owner */ + } +} + +function copyFileAtomically(source: string, target: string): void { + const dir = path.dirname(target); + fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE }); + fs.chmodSync(dir, DIR_MODE); + const tmp = `${target}.${process.pid}.migration.tmp`; + try { + fs.copyFileSync(source, tmp); + fs.chmodSync(tmp, FILE_MODE); + fs.renameSync(tmp, target); + fs.chmodSync(target, FILE_MODE); + } finally { + try { + fs.rmSync(tmp, { force: true }); + } catch { + /* ignore cleanup failures */ + } + } +} + +/** + * Migrate files from the old host-managed store(s) once. If both stores exist, + * the newest source file wins; after migration all current code writes only to + * resolveDataDir(). The marker prevents an old, already-running process from + * repeatedly overwriting the canonical store on every request. + */ +export function migrateLegacyData(): void { + const canonical = resolveDataDir(); + const sources = legacyDataDirs(); + if (sources.length === 0) return; + + const marker = path.join(canonical, MIGRATION_MARKER); + try { + if (fs.existsSync(marker)) return; + } catch { + return; + } + + const lock = acquireDataFileLockSync( + MIGRATION_LOCK.slice(1), + { waitMs: 5_000, staleMs: 60_000 }, + ); + if (!lock) return; + + try { + if (fs.existsSync(marker)) return; + fs.mkdirSync(canonical, { recursive: true, mode: DIR_MODE }); + fs.chmodSync(canonical, DIR_MODE); + + for (const filename of MIGRATED_FILES) { + const candidates = sources + .map((dir) => path.join(dir, filename)) + .filter((file) => { + try { + return fs.statSync(file).isFile(); + } catch { + return false; + } + }) + .sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs); + if (candidates.length === 0) continue; + + const target = path.join(canonical, filename); + const newestSource = candidates[0]; + let targetIsOlder = true; + try { + targetIsOlder = fs.statSync(target).mtimeMs < fs.statSync(newestSource).mtimeMs; + } catch { + /* target does not exist */ + } + if (!fs.existsSync(target) || targetIsOlder) { + copyFileAtomically(newestSource, target); + console.error(`[auth] Migrated legacy data: ${filename}`); + } + } + + fs.writeFileSync( + marker, + JSON.stringify({ migratedAt: new Date().toISOString(), sources }), + { encoding: "utf-8", mode: FILE_MODE }, + ); + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + console.error(`[auth] Failed to migrate legacy data: ${msg}`); + } finally { + releaseDataFileLock(lock); + } +} + +export function ensureDataDir(): string { + const dir = resolveDataDir(); + fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE }); + fs.chmodSync(dir, DIR_MODE); + return dir; +} + +export const dataDirConstants = { + DIR_MODE, + FILE_MODE, + MIGRATION_MARKER, +}; diff --git a/src/index.ts b/src/index.ts index bf87b6d..df57b1c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -8,13 +8,17 @@ import { } from "@modelcontextprotocol/sdk/types.js"; import path from "node:path"; import fs from "node:fs"; -import { homedir, tmpdir } from "node:os"; +import { tmpdir } from "node:os"; import { AuthRequiredError, createRemoteClient, type RemoteClientOptions, } from "./remote-client.js"; -import { GleanOAuthClientProvider, openBrowser } from "./auth-provider.js"; +import { + GleanOAuthClientProvider, + normalizeAccountEmail, + openBrowser, +} from "./auth-provider.js"; import { startCallbackServer, closeCallbackServer, @@ -31,7 +35,11 @@ import { saveServerUrl, clearServerUrl, } from "./url-config-store.js"; -import { clearCredentials } from "./token-store.js"; +import { + clearCredentials, + loadCredentials, + saveCredentials, +} from "./token-store.js"; import { loadRemoteTools, saveRemoteTools, @@ -45,6 +53,7 @@ import { } from "./tools/remote-passthrough.js"; import { resolveSessionId } from "./session-id.js"; import { resolveServerUrlFromEmail } from "./config-search.js"; +import { resolveDataDir } from "./data-dir.js"; function readEnv(...keys: string[]): string | undefined { for (const key of keys) { @@ -92,8 +101,7 @@ const AUTH_REDIRECT_TO_SETUP_TEXT = "(no arguments) to sign in to Glean, then retry this tool."; function resolveLogPath(): string { - const base = process.env.PLUGIN_DATA_DIR || path.join(homedir(), ".glean"); - return path.join(base, "glean-server.log"); + return path.join(resolveDataDir(), "glean-server.log"); } const LOG_PATH = resolveLogPath(); @@ -264,7 +272,9 @@ const SETUP_TOOL: Tool = { "(3) fetch the remote tool catalog. Call with no arguments to advance " + "through the next missing stage. Call with email to look up and " + "(re)configure user's Glean instance. Call with reset=true to clear " + - "all configuration.", + "the current authentication and setup URL while retaining the DCR client " + + "when it can safely be reused. Pass fresh_client=true only when a new " + + "OAuth client registration is explicitly required.", inputSchema: { type: "object" as const, properties: { @@ -284,7 +294,15 @@ const SETUP_TOOL: Tool = { }, reset: { type: "boolean", - description: "Clear cached URL, credentials, and remote tool cache.", + description: + "Clear the cached URL, authentication, and remote tool cache. " + + "The registered OAuth client is retained when possible.", + }, + fresh_client: { + type: "boolean", + description: + "With reset=true, also discard the registered OAuth client and " + + "force a new dynamic client registration.", }, }, required: [], @@ -521,6 +539,11 @@ async function advanceSetup(): Promise { return { content: [{ type: "text", text: SETUP_REQUIRED_TEXT }] }; } + const provider = getOAuthProvider(); + if (provider.clientServerUrl() !== serverUrl) { + provider.setAccountContext(provider.accountEmail(), serverUrl); + } + const conn = await connectWithSignIn(serverUrl); if (!conn.ok) return conn.result; const remoteClient = conn.client; @@ -730,12 +753,36 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => { clientInfo: server.getClientVersion() ?? null, }); if (args.reset === true) { + const freshClient = args.fresh_client === true; + const stored = loadCredentials(); + const previousServerUrl = loadServerUrl(); clearServerUrl(); - clearCredentials(); + if (freshClient) { + clearCredentials(); + } else if (stored) { + // Reset authentication and setup state, but retain the DCR client + // plus the server it belongs to. The next setup can reuse that + // registration when it targets the same server. + saveCredentials( + undefined, + stored.clientInfo, + { + accountEmail: null, + clientServerUrl: + stored.clientServerUrl ?? previousServerUrl ?? null, + abandonedSignIns: 0, + tokenUpdatedAt: Date.now(), + }, + { forceTokenUpdate: true }, + ); + } clearRemoteTools(); oauthProvider = undefined; cachedRemoteTools = []; - logLine("setup.reset"); + logLine("setup.reset", { + freshClient, + retainedClient: !freshClient && !!stored?.clientInfo, + }); // Fire-and-forget — tools list is shorter without the dynamic // surface; the host should re-fetch on its next idle cycle. server.sendToolListChanged().catch(() => { @@ -746,8 +793,10 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => { { type: "text", text: - "Glean configuration has been reset. Call setup again with " + - "your email to reconfigure.", + "Glean authentication has been reset. Call setup again with " + + "your email to sign in. The registered OAuth client will be " + + "reused when it belongs to the same server; pass " + + "fresh_client=true with reset=true to register a new client.", }, ], }; @@ -796,6 +845,16 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => { } const previousUrl = loadServerUrl(); + const stored = loadCredentials(); + const requestedEmail = normalizeAccountEmail(email); + const urlChanged = previousUrl !== normalized; + const reusableClient = + !!stored?.clientInfo && stored.clientServerUrl === normalized; + const accountChanged = + !!requestedEmail && + !!stored?.tokens && + stored.accountEmail !== requestedEmail; + try { saveServerUrl(normalized); } catch (err) { @@ -808,15 +867,33 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => { }; } - // Only wipe auth state when actually switching instances — a same-URL - // re-setup must keep the DCR client. Old URL's tool cache is kept. - const urlChanged = previousUrl !== normalized; - if (urlChanged) { + // A DCR client is scoped to its server. Reuse a retained client after + // reset only when its recorded server matches; otherwise remove it. + if (urlChanged && !reusableClient) { clearCredentials(); oauthProvider = undefined; } + + const provider = getOAuthProvider(); + if (accountChanged) { + // Email is an account-switch request. Clear only the grant and keep + // the server's DCR client, so switching users does not create a new + // authorized-app entry. + provider.resetAuthentication(requestedEmail, normalized); + } else { + provider.setAccountContext( + requestedEmail ?? provider.accountEmail(), + normalized, + ); + } + cachedRemoteTools = loadRemoteTools(normalized); - logLine("setup.configured", { serverUrl: normalized, urlChanged }); + logLine("setup.configured", { + serverUrl: normalized, + urlChanged, + reusableClient, + accountChanged, + }); // Fall through to advanceSetup, which will now find URL ✓ and try // to drive auth + tool fetch in the same call. } diff --git a/src/remote-client.ts b/src/remote-client.ts index d718bf4..d58c5df 100644 --- a/src/remote-client.ts +++ b/src/remote-client.ts @@ -111,6 +111,14 @@ export class AuthRequiredError extends Error { } let pendingTransport: StreamableHTTPClientTransport | undefined; +// The provider API is synchronous, so two connect calls in one MCP process can +// both observe an empty client before the SDK's async DCR request completes. +// Serialize that first registration per provider in addition to the OS lock +// used by token-store for sibling processes. +const pendingRegistrations = new WeakMap< + GleanOAuthClientProvider, + Promise +>(); function buildTransport( serverUrl: string, @@ -170,9 +178,10 @@ export async function createRemoteClient( const msg = err instanceof Error ? err.message : String(err); console.error(`[auth] Code exchange failed: ${msg} — discarding stale auth state`); pendingTransport = undefined; - // Exchange failures are about the code/verifier, not the client — keep - // the registration; repeat failure escalates to a fresh DCR. - if (!authProvider.abandonPendingSignIn()) { + // Keep the registration for code/verifier failures. An explicit + // invalid_client response escalates immediately; generic repeated + // failures use the shared two-attempt recovery budget. + if (!authProvider.abandonPendingSignIn(isInvalidClientError(err))) { await authProvider.invalidateCredentials("all"); } return createRemoteClient(serverUrl, opts, chatSessionId); @@ -194,6 +203,18 @@ export async function createRemoteClient( } } + let registrationNeeded = false; + if (authProvider?.clientInformation) { + registrationNeeded = !authProvider.clientInformation(); + if (registrationNeeded) { + const pending = pendingRegistrations.get(authProvider); + if (pending) { + await pending; + registrationNeeded = !authProvider.clientInformation(); + } + } + } + const client = new Client( { name: "glean", version: "1.0.0" }, { capabilities: {} }, @@ -203,10 +224,25 @@ export async function createRemoteClient( const accessTokenAtConnect = authProvider?.tokens()?.access_token; const transport = buildTransport(serverUrl, opts, chatSessionId); + let trackedRegistration: Promise | undefined; + let connectPromise: Promise; + if (registrationNeeded && authProvider) { + connectPromise = client.connect(transport); + trackedRegistration = connectPromise.then( + () => undefined, + () => undefined, + ); + pendingRegistrations.set(authProvider, trackedRegistration); + } else { + connectPromise = client.connect(transport); + } try { - await client.connect(transport); + await connectPromise; } catch (error) { + // If registration failed before saveClientInformation() ran, do not leave + // the cross-process registration lock behind until stale-lock expiry. + authProvider?.releaseClientRegistrationLock?.(); if (error instanceof UnauthorizedError && authProvider) { const refreshedAccessToken = authProvider.tokens()?.access_token; if ( @@ -239,11 +275,24 @@ export async function createRemoteClient( return createRemoteClient(serverUrl, opts, chatSessionId, true); } throw error; + } finally { + if ( + trackedRegistration && + authProvider && + pendingRegistrations.get(authProvider) === trackedRegistration + ) { + pendingRegistrations.delete(authProvider); + } } return client; } +function isInvalidClientError(error: unknown): boolean { + const msg = error instanceof Error ? error.message : String(error); + return /invalid[_ -]?client|unknown client|client authentication failed/i.test(msg); +} + // Match broadly; the caller's disk re-check gates the actual retry. function isLikelyRefreshFailure(error: unknown): boolean { const msg = error instanceof Error ? error.message : String(error); diff --git a/src/remote-tools-cache-store.ts b/src/remote-tools-cache-store.ts index fa2900b..e3ad5cc 100644 --- a/src/remote-tools-cache-store.ts +++ b/src/remote-tools-cache-store.ts @@ -1,14 +1,18 @@ import fs from "node:fs"; import path from "node:path"; -import { homedir } from "node:os"; import type { Tool } from "@modelcontextprotocol/sdk/types.js"; +import { + ensureDataDir, + migrateLegacyData, + resolveDataDir, +} from "./data-dir.js"; const CACHE_FILENAME = "remote-tools-cache.json"; const DIR_MODE = 0o700; const FILE_MODE = 0o600; function resolveCacheDir(): string { - return process.env.PLUGIN_DATA_DIR || path.join(homedir(), ".glean"); + return resolveDataDir(); } function cacheFile(): string { @@ -23,6 +27,7 @@ interface CacheEntry { type Store = Record; function readStore(): Store { + migrateLegacyData(); try { const raw = fs.readFileSync(cacheFile(), "utf-8"); const data = JSON.parse(raw); @@ -37,8 +42,7 @@ function readStore(): Store { function writeStore(store: Store): void { const filePath = cacheFile(); - const dir = path.dirname(filePath); - fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE }); + const dir = ensureDataDir(); fs.chmodSync(dir, DIR_MODE); fs.writeFileSync(filePath, JSON.stringify(store, null, 2), { encoding: "utf-8", @@ -68,6 +72,7 @@ export function saveRemoteTools(serverUrl: string, tools: Tool[]): void { } export function clearRemoteTools(serverUrl?: string): void { + migrateLegacyData(); try { if (!serverUrl) { fs.rmSync(cacheFile(), { force: true }); diff --git a/src/token-store.ts b/src/token-store.ts index 535a07d..476bc77 100644 --- a/src/token-store.ts +++ b/src/token-store.ts @@ -1,38 +1,64 @@ import fs from "node:fs"; import path from "node:path"; -import { homedir } from "node:os"; +import { + acquireDataFileLockSync, + ensureDataDir, + type DataLockHandle, + migrateLegacyData, + releaseDataFileLock, + resolveDataDir, +} from "./data-dir.js"; const CREDENTIALS_FILENAME = "mcp-credentials.json"; const DIR_MODE = 0o700; const FILE_MODE = 0o600; +const CLIENT_REGISTRATION_LOCK = "mcp-client-registration"; -function resolveCredentialsDir(): string { - return process.env.PLUGIN_DATA_DIR || path.join(homedir(), ".glean"); +export interface CredentialMetadata { + /** Work account used for the last successful/initiated sign-in. */ + accountEmail?: string | null; + /** OAuth clients are server-specific. */ + clientServerUrl?: string | null; + /** Shared recovery budget across sibling plugin processes. */ + abandonedSignIns?: number | null; + /** Local monotonic-ish timestamp for conflict-free token merging. */ + tokenUpdatedAt?: number | null; } -function credentialsFile(): string { - return path.join(resolveCredentialsDir(), CREDENTIALS_FILENAME); -} - -interface StoredCredentials { +export interface StoredCredentials extends CredentialMetadata { tokens?: unknown; clientInfo?: unknown; } -export function loadCredentials(): StoredCredentials | undefined { +export interface SaveCredentialsOptions { + forceTokenUpdate?: boolean; + forceClientUpdate?: boolean; +} + +function credentialsFile(): string { + return path.join(resolveDataDir(), CREDENTIALS_FILENAME); +} + +function readCredentialsFile(filePath: string): StoredCredentials | undefined { try { - const raw = fs.readFileSync(credentialsFile(), "utf-8"); + const raw = fs.readFileSync(filePath, "utf-8"); return JSON.parse(raw) as StoredCredentials; } catch { return undefined; } } +export function loadCredentials(): StoredCredentials | undefined { + migrateLegacyData(); + return readCredentialsFile(credentialsFile()); +} + /** * mtime of the credentials file (epoch ms), or undefined if unreadable. * Cheap change probe: a single stat, no read + parse. */ export function credentialsMtimeMs(): number | undefined { + migrateLegacyData(); try { return fs.statSync(credentialsFile()).mtimeMs; } catch { @@ -40,13 +66,71 @@ export function credentialsMtimeMs(): number | undefined { } } -export function saveCredentials(tokens: unknown, clientInfo: unknown): void { +/** + * Acquire the registration lock before returning undefined from + * clientInformation(). The MCP SDK interprets undefined as permission to call + * /oauth/register, so the lock must span that asynchronous SDK operation and + * is released by saveClientInformation() or the connection error path. + */ +export function acquireClientRegistrationLock(): DataLockHandle | undefined { + return acquireDataFileLockSync(CLIENT_REGISTRATION_LOCK, { + waitMs: 30_000, + staleMs: 120_000, + }); +} + +export function releaseClientRegistrationLock(lock: DataLockHandle | undefined): void { + releaseDataFileLock(lock); +} + +export function saveCredentials( + tokens: unknown, + clientInfo: unknown, + metadata: CredentialMetadata = {}, + options: SaveCredentialsOptions = {}, +): void { try { + migrateLegacyData(); const filePath = credentialsFile(); - const dir = path.dirname(filePath); - fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE }); - fs.chmodSync(dir, DIR_MODE); - const data: StoredCredentials = { tokens, clientInfo }; + const dir = ensureDataDir(); + const existing = readCredentialsFile(filePath); + const incomingTokenTime = metadata.tokenUpdatedAt ?? undefined; + const existingTokenTime = existing?.tokenUpdatedAt ?? undefined; + const existingTokenIsNewer = + !options.forceTokenUpdate && + existing?.tokens !== undefined && + (tokens === undefined || + (existingTokenTime !== undefined && + (incomingTokenTime === undefined || + existingTokenTime > incomingTokenTime))); + const effectiveTokens = existingTokenIsNewer ? existing?.tokens : tokens; + const effectiveTokenTime = existingTokenIsNewer + ? existingTokenTime + : metadata.tokenUpdatedAt !== undefined + ? metadata.tokenUpdatedAt + : existing?.tokenUpdatedAt; + const effectiveClientInfo = + !options.forceClientUpdate && clientInfo === undefined + ? existing?.clientInfo + : clientInfo; + const data: StoredCredentials = { + tokens: effectiveTokens, + clientInfo: effectiveClientInfo, + // Omitted metadata means preserve it; null explicitly clears it. + accountEmail: + metadata.accountEmail !== undefined + ? metadata.accountEmail + : existing?.accountEmail, + clientServerUrl: + metadata.clientServerUrl !== undefined + ? metadata.clientServerUrl + : existing?.clientServerUrl, + abandonedSignIns: + metadata.abandonedSignIns !== undefined + ? metadata.abandonedSignIns + : existing?.abandonedSignIns, + tokenUpdatedAt: effectiveTokenTime, + }; // Temp-file + rename: concurrent readers never see a half-written store. const tmpPath = `${filePath}.${process.pid}.tmp`; fs.writeFileSync(tmpPath, JSON.stringify(data, null, 2), { @@ -54,6 +138,8 @@ export function saveCredentials(tokens: unknown, clientInfo: unknown): void { mode: FILE_MODE, }); fs.renameSync(tmpPath, filePath); + fs.chmodSync(dir, DIR_MODE); + fs.chmodSync(filePath, FILE_MODE); } catch (err) { const msg = err instanceof Error ? err.message : String(err); console.error(`[auth] Failed to persist credentials: ${msg}`); @@ -62,6 +148,7 @@ export function saveCredentials(tokens: unknown, clientInfo: unknown): void { export function clearCredentials(): void { try { + migrateLegacyData(); fs.rmSync(credentialsFile(), { force: true }); } catch (err) { const msg = err instanceof Error ? err.message : String(err); diff --git a/src/url-config-store.ts b/src/url-config-store.ts index df46d7e..6a7d9e6 100644 --- a/src/url-config-store.ts +++ b/src/url-config-store.ts @@ -1,13 +1,17 @@ import fs from "node:fs"; import path from "node:path"; -import { homedir } from "node:os"; +import { + ensureDataDir, + migrateLegacyData, + resolveDataDir, +} from "./data-dir.js"; const CONFIG_FILENAME = "mcp-server-url.json"; const DIR_MODE = 0o700; const FILE_MODE = 0o600; function resolveConfigDir(): string { - return process.env.PLUGIN_DATA_DIR || path.join(homedir(), ".glean"); + return resolveDataDir(); } function configFile(): string { @@ -19,6 +23,7 @@ interface StoredConfig { } export function loadServerUrl(): string | undefined { + migrateLegacyData(); try { const raw = fs.readFileSync(configFile(), "utf-8"); const data = JSON.parse(raw) as StoredConfig; @@ -30,9 +35,9 @@ export function loadServerUrl(): string | undefined { } export function saveServerUrl(url: string): void { + migrateLegacyData(); const filePath = configFile(); - const dir = path.dirname(filePath); - fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE }); + const dir = ensureDataDir(); fs.chmodSync(dir, DIR_MODE); const data: StoredConfig = { serverUrl: url }; fs.writeFileSync(filePath, JSON.stringify(data, null, 2), { @@ -43,6 +48,7 @@ export function saveServerUrl(url: string): void { } export function clearServerUrl(): void { + migrateLegacyData(); try { fs.rmSync(configFile(), { force: true }); } catch { diff --git a/tests/auth-provider.test.ts b/tests/auth-provider.test.ts index b73a1c5..7308004 100644 --- a/tests/auth-provider.test.ts +++ b/tests/auth-provider.test.ts @@ -28,6 +28,8 @@ describe("GleanOAuthClientProvider", () => { beforeEach(() => { delete process.env.PLUGIN_DATA_DIR; + delete process.env.CLAUDE_PLUGIN_DATA; + delete process.env.GLEAN_AUTH_DATA_DIR; // Skip the rotation grace window by default so invalidation tests don't // wait out the real 2s poll; the grace test overrides this explicitly. process.env.GLEAN_ROTATION_GRACE_MS = "0"; @@ -449,4 +451,43 @@ describe("GleanOAuthClientProvider", () => { await provider.invalidateCredentials("client"); expect(observed).toEqual([]); }); + + it("switches accounts without creating a new DCR client", () => { + const provider = new GleanOAuthClientProvider(); + provider.saveClientInformation({ client_id: "cid" } as any); + provider.setAccountContext( + "Alice@Example.com", + "https://acme-be.glean.com/mcp/gateway/proxy", + ); + provider.saveTokens({ access_token: "alice-token" } as any); + + provider.resetAuthentication( + "Bob@Example.com", + "https://acme-be.glean.com/mcp/gateway/proxy", + ); + + expect(provider.tokens()).toBeUndefined(); + expect(provider.clientInformation()).toEqual({ client_id: "cid" }); + expect(provider.accountEmail()).toBe("bob@example.com"); + const raw = JSON.parse(fs.readFileSync(credFile, "utf-8")); + expect(raw.clientInfo.client_id).toBe("cid"); + expect(raw.tokens).toBeUndefined(); + expect(raw.accountEmail).toBe("bob@example.com"); + }); + + it("shares the abandoned-sign-in budget across provider instances", () => { + const first = new GleanOAuthClientProvider(); + first.saveClientInformation({ client_id: "cid" } as any); + expect(first.abandonPendingSignIn()).toBe(true); + + const second = new GleanOAuthClientProvider(); + expect(second.abandonPendingSignIn()).toBe(false); + }); + + it("immediately escalates when the server explicitly rejects the client", () => { + const provider = new GleanOAuthClientProvider(); + expect(provider.abandonPendingSignIn(true)).toBe(false); + const raw = JSON.parse(fs.readFileSync(credFile, "utf-8")); + expect(raw.abandonedSignIns).toBe(2); + }); }); diff --git a/tests/remote-client-auth-retry.test.ts b/tests/remote-client-auth-retry.test.ts index 2508234..7cff58b 100644 --- a/tests/remote-client-auth-retry.test.ts +++ b/tests/remote-client-auth-retry.test.ts @@ -135,6 +135,60 @@ describe("createRemoteClient abandoned sign-in client reuse", () => { }); }); +describe("createRemoteClient same-process registration gate", () => { + beforeEach(() => { + connectMock.mockReset(); + }); + + it("allows only one concurrent first-time DCR registration", async () => { + let release!: () => void; + const gate = new Promise((resolve) => { + release = resolve; + }); + let registrationCount = 0; + const provider: any = { + clientInfo: undefined, + tokens: () => ({ access_token: "T0" }), + authorizationUrl: undefined, + pendingAuthCode: undefined, + needsFreshClient: () => false, + clientInformation() { + return this.clientInfo; + }, + saveClientInformation(info: unknown) { + this.clientInfo = info; + registrationCount += 1; + }, + }; + + connectMock.mockImplementation(async () => { + if (registrationCount === 0) { + await gate; + provider.saveClientInformation({ client_id: "cid" }); + } + }); + + const first = createRemoteClient( + "https://acme-be.glean.com/mcp/gateway/proxy", + { authProvider: provider }, + "same-process-1", + ); + // Let the first call enter its async connect and publish the pending gate. + await Promise.resolve(); + const second = createRemoteClient( + "https://acme-be.glean.com/mcp/gateway/proxy", + { authProvider: provider }, + "same-process-2", + ); + await Promise.resolve(); + release(); + + await Promise.all([first, second]); + expect(registrationCount).toBe(1); + expect(connectMock).toHaveBeenCalledTimes(2); + }); +}); + describe("createRemoteClient refresh-collision retry", () => { beforeEach(() => { connectMock.mockReset(); diff --git a/tests/remote-tools-cache-store.test.ts b/tests/remote-tools-cache-store.test.ts index 0c0987f..4638400 100644 --- a/tests/remote-tools-cache-store.test.ts +++ b/tests/remote-tools-cache-store.test.ts @@ -8,7 +8,7 @@ const tmpDir = fs.mkdtempSync( path.join(os.tmpdir(), "remote-tools-cache-store-test-"), ); -vi.stubEnv("PLUGIN_DATA_DIR", tmpDir); +vi.stubEnv("GLEAN_AUTH_DATA_DIR", tmpDir); const { loadRemoteTools, saveRemoteTools, clearRemoteTools } = await import( "../src/remote-tools-cache-store.js" diff --git a/tests/token-store.test.ts b/tests/token-store.test.ts index 88685ad..1f9f47c 100644 --- a/tests/token-store.test.ts +++ b/tests/token-store.test.ts @@ -10,19 +10,34 @@ vi.mock("node:os", async () => { return { ...actual, homedir: () => tmpDir }; }); -const { clearCredentials, credentialsMtimeMs, loadCredentials, saveCredentials } = - await import("../src/token-store.js"); +const { + acquireClientRegistrationLock, + clearCredentials, + credentialsMtimeMs, + loadCredentials, + releaseClientRegistrationLock, + saveCredentials, +} = await import("../src/token-store.js"); +const { acquireDataFileLockSync, releaseDataFileLock } = await import( + "../src/data-dir.js" +); describe("token-store", () => { const gleanDir = path.join(tmpDir, ".glean"); const credFile = path.join(gleanDir, "mcp-credentials.json"); + const legacyDir = path.join(tmpDir, "managed-plugin-data"); beforeEach(() => { + delete process.env.PLUGIN_DATA_DIR; + delete process.env.CLAUDE_PLUGIN_DATA; + delete process.env.GLEAN_AUTH_DATA_DIR; fs.rmSync(gleanDir, { recursive: true, force: true }); + fs.rmSync(legacyDir, { recursive: true, force: true }); }); afterEach(() => { fs.rmSync(gleanDir, { recursive: true, force: true }); + fs.rmSync(legacyDir, { recursive: true, force: true }); }); it("returns undefined when credentials file does not exist", () => { @@ -106,4 +121,61 @@ describe("token-store", () => { fs.utimesSync(credFile, future, future); expect(credentialsMtimeMs()!).toBeGreaterThan(first); }); + + it("migrates a host-managed credentials store into the canonical store", () => { + process.env.PLUGIN_DATA_DIR = legacyDir; + fs.mkdirSync(legacyDir, { recursive: true }); + fs.writeFileSync( + path.join(legacyDir, "mcp-credentials.json"), + JSON.stringify({ + tokens: { access_token: "legacy-token" }, + clientInfo: { client_id: "legacy-client" }, + }), + ); + + expect(loadCredentials()).toEqual({ + tokens: { access_token: "legacy-token" }, + clientInfo: { client_id: "legacy-client" }, + }); + expect(fs.existsSync(credFile)).toBe(true); + }); + + it("serializes cross-process lock acquisition", () => { + const first = acquireDataFileLockSync("lock-test", { waitMs: 0 }); + expect(first).toBeTruthy(); + const second = acquireDataFileLockSync("lock-test", { waitMs: 0 }); + expect(second).toBeUndefined(); + releaseDataFileLock(first); + const third = acquireDataFileLockSync("lock-test", { waitMs: 0 }); + expect(third).toBeTruthy(); + releaseDataFileLock(third); + }); + + it("holds a client registration lock until registration completes", () => { + const first = acquireClientRegistrationLock(); + expect(first).toBeTruthy(); + const second = acquireDataFileLockSync("mcp-client-registration", { waitMs: 0 }); + expect(second).toBeUndefined(); + releaseClientRegistrationLock(first); + }); + + it("does not let a metadata write clobber a newer token grant", () => { + saveCredentials( + { access_token: "new-token", refresh_token: "new-refresh" }, + { client_id: "cid" }, + { tokenUpdatedAt: 200 }, + ); + saveCredentials( + undefined, + undefined, + { accountEmail: "user@example.com", tokenUpdatedAt: 100 }, + ); + + expect(loadCredentials()).toMatchObject({ + tokens: { access_token: "new-token", refresh_token: "new-refresh" }, + clientInfo: { client_id: "cid" }, + accountEmail: "user@example.com", + tokenUpdatedAt: 200, + }); + }); }); diff --git a/tests/url-config-store.test.ts b/tests/url-config-store.test.ts index b7c9a5f..a4856af 100644 --- a/tests/url-config-store.test.ts +++ b/tests/url-config-store.test.ts @@ -5,7 +5,7 @@ import os from "node:os"; const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "url-config-store-test-")); -vi.stubEnv("PLUGIN_DATA_DIR", tmpDir); +vi.stubEnv("GLEAN_AUTH_DATA_DIR", tmpDir); const { loadServerUrl, saveServerUrl, clearServerUrl } = await import( "../src/url-config-store.js" From 9722b38f52cab3142364cabad8f22e5e939905ad Mon Sep 17 00:00:00 2001 From: Pragati Agrawal Date: Mon, 3 Aug 2026 01:46:37 +0530 Subject: [PATCH 09/10] [Plugin] Preserve experimental QE URL prefixes --- plugins/glean/dist/index.js | 13 +++++++++---- src/index.ts | 6 +----- src/server-url.ts | 22 +++++++++++++++++++++ tests/server-url.test.ts | 38 +++++++++++++++++++++++++++++++++++++ 4 files changed, 70 insertions(+), 9 deletions(-) create mode 100644 src/server-url.ts create mode 100644 tests/server-url.test.ts diff --git a/plugins/glean/dist/index.js b/plugins/glean/dist/index.js index 777eb4d..187d1ac 100644 --- a/plugins/glean/dist/index.js +++ b/plugins/glean/dist/index.js @@ -26770,6 +26770,15 @@ function sameOrigin(a, b) { } } +// src/server-url.ts +var MCP_GATEWAY_PATH = "/mcp/gateway/proxy"; +function normalizeServerUrl(raw) { + const parsed = new URL(raw); + const pathname = parsed.pathname.replace(/\/+$/, ""); + const prefix = pathname.endsWith(MCP_GATEWAY_PATH) ? pathname.slice(0, -MCP_GATEWAY_PATH.length) : pathname === "/" ? "" : pathname; + return `${parsed.origin}${prefix}${MCP_GATEWAY_PATH}${parsed.search}`; +} + // src/index.ts function readEnv(...keys) { for (const key of keys) { @@ -26785,10 +26794,6 @@ function resolveServerUrl() { if (fromEnv) return fromEnv; return loadServerUrl(); } -function normalizeServerUrl(raw) { - const parsed = new URL(raw); - return `${parsed.origin}/mcp/gateway/proxy`; -} var SETUP_REQUIRED_TEXT = `[SETUP_REQUIRED] To connect, enter your work email (e.g. you@acme.com) and we'll find your Glean instance automatically. diff --git a/src/index.ts b/src/index.ts index df57b1c..9cba192 100644 --- a/src/index.ts +++ b/src/index.ts @@ -54,6 +54,7 @@ import { import { resolveSessionId } from "./session-id.js"; import { resolveServerUrlFromEmail } from "./config-search.js"; import { resolveDataDir } from "./data-dir.js"; +import { normalizeServerUrl } from "./server-url.js"; function readEnv(...keys: string[]): string | undefined { for (const key of keys) { @@ -71,11 +72,6 @@ function resolveServerUrl(): string | undefined { return loadServerUrl(); } -function normalizeServerUrl(raw: string): string { - const parsed = new URL(raw); - return `${parsed.origin}/mcp/gateway/proxy`; -} - const SETUP_REQUIRED_TEXT = `[SETUP_REQUIRED]\n\n` + `To connect, enter your work email (e.g. you@acme.com) and we'll find ` + diff --git a/src/server-url.ts b/src/server-url.ts new file mode 100644 index 0000000..86c72ee --- /dev/null +++ b/src/server-url.ts @@ -0,0 +1,22 @@ +const MCP_GATEWAY_PATH = "/mcp/gateway/proxy"; + +/** + * Normalize either a normal QE origin or a path-prefixed experimental QE URL + * to the MCP gateway endpoint. + * + * Examples: + * https://acme-be.glean.com + * -> https://acme-be.glean.com/mcp/gateway/proxy + * https://scio-prod-be.glean.com/qe-glean-exp-101 + * -> https://scio-prod-be.glean.com/qe-glean-exp-101/mcp/gateway/proxy + */ +export function normalizeServerUrl(raw: string): string { + const parsed = new URL(raw); + const pathname = parsed.pathname.replace(/\/+$/, ""); + const prefix = pathname.endsWith(MCP_GATEWAY_PATH) + ? pathname.slice(0, -MCP_GATEWAY_PATH.length) + : pathname === "/" + ? "" + : pathname; + return `${parsed.origin}${prefix}${MCP_GATEWAY_PATH}${parsed.search}`; +} diff --git a/tests/server-url.test.ts b/tests/server-url.test.ts new file mode 100644 index 0000000..2219c20 --- /dev/null +++ b/tests/server-url.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from "vitest"; +import { normalizeServerUrl } from "../src/server-url.js"; + +describe("normalizeServerUrl", () => { + it("adds the MCP gateway path to a normal QE origin", () => { + expect(normalizeServerUrl("https://acme-be.glean.com")).toBe( + "https://acme-be.glean.com/mcp/gateway/proxy", + ); + }); + + it("preserves an experimental QE path prefix", () => { + expect( + normalizeServerUrl("https://scio-prod-be.glean.com/qe-glean-exp-101"), + ).toBe( + "https://scio-prod-be.glean.com/qe-glean-exp-101/mcp/gateway/proxy", + ); + }); + + it("does not duplicate the gateway path", () => { + expect( + normalizeServerUrl( + "https://scio-prod-be.glean.com/qe-glean-exp-101/mcp/gateway/proxy/", + ), + ).toBe( + "https://scio-prod-be.glean.com/qe-glean-exp-101/mcp/gateway/proxy", + ); + }); + + it("preserves query parameters such as sc overrides", () => { + expect( + normalizeServerUrl( + "https://scio-prod-be.glean.com/qe-glean-exp-101?sc=db.debug_mode%3D1", + ), + ).toBe( + "https://scio-prod-be.glean.com/qe-glean-exp-101/mcp/gateway/proxy?sc=db.debug_mode%3D1", + ); + }); +}); From 815f4d84a034f6ec6402f607bb2313e60714c8df Mon Sep 17 00:00:00 2001 From: Pragati Agrawal Date: Thu, 13 Aug 2026 11:26:15 +0530 Subject: [PATCH 10/10] [Plugin] Make setup reset register a new DCR client --- README.md | 6 ++--- plugins/glean/dist/index.js | 38 ++++++---------------------- src/auth-provider.ts | 5 ++-- src/index.ts | 49 ++++++++----------------------------- tests/auth-provider.test.ts | 18 ++++++++++++++ 5 files changed, 40 insertions(+), 76 deletions(-) diff --git a/README.md b/README.md index 726d969..3313c79 100644 --- a/README.md +++ b/README.md @@ -137,10 +137,8 @@ every launch and setting them yourself has no effect: - **Sign-in loop or stale auth** — prompt the agent to reset and sign in again (e.g. "reset the Glean setup"). It calls the `setup` tool with `reset=true` to - clear the saved configuration and grant, while retaining the registered OAuth - client when it belongs to the same server. Use `fresh_client=true` with - `reset=true` only when the server explicitly rejects the client or a genuinely - new registration is required. + clear the saved configuration, grant, and registered OAuth client. The next + setup registers a new client and signs in again. - **Tools return `[SETUP_REQUIRED]`** — the plugin isn't configured or authenticated yet. Prompt the agent to set up Glean (e.g. "set up Glean"). The `setup` tool, called with no arguments, advances through the next missing diff --git a/plugins/glean/dist/index.js b/plugins/glean/dist/index.js index aacec8e..5c048ea 100644 --- a/plugins/glean/dist/index.js +++ b/plugins/glean/dist/index.js @@ -25880,9 +25880,8 @@ var GleanOAuthClientProvider = class { } /** * Force a new user sign-in while retaining a client registered for the same - * server. This is used for account switching and normal reset. A fresh DCR - * is only required when the server changes or the caller explicitly asks - * for a fresh client. + * server. This is used for account switching; full setup reset clears the + * provider and registered client in the setup tool. */ resetAuthentication(accountEmail, serverUrl) { const hadTokens = this._tokens !== void 0; @@ -26895,7 +26894,7 @@ var RUN_TOOL_TOOL = { var SETUP_TOOL = { name: "setup", annotations: { readOnlyHint: true }, - description: "Check or configure the Glean connection. Setup completes in three stages: (1) resolve and save the Server URL, (2) authenticate, (3) fetch the remote tool catalog. Call with no arguments to advance through the next missing stage. Call with email to look up and (re)configure user's Glean instance. Call with reset=true to clear the current authentication and setup URL while retaining the DCR client when it can safely be reused. Pass fresh_client=true only when a new OAuth client registration is explicitly required.", + description: "Check or configure the Glean connection. Setup completes in three stages: (1) resolve and save the Server URL, (2) authenticate, (3) fetch the remote tool catalog. Call with no arguments to advance through the next missing stage. Call with email to look up and (re)configure user's Glean instance. Call with reset=true to clear the current authentication, setup URL, and registered DCR client before starting a new setup flow.", inputSchema: { type: "object", properties: { @@ -26909,11 +26908,7 @@ var SETUP_TOOL = { }, reset: { type: "boolean", - description: "Clear the cached URL, authentication, and remote tool cache. The registered OAuth client is retained when possible." - }, - fresh_client: { - type: "boolean", - description: "With reset=true, also discard the registered OAuth client and force a new dynamic client registration." + description: "Clear the cached URL, authentication, registered OAuth client, and remote tool cache. The next setup registers a new client." } }, required: [] @@ -27278,31 +27273,14 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => { clientInfo: server.getClientVersion() ?? null }); if (args.reset === true) { - const freshClient = args.fresh_client === true; - const stored = loadCredentials(); - const previousServerUrl = loadServerUrl(); + const hadClient = !!loadCredentials()?.clientInfo; clearServerUrl(); - if (freshClient) { - clearCredentials(); - } else if (stored) { - saveCredentials( - void 0, - stored.clientInfo, - { - accountEmail: null, - clientServerUrl: stored.clientServerUrl ?? previousServerUrl ?? null, - abandonedSignIns: 0, - tokenUpdatedAt: Date.now() - }, - { forceTokenUpdate: true } - ); - } + clearCredentials(); clearRemoteTools(); oauthProvider = void 0; cachedRemoteTools = []; logLine("setup.reset", { - freshClient, - retainedClient: !freshClient && !!stored?.clientInfo + clearedClient: hadClient }); server.sendToolListChanged().catch(() => { }); @@ -27310,7 +27288,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => { content: [ { type: "text", - text: "Glean authentication has been reset. Call setup again with your email to sign in. The registered OAuth client will be reused when it belongs to the same server; pass fresh_client=true with reset=true to register a new client." + text: "Glean authentication has been reset, including the registered OAuth client. Call setup again with your email to register a new client and sign in." } ] }; diff --git a/src/auth-provider.ts b/src/auth-provider.ts index 0f1425d..4c4d198 100644 --- a/src/auth-provider.ts +++ b/src/auth-provider.ts @@ -302,9 +302,8 @@ export class GleanOAuthClientProvider implements OAuthClientProvider { /** * Force a new user sign-in while retaining a client registered for the same - * server. This is used for account switching and normal reset. A fresh DCR - * is only required when the server changes or the caller explicitly asks - * for a fresh client. + * server. This is used for account switching; full setup reset clears the + * provider and registered client in the setup tool. */ resetAuthentication(accountEmail: string | undefined, serverUrl: string): void { const hadTokens = this._tokens !== undefined; diff --git a/src/index.ts b/src/index.ts index 7e8d98a..6e3a0eb 100644 --- a/src/index.ts +++ b/src/index.ts @@ -268,9 +268,8 @@ const SETUP_TOOL: Tool = { "(3) fetch the remote tool catalog. Call with no arguments to advance " + "through the next missing stage. Call with email to look up and " + "(re)configure user's Glean instance. Call with reset=true to clear " + - "the current authentication and setup URL while retaining the DCR client " + - "when it can safely be reused. Pass fresh_client=true only when a new " + - "OAuth client registration is explicitly required.", + "the current authentication, setup URL, and registered DCR client before " + + "starting a new setup flow.", inputSchema: { type: "object" as const, properties: { @@ -291,14 +290,8 @@ const SETUP_TOOL: Tool = { reset: { type: "boolean", description: - "Clear the cached URL, authentication, and remote tool cache. " + - "The registered OAuth client is retained when possible.", - }, - fresh_client: { - type: "boolean", - description: - "With reset=true, also discard the registered OAuth client and " + - "force a new dynamic client registration.", + "Clear the cached URL, authentication, registered OAuth client, " + + "and remote tool cache. The next setup registers a new client.", }, }, required: [], @@ -749,35 +742,14 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => { clientInfo: server.getClientVersion() ?? null, }); if (args.reset === true) { - const freshClient = args.fresh_client === true; - const stored = loadCredentials(); - const previousServerUrl = loadServerUrl(); + const hadClient = !!loadCredentials()?.clientInfo; clearServerUrl(); - if (freshClient) { - clearCredentials(); - } else if (stored) { - // Reset authentication and setup state, but retain the DCR client - // plus the server it belongs to. The next setup can reuse that - // registration when it targets the same server. - saveCredentials( - undefined, - stored.clientInfo, - { - accountEmail: null, - clientServerUrl: - stored.clientServerUrl ?? previousServerUrl ?? null, - abandonedSignIns: 0, - tokenUpdatedAt: Date.now(), - }, - { forceTokenUpdate: true }, - ); - } + clearCredentials(); clearRemoteTools(); oauthProvider = undefined; cachedRemoteTools = []; logLine("setup.reset", { - freshClient, - retainedClient: !freshClient && !!stored?.clientInfo, + clearedClient: hadClient, }); // Fire-and-forget — tools list is shorter without the dynamic // surface; the host should re-fetch on its next idle cycle. @@ -789,10 +761,9 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => { { type: "text", text: - "Glean authentication has been reset. Call setup again with " + - "your email to sign in. The registered OAuth client will be " + - "reused when it belongs to the same server; pass " + - "fresh_client=true with reset=true to register a new client.", + "Glean authentication has been reset, including the registered " + + "OAuth client. Call setup again with your email to register a " + + "new client and sign in.", }, ], }; diff --git a/tests/auth-provider.test.ts b/tests/auth-provider.test.ts index 7308004..a3863bd 100644 --- a/tests/auth-provider.test.ts +++ b/tests/auth-provider.test.ts @@ -275,6 +275,24 @@ describe("GleanOAuthClientProvider", () => { expect(provider.abandonPendingSignIn()).toBe(true); }); + it("resetAuthentication keeps the client for account switching", () => { + const provider = new GleanOAuthClientProvider(); + provider.saveTokens({ access_token: "tok", refresh_token: "refresh" } as any); + provider.saveClientInformation({ client_id: "cid" } as any); + + provider.resetAuthentication( + "new-account@example.com", + "https://example.com/mcp/gateway/proxy", + ); + + expect(provider.tokens()).toBeUndefined(); + expect(provider.clientInformation()).toEqual({ client_id: "cid" }); + expect(provider.accountEmail()).toBe("new-account@example.com"); + const raw = JSON.parse(fs.readFileSync(credFile, "utf-8")); + expect(raw.tokens).toBeUndefined(); + expect(raw.clientInfo.client_id).toBe("cid"); + }); + it("saveClientInformation persists to disk", () => { const provider = new GleanOAuthClientProvider(); const info = { client_id: "cid", client_secret: "sec" } as any;