From aa248ef3ddec2669c15b0f97a85dbc7c053196e2 Mon Sep 17 00:00:00 2001 From: theluckystrike <51033404+theluckystrike@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:51:59 +0700 Subject: [PATCH] fix: exchange the Keystatic Cloud authorization code only once --- .changeset/cloud-callback-exchange-once.md | 5 ++ .../src/app/cloud-auth-callback.test.tsx | 88 +++++++++++++++++++ .../keystatic/src/app/cloud-auth-callback.tsx | 14 ++- 3 files changed, 105 insertions(+), 2 deletions(-) create mode 100644 .changeset/cloud-callback-exchange-once.md create mode 100644 packages/keystatic/src/app/cloud-auth-callback.test.tsx diff --git a/.changeset/cloud-callback-exchange-once.md b/.changeset/cloud-callback-exchange-once.md new file mode 100644 index 000000000..aab56eae2 --- /dev/null +++ b/.changeset/cloud-callback-exchange-once.md @@ -0,0 +1,5 @@ +--- +'@keystatic/core': patch +--- + +Fix signing in with Keystatic Cloud sometimes ending on a `400 invalid_grant` error page even though the sign-in succeeded. The OAuth callback now exchanges the authorization code only once, instead of again on every re-render of the router. diff --git a/packages/keystatic/src/app/cloud-auth-callback.test.tsx b/packages/keystatic/src/app/cloud-auth-callback.test.tsx new file mode 100644 index 000000000..b51fecac0 --- /dev/null +++ b/packages/keystatic/src/app/cloud-auth-callback.test.tsx @@ -0,0 +1,88 @@ +import { render, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, expect, test, vi } from 'vitest'; +import { Config } from '..'; + +const mocks = vi.hoisted(() => ({ + push: vi.fn(), +})); + +// RouterProvider builds a new router object on every render, mirror that here +vi.mock('./router', () => ({ + useRouter: () => ({ + push: mocks.push, + replace: vi.fn(), + href: '/keystatic/cloud/oauth/callback', + params: ['cloud', 'oauth', 'callback'], + pathname: '/keystatic/cloud/oauth/callback', + search: '', + }), +})); + +// imported after the mocks are registered +const { KeystaticCloudAuthCallback } = await import('./cloud-auth-callback'); + +const config: Config = { + storage: { kind: 'cloud' }, + cloud: { project: 'team/project' }, +}; + +const fetchMock = vi.fn(); + +beforeEach(() => { + window.history.replaceState( + null, + '', + '/keystatic/cloud/oauth/callback?code=the-code&state=the-state' + ); + localStorage.setItem( + 'keystatic-cloud-state', + JSON.stringify({ + state: 'the-state', + from: 'collection/posts', + code_verifier: 'verifier', + }) + ); + let calls = 0; + fetchMock.mockImplementation(async () => { + calls++; + if (calls > 1) { + return new Response( + JSON.stringify({ + error: 'invalid_grant', + error_description: 'Invalid code', + }), + { status: 400 } + ); + } + return new Response( + JSON.stringify({ + access_token: 'token', + token_type: 'bearer', + expires_in: 3600, + }), + { status: 200 } + ); + }); + vi.stubGlobal('fetch', fetchMock); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + localStorage.clear(); +}); + +test('exchanges the authorization code only once when the router changes', async () => { + const { rerender } = render(); + rerender(); + rerender(); + + await waitFor(() => { + expect(mocks.push).toHaveBeenCalledWith('/keystatic/collection/posts'); + }); + + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(screen.queryByText(/invalid_grant/)).not.toBeInTheDocument(); + expect( + JSON.parse(localStorage.getItem('keystatic-cloud-access-token')!).token + ).toBe('token'); +}); diff --git a/packages/keystatic/src/app/cloud-auth-callback.tsx b/packages/keystatic/src/app/cloud-auth-callback.tsx index cec4eae10..dc3d7b23c 100644 --- a/packages/keystatic/src/app/cloud-auth-callback.tsx +++ b/packages/keystatic/src/app/cloud-auth-callback.tsx @@ -1,6 +1,6 @@ import { ProgressCircle } from '@keystar/ui/progress'; import { Text } from '@keystar/ui/typography'; -import { useEffect, useMemo, useState } from 'react'; +import { useEffect, useMemo, useRef, useState } from 'react'; import * as s from 'superstruct'; import { Config } from '../config'; import { useRouter } from './router'; @@ -35,8 +35,18 @@ export function KeystaticCloudAuthCallback({ config }: { config: Config }) { return storedState; }, []); const [error, setError] = useState(null); + // the authorization code can only be exchanged once, but the effect re-runs + // whenever the router changes, which happens on every RouterProvider render + const hasExchangedCode = useRef(false); useEffect(() => { - if (code && state && storedState && config.cloud?.project) { + if ( + !hasExchangedCode.current && + code && + state && + storedState && + config.cloud?.project + ) { + hasExchangedCode.current = true; const { project } = config.cloud; (async () => { const res = await fetch(`${KEYSTATIC_CLOUD_API_URL}/oauth/token`, {