From c033afc10a64301882d72ab2b0dadfaf90266a0b Mon Sep 17 00:00:00 2001 From: Henry Wallace Date: Sun, 22 Nov 2026 10:05:13 -0500 Subject: [PATCH 1/7] fix(amethyst): wait for complete sign-in callback parameters --- apps/amethyst/app/auth/callback.tsx | 59 ++++--------- .../lib/__tests__/oauthCallback.test.ts | 82 +++++++++++++++++++ apps/amethyst/lib/atp/useOAuthCallback.ts | 34 ++++++++ apps/amethyst/stores/authenticationSlice.tsx | 3 + 4 files changed, 135 insertions(+), 43 deletions(-) create mode 100644 apps/amethyst/lib/__tests__/oauthCallback.test.ts create mode 100644 apps/amethyst/lib/atp/useOAuthCallback.ts diff --git a/apps/amethyst/app/auth/callback.tsx b/apps/amethyst/app/auth/callback.tsx index d0d60b0f..8bbb76e0 100644 --- a/apps/amethyst/app/auth/callback.tsx +++ b/apps/amethyst/app/auth/callback.tsx @@ -1,56 +1,32 @@ -import React, { useEffect, useRef } from "react"; +import React, { useEffect } from "react"; import { View } from "react-native"; -import { Link, router, Stack } from "expo-router"; -import { useLocalSearchParams } from "expo-router/build/hooks"; +import { Link, router, Stack, useLocalSearchParams } from "expo-router"; +import { useOAuthCallback } from "@/lib/atp/useOAuthCallback"; import { Text } from "@/components/ui/text"; import { Icon } from "@/lib/icons/iconWithClassName"; import { useStore } from "@/stores/mainStore"; import { PencilLine } from "lucide-react-native"; -const toSearchParams = ( - params: Record, -): URLSearchParams => { - const searchParams = new URLSearchParams(); - for (const [key, value] of Object.entries(params)) { - if (Array.isArray(value)) { - for (const item of value) { - searchParams.append(key, item); - } - } else if (value !== undefined) { - searchParams.set(key, value); - } - } - return searchParams; -}; - -export default function AuthOptions() { +export default function AuthCallback() { const status = useStore((state) => state.status); - const params = useLocalSearchParams<"iss" | "state" | "code">(); - const { state } = params; - const calledRef = useRef(false); + const complete = useStore((state) => state.oauthCallback); + const loginError = useStore((state) => state.login.error); + const params = useLocalSearchParams(); + useOAuthCallback(params, complete); + const providerError = params.error !== undefined; useEffect(() => { - // The OAuth state in IndexedDB is deleted on first read (replay prevention). - // Must only call oauthCallback once -- a second call will fail with - // "Unknown authorization session". - if (calledRef.current || !params) return; - calledRef.current = true; - const searchParams = toSearchParams(params); - useStore.getState().oauthCallback(searchParams); - }, [params]); - - useEffect(() => { - if (status === "loggedIn") { - requestAnimationFrame(() => { - router.replace("/"); - }); + if (status === "loggedIn" && !providerError) { + const frame = requestAnimationFrame(() => router.replace("/")); + return () => cancelAnimationFrame(frame); } - }, [status]); + }, [status, providerError]); - if (!params) { + if (providerError || (status === "loggedOut" && loginError)) { return ( - + Sign-in did not complete. + Try signing in again ); } @@ -69,9 +45,6 @@ export default function AuthOptions() { This may take a few seconds {status} - - {state} - ); } diff --git a/apps/amethyst/lib/__tests__/oauthCallback.test.ts b/apps/amethyst/lib/__tests__/oauthCallback.test.ts new file mode 100644 index 00000000..b73dd96e --- /dev/null +++ b/apps/amethyst/lib/__tests__/oauthCallback.test.ts @@ -0,0 +1,82 @@ +import { createElement, StrictMode } from "react"; +import { act, create, type ReactTestRenderer } from "react-test-renderer"; +import { useOAuthCallback } from "../atp/useOAuthCallback"; + +Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + +type Params = Parameters[0]; + +function Callback({ + params, + complete, +}: { + params: Params; + complete: (response: URLSearchParams) => Promise; +}) { + useOAuthCallback(params, complete); + return null; +} + +const full = { state: "first", code: "granted", iss: "https://issuer.example" }; + +describe("the OAuth callback route effect", () => { + let screen: ReactTestRenderer | undefined; + const complete = jest.fn, [URLSearchParams]>(); + + async function render(params: Params) { + const tree = createElement( + StrictMode, + null, + createElement(Callback, { params, complete }), + ); + await act(async () => { + if (screen) screen.update(tree); + else screen = create(tree); + }); + } + + afterEach(async () => { + await act(async () => screen?.unmount()); + screen = undefined; + complete.mockReset(); + }); + + it("waits for a complete response and submits it once even while pending", async () => { + let finish!: () => void; + complete.mockReturnValue( + new Promise((resolve) => { + finish = resolve; + }), + ); + await render({}); + await render({ state: full.state, code: full.code }); + await render({ ...full, code: "" }); + expect(complete).not.toHaveBeenCalled(); + + const params = { ...full, extra: ["one", "two"] }; + await render(params); + await render({ ...params }); + expect(complete).toHaveBeenCalledTimes(1); + const [response] = complete.mock.calls[0]; + expect(response.get("code")).toBe(full.code); + expect(response.get("state")).toBe(full.state); + expect(response.get("iss")).toBe(full.iss); + expect(response.getAll("extra")).toEqual(["one", "two"]); + finish(); + }); + + it("leaves provider errors alone and handles each subsequent sign-in once", async () => { + complete.mockResolvedValue(undefined); + await render({ state: "denied", error: "access_denied" }); + await render({ ...full, error: "access_denied" }); + expect(complete).not.toHaveBeenCalled(); + + await render(full); + await render({ ...full, state: "second" }); + await render({ ...full }); + expect(complete.mock.calls.map(([p]) => p.get("state"))).toEqual([ + "first", + "second", + ]); + }); +}); diff --git a/apps/amethyst/lib/atp/useOAuthCallback.ts b/apps/amethyst/lib/atp/useOAuthCallback.ts new file mode 100644 index 00000000..d9ace72e --- /dev/null +++ b/apps/amethyst/lib/atp/useOAuthCallback.ts @@ -0,0 +1,34 @@ +import { useEffect, useRef } from "react"; + +type RouteParams = Record; + +export function useOAuthCallback( + params: RouteParams, + complete: (response: URLSearchParams) => Promise, +) { + const handledStates = useRef(new Set()); + useEffect(() => { + const response = new URLSearchParams(); + for (const [key, value] of Object.entries(params)) { + if (Array.isArray(value)) { + for (const item of value) response.append(key, item); + } else if (value !== undefined) { + response.set(key, value); + } + } + + const state = response.get("state"); + if ( + response.has("error") || + !state || + !response.get("code") || + !response.get("iss") + ) { + return; + } + // The client consumes this state on first use. Renders can repeat before it settles. + if (handledStates.current.has(state)) return; + handledStates.current.add(state); + void complete(response); + }, [params, complete]); +} diff --git a/apps/amethyst/stores/authenticationSlice.tsx b/apps/amethyst/stores/authenticationSlice.tsx index 28d5f400..d25475aa 100644 --- a/apps/amethyst/stores/authenticationSlice.tsx +++ b/apps/amethyst/stores/authenticationSlice.tsx @@ -73,6 +73,7 @@ export const createAuthenticationSlice: StateCreator = ( const url = await auth.authorize(handle); set({ auth, + login: { loading: false, error: null }, pds: { url: url.toString(), loading: false, @@ -95,6 +96,7 @@ export const createAuthenticationSlice: StateCreator = ( if (get().status === "loggedIn") { return; } + set({ login: { loading: true, error: null } }); const { session, state: oauthState } = await initialAuth.callback(state); const agent = new Agent(session); @@ -103,6 +105,7 @@ export const createAuthenticationSlice: StateCreator = ( oauthSession: session as any, oauthState, status: "loggedIn", + login: { loading: false, error: null }, pdsAgent: addDocs(agent), isAgentReady: true, }); From 0a786938d98e50e90c98c9a84421aca4d76538bd Mon Sep 17 00:00:00 2001 From: Henry Wallace Date: Sun, 22 Nov 2026 10:33:47 -0500 Subject: [PATCH 2/7] fix(amethyst): keep the latest sign-in when callbacks overlap --- .../lib/__tests__/oauthCallbackRace.test.ts | 79 +++++++++++++++++++ apps/amethyst/lib/atp/latestOAuthCallback.ts | 22 ++++++ apps/amethyst/stores/authenticationSlice.tsx | 74 +++++++++-------- 3 files changed, 140 insertions(+), 35 deletions(-) create mode 100644 apps/amethyst/lib/__tests__/oauthCallbackRace.test.ts create mode 100644 apps/amethyst/lib/atp/latestOAuthCallback.ts diff --git a/apps/amethyst/lib/__tests__/oauthCallbackRace.test.ts b/apps/amethyst/lib/__tests__/oauthCallbackRace.test.ts new file mode 100644 index 00000000..db7f28b6 --- /dev/null +++ b/apps/amethyst/lib/__tests__/oauthCallbackRace.test.ts @@ -0,0 +1,79 @@ +import { latestOAuthCallback } from "../atp/latestOAuthCallback"; + +function exchange() { + let resolve!: (result: string) => void; + let reject!: (error: Error) => void; + const promise = new Promise((ok, err) => { + resolve = ok; + reject = err; + }); + return { promise, resolve, reject }; +} + +function overlap() { + const previous = exchange(); + const current = exchange(); + const onSuccess = jest.fn(); + const onFailure = jest.fn(); + const callback = latestOAuthCallback( + (params) => + params.get("state") === "first" ? previous.promise : current.promise, + onSuccess, + onFailure, + ); + const first = callback.complete(new URLSearchParams({ state: "first" })); + const second = callback.complete(new URLSearchParams({ state: "second" })); + return { callback, first, second, previous, current, onFailure, onSuccess }; +} + +it.each(["before", "after"])( + "ignores a stale failure %s the successful callback", + async (order) => { + const { first, second, previous, current, onFailure, onSuccess } = + overlap(); + if (order === "before") { + previous.reject(new Error("Old request failed")); + await first; + } + current.resolve("current session"); + await second; + if (order === "after") { + previous.reject(new Error("Old request failed")); + await first; + } + expect(onFailure).not.toHaveBeenCalled(); + expect(onSuccess.mock.calls).toEqual([["current session"]]); + }, +); + +it.each(["before", "after"])( + "ignores a stale success %s the failed callback", + async (order) => { + const { first, second, previous, current, onFailure, onSuccess } = + overlap(); + if (order === "before") { + previous.resolve("old session"); + await first; + } + const failure = new Error("Current request failed"); + current.reject(failure); + await second; + if (order === "after") { + previous.resolve("old session"); + await first; + } + expect(onFailure.mock.calls).toEqual([[failure]]); + expect(onSuccess).not.toHaveBeenCalled(); + }, +); + +it("ignores pending callbacks after logout", async () => { + const { callback, first, second, previous, current, onFailure, onSuccess } = + overlap(); + callback.cancel(); + previous.reject(new Error("Old request failed")); + current.resolve("session"); + await Promise.all([first, second]); + expect(onFailure).not.toHaveBeenCalled(); + expect(onSuccess).not.toHaveBeenCalled(); +}); diff --git a/apps/amethyst/lib/atp/latestOAuthCallback.ts b/apps/amethyst/lib/atp/latestOAuthCallback.ts new file mode 100644 index 00000000..e89103a9 --- /dev/null +++ b/apps/amethyst/lib/atp/latestOAuthCallback.ts @@ -0,0 +1,22 @@ +// Provider responses can finish after a newer sign-in or a logout. +export function latestOAuthCallback( + exchange: (params: URLSearchParams) => Promise, + onSuccess: (result: T) => void, + onFailure: (error: unknown) => void, +) { + let generation = 0; + return { + cancel() { + generation++; + }, + async complete(params: URLSearchParams) { + const attempt = ++generation; + try { + const result = await exchange(params); + if (attempt === generation) onSuccess(result); + } catch (error) { + if (attempt === generation) onFailure(error); + } + }, + }; +} diff --git a/apps/amethyst/stores/authenticationSlice.tsx b/apps/amethyst/stores/authenticationSlice.tsx index d25475aa..39ab62d0 100644 --- a/apps/amethyst/stores/authenticationSlice.tsx +++ b/apps/amethyst/stores/authenticationSlice.tsx @@ -1,3 +1,4 @@ +import { latestOAuthCallback } from "../lib/atp/latestOAuthCallback"; import { resolveFromIdentity } from "@/lib/atp/pid"; import { Agent, type AppBskyActorDefs } from "@atproto/api"; import { OAuthSession } from "@atproto/oauth-client"; @@ -47,6 +48,40 @@ export const createAuthenticationSlice: StateCreator = ( const baseUrl = process.env.EXPO_PUBLIC_BASE_URL || "http://localhost:8081"; console.log("Using base URL:", baseUrl); const initialAuth = createOAuthClient(baseUrl, "bsky.social"); + const callback = latestOAuthCallback( + async (params) => { + if (!(params.has("code") && params.has("state") && params.has("iss"))) { + throw new Error("Missing callback parameters"); + } + set({ login: { loading: true, error: null } }); + return initialAuth.callback(params); + }, + ({ session, state }) => { + if (get().status === "loggedIn") return; + const agent = new Agent(session); + set({ + // TODO: fork or update auth lib + oauthSession: session as any, + oauthState: state, + status: "loggedIn", + login: { loading: false, error: null }, + pdsAgent: addDocs(agent), + isAgentReady: true, + }); + get().populateLoggedInProfile(); + }, + (error) => { + if (get().status === "loggedIn") return; + console.error("OAuth callback failed:", error); + set({ + status: "loggedOut", + login: { + loading: false, + error: error instanceof Error ? error.message : "Unknown error during OAuth callback", + }, + }); + }, + ); console.log("Auth client created!"); @@ -87,41 +122,8 @@ export const createAuthenticationSlice: StateCreator = ( } }, - oauthCallback: async (state: URLSearchParams) => { - try { - if (!(state.has("code") && state.has("state") && state.has("iss"))) { - throw new Error("Missing params, got: " + state); - } - // are we already logged in? - if (get().status === "loggedIn") { - return; - } - set({ login: { loading: true, error: null } }); - const { session, state: oauthState } = - await initialAuth.callback(state); - const agent = new Agent(session); - set({ - // TODO: fork or update auth lib - oauthSession: session as any, - oauthState, - status: "loggedIn", - login: { loading: false, error: null }, - pdsAgent: addDocs(agent), - isAgentReady: true, - }); - get().populateLoggedInProfile(); - } catch (error: any) { - console.error("OAuth callback failed:", error); - set({ - status: "loggedOut", - login: { - loading: false, - error: - (error?.message as string) || - "Unknown error during OAuth callback", - }, - }); - } + oauthCallback: async (params) => { + if (get().status !== "loggedIn") await callback.complete(params); }, restorePdsAgent: async () => { let did = get().oauthSession?.sub; @@ -153,6 +155,7 @@ export const createAuthenticationSlice: StateCreator = ( } }, logOut: () => { + callback.cancel(); console.log("Logging out"); let profiles = { ...get().profiles }; // TODO: something better than 'delete' @@ -161,6 +164,7 @@ export const createAuthenticationSlice: StateCreator = ( status: "loggedOut", oauthSession: null, oauthState: null, + login: { loading: false, error: null }, profiles, pdsAgent: null, client: null, From 479817753bdfa011161f1170e660f7b27d16004a Mon Sep 17 00:00:00 2001 From: Henry Wallace Date: Sun, 22 Nov 2026 11:05:35 -0500 Subject: [PATCH 3/7] Invalidate a pending callback when sign-in restarts --- apps/amethyst/stores/authenticationSlice.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/amethyst/stores/authenticationSlice.tsx b/apps/amethyst/stores/authenticationSlice.tsx index 39ab62d0..69c761ef 100644 --- a/apps/amethyst/stores/authenticationSlice.tsx +++ b/apps/amethyst/stores/authenticationSlice.tsx @@ -101,6 +101,8 @@ export const createAuthenticationSlice: StateCreator = ( pds: null, getLoginUrl: async (handle: string) => { + callback.cancel(); + set({ login: { loading: false, error: null } }); try { // resolve the handle to a PDS URL const r = resolveFromIdentity(handle); @@ -108,7 +110,6 @@ export const createAuthenticationSlice: StateCreator = ( const url = await auth.authorize(handle); set({ auth, - login: { loading: false, error: null }, pds: { url: url.toString(), loading: false, From 180fd03af2dd5aceb989d69d161d4d358c7a713f Mon Sep 17 00:00:00 2001 From: Henry Wallace Date: Sun, 22 Nov 2026 11:07:22 -0500 Subject: [PATCH 4/7] Keep a stale restored session from undoing sign-out --- apps/amethyst/stores/authenticationSlice.tsx | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/apps/amethyst/stores/authenticationSlice.tsx b/apps/amethyst/stores/authenticationSlice.tsx index 69c761ef..ad4e4416 100644 --- a/apps/amethyst/stores/authenticationSlice.tsx +++ b/apps/amethyst/stores/authenticationSlice.tsx @@ -127,15 +127,13 @@ export const createAuthenticationSlice: StateCreator = ( if (get().status !== "loggedIn") await callback.complete(params); }, restorePdsAgent: async () => { - let did = get().oauthSession?.sub; - if (!did) { - // - // throw new Error("No session"); - return; - } + const sessionToRestore = get().oauthSession; + const did = sessionToRestore?.sub; + if (!did) return; try { // restore session - let sess = await initialAuth.restore(did); + const sess = await initialAuth.restore(did); + if (get().oauthSession !== sessionToRestore) return; if (!sess) { throw new Error("Failed to restore session"); @@ -151,6 +149,7 @@ export const createAuthenticationSlice: StateCreator = ( get().populateLoggedInProfile(); console.log("Restored agent"); } catch (error) { + if (get().oauthSession !== sessionToRestore || get().isAgentReady) return; console.error("Failed to restore agent:", error); get().logOut(); } @@ -168,6 +167,7 @@ export const createAuthenticationSlice: StateCreator = ( login: { loading: false, error: null }, profiles, pdsAgent: null, + isAgentReady: false, client: null, pds: null, }); From 6698355142e911636ab1258df5a0ccc173644d21 Mon Sep 17 00:00:00 2001 From: Henry Wallace Date: Sun, 22 Nov 2026 11:33:12 -0500 Subject: [PATCH 5/7] Recover when native sign-in does not complete --- apps/amethyst/app/auth/callback.tsx | 2 +- apps/amethyst/app/auth/login.tsx | 14 ++++++++++++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/apps/amethyst/app/auth/callback.tsx b/apps/amethyst/app/auth/callback.tsx index 8bbb76e0..25bc4dfe 100644 --- a/apps/amethyst/app/auth/callback.tsx +++ b/apps/amethyst/app/auth/callback.tsx @@ -43,7 +43,7 @@ export default function AuthCallback() { {status === "loggedIn" ? "Success!" : "Fetching your data..."} - This may take a few seconds {status} + This may take a few seconds. ); diff --git a/apps/amethyst/app/auth/login.tsx b/apps/amethyst/app/auth/login.tsx index 3c8f9157..a4b35541 100644 --- a/apps/amethyst/app/auth/login.tsx +++ b/apps/amethyst/app/auth/login.tsx @@ -171,6 +171,8 @@ const LoginScreen = () => { ); const handleLogin = async () => { + if (isLoading || isRedirecting) return; + // reset state if (debounceTimeoutRef.current) { clearTimeout(debounceTimeoutRef.current); @@ -200,8 +202,15 @@ const LoginScreen = () => { "http://127.0.0.1:8081/login", ); if (res.type === "success") { - const params = new URLSearchParams(res.url.split("?")[1]); + const params = new URL(res.url).searchParams; + if (params.has("error")) { + throw new Error("Sign-in did not complete. Try signing in again."); + } await oauthCallback(params); + if (useStore.getState().status !== "loggedIn") { + throw new Error("Sign-in did not complete. Try signing in again."); + } + router.replace("/"); } else if (res.type === "cancel" || res.type === "dismiss") { setErr("Login cancelled by user."); setIsRedirecting(false); @@ -314,6 +323,7 @@ const LoginScreen = () => { + {err ? {err} : null}