diff --git a/src/auth/oauth-handler.ts b/src/auth/oauth-handler.ts index 1a15be35..907fcf4b 100644 --- a/src/auth/oauth-handler.ts +++ b/src/auth/oauth-handler.ts @@ -56,6 +56,40 @@ function authErrorMessage(prefix: string, e: unknown): string { return `${prefix}: ${message}` } +/** + * workers-oauth-provider's descriptions of a sign-in transaction it can't use, and what to tell the + * person instead. The provider gives these no distinct error code, so they are matched by text; + * tests/auth/oauth-routes.test.ts drives each through the real provider, so a reworded provider + * message fails a test rather than silently falling back to the provider's text. + */ +const TRANSACTION_ERROR_PAGES: readonly { + readonly matches: readonly string[] + readonly title: string + readonly message: string +}[] = [ + { + matches: ['expired or was already used'], + title: 'This sign-in has already finished', + message: + 'This sign-in was already completed, or it took longer than 10 minutes. If your app shows Cloudflare as connected, you can close this page. Otherwise, go back to the app and connect again.' + }, + { + matches: ['not started in this browser', 'belongs to a different browser session'], + title: 'Finish signing in where you started', + message: + 'This sign-in was started in a different browser or browser profile. Go back to the app, connect again, and complete every step in the same browser.' + } +] + +/** The error page for an `AuthorizationError`, explaining unusable sign-in transactions in plain words. */ +function authorizationErrorResponse(error: AuthorizationError): Response { + const page = TRANSACTION_ERROR_PAGES.find(({ matches }) => + matches.some((match) => error.description.includes(match)) + ) + if (!page) return new OAuthError(error.code, error.description).toHtmlResponse() + return renderErrorPage(page.title, page.message, `Error code: ${error.code}`, 400) +} + /** * The scopes an MCP token may claim: those requested that Cloudflare actually granted. Cloudflare can * grant fewer than requested (the account can't grant one, or the user narrows them on its consent); @@ -286,8 +320,7 @@ export function createAuthHandlers() { } catch (e) { metrics.logEvent(new AuthUser({ errorMessage: authErrorMessage('Authorize POST Error', e) })) // Consent/upstream transaction expired, used, or opened in another browser: render locally. - if (e instanceof AuthorizationError) - return new OAuthError(e.code, e.description).toHtmlResponse() + if (e instanceof AuthorizationError) return authorizationErrorResponse(e) if (e instanceof OAuthError) return e.toHtmlResponse() const errorId = crypto.randomUUID() console.error(`Authorize POST error [${errorId}]:`, e) @@ -369,8 +402,7 @@ export function createAuthHandlers() { if (e instanceof CimdFetchError) return cimdCallbackFailureResponse() metrics.logEvent(new AuthUser({ errorMessage: authErrorMessage('Callback Error', e) })) // Consent/upstream transaction expired, used, or opened in another browser: render locally. - if (e instanceof AuthorizationError) - return new OAuthError(e.code, e.description).toHtmlResponse() + if (e instanceof AuthorizationError) return authorizationErrorResponse(e) if (e instanceof OAuthError) return e.toHtmlResponse() const errorId = crypto.randomUUID() console.error(`Callback error [${errorId}]:`, e) diff --git a/tests/auth/oauth-routes.test.ts b/tests/auth/oauth-routes.test.ts index a2514bec..e9142e69 100644 --- a/tests/auth/oauth-routes.test.ts +++ b/tests/auth/oauth-routes.test.ts @@ -1006,7 +1006,9 @@ describe('GET /oauth/callback', () => { ) expect(res.status).toBe(400) - expect(await res.text()).toContain('not started in this browser') + const html = await res.text() + expect(html).toContain('started in a different browser or browser profile') + expect(html).toContain('Error code: invalid_request') }) it('rejects a valid state token bound to a different browser session', async () => { @@ -1021,7 +1023,7 @@ describe('GET /oauth/callback', () => { ) expect(res.status).toBe(400) - expect(await res.text()).toContain('not started in this browser') + expect(await res.text()).toContain('started in a different browser or browser profile') }) it('rejects replay after a state token has completed authorization', async () => { @@ -1038,7 +1040,41 @@ describe('GET /oauth/callback', () => { new Request(callbackUrl, { headers: { Cookie: sessionCookie }, redirect: 'manual' }) ) expect(replay.status).toBe(400) - expect(await replay.text()).toContain('expired or was already used') + const html = await replay.text() + expect(html).toContain('This sign-in has already finished') + expect(html).toContain('If your app shows Cloudflare as connected, you can close this page.') + expect(html).not.toContain('start again') + }) + + it('explains a consent form submitted twice as a finished sign-in', async () => { + const clientId = await registerClient() + const authRes = await exports.default.fetch( + new Request( + authorizeUrl({ + response_type: 'code', + client_id: clientId, + redirect_uri: REDIRECT_URI, + scope: 'user:read' + }) + ) + ) + const consentCookie = cookiesFrom(authRes) + const handle = consentHandle(await authRes.text()) + const submit = () => + exports.default.fetch( + new Request(`${MCP_ORIGIN}/authorize`, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded', Cookie: consentCookie }, + body: new URLSearchParams({ handle, scopes: 'user:read' }).toString(), + redirect: 'manual' + }) + ) + + expect((await submit()).status).toBe(302) + const again = await submit() + + expect(again.status).toBe(400) + expect(await again.text()).toContain('This sign-in has already finished') }) it('returns 400 invalid_request when the code is missing', async () => {