diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c96983..aabab6a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] ### Added +- **Unit tests for the device-authorize state machine.** Extracted the + 8-phase `Phase` union from `AuthorizeDeviceClient` into a pure + `phaseReducer` function so every transition can be verified without + React, the DOM, or Better Auth mocks. Adds 20 reducer unit tests + (100% branch coverage) and 15 thin integration tests covering the + effect derivation, providers-prop rendering, and async handler + dispatch sites. Also wires up `@vitejs/plugin-react` + jsdom so + future component tests in `apps/web` have a working harness. - **Branded HTML magic-link email.** The sign-in email is now a React Email component (`apps/web/emails/sign-in-magic-link.tsx`) matching the editorial-technical look of the site — helpbase wordmark, near- diff --git a/apps/web/app/device/AuthorizeDeviceClient.test.tsx b/apps/web/app/device/AuthorizeDeviceClient.test.tsx new file mode 100644 index 0000000..8e2669b --- /dev/null +++ b/apps/web/app/device/AuthorizeDeviceClient.test.tsx @@ -0,0 +1,425 @@ +/* @vitest-environment jsdom */ + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" +import { cleanup, render, screen, waitFor } from "@testing-library/react" +import userEvent from "@testing-library/user-event" +import "@testing-library/jest-dom/vitest" + +// Vitest 4 doesn't wire RTL's afterEach cleanup by default — renders +// accumulate in document.body across tests without this. +afterEach(() => { + cleanup() +}) + +/** + * Integration layer for AuthorizeDeviceClient. The pure transition + * logic is covered by phase-reducer.test.ts — these tests verify + * (a) the useReducer is wired up to the effect + dispatch sites, + * (b) provider-prop rendering respects the availability map, + * (c) async handlers dispatch the expected actions on success + error. + * + * Only the minimum set of flows is covered here. Add a new reducer + * test before adding another integration test. + */ + +// Module-level stubs — tests override behavior per-case. +// Types left inferred rather than using generic `vi.fn<...>()` because the +// `<[],` syntax trips rolldown's JSX parser in .tsx files. +const mockUseSession = vi.fn() +const mockSignInMagicLink = vi.fn() +const mockSignInSocial = vi.fn() +const mockDeviceApprove = vi.fn() +const mockDeviceDeny = vi.fn() + +vi.mock("better-auth/react", () => ({ + createAuthClient: () => ({ + useSession: mockUseSession, + signIn: { + magicLink: mockSignInMagicLink, + social: mockSignInSocial, + }, + device: { + approve: mockDeviceApprove, + deny: mockDeviceDeny, + }, + }), +})) + +vi.mock("better-auth/client/plugins", () => ({ + magicLinkClient: () => ({}), + deviceAuthorizationClient: () => ({}), +})) + +// Import AFTER mocks so the module-level createAuthClient() call +// picks up the stub. +const { AuthorizeDeviceClient } = await import("./AuthorizeDeviceClient") + +beforeEach(() => { + mockUseSession.mockReset() + mockSignInMagicLink.mockReset() + mockSignInSocial.mockReset() + mockDeviceApprove.mockReset() + mockDeviceDeny.mockReset() +}) + +const bothProviders = { google: true, github: true } as const +const noProviders = { google: false, github: false } as const + +describe("AuthorizeDeviceClient — derivation", () => { + it("renders the loading placeholder while session is pending", () => { + mockUseSession.mockReturnValue({ data: null, isPending: true }) + render( + , + ) + expect(screen.getByText(/checking session/i)).toBeInTheDocument() + }) + + it("routes to signed-out when the user has no session", async () => { + mockUseSession.mockReturnValue({ data: null, isPending: false }) + render( + , + ) + expect( + await screen.findByRole("button", { name: /send sign-in link/i }), + ).toBeInTheDocument() + }) + + it("routes to signed-in when session + userCode present", async () => { + mockUseSession.mockReturnValue({ + data: { user: { email: "x@y.com" } }, + isPending: false, + }) + render( + , + ) + expect(await screen.findByRole("button", { name: /authorize/i })) + .toBeInTheDocument() + expect(screen.getByText(/signed in as/i)).toBeInTheDocument() + expect(screen.getByText("x@y.com")).toBeInTheDocument() + expect(screen.getByText("ABCD-EFGH")).toBeInTheDocument() + }) +}) + +describe("AuthorizeDeviceClient — providers prop", () => { + beforeEach(() => { + mockUseSession.mockReturnValue({ data: null, isPending: false }) + }) + + it("renders both OAuth buttons when both providers are enabled", async () => { + render( + , + ) + expect( + await screen.findByRole("button", { name: /continue with google/i }), + ).toBeInTheDocument() + expect( + screen.getByRole("button", { name: /continue with github/i }), + ).toBeInTheDocument() + expect(screen.getByText(/new provider or email/i)).toBeInTheDocument() + }) + + it("hides OAuth buttons and divider when no providers are enabled", async () => { + render( + , + ) + await screen.findByRole("button", { name: /send sign-in link/i }) + expect( + screen.queryByRole("button", { name: /continue with google/i }), + ).not.toBeInTheDocument() + expect( + screen.queryByRole("button", { name: /continue with github/i }), + ).not.toBeInTheDocument() + expect(screen.getByText(/new email creates one/i)).toBeInTheDocument() + }) + + it("renders only the enabled provider when one is configured", async () => { + render( + , + ) + expect( + await screen.findByRole("button", { name: /continue with google/i }), + ).toBeInTheDocument() + expect( + screen.queryByRole("button", { name: /continue with github/i }), + ).not.toBeInTheDocument() + }) +}) + +describe("AuthorizeDeviceClient — magic-link handler", () => { + beforeEach(() => { + mockUseSession.mockReturnValue({ data: null, isPending: false }) + }) + + it("dispatches MAGIC_LINK_SENT on success and shows the email-sent screen", async () => { + mockSignInMagicLink.mockResolvedValue({ error: null }) + const user = userEvent.setup() + render( + , + ) + const emailInput = await screen.findByPlaceholderText("you@company.com") + await user.type(emailInput, "x@y.com") + await user.click(screen.getByRole("button", { name: /send sign-in link/i })) + + await waitFor(() => { + expect(mockSignInMagicLink).toHaveBeenCalledWith({ + email: "x@y.com", + callbackURL: "/device?user_code=ABCD-EFGH", + }) + }) + // Assert unique email-sent copy. The prior /check/i regex also matched + // "Checking session…" on the loading screen, so it was false-confidence. + expect( + await screen.findByText(/for your.*sign-in link/i), + ).toBeInTheDocument() + expect(screen.getByText("x@y.com")).toBeInTheDocument() + }) + + it("dispatches ERROR when magic-link returns an error", async () => { + mockSignInMagicLink.mockResolvedValue({ + error: { message: "Rate limited" }, + }) + const user = userEvent.setup() + render( + , + ) + const emailInput = await screen.findByPlaceholderText("you@company.com") + await user.type(emailInput, "x@y.com") + await user.click(screen.getByRole("button", { name: /send sign-in link/i })) + + expect(await screen.findByText("Rate limited")).toBeInTheDocument() + expect( + screen.getByRole("button", { name: /try again/i }), + ).toBeInTheDocument() + }) +}) + +describe("AuthorizeDeviceClient — social sign-in handler", () => { + beforeEach(() => { + mockUseSession.mockReturnValue({ data: null, isPending: false }) + }) + + it("calls signIn.social with the chosen provider and preserved userCode", async () => { + // Never resolves — simulates the browser starting its OAuth redirect. + mockSignInSocial.mockImplementation(() => new Promise(() => {})) + const user = userEvent.setup() + render( + , + ) + await user.click( + await screen.findByRole("button", { name: /continue with google/i }), + ) + await waitFor(() => { + expect(mockSignInSocial).toHaveBeenCalledWith({ + provider: "google", + callbackURL: "/device?user_code=ABCD-EFGH", + }) + }) + }) + + it("dispatches ERROR when signIn.social throws", async () => { + mockSignInSocial.mockRejectedValue(new Error("OAuth config bad")) + const user = userEvent.setup() + render( + , + ) + await user.click( + await screen.findByRole("button", { name: /continue with github/i }), + ) + expect(await screen.findByText("OAuth config bad")).toBeInTheDocument() + }) + + it("disables all sign-in surfaces while a social redirect is in flight", async () => { + // Prevents a user double-clicking Google (or clicking GitHub mid-flight) + // and firing two concurrent OAuth redirects. The component gates + // everything on `socialBusy || submitting`. + mockSignInSocial.mockImplementation(() => new Promise(() => {})) + const user = userEvent.setup() + render( + , + ) + await user.click( + await screen.findByRole("button", { name: /continue with google/i }), + ) + await waitFor(() => { + // Label flips to "Redirecting…" once the submit starts. + expect( + screen.getByRole("button", { name: /redirecting…/i }), + ).toBeDisabled() + }) + expect( + screen.getByRole("button", { name: /continue with github/i }), + ).toBeDisabled() + expect( + screen.getByRole("button", { name: /send sign-in link/i }), + ).toBeDisabled() + }) +}) + +describe("AuthorizeDeviceClient — approve/deny handlers", () => { + beforeEach(() => { + mockUseSession.mockReturnValue({ + data: { user: { email: "x@y.com" } }, + isPending: false, + }) + }) + + it("dispatches APPROVE_SUCCEEDED and shows the approved screen", async () => { + mockDeviceApprove.mockResolvedValue({ error: null }) + const user = userEvent.setup() + render( + , + ) + await user.click( + await screen.findByRole("button", { name: /^authorize$/i }), + ) + expect( + await screen.findByText(/return to your terminal/i), + ).toBeInTheDocument() + expect(mockDeviceApprove).toHaveBeenCalledWith({ userCode: "ABCD-EFGH" }) + }) + + it("dispatches ERROR with RFC error_description on access_denied", async () => { + mockDeviceApprove.mockResolvedValue({ + error: { error: "access_denied", error_description: "User said no" }, + }) + const user = userEvent.setup() + render( + , + ) + await user.click( + await screen.findByRole("button", { name: /^authorize$/i }), + ) + expect(await screen.findByText("User said no")).toBeInTheDocument() + }) + + it("falls back to generic copy when RFC error has no description", async () => { + mockDeviceApprove.mockResolvedValue({ + error: { error: "server_error" }, + }) + const user = userEvent.setup() + render( + , + ) + await user.click( + await screen.findByRole("button", { name: /^authorize$/i }), + ) + expect( + await screen.findByText(/authorization failed/i), + ).toBeInTheDocument() + }) + + it("swallows thrown errors from deny and still shows the denied screen", async () => { + mockDeviceDeny.mockRejectedValue(new Error("network blip")) + const user = userEvent.setup() + render( + , + ) + await user.click(await screen.findByRole("button", { name: /cancel/i })) + expect(await screen.findByText(/cancelled/i)).toBeInTheDocument() + }) + + it("disables both Authorize and Cancel buttons while approve is in flight", async () => { + // Never-resolving mock keeps us in the approving phase so we can + // assert the disabled state. Prevents a user from double-clicking + // Authorize OR pressing Cancel mid-flight, which would dispatch + // DENIED on top of an in-flight approve. + mockDeviceApprove.mockImplementation(() => new Promise(() => {})) + const user = userEvent.setup() + render( + , + ) + const authorize = await screen.findByRole("button", { name: /^authorize$/i }) + const cancel = screen.getByRole("button", { name: /cancel/i }) + await user.click(authorize) + await waitFor(() => { + expect( + screen.getByRole("button", { name: /authorizing…/i }), + ).toBeDisabled() + }) + expect(cancel).toBeDisabled() + }) +}) + +describe("AuthorizeDeviceClient — Try again button", () => { + it("routes back to signed-in when session is still valid", async () => { + mockUseSession.mockReturnValue({ + data: { user: { email: "x@y.com" } }, + isPending: false, + }) + mockDeviceApprove.mockResolvedValue({ + error: { error: "server_error", error_description: "boom" }, + }) + const user = userEvent.setup() + render( + , + ) + // Enter the error state via a failed approve… + await user.click( + await screen.findByRole("button", { name: /^authorize$/i }), + ) + await user.click( + await screen.findByRole("button", { name: /try again/i }), + ) + // …and confirm we're back on the signed-in surface. + expect( + await screen.findByRole("button", { name: /^authorize$/i }), + ).toBeInTheDocument() + }) + + // Note: the reverse case — "Try again with no session routes to + // signed-out" — is covered by the pure reducer test. Reaching that + // state from the integration layer is impossible in practice because + // a session change makes the useEffect re-run SESSION_RESOLVED, + // which overrides the error phase before the user can click. +}) diff --git a/apps/web/app/device/AuthorizeDeviceClient.tsx b/apps/web/app/device/AuthorizeDeviceClient.tsx index baa28e3..2766bce 100644 --- a/apps/web/app/device/AuthorizeDeviceClient.tsx +++ b/apps/web/app/device/AuthorizeDeviceClient.tsx @@ -1,8 +1,9 @@ "use client" -import { useEffect, useState, type FormEvent } from "react" +import { useEffect, useReducer, useState, type FormEvent } from "react" import { createAuthClient } from "better-auth/react" import { magicLinkClient, deviceAuthorizationClient } from "better-auth/client/plugins" +import { initialPhase, phaseReducer } from "./phase-reducer" // Inline the auth client here (one consumer, one module) to side-step // TS's "inferred type cannot be named" portability complaint on the @@ -13,16 +14,6 @@ const authClient = createAuthClient({ plugins: [magicLinkClient(), deviceAuthorizationClient()], }) -type Phase = - | { kind: "loading" } - | { kind: "signed-out" } - | { kind: "email-sent"; email: string } - | { kind: "signed-in"; email: string; userCode: string } - | { kind: "approving" } - | { kind: "approved"; email: string } - | { kind: "denied" } - | { kind: "error"; message: string } - export interface ProviderAvailability { google: boolean github: boolean @@ -37,30 +28,22 @@ export function AuthorizeDeviceClient({ }) { const { data: session, isPending: sessionPending } = authClient.useSession() const [userCode, setUserCode] = useState(initialUserCode) - const [phase, setPhase] = useState({ kind: "loading" }) + const [phase, dispatch] = useReducer(phaseReducer, initialPhase) const [email, setEmail] = useState("") const [submitting, setSubmitting] = useState(false) const [socialSubmitting, setSocialSubmitting] = useState<"google" | "github" | null>(null) // Derive the UI phase from session state + URL-provided user_code. + // Transition rules live in ./phase-reducer so they're unit-testable + // without React + DOM. Here we just hand the reducer the raw inputs. useEffect(() => { if (sessionPending) { - setPhase({ kind: "loading" }) - return - } - if (!userCode) { - // No user_code on the URL — show an input. Rare path; the CLI - // always provides verification_uri_complete which carries it. - setPhase({ kind: "signed-out" }) - return - } - if (!session?.user) { - setPhase({ kind: "signed-out" }) + dispatch({ type: "SESSION_LOADING" }) return } - setPhase({ - kind: "signed-in", - email: session.user.email ?? "", + dispatch({ + type: "SESSION_RESOLVED", + session: session ?? null, userCode, }) }, [sessionPending, session, userCode]) @@ -80,8 +63,8 @@ export function AuthorizeDeviceClient({ // through to the catch. } catch (err) { setSocialSubmitting(null) - setPhase({ - kind: "error", + dispatch({ + type: "ERROR", message: err instanceof Error ? err.message : String(err), }) } @@ -100,16 +83,16 @@ export function AuthorizeDeviceClient({ callbackURL: callback, }) if (error) { - setPhase({ - kind: "error", + dispatch({ + type: "ERROR", message: error.message ?? "Couldn't send sign-in email.", }) } else { - setPhase({ kind: "email-sent", email }) + dispatch({ type: "MAGIC_LINK_SENT", email }) } } catch (err) { - setPhase({ - kind: "error", + dispatch({ + type: "ERROR", message: err instanceof Error ? err.message : String(err), }) } finally { @@ -118,26 +101,26 @@ export function AuthorizeDeviceClient({ } async function handleApprove() { - setPhase({ kind: "approving" }) + dispatch({ type: "APPROVE_STARTED" }) try { const { error } = await authClient.device.approve({ userCode }) if (error) { // device.approve returns RFC-8628-shaped error codes // ("access_denied", "expired_token", etc.) rather than a plain // message field. error_description is the human-readable text. - setPhase({ - kind: "error", + dispatch({ + type: "ERROR", message: error.error_description ?? "Authorization failed.", }) return } - setPhase({ - kind: "approved", + dispatch({ + type: "APPROVE_SUCCEEDED", email: session?.user?.email ?? "", }) } catch (err) { - setPhase({ - kind: "error", + dispatch({ + type: "ERROR", message: err instanceof Error ? err.message : String(err), }) } @@ -149,7 +132,7 @@ export function AuthorizeDeviceClient({ } catch { // best-effort — regardless, we show the denied screen } - setPhase({ kind: "denied" }) + dispatch({ type: "DENIED" }) } if (phase.kind === "loading") { @@ -313,17 +296,13 @@ export function AuthorizeDeviceClient({

{phase.message}