Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Fix SaaS OAuth consent discarding the code on reconnect (#8377)

Anthony Stirling4424d86bfdcf
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index cde2d85876..a42128df23 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -6201,7 +6201,7 @@ title = "Authentication Successful"
[oauthConsent]
approve = "Allow access"
approving = "Allowing..."
-decisionFailed = "Could not submit your decision. Please try again."
+decisionFailed = "Could not complete this authorization. It may already have been used or expired - start the connection again from your app."
deny = "Deny"
denying = "Denying..."
loadFailed = "This authorization request is invalid or has expired. Close this tab and try connecting again from the app."
diff --git a/frontend/editor/src/saas/routes/OAuthConsent.test.tsx b/frontend/editor/src/saas/routes/OAuthConsent.test.tsx
new file mode 100644
index 0000000000..e17e75cc59
--- /dev/null
+++ b/frontend/editor/src/saas/routes/OAuthConsent.test.tsx
@@ -0,0 +1,199 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { render, screen, waitFor } from "@testing-library/react";
+import { MemoryRouter } from "react-router-dom";
+import { MantineProvider } from "@mantine/core";
+import type { ReactNode } from "react";
+
+// GoTrue returns consent details on first connect, then a bare {redirect_url} with the
+// code already issued; treating that as details broke every reconnect.
+
+const fetchMock = vi.fn();
+let search = "?authorization_id=auth-123";
+
+vi.mock("@app/auth/UseSession", () => ({
+ useAuth: () => ({
+ session: { access_token: "token-abc" },
+ loading: false,
+ displayName: "Ada",
+ }),
+}));
+
+vi.mock("@app/hooks/useTranslation", () => ({
+ useTranslation: () => ({
+ t: (_key: string, fallback?: unknown) =>
+ typeof fallback === "string"
+ ? fallback
+ : ((fallback as { defaultValue?: string })?.defaultValue ?? _key),
+ }),
+}));
+
+vi.mock("@app/hooks/useDocumentMeta", () => ({ useDocumentMeta: () => {} }));
+
+vi.mock("@app/routes/authShared/AuthLayout", () => ({
+ default: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+}));
+
+vi.mock("@app/auth/ui/ErrorMessage", () => ({
+ default: ({ error }: { error?: string | null }) =>
+ error ? <div role="alert">{error}</div> : null,
+}));
+
+vi.mock("@app/ui/Button", () => ({
+ Button: ({ children, ...rest }: { children: ReactNode }) => (
+ <button {...rest}>{children}</button>
+ ),
+}));
+
+vi.mock("react-router-dom", async () => {
+ const actual =
+ await vi.importActual<typeof import("react-router-dom")>(
+ "react-router-dom",
+ );
+ return {
+ ...actual,
+ useNavigate: () => vi.fn(),
+ useLocation: () => ({ pathname: "/oauth/consent", search }),
+ };
+});
+
+const OAuthConsent = (await import("@app/routes/OAuthConsent")).default;
+
+const json = (status: number, body: unknown) =>
+ Promise.resolve({
+ ok: status >= 200 && status < 300,
+ status,
+ json: () => Promise.resolve(body),
+ });
+
+const assign = vi.fn();
+
+function renderPage() {
+ return render(
+ <MantineProvider>
+ <MemoryRouter>
+ <OAuthConsent />
+ </MemoryRouter>
+ </MantineProvider>,
+ );
+}
+
+describe("OAuthConsent", () => {
+ beforeEach(() => {
+ search = "?authorization_id=auth-123";
+ fetchMock.mockReset();
+ assign.mockReset();
+ vi.stubGlobal("fetch", fetchMock);
+ // jsdom's location is not assignable; swap in a stub we can observe.
+ Object.defineProperty(window, "location", {
+ configurable: true,
+ value: { assign, pathname: "/oauth/consent", search: "" },
+ });
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ });
+
+ it("renders the consent screen and names the requesting client", async () => {
+ fetchMock.mockReturnValueOnce(
+ json(200, {
+ authorization_id: "auth-123",
+ scope: "openid email",
+ client: { name: "Claude" },
+ }),
+ );
+
+ renderPage();
+
+ expect(await screen.findByText(/Claude wants to access/)).toBeTruthy();
+ expect(assign).not.toHaveBeenCalled();
+ });
+
+ it("follows redirect_url instead of rendering consent when the grant already exists", async () => {
+ fetchMock.mockReturnValueOnce(
+ json(200, {
+ redirect_url: "https://client.example/cb?code=xyz&state=s1",
+ }),
+ );
+
+ renderPage();
+
+ await waitFor(() =>
+ expect(assign).toHaveBeenCalledWith(
+ "https://client.example/cb?code=xyz&state=s1",
+ ),
+ );
+ // The already-issued code must not be thrown away behind a consent screen.
+ expect(screen.queryByText(/wants to access/)).toBeNull();
+ });
+
+ it("does not POST consent for an already-granted authorization", async () => {
+ fetchMock.mockReturnValueOnce(
+ json(200, { redirect_url: "https://client.example/cb?code=xyz" }),
+ );
+
+ renderPage();
+
+ await waitFor(() => expect(assign).toHaveBeenCalled());
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(String(fetchMock.mock.calls[0][0])).not.toContain("/consent");
+ });
+
+ it("refuses to render a consent screen it cannot attribute to a client", async () => {
+ // A 2xx that is neither shape, e.g. an SPA index.html served for a wrong base URL.
+ fetchMock.mockReturnValueOnce(json(200, { unexpected: true }));
+
+ renderPage();
+
+ expect(await screen.findByRole("alert")).toBeTruthy();
+ expect(screen.queryByText(/wants to access/)).toBeNull();
+ });
+
+ it("surfaces an error when the authorization is expired or unknown", async () => {
+ fetchMock.mockReturnValueOnce(
+ json(404, { error: "oauth_authorization_not_found" }),
+ );
+
+ renderPage();
+
+ expect(await screen.findByRole("alert")).toBeTruthy();
+ });
+
+ it("loads once per id, because the GET consumes the authorization server-side", async () => {
+ fetchMock.mockReturnValue(
+ json(200, { authorization_id: "auth-123", client: { name: "Claude" } }),
+ );
+
+ const { rerender } = renderPage();
+ await screen.findByText(/Claude wants to access/);
+ rerender(
+ <MantineProvider>
+ <MemoryRouter>
+ <OAuthConsent />
+ </MemoryRouter>
+ </MantineProvider>,
+ );
+
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
+ });
+
+ it("asks the user to restart from the app rather than retry a dead authorization", async () => {
+ fetchMock.mockReturnValueOnce(json(404, {}));
+
+ renderPage();
+
+ const alert = await screen.findByRole("alert");
+ expect(alert.textContent).not.toMatch(/try again/i);
+ });
+
+ it("shows a missing-request error when authorization_id is absent", async () => {
+ search = "";
+
+ renderPage();
+
+ expect(await screen.findByRole("alert")).toBeTruthy();
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/editor/src/saas/routes/OAuthConsent.tsx b/frontend/editor/src/saas/routes/OAuthConsent.tsx
index f2acc03899..66013953ee 100644
--- a/frontend/editor/src/saas/routes/OAuthConsent.tsx
+++ b/frontend/editor/src/saas/routes/OAuthConsent.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { List, Paper, Text } from "@mantine/core";
import { Button } from "@app/ui/Button";
@@ -12,17 +12,8 @@ import { withBasePath } from "@app/constants/app";
import ErrorMessage from "@app/auth/ui/ErrorMessage";
import loginHeader from "@app/assets/brand/modern-logo/LoginLightModeHeader.svg";
-/**
- * OAuth 2.1 consent screen for the Supabase OAuth server (used by MCP clients
- * such as Claude). Supabase redirects the user here as
- * {SiteURL}/oauth/consent?authorization_id=X; this page loads the pending
- * authorization, shows what the third-party app is asking for, and forwards
- * the user's approve/deny decision back to Supabase, which then redirects to
- * the requesting app with an authorization code (or an error).
- *
- * The installed supabase-js does not yet wrap these endpoints, so the GoTrue
- * REST API is called directly with the user's session token.
- */
+// Supabase OAuth consent screen for MCP clients (e.g. Claude): loads the pending
+// authorization and forwards approve/deny to GoTrue, which redirects to the client.
interface AuthorizationDetails {
authorization_id: string;
@@ -35,6 +26,20 @@ interface AuthorizationDetails {
};
}
+// GoTrue's other response shape: an already-granted client gets its code up front
+// (supabase-js `AuthOAuthAuthorizationDetailsResponse` is a union of the two).
+interface AuthorizationRedirect {
+ redirect_url: string;
+}
+
+const needsConsent = (body: unknown): body is AuthorizationDetails =>
+ typeof body === "object" && body !== null && "authorization_id" in body;
+
+const alreadyGranted = (body: unknown): body is AuthorizationRedirect =>
+ typeof body === "object" &&
+ body !== null &&
+ typeof (body as AuthorizationRedirect).redirect_url === "string";
+
const SUPABASE_URL = import.meta.env.VITE_SUPABASE_URL;
const SUPABASE_KEY = import.meta.env.VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY;
@@ -78,12 +83,26 @@ export default function OAuthConsent() {
title: `${t("oauthConsent.title", "Authorize access")} - Stirling PDF`,
});
+ // The GET consumes the authorization, so run it once per id: a StrictMode rerun
+ // would 404, and dropping the first response strands the user on "Loading...".
+ const loadedIdRef = useRef<string | null>(null);
+
// Load the pending authorization once a session is available.
useEffect(() => {
if (sessionLoading || !session || !authorizationId) {
return;
}
- let cancelled = false;
+ if (loadedIdRef.current === authorizationId) return;
+ loadedIdRef.current = authorizationId;
+
+ const loadFailed = () =>
+ setError(
+ t(
+ "oauthConsent.loadFailed",
+ "This authorization request is invalid or has expired. Close this tab and try connecting again from the app.",
+ ),
+ );
+
(async () => {
try {
setLoadingDetails(true);
@@ -92,35 +111,36 @@ export default function OAuthConsent() {
session.access_token,
);
const body = await response.json().catch(() => ({}));
- if (cancelled) return;
if (!response.ok) {
console.error("[OAuthConsent] Failed to load authorization:", body);
- setError(
- t(
- "oauthConsent.loadFailed",
- "This authorization request is invalid or has expired. Close this tab and try connecting again from the app.",
- ),
+ loadFailed();
+ return;
+ }
+ // Reconnect of an already-granted client: follow the issued code, since
+ // showing consent would drop it and approve would 400 "no longer pending".
+ if (alreadyGranted(body)) {
+ setRedirecting(true);
+ window.location.assign(body.redirect_url);
+ return;
+ }
+ // A 2xx that is neither shape must not render a consent screen that
+ // cannot say who is asking for access.
+ if (!needsConsent(body)) {
+ console.error(
+ "[OAuthConsent] Unrecognised authorization response:",
+ body,
);
- } else {
- setDetails(body as AuthorizationDetails);
+ loadFailed();
+ return;
}
+ setDetails(body);
} catch (err) {
console.error("[OAuthConsent] Unexpected error:", err);
- if (!cancelled) {
- setError(
- t(
- "oauthConsent.loadFailed",
- "This authorization request is invalid or has expired. Close this tab and try connecting again from the app.",
- ),
- );
- }
+ loadFailed();
} finally {
- if (!cancelled) setLoadingDetails(false);
+ setLoadingDetails(false);
}
})();
- return () => {
- cancelled = true;
- };
}, [sessionLoading, session, authorizationId, t]);
const decide = useCallback(
@@ -140,7 +160,7 @@ export default function OAuthConsent() {
setError(
t(
"oauthConsent.decisionFailed",
- "Could not submit your decision. Please try again.",
+ "Could not complete this authorization. It may already have been used or expired - start the connection again from your app.",
),
);
setDeciding(null);
@@ -154,7 +174,7 @@ export default function OAuthConsent() {
setError(
t(
"oauthConsent.decisionFailed",
- "Could not submit your decision. Please try again.",
+ "Could not complete this authorization. It may already have been used or expired - start the connection again from your app.",
),
);
setDeciding(null);