Skip to content

Open source alternative to Semrush and Ahrefs

Keep active MCP OAuth sessions signed in (EVE-455) (#1013)

Carter Smith8b2706aa8902
diff --git a/package.json b/package.json
index fbed1042..0f944ac7 100644
--- a/package.json
+++ b/package.json
@@ -80,7 +80,7 @@
"@base-ui/react": "^1.8.0",
"@better-auth/api-key": "1.6.22",
"@cloudflare/think": "0.17.0",
- "@cloudflare/workers-oauth-provider": "^0.10.2",
+ "@cloudflare/workers-oauth-provider": "^1.2.3",
"@every-app/sdk": "^0.1.14",
"@modelcontextprotocol/client": "2.0.0",
"@modelcontextprotocol/sdk": "1.30.0",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 6ea684f0..1c57594b 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -54,8 +54,8 @@ importers:
specifier: 0.17.0
'@cloudflare/workers-oauth-provider':
- specifier: ^0.10.2
- version: 0.10.2
+ specifier: ^1.2.3
+ version: 1.2.3
'@every-app/sdk':
specifier: ^0.1.14
@@ -911,8 +911,8 @@ packages:
cpu: [x64]
os: [win32]
- '@cloudflare/[email protected]':
- resolution: {integrity: sha512-3yWtnPaZyNaiLuv9tWkWfEyqbILFsvfG0Q5RwZGJ2jkSkrOMM8IxKYaGCFakSGbMXmatvyrhFDCDZ70S6TVnqQ==}
+ '@cloudflare/[email protected]':
+ resolution: {integrity: sha512-40eGeA3DnTOEl2ijHYY5Z9yNIf0fdjgomoaA6GHPo4FyKQw0oXPuy4GVjTE/uNfS/MoFAvzsuVBRwTPKUki4hA==}
'@cloudflare/[email protected]':
resolution: {integrity: sha512-mOhf5TUEB1m2vPrxtqoIGfz0fUC9xyxRDx5gWHy5s+OCo6dcV+g7wI1R7gYCMFohhqF/2y2xeKVwMwCJjfn/WA==}
@@ -7436,7 +7436,7 @@ snapshots:
'@cloudflare/[email protected]':
optional: true
- '@cloudflare/[email protected]': {}
+ '@cloudflare/[email protected]': {}
'@cloudflare/[email protected]': {}
diff --git a/src/server.ts b/src/server.ts
index c85fc8bc..82496876 100644
--- a/src/server.ts
+++ b/src/server.ts
@@ -210,12 +210,6 @@ export default {
env as OpenSeoOAuthEnv,
);
console.log("[mcp-oauth] purged expired OAuth data", result);
- if (!result.done) {
- // The sweep only advances past live records via deletions; a
- // persistent incomplete scan means the keyspace outgrew the batch.
- console.warn("[mcp-oauth] purge did not cover the full keyspace");
- }
-
// Daily referral-sale sweep: catches paid Autumn invoices the
// billing.updated webhook path misses (renewals, one-time top-ups).
try {
diff --git a/src/server/mcp/oauth-provider.test.ts b/src/server/mcp/oauth-provider.test.ts
index 32ef2403..05aaaef2 100644
--- a/src/server/mcp/oauth-provider.test.ts
+++ b/src/server/mcp/oauth-provider.test.ts
@@ -5,6 +5,7 @@ import {
type OAuthProviderOptions,
type TokenExchangeCallbackOptions,
} from "@cloudflare/workers-oauth-provider";
+import type * as WorkersOAuthProvider from "@cloudflare/workers-oauth-provider";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { z } from "zod";
import { createOpenSeoOAuthProvider } from "./oauth-provider";
@@ -17,52 +18,17 @@ const mocks = vi.hoisted(() => ({
vi.mock("cloudflare:workers", () => ({
waitUntil: (promise: Promise<unknown>) => void promise,
+ // oxlint-disable-next-line typescript/no-extraneous-class -- runtime shim for the real provider's exported classes
+ WorkerEntrypoint: class {},
// api-key-auth pulls the db client into this module graph; it reads env at
// module load.
env: {},
}));
-// The whole module is doubled because the real one imports "cloudflare:workers"
-// at top level, which vitest's node environment cannot load even via
-// importOriginal. The error-class doubles must stay signature-compatible with
-// the real AuthorizationError/OAuthError.
-vi.mock("@cloudflare/workers-oauth-provider", () => {
- class AuthorizationError extends Error {
- readonly description: string;
- readonly redirectUri?: string;
- readonly state?: string;
- readonly issuer?: string;
-
- constructor(
- readonly code: string,
- options: {
- description: string;
- redirectUri?: string;
- state?: string;
- issuer?: string;
- },
- ) {
- super(options.description);
- this.description = options.description;
- this.redirectUri = options.redirectUri;
- this.state = options.state;
- this.issuer = options.issuer;
- }
- }
-
- class OAuthError extends Error {
- constructor(
- readonly code: string,
- options?: { description?: string },
- ) {
- super(options?.description);
- }
- }
-
+vi.mock("@cloudflare/workers-oauth-provider", async (importOriginal) => {
+ const actual = await importOriginal<typeof WorkersOAuthProvider>();
return {
- AuthorizationError,
- GrantType: { REFRESH_TOKEN: "refresh_token" },
- OAuthError,
+ ...actual,
OAuthProvider: class {
constructor(options: OAuthProviderOptions<unknown>) {
mocks.options.push(options);
@@ -124,12 +90,15 @@ async function dispatch(
function tokenExchangeOptions(
requestedScope: string[],
-): TokenExchangeCallbackOptions {
+): TokenExchangeCallbackOptions<unknown> {
return {
grantType: GrantType.REFRESH_TOKEN,
clientId: "client-1",
+ subjectClientId: "client-1",
userId: "user-1",
grantId: "grant-1",
+ resource: "https://app.openseo.so/mcp",
+ env: {},
scope: ["offline_access", "mcp"],
requestedScope,
props: {
diff --git a/src/server/mcp/oauth-provider.ts b/src/server/mcp/oauth-provider.ts
index e9bb7141..d20076a1 100644
--- a/src/server/mcp/oauth-provider.ts
+++ b/src/server/mcp/oauth-provider.ts
@@ -3,9 +3,9 @@ import {
AuthorizationError,
OAuthError,
OAuthProvider,
+ authorizationErrorRedirect,
type AuthRequest,
type OAuthHelpers,
- type OAuthProviderOptions,
} from "@cloudflare/workers-oauth-provider";
import { z } from "zod";
import { getHostedBaseUrl } from "@/lib/auth";
@@ -35,6 +35,7 @@ import { handleMcpApiKeyRequest } from "@/server/mcp/api-key-auth";
const OAUTH_TOKEN_PATH = "/api/auth/oauth2/token";
const OAUTH_REGISTER_PATH = "/api/auth/oauth2/register";
+const OAUTH_PURGE_CURSOR_KEY = "purge-cursor";
const OAUTH_CONSENT_RESPONSE_PATH = "/api/oauth/consent";
const OAUTH_AUTHORIZATION_PARAM_NAMES = [
@@ -51,10 +52,6 @@ const OAUTH_AUTHORIZATION_PARAM_NAMES = [
// preserve MCP sessions across normal usage.
const MCP_ACCESS_TOKEN_TTL_SECONDS = 60 * 60 * 24;
const MCP_REFRESH_TOKEN_TTL_SECONDS = 60 * 60 * 24 * 30;
-// DCR client records expire on a fixed clock from registration (the provider
-// defaults to 90 days), and an actively refreshing client breaks with
-// invalid_client the moment its record lapses. A year keeps that cliff rare;
-// rolling 30-day refresh tokens already reap inactive clients' sessions.
const MCP_CLIENT_REGISTRATION_TTL_SECONDS = 60 * 60 * 24 * 365;
export type OpenSeoOAuthEnv = Env & {
@@ -92,36 +89,12 @@ function redirectToSignIn(request: Request) {
return Response.redirect(signInUrl.toString(), 302);
}
-function oauthErrorRedirect(input: {
- redirectUri: string;
- code: string;
- description: string;
- state?: string;
- issuer?: string;
-}) {
- const redirectUrl = new URL(input.redirectUri);
- redirectUrl.searchParams.set("error", input.code);
- redirectUrl.searchParams.set("error_description", input.description);
- if (input.state) redirectUrl.searchParams.set("state", input.state);
- if (input.issuer) redirectUrl.searchParams.set("iss", input.issuer);
- return redirectUrl.toString();
-}
-
function authorizationErrorResponse(error: AuthorizationError) {
- if (!error.redirectUri) {
+ if (!error.redirectTo) {
return new Response(error.description, { status: 400 });
}
- return Response.redirect(
- oauthErrorRedirect({
- redirectUri: error.redirectUri,
- code: error.code,
- description: error.description,
- state: error.state,
- issuer: error.issuer,
- }),
- 302,
- );
+ return Response.redirect(error.redirectTo, 302);
}
function jsonResponse(body: unknown, init?: ResponseInit) {
@@ -241,16 +214,6 @@ function getGrantedMcpScopes(requestedScopes: string[]) {
return granted;
}
-function deniedRedirect(authRequest: AuthRequest) {
- return oauthErrorRedirect({
- redirectUri: authRequest.redirectUri,
- code: "access_denied",
- description: "The user denied access",
- state: authRequest.state,
- issuer: authRequest.issuer,
- });
-}
-
async function handleOAuthAuthorizeRequest(
request: Request,
env: OpenSeoOAuthEnv,
@@ -316,7 +279,13 @@ async function handleOAuthConsentResponse(
}
if (!body.data.accept) {
- return jsonResponse({ redirectTo: deniedRedirect(authRequest) });
+ return jsonResponse({
+ redirectTo: authorizationErrorRedirect(
+ authRequest,
+ "access_denied",
+ "The user denied access",
+ ),
+ });
}
const context = await resolveContextForConsent(request);
@@ -410,7 +379,7 @@ const mcpApiHandler: ExportedHandlerWithFetch<OpenSeoOAuthEnv> = {
};
function createProvider(appFetch: AppFetch, resource: string) {
- const options: OAuthProviderOptions<OpenSeoOAuthEnv> = {
+ return new OAuthProvider<OpenSeoOAuthEnv>({
apiRoute: MCP_ROUTE,
apiHandler: mcpApiHandler,
defaultHandler: createDefaultHandler(appFetch),
@@ -420,7 +389,9 @@ function createProvider(appFetch: AppFetch, resource: string) {
scopesSupported: [...MCP_OAUTH_SCOPES],
accessTokenTTL: MCP_ACCESS_TOKEN_TTL_SECONDS,
refreshTokenTTL: MCP_REFRESH_TOKEN_TTL_SECONDS,
+ refreshTokenIdleTTL: MCP_REFRESH_TOKEN_TTL_SECONDS,
clientRegistrationTTL: MCP_CLIENT_REGISTRATION_TTL_SECONDS,
+ allowPrivateUseRedirectUris: true,
resourceMetadata: {
resource,
scopes_supported: [MCP_SCOPE],
@@ -443,9 +414,7 @@ function createProvider(appFetch: AppFetch, resource: string) {
};
},
onError: logOAuthError,
- };
-
- return new OAuthProvider(options);
+ });
}
export function createOpenSeoOAuthProvider(appFetch: AppFetch) {
@@ -474,13 +443,20 @@ export function createOpenSeoOAuthProvider(appFetch: AppFetch) {
return getProvider().fetch(request, env, ctx);
},
- // Cron GC for OAUTH_KV: sweeps orphaned grants/tokens (e.g. from expired
- // client registrations) that KV TTLs alone don't reclaim. The sweep only
- // advances past live records by deleting dead ones, so give it a batch
- // large enough to cover the whole keyspace in one pass while staying
- // within the invocation's subrequest budget.
- purgeExpiredData(env: OpenSeoOAuthEnv) {
- return getProvider().purgeExpiredData(env, { batchSize: 200 });
+ // Resume the bounded sweep across cron runs, including past live records.
+ async purgeExpiredData(env: OpenSeoOAuthEnv) {
+ const cursor =
+ (await env.OAUTH_KV.get(OAUTH_PURGE_CURSOR_KEY)) ?? undefined;
+ const result = await getProvider().purgeExpiredData(env, {
+ batchSize: 200,
+ cursor,
+ });
+ if (result.cursor) {
+ await env.OAUTH_KV.put(OAUTH_PURGE_CURSOR_KEY, result.cursor);
+ } else {
+ await env.OAUTH_KV.delete(OAUTH_PURGE_CURSOR_KEY);
+ }
+ return result;
},
};
}
diff --git a/src/server/mcp/oauth-refresh.e2e.test.ts b/src/server/mcp/oauth-refresh.e2e.test.ts
index 6fbb9f77..e3c94b1f 100644
--- a/src/server/mcp/oauth-refresh.e2e.test.ts
+++ b/src/server/mcp/oauth-refresh.e2e.test.ts
@@ -1,5 +1,6 @@
import { createHash, randomBytes } from "node:crypto";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { sortBy } from "remeda";
import { z } from "zod";
import { createOpenSeoOAuthProvider } from "./oauth-provider";
@@ -103,21 +104,28 @@ function createKvFake() {
return Promise.resolve();
},
list(options?: { prefix?: string; cursor?: string; limit?: number }) {
- const keys = [...store.keys()]
- .filter((key) => live(key))
- .filter((key) => !options?.prefix || key.startsWith(options.prefix))
- .slice(0, options?.limit ?? 1000)
- .map((name) => {
- const entry = store.get(name);
- return {
- name,
- metadata: entry?.metadata,
- expiration: entry?.expiresAt
- ? Math.floor(entry.expiresAt / 1000)
- : undefined,
- };
- });
- return Promise.resolve({ keys, list_complete: true, cursor: "" });
+ const remaining = sortBy(
+ [...store.keys()]
+ .filter((key) => live(key))
+ .filter((key) => !options?.prefix || key.startsWith(options.prefix))
+ .filter((key) => !options?.cursor || key > options.cursor),
+ (key) => key,
+ );
+ const keys = remaining.slice(0, options?.limit ?? 1000).map((name) => {
+ const entry = store.get(name);
+ return {
+ name,
+ metadata: entry?.metadata,
+ expiration: entry?.expiresAt
+ ? Math.floor(entry.expiresAt / 1000)
+ : undefined,
+ };
+ });
+ return Promise.resolve({
+ keys,
+ list_complete: keys.length === remaining.length,
+ cursor: keys.at(-1)?.name ?? "",
+ });
},
};
}
@@ -135,12 +143,13 @@ let provider: Provider;
let env: Env;
beforeEach(() => {
- vi.useRealTimers();
provider = createOpenSeoOAuthProvider(() => new Response("app"));
// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the provider touches only OAUTH_KV
env = { OAUTH_KV: createKvFake() } as unknown as Env;
});
+afterEach(() => vi.useRealTimers());
+
const registrationSchema = z.looseObject({
client_id: z.string(),
token_endpoint_auth_method: z.string(),
@@ -300,8 +309,12 @@ describe("Codex-style OAuth token refresh (real workers-oauth-provider)", () =>
expect(auth.scopes).toContain("mcp");
});
- it("refreshes with client_id only and the new token still carries the mcp scope", async () => {
+ it("keeps an active session beyond its original expiry, then expires after inactivity", async () => {
const { client, tokens } = await setupSession();
+ const day = 24 * 60 * 60 * 1000;
+ const startedAt = Date.now();
+ vi.useFakeTimers({ toFake: ["Date"] });
+ vi.setSystemTime(startedAt + 29 * day);
const response = await refresh(client.client_id, tokens.refresh_token);
expect(response.status).toBe(200);
@@ -312,9 +325,61 @@ describe("Codex-style OAuth token refresh (real workers-oauth-provider)", () =>
expect(auth.scopes).toContain("mcp");
expect(auth.clientId).toBe(client.client_id);
- // And the rotated refresh token keeps working for the next cycle.
+ vi.setSystemTime(startedAt + 31 * day);
const second = await refresh(client.client_id, refreshed.refresh_token);
expect(second.status).toBe(200);
+ const rotated = tokenResponseSchema.parse(await second.json());
+ expect((await callMcp(rotated.access_token)).scopes).toContain("mcp");
+
+ vi.setSystemTime(startedAt + 62 * day);
+ const expired = await refresh(client.client_id, rotated.refresh_token);
+ expect(expired.status).toBe(400);
+ expect(tokenErrorSchema.parse(await expired.json()).error).toBe(
+ "invalid_grant",
+ );
+ });
+
+ it("resumes OAuth cleanup across grant and token pages, then resets the cursor", async () => {
+ const client = await registerCodexStyleClient();
+ for (let index = 0; index < 200; index++) {
+ const id = String(index).padStart(3, "0");
+ await env.OAUTH_KV.put(
+ `grant:user-1:${id}`,
+ JSON.stringify({ id, userId: "user-1", clientId: client.client_id }),
+ );
+ await env.OAUTH_KV.put(
+ `token:${id}`,
+ JSON.stringify({ userId: "user-1", grantId: id }),
+ );
+ }
+ const orphanedGrant = "grant:user-1:zzz";
+ const orphanedToken = "token:zzz";
+ await env.OAUTH_KV.put(
+ orphanedGrant,
+ JSON.stringify({
+ id: "zzz",
+ userId: "user-1",
+ clientId: "missing-client",
+ }),
+ );
+ await env.OAUTH_KV.put(
+ orphanedToken,
+ JSON.stringify({ userId: "missing-user", grantId: "missing-grant" }),
+ );
+
+ expect((await provider.purgeExpiredData(env)).done).toBe(false);
+ expect(await env.OAUTH_KV.get("purge-cursor")).not.toBeNull();
+ expect(await env.OAUTH_KV.get(orphanedGrant)).not.toBeNull();
+
+ const nextRun = createOpenSeoOAuthProvider(() => new Response("app"));
+ expect((await nextRun.purgeExpiredData(env)).done).toBe(false);
+ expect(await env.OAUTH_KV.get(orphanedGrant)).toBeNull();
+ expect(await env.OAUTH_KV.get(orphanedToken)).not.toBeNull();
+
+ expect((await nextRun.purgeExpiredData(env)).done).toBe(true);
+ expect(await env.OAUTH_KV.get(orphanedToken)).toBeNull();
+ expect(await env.OAUTH_KV.get("purge-cursor")).toBeNull();
+ expect(await env.OAUTH_KV.get("grant:user-1:000")).not.toBeNull();
});
it("accepts a refresh carrying the canonical RFC 8707 resource and rejects a mismatched one", async () => {