Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(mcp): keep the spent refresh token in the store, and clear it when the server keeps it
Cybor06eb477c1d6f
diff --git a/server/mcp-oauth-refresh-races.test.ts b/server/mcp-oauth-refresh-races.test.tsindex af20eff5bf..c521f767b3 100644--- a/server/mcp-oauth-refresh-races.test.ts+++ b/server/mcp-oauth-refresh-races.test.ts@@ -146,6 +146,44 @@ it("never presents a refresh token it already sent, so a rotating server does noexpect(manager.authState("docs", resource)).toBe("needs-sign-in");});+it("does not present a spent refresh token again after a restart", async () => {+ // The mark of a spent token lives in the store, not in memory: a manager that starts again reads it from the file+ // and must not present that token, or a rotating server revokes the grant.+ const first = manager.accessToken("docs", resource);+ const request = await nextRequest();+ expect(request.form.get("refresh_token")).toBe("old-refresh");+ request.response.destroy();+ await first.catch(() => undefined);++ const restarted = new McpOAuthManager({ file: join(directory, "oauth.json") });+ try {+ const second = restarted.accessToken("docs", resource);+ await second.catch(() => undefined);+ expect(requests).toHaveLength(0);+ expect(restarted.authState("docs", resource)).toBe("needs-sign-in");+ } finally {+ restarted.dispose();+ }+});++it("presents the refresh token again when the server kept it", async () => {+ // A server that does not rotate refresh tokens answers without a new one, and the old token stays valid+ // (RFC 6749 section 6). The next renewal has to present it again, so the mark of a spent token is cleared when+ // the server answers and keeps that same token.+ const first = manager.accessToken("docs", resource);+ const request = await nextRequest();+ expect(request.form.get("refresh_token")).toBe("old-refresh");+ reply(request, 200, { access_token: "first-access" });+ expect(await first).toBe("first-access");++ // The server refused the access token, so the grant is renewed: the refresh token is presented again.+ const refused = manager.tokenRefused("docs", resource);+ const again = await nextRequest();+ expect(again.form.get("refresh_token")).toBe("old-refresh");+ reply(again, 200, { access_token: "second-access" });+ expect(await refused).toBe("refreshed");+});+it("signs out immediately and keeps a later sign-in when revocation completes", async () => {const signingOut = manager.signOut("docs", resource);const revocation = await nextRequest();diff --git a/server/mcp-oauth-store.ts b/server/mcp-oauth-store.tsindex 0d58219cb7..4e7d2a7c2b 100644--- a/server/mcp-oauth-store.ts+++ b/server/mcp-oauth-store.ts@@ -27,6 +27,9 @@ const recordSchema = z.object({const fileSchema = z.object({servers: z.record(z.string(), recordSchema).default({}),+ /** Refresh tokens already sent to a token endpoint, per server. Presenting one of them again can be a replay, so the+ * mark is kept here and not in memory: a restart must not present it either. */+ spentRefresh: z.record(z.string(), z.string().min(1)).default({}),});export type McpOAuthTokens = z.infer<typeof tokensSchema>;@@ -59,8 +62,38 @@ export class McpOAuthStore {delete(name: string): void {const data = this.read();- if (!Object.hasOwn(data.servers, name)) return;+ if (!Object.hasOwn(data.servers, name) && !Object.hasOwn(data.spentRefresh ?? {}, name)) return;delete data.servers[name];+ delete data.spentRefresh?.[name];+ this.write(data);+ }++ /** Forget the refresh token marked as spent for this server: a new sign-in brings a new token. */+ forgetSpentRefresh(name: string): void {+ const data = this.read();+ if (!Object.hasOwn(data.spentRefresh ?? {}, name)) return;+ delete data.spentRefresh?.[name];+ this.write(data);+ }++ /** The refresh token already sent for this server, when presenting it again could be a replay. */+ spentRefreshFor(name: string): string | undefined {+ return this.read().spentRefresh?.[name];+ }++ /** Remember a refresh token that has been sent, before its answer arrives: a lost answer may mean the server+ * rotated it, and a restart must not present it again. */+ markSpentRefresh(name: string, token: string): void {+ const data = this.read();+ data.spentRefresh = { ...data.spentRefresh, [name]: token };+ this.write(data);+ }++ /** Forget a sent refresh token once the server has answered and kept it: it is still valid. */+ clearSpentRefresh(name: string, token: string): void {+ const data = this.read();+ if (data.spentRefresh?.[name] !== token) return;+ delete data.spentRefresh?.[name];this.write(data);}diff --git a/server/mcp-oauth.ts b/server/mcp-oauth.tsindex 01a55b76a2..fefed221d0 100644--- a/server/mcp-oauth.ts+++ b/server/mcp-oauth.ts@@ -221,10 +221,6 @@ export class McpOAuthManager {private readonly starting = new Map<string, StartingFlow>();private readonly refreshing = new Map<string, Promise<{ token: string | null; outcome: McpRefreshOutcome | null }>>();private readonly renewedAfterRefusal = new Map<string, number>();- /** Refresh tokens already sent to a token endpoint, per server name. A server that rotates refresh tokens revokes- * the whole grant when it sees one of them again, so a token is never presented twice, not even after a lost- * answer: the sign-in ends instead of being refreshed a second time with the same token. */- private readonly spentRefreshTokens = new Map<string, Set<string>>();private readonly clients: (name: string, url: string) => McpOAuthClientConfig | undefined;private readonly onSettled: (name: string, phase: McpSignInPhase, owner: string) => void;private readonly onRefresh: (name: string, outcome: McpRefreshOutcome) => void;@@ -273,6 +269,8 @@ export class McpOAuthManager {if (current && this.authState(name, url) === "signed-in" && !replaces?.(current)) return "kept";this.cancel(name);this.store.put(name, { ...record, url, state: record.tokens ? "signed-in" : "needs-sign-in" });+ // The sign-in that was replaced brought its own token: the mark of the old one no longer means anything.+ this.store.forgetSpentRefresh(name);return "adopted";}@@ -463,12 +461,15 @@ export class McpOAuthManager {// A refresh token the server may already have rotated must never be presented again: such a server revokes the// whole grant when it sees one of them a second time. A token this server already sent is therefore spent, whatever// the answer was, and the sign-in ends rather than being refreshed a second time with it.- const spent = this.spentRefreshTokens.get(name);- if (spent?.has(tokens.refresh)) {+ // The mark lives in the store, not in memory: a restart must not present the token either.+ if (this.store.spentRefreshFor(name) === tokens.refresh) {this.markNeedsSignIn(name, record.url);return { token: null, outcome: "expired" };}- this.spentRefreshTokens.set(name, new Set([...(spent ?? []), tokens.refresh]));+ // Remember it before the request leaves: if the answer is lost the server may have rotated it, and the next+ // attempt must not send it again.+ const sent = tokens.refresh;+ this.store.markSpentRefresh(name, sent);let answer: Awaited<ReturnType<typeof postForm>>;try {answer = await postForm(record.tokenEndpoint, {@@ -477,6 +478,7 @@ export class McpOAuthManager {resource: record.url,}, client);} catch {+ // The answer was lost: the token stays spent, because the server may have rotated it.if (!isDeepStrictEqual(this.store.get(name, record.url), record)) return { token: null, outcome: null };return { token: stillValid ? tokens.access : null, outcome: "unreachable" };}@@ -485,10 +487,14 @@ export class McpOAuthManager {if (!next) {const dead = (answer.status === 400 || answer.status === 401)&& (answer.body.error === "invalid_grant" || answer.body.error === "invalid_client");+ // The answer came, but it was no token: the server may have rotated the token anyway, so it stays spent.if (!dead) return { token: stillValid ? tokens.access : null, outcome: "unreachable" };this.markNeedsSignIn(name, record.url);return { token: null, outcome: "rejected" };}+ // The server answered and kept the same refresh token: it is still valid (RFC 6749 section 6), so it may be+ // presented again later. A rotated token leaves its mark: the one that was sent is dead for good.+ if (next.refresh === sent) this.store.clearSpentRefresh(name, sent);this.store.put(name, { ...record, state: "signed-in", tokens: next });return { token: next.access, outcome: "refreshed" };}