Skip to content
Closed
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
66 changes: 22 additions & 44 deletions apps/amethyst/app/auth/callback.tsx
Original file line number Diff line number Diff line change
@@ -1,56 +1,37 @@
import React, { useEffect, useRef } from "react";
import React, { useEffect, useSyncExternalStore } 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<string, string | string[] | undefined>,
): 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);

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]);
const complete = useStore((state) => state.oauthCallback);
const loginError = useStore((state) => state.login.error);
const params = useLocalSearchParams();
const hydrated = useSyncExternalStore(
useStore.persist.onFinishHydration,
useStore.persist.hasHydrated,
() => false,
);
useOAuthCallback(params, complete, hydrated);
const providerError = params.error !== undefined;

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 (
<View>
<Link href="/error" />
<Text accessibilityRole="alert">Sign-in did not complete.</Text>
<Link href="/auth/login">Try signing in again</Link>
</View>
);
}
Expand All @@ -67,10 +48,7 @@ export default function AuthOptions() {
{status === "loggedIn" ? "Success!" : "Fetching your data..."}
</Text>
<Text className="text-sm text-muted-foreground">
This may take a few seconds {status}
</Text>
<Text className="rounded-full bg-muted-foreground/30 px-2 py-1 font-mono text-sm text-muted-foreground">
{state}
This may take a few seconds.
</Text>
</View>
);
Expand Down
14 changes: 12 additions & 2 deletions apps/amethyst/app/auth/login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,8 @@ const LoginScreen = () => {
);

const handleLogin = async () => {
if (isLoading || isRedirecting) return;

// reset state
if (debounceTimeoutRef.current) {
clearTimeout(debounceTimeoutRef.current);
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -314,6 +323,7 @@ const LoginScreen = () => {
</View>
</Animated.View>
</View>
{err ? <Text accessibilityRole="alert">{err}</Text> : null}
<View className="flex flex-row items-center justify-between">
<Link href="https://bsky.app/signup" asChild>
<Button variant="link" className="p-0">
Expand All @@ -328,7 +338,7 @@ const LoginScreen = () => {
isRedirecting ? "bg-green-500" : "bg-bsky",
)}
onPress={handleLogin}
disabled={!pdsUrl}
disabled={!pdsUrl || isLoading || isRedirecting}
>
{isRedirecting ? (
<>
Expand Down
91 changes: 91 additions & 0 deletions apps/amethyst/lib/__tests__/oauthCallback.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
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<typeof useOAuthCallback>[0];

function Callback({
params,
complete,
ready,
}: {
params: Params;
complete: (response: URLSearchParams) => Promise<void>;
ready: boolean;
}) {
useOAuthCallback(params, complete, ready);
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<Promise<void>, [URLSearchParams]>();

async function render(params: Params, ready = true) {
const tree = createElement(
StrictMode,
null,
createElement(Callback, { params, complete, ready }),
);
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 preserves all parameters", async () => {
let finish!: () => void;
complete.mockReturnValue(
new Promise<void>((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);
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 forwards complete responses", 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" });
expect(complete.mock.calls.map(([p]) => p.get("state"))).toEqual([
"first",
"second",
]);
});

it("waits for the persisted sign-in attempt before submitting a callback", async () => {
complete.mockResolvedValue(undefined);
await render(full, false);
expect(complete).not.toHaveBeenCalled();

await render(full);
expect(complete).toHaveBeenCalledTimes(1);
});
});
72 changes: 72 additions & 0 deletions apps/amethyst/lib/__tests__/oauthCallbackRace.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { latestOAuthCallback } from "../atp/latestOAuthCallback";

function response(state: string) {
return new URLSearchParams({ state, code: "granted", iss: "https://issuer.example" });
}

function pendingExchange() {
let resolve!: (result: { state: string }) => void;
const promise = new Promise<{ state: string }>((done) => { resolve = done; });
return { resolve, promise };
}

it("accepts the current authorization when the older callback arrives for the first time", async () => {
const current = pendingExchange();
const onSuccess = jest.fn();
const onFailure = jest.fn();
const callback = latestOAuthCallback(
() => 2,
(params) => params.get("state") === "new" ? current.promise : Promise.resolve({ state: "1" }),
onSuccess,
onFailure,
);
const newer = callback.complete(response("new"));
await callback.complete(response("old"));
expect(onSuccess).not.toHaveBeenCalled();
current.resolve({ state: "2" });
await newer;
expect(onSuccess.mock.calls).toEqual([[{ state: "2" }]]);
expect(onFailure).not.toHaveBeenCalled();
});

it("ignores an older exchange that finishes after logout", async () => {
let attempt = 1;
const pending = pendingExchange();
const onSuccess = jest.fn();
const callback = latestOAuthCallback(() => attempt, () => pending.promise, onSuccess, jest.fn());
const exchange = callback.complete(response("old"));
attempt++;
pending.resolve({ state: "1" });
await exchange;
expect(onSuccess).not.toHaveBeenCalled();
});

it("reports provider failures for the active attempt", async () => {
const failure = Object.assign(new Error("Failed"), { state: "2" });
const onFailure = jest.fn();
const callback = latestOAuthCallback(
() => 2,
async (params) => {
if (params.get("state") === "old") throw Object.assign(new Error("Old failure"), { state: "1" });
throw failure;
},
jest.fn(),
onFailure,
);
await callback.complete(response("old"));
await callback.complete(response("new"));
expect(onFailure.mock.calls).toEqual([[failure]]);
});

it("shares the exchange when the route resubmits the same provider state", async () => {
const pending = pendingExchange();
const exchange = jest.fn(() => pending.promise);
const onSuccess = jest.fn();
const callback = latestOAuthCallback(() => 1, exchange, onSuccess, jest.fn());
const first = callback.complete(response("provider-state"));
const duplicate = callback.complete(response("provider-state"));
pending.resolve({ state: "1" });
await Promise.all([first, duplicate]);
expect(exchange).toHaveBeenCalledTimes(1);
expect(onSuccess.mock.calls).toEqual([[{ state: "1" }]]);
});
41 changes: 41 additions & 0 deletions apps/amethyst/lib/atp/latestOAuthCallback.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
export function isCompleteOAuthResponse(params: URLSearchParams): boolean {
return !!(params.get("state") && params.get("code") && params.get("iss") && !params.has("error"));
}

// The SDK returns the application state saved when authorization started.
export function latestOAuthCallback<T extends { state: string | null }>(
currentAttempt: () => number,
exchange: (params: URLSearchParams) => Promise<T>,
onSuccess: (result: T) => void,
onFailure: (error: unknown) => void,
) {
const responses = new Map<string, Promise<void>>();

async function exchangeForAttempt(params: URLSearchParams) {
const attempt = currentAttempt();
try {
const result = await exchange(params);
if (attempt === currentAttempt() && result.state === String(attempt)) {
onSuccess(result);
}
} catch (error) {
if (attempt !== currentAttempt()) return;
if (error && typeof error === "object" && "state" in error && error.state !== String(attempt)) return;
onFailure(error);
}
}

return {
async complete(params: URLSearchParams) {
if (!isCompleteOAuthResponse(params)) return;
const state = params.get("state")!;
// The OAuth client consumes state once, even when the callback route remounts.
const response = responses.get(state);
if (response) return response;

const pending = exchangeForAttempt(params);
responses.set(state, pending);
return pending;
},
};
}
24 changes: 24 additions & 0 deletions apps/amethyst/lib/atp/useOAuthCallback.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { useEffect } from "react";
import { isCompleteOAuthResponse } from "./latestOAuthCallback";

type RouteParams = Record<string, string | string[] | undefined>;

export function useOAuthCallback(
params: RouteParams,
complete: (response: URLSearchParams) => Promise<void>,
ready = true,
) {
useEffect(() => {
if (!ready) return;
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);
}
}

if (isCompleteOAuthResponse(response)) void complete(response);
}, [params, complete, ready]);
}
Loading
Loading