Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/cloud-callback-exchange-once.md
Original file line number Diff line number Diff line change
@@ -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.
88 changes: 88 additions & 0 deletions packages/keystatic/src/app/cloud-auth-callback.test.tsx
Original file line number Diff line number Diff line change
@@ -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(<KeystaticCloudAuthCallback config={config} />);
rerender(<KeystaticCloudAuthCallback config={config} />);
rerender(<KeystaticCloudAuthCallback config={config} />);

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');
});
14 changes: 12 additions & 2 deletions packages/keystatic/src/app/cloud-auth-callback.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -35,8 +35,18 @@ export function KeystaticCloudAuthCallback({ config }: { config: Config }) {
return storedState;
}, []);
const [error, setError] = useState<null | Error>(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`, {
Expand Down