From c8ba7cb1a410708a6ad6dced109b4450d4e85920 Mon Sep 17 00:00:00 2001 From: Sarthak Agrawal Date: Sun, 15 Nov 2026 13:44:50 +0530 Subject: [PATCH 1/3] test: reproduce missing MCP offline renewal scopes --- src/__tests__/resume-access.test.ts | 21 +++++++ src/__tests__/resume-oauth.test.ts | 89 +++++++++++++++++++++++++++-- 2 files changed, 106 insertions(+), 4 deletions(-) diff --git a/src/__tests__/resume-access.test.ts b/src/__tests__/resume-access.test.ts index 5784149..38139dd 100644 --- a/src/__tests__/resume-access.test.ts +++ b/src/__tests__/resume-access.test.ts @@ -245,6 +245,27 @@ it('requires an ordinary signed-in session to issue capabilities', async () => { expect(await createResumeApiAccess()).toMatchObject({ ok: false }); }); +it('requests renewal only for MCP authentication and keeps missing resume scope distinct', async () => { + state.requestHeaders = new Headers(); + const action = vi.fn(async () => new Response()); + for (const path of ['/api/resume', '/api/mcp']) { + const unauthenticated = await withResumeAccess(request(undefined, path), action, true); + expect(unauthenticated.status).toBe(401); + expect(unauthenticated.headers.get('www-authenticate')).toContain( + `scope="${path === '/api/mcp' ? 'resume offline_access' : 'resume'}"` + ); + const oauth = await import('@/lib/resume-oauth'); + vi.spyOn(oauth, 'verifyResumeOAuth').mockRejectedValueOnce( + Object.assign(new Error('Missing scope'), { name: 'ResumeOAuthScopeError' }) + ); + const forbidden = await withResumeAccess(request('synthetic-oauth-token', path), action); + expect(forbidden.status).toBe(403); + expect(forbidden.headers.get('www-authenticate')).toContain('scope="resume"'); + expect(forbidden.headers.get('www-authenticate')).toContain('error="insufficient_scope"'); + } + expect(action).not.toHaveBeenCalled(); +}); + it('omits fallback_reason on an AI-generated API response', async () => { state.generate.mockResolvedValue({ object: { diff --git a/src/__tests__/resume-oauth.test.ts b/src/__tests__/resume-oauth.test.ts index 027d1d5..7fd9bbb 100644 --- a/src/__tests__/resume-oauth.test.ts +++ b/src/__tests__/resume-oauth.test.ts @@ -7,6 +7,7 @@ import { getAuth } from '@/lib/auth'; import { db } from '@/lib/db'; import { getResumeApiUserId, withResumeAccess } from '@/lib/resume-access'; import { getResumeOAuthRequest, consentResumeOAuth } from '@/lib/actions/resume-oauth-actions'; +import { GET as discovery } from '@/app/.well-known/[...metadata]/route'; const state = vi.hoisted(() => ({ headers: new Headers() })); const origin = 'http://localhost:4366'; const secret = 'oauth-local-synthetic-test-secret-20261008'; @@ -115,7 +116,7 @@ beforeAll(() => { }); afterAll(() => sql.close()); it('advertises resource-bound OAuth endpoints through real provider discovery', async () => { - const response = await getAuth().handler( + const response = await discovery( new Request(`${origin}/.well-known/oauth-authorization-server/api/auth`) ); expect(response.status).toBe(200); @@ -124,11 +125,91 @@ it('advertises resource-bound OAuth endpoints through real provider discovery', expect(metadata.registration_endpoint).toBe(`${origin}/api/auth/oauth2/register`); expect(metadata.code_challenge_methods_supported).toEqual(['S256']); expect(metadata.grant_types_supported).not.toContain('client_credentials'); - const protectedResponse = await getAuth().handler( - new Request(`${origin}/.well-known/oauth-protected-resource/api/mcp`) + for (const suffix of ['', '/api/mcp']) { + const request = new Request(`${origin}/.well-known/oauth-protected-resource${suffix}`); + const provider = await getAuth().handler(request.clone()); + const protectedResponse = await discovery(request); + expect(protectedResponse.status).toBe(provider.status); + expect([...protectedResponse.headers]).toEqual([...provider.headers]); + expect(await protectedResponse.json()).toEqual({ + ...(await provider.json()), + scopes_supported: ['resume', 'offline_access'], + }); + } + const resume = await discovery( + new Request(`${origin}/.well-known/oauth-protected-resource/api/resume`) ); - expect(await protectedResponse.json()).toMatchObject({ resource, scopes_supported: ['resume'] }); + expect(await resume.json()).toMatchObject({ scopes_supported: ['resume'] }); }); +it.each(['discovery', 'challenge'])( + 'renews an expired owner grant using scopes from app %s', + async (source) => { + let scope: string; + if (source === 'discovery') { + const response = await discovery( + new Request(`${origin}/.well-known/oauth-protected-resource/api/mcp`) + ); + scope = (await response.json()).scopes_supported.join(' '); + } else { + const response = await withResumeAccess( + new Request(resource), + async () => new Response(), + true + ); + expect(response.status).toBe(401); + scope = response.headers.get('www-authenticate')!.match(/scope="([^"]+)"/)![1]; + } + const registration = await send('/oauth2/register', { + client_name: `Synthetic ${source} Assistant`, + redirect_uris: [redirect], + token_endpoint_auth_method: 'none', + grant_types: ['authorization_code', 'refresh_token'], + response_types: ['code'], + scope, + }); + expect(registration.status).toBe(201); + const client = await registration.json(); + const signedQuery = await consentQuery(client.client_id, true, { scope }); + expect(await getResumeOAuthRequest(signedQuery)).toMatchObject({ + ok: true, + scopes: ['resume', 'offline_access'], + signed_in: true, + }); + const accepted = await consentResumeOAuth(signedQuery, true); + expect(accepted.ok).toBe(true); + if (!accepted.ok) throw new Error(accepted.error); + const issued = await token({ + grant_type: 'authorization_code', + client_id: client.client_id, + redirect_uri: redirect, + code_verifier: verifier, + resource, + code: new URL(accepted.redirect_uri).searchParams.get('code')!, + }); + expect(issued.status).toBe(200); + const tokens = await issued.json(); + expect(tokens.refresh_token).toBeTruthy(); + expect(tokens.expires_in).toBe(300); + expect(await (await invoke(tokens.access_token)).json()).toEqual({ user: 'oauth-owner' }); + vi.useFakeTimers({ toFake: ['Date'] }); + try { + vi.setSystemTime(Date.now() + 301_000); + expect((await invoke(tokens.access_token)).status).toBe(401); + const renewed = await token({ + grant_type: 'refresh_token', + client_id: client.client_id, + refresh_token: tokens.refresh_token, + resource, + }); + expect(renewed.status).toBe(200); + expect(await (await invoke((await renewed.json()).access_token)).json()).toEqual({ + user: 'oauth-owner', + }); + } finally { + vi.useRealTimers(); + } + } +); it('qualifies registration, consent, PKCE, replay resistance, owner identity, refresh and immediate session revocation', async () => { const registration = await send('/oauth2/register', { client_name: 'Synthetic Assistant', From ca1db5c17940944ceaa32813d4d71df1b7d19aaf Mon Sep 17 00:00:00 2001 From: Sarthak Agrawal Date: Sun, 15 Nov 2026 13:48:00 +0530 Subject: [PATCH 2/3] fix: advertise offline renewal scopes to MCP clients --- docs/operations/runbooks/resume-oauth.md | 8 +++++ src/__tests__/resume-oauth.test.ts | 36 +++++++++++++++++++++- src/app/.well-known/[...metadata]/route.ts | 22 ++++++++++++- src/lib/resume-access.ts | 2 +- 4 files changed, 65 insertions(+), 3 deletions(-) diff --git a/docs/operations/runbooks/resume-oauth.md b/docs/operations/runbooks/resume-oauth.md index d1a5404..42e6ca7 100644 --- a/docs/operations/runbooks/resume-oauth.md +++ b/docs/operations/runbooks/resume-oauth.md @@ -26,6 +26,14 @@ exact callbacks and use PKCE S256 with authorization-code and refresh grants. The implementation retains the deployed MCP protocol versions and does not claim CIMD or the newer MCP transport profile. +MCP discovery and its 401 challenge advertise `resume offline_access` so deployed +ChatGPT clients using MCP 2025-06-18 or earlier request renewal during explicit +consent. This is a compatibility exception to the newer guidance that +authorization-server-only scopes should not appear in protected-resource +metadata. `/api/resume` discovery and challenges, and 403 scope challenges, +continue to request only `resume`. Existing grants without renewal need a new +connection and consent; no refresh grant is issued silently. + Access JWTs expire in five minutes. Refresh lasts at most seven days while the linked browser session stays active. Verification checks signature, type, issuer, audience, expiry, scope, DPoP and current session/client/consent records. diff --git a/src/__tests__/resume-oauth.test.ts b/src/__tests__/resume-oauth.test.ts index 7fd9bbb..7eb1ab0 100644 --- a/src/__tests__/resume-oauth.test.ts +++ b/src/__tests__/resume-oauth.test.ts @@ -141,6 +141,38 @@ it('advertises resource-bound OAuth endpoints through real provider discovery', ); expect(await resume.json()).toMatchObject({ scopes_supported: ['resume'] }); }); +it('preserves provider errors and authorization-server metadata without rewriting them', async () => { + const handler = vi.spyOn(getAuth(), 'handler'); + try { + for (const status of [302, 400, 500]) { + const response = new Response('Provider response', { + status, + headers: { 'x-provider': 'retained' }, + }); + handler.mockResolvedValueOnce(response); + expect( + await discovery(new Request(`${origin}/.well-known/oauth-protected-resource/api/mcp`)) + ).toBe(response); + } + const response = Response.json({ scopes_supported: ['resume', 'offline_access'] }); + handler.mockResolvedValueOnce(response); + expect( + await discovery(new Request(`${origin}/.well-known/oauth-authorization-server/api/auth`)) + ).toBe(response); + } finally { + handler.mockRestore(); + } +}); +it.each(['', '/api/mcp'])('preserves bodyless provider HEAD discovery for %s', async (suffix) => { + const request = new Request(`${origin}/.well-known/oauth-protected-resource${suffix}`, { + method: 'HEAD', + }); + const provider = await getAuth().handler(request.clone()); + const response = await discovery(request); + expect(response.status).toBe(provider.status); + expect([...response.headers]).toEqual([...provider.headers]); + expect(await response.text()).toBe(''); +}); it.each(['discovery', 'challenge'])( 'renews an expired owner grant using scopes from app %s', async (source) => { @@ -238,7 +270,9 @@ it('qualifies registration, consent, PKCE, replay resistance, owner identity, re const denied = await consentResumeOAuth(signedQuery, false); expect(denied.ok).toBe(true); if (denied.ok) expect(denied.redirect_uri).toContain('access_denied'); - expect(sql.prepare('SELECT COUNT(*) n FROM oauthConsent').get().n).toBe(0); + expect( + sql.prepare('SELECT COUNT(*) n FROM oauthConsent WHERE clientId=?').get(client.client_id).n + ).toBe(0); const accepted = await consentResumeOAuth(signedQuery, true); expect(accepted.ok).toBe(true); if (!accepted.ok) throw new Error(accepted.error); diff --git a/src/app/.well-known/[...metadata]/route.ts b/src/app/.well-known/[...metadata]/route.ts index 87e4f2c..6611d2b 100644 --- a/src/app/.well-known/[...metadata]/route.ts +++ b/src/app/.well-known/[...metadata]/route.ts @@ -27,5 +27,25 @@ export async function GET(request: Request) { ].includes(path) ) return new Response('Not found', { status: 404 }); - return getAuth().handler(request); + const response = await getAuth().handler(request); + if ( + request.method === 'GET' && + response.ok && + [ + '/.well-known/oauth-protected-resource', + '/.well-known/oauth-protected-resource/api/mcp', + ].includes(path) + ) { + const metadata = await response.json(); + return Response.json( + { + ...metadata, + scopes_supported: metadata.scopes_supported.includes('offline_access') + ? metadata.scopes_supported + : [...metadata.scopes_supported, 'offline_access'], + }, + response + ); + } + return response; } diff --git a/src/lib/resume-access.ts b/src/lib/resume-access.ts index f05412a..e5e094c 100644 --- a/src/lib/resume-access.ts +++ b/src/lib/resume-access.ts @@ -136,7 +136,7 @@ export async function withResumeAccess( status: insufficientScope ? 403 : 401, headers: { 'Cache-Control': 'private, no-store', - 'WWW-Authenticate': `Bearer resource_metadata="${new URL(request.url).origin}/.well-known/oauth-protected-resource${path}", scope="resume", error="${insufficientScope ? 'insufficient_scope' : 'invalid_token'}"`, + 'WWW-Authenticate': `Bearer resource_metadata="${new URL(request.url).origin}/.well-known/oauth-protected-resource${path}", scope="${path === '/api/mcp' && !insufficientScope ? 'resume offline_access' : 'resume'}", error="${insufficientScope ? 'insufficient_scope' : 'invalid_token'}"`, }, } ); From ba06092ec7bdc1bbba37a1bfff4dc062254ad6dd Mon Sep 17 00:00:00 2001 From: Sarthak Agrawal Date: Sun, 15 Nov 2026 14:05:39 +0530 Subject: [PATCH 3/3] Cover provider registration scopes and optional discovery metadata --- docs/operations/runbooks/resume-oauth.md | 11 ++++-- src/__tests__/resume-oauth.test.ts | 41 ++++++++++++++++++++-- src/app/.well-known/[...metadata]/route.ts | 7 ++-- 3 files changed, 52 insertions(+), 7 deletions(-) diff --git a/docs/operations/runbooks/resume-oauth.md b/docs/operations/runbooks/resume-oauth.md index 42e6ca7..6f92d08 100644 --- a/docs/operations/runbooks/resume-oauth.md +++ b/docs/operations/runbooks/resume-oauth.md @@ -31,8 +31,15 @@ ChatGPT clients using MCP 2025-06-18 or earlier request renewal during explicit consent. This is a compatibility exception to the newer guidance that authorization-server-only scopes should not appear in protected-resource metadata. `/api/resume` discovery and challenges, and 403 scope challenges, -continue to request only `resume`. Existing grants without renewal need a new -connection and consent; no refresh grant is issued silently. +continue to request only `resume`. + +Existing grants without renewal need the assistant to refresh discovery and +reauthorize with explicit consent to `resume offline_access`. The current provider +stores both configured scopes for dynamic clients even when registration +requests only `resume`; this does not grant consent or issue a refresh token by +itself. No saved client's scopes are widened and no refresh grant is issued +silently. Verify the assistant's actual consent and a call after the five-minute +access-token expiry before claiming renewal works. Access JWTs expire in five minutes. Refresh lasts at most seven days while the linked browser session stays active. Verification checks signature, type, diff --git a/src/__tests__/resume-oauth.test.ts b/src/__tests__/resume-oauth.test.ts index 7eb1ab0..5761cea 100644 --- a/src/__tests__/resume-oauth.test.ts +++ b/src/__tests__/resume-oauth.test.ts @@ -163,6 +163,30 @@ it('preserves provider errors and authorization-server metadata without rewritin handler.mockRestore(); } }); +it('adds renewal guidance when provider metadata omits optional supported scopes', async () => { + const handler = vi.spyOn(getAuth(), 'handler'); + const metadata = { resource, authorization_servers: [`${origin}/api/auth`] }; + try { + const provider = Response.json(metadata, { + status: 203, + statusText: 'Non-Authoritative Information', + headers: { 'cache-control': 'no-store', 'x-provider': 'retained' }, + }); + handler.mockResolvedValueOnce(provider); + const response = await discovery( + new Request(`${origin}/.well-known/oauth-protected-resource/api/mcp`) + ); + expect(response.status).toBe(provider.status); + expect(response.statusText).toBe(provider.statusText); + expect([...response.headers]).toEqual([...provider.headers]); + expect(await response.json()).toEqual({ + ...metadata, + scopes_supported: ['offline_access'], + }); + } finally { + handler.mockRestore(); + } +}); it.each(['', '/api/mcp'])('preserves bodyless provider HEAD discovery for %s', async (suffix) => { const request = new Request(`${origin}/.well-known/oauth-protected-resource${suffix}`, { method: 'HEAD', @@ -173,7 +197,7 @@ it.each(['', '/api/mcp'])('preserves bodyless provider HEAD discovery for %s', a expect([...response.headers]).toEqual([...provider.headers]); expect(await response.text()).toBe(''); }); -it.each(['discovery', 'challenge'])( +it.each(['discovery', 'challenge', 'resume-only registration'])( 'renews an expired owner grant using scopes from app %s', async (source) => { let scope: string; @@ -197,10 +221,23 @@ it.each(['discovery', 'challenge'])( token_endpoint_auth_method: 'none', grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'], - scope, + scope: source === 'resume-only registration' ? 'resume' : scope, }); expect(registration.status).toBe(201); const client = await registration.json(); + if (source === 'resume-only registration') { + // The maintained provider stores all registration scopes even when DCR requests fewer. + expect(client.scope.split(' ')).toEqual(['offline_access', 'resume']); + expect( + JSON.parse( + sql.prepare('SELECT scopes FROM oauthClient WHERE clientId=?').get(client.client_id) + .scopes as string + ) + ).toEqual(['offline_access', 'resume']); + expect( + sql.prepare('SELECT COUNT(*) n FROM oauthConsent WHERE clientId=?').get(client.client_id).n + ).toBe(0); + } const signedQuery = await consentQuery(client.client_id, true, { scope }); expect(await getResumeOAuthRequest(signedQuery)).toMatchObject({ ok: true, diff --git a/src/app/.well-known/[...metadata]/route.ts b/src/app/.well-known/[...metadata]/route.ts index 6611d2b..c2d6c19 100644 --- a/src/app/.well-known/[...metadata]/route.ts +++ b/src/app/.well-known/[...metadata]/route.ts @@ -37,12 +37,13 @@ export async function GET(request: Request) { ].includes(path) ) { const metadata = await response.json(); + const scopes = metadata.scopes_supported ?? []; return Response.json( { ...metadata, - scopes_supported: metadata.scopes_supported.includes('offline_access') - ? metadata.scopes_supported - : [...metadata.scopes_supported, 'offline_access'], + scopes_supported: scopes.includes('offline_access') + ? scopes + : [...scopes, 'offline_access'], }, response );