diff --git a/src/adapters/auth/external-session-adapter.ts b/src/adapters/auth/external-session-adapter.ts index 4ae2efc9..34a86321 100644 --- a/src/adapters/auth/external-session-adapter.ts +++ b/src/adapters/auth/external-session-adapter.ts @@ -22,7 +22,17 @@ export type ExternalSessionOwner = Readonly<{ binding: CredentialRequestBinding, context?: CredentialOperationContext, ): Promise; + /** + * Moves the state as `SessionGateway.recover` says before it settles: + * `"restored"` → `authenticated`, `"no-session"` → `unauthenticated`, a + * rejection leaves it. The transitions are listed on `SessionState`. + */ recoverSession(): Promise<"restored" | "no-session">; + /** + * The runtime read a server 401 as a session verdict (R-3.2). Move to + * `unauthenticated`, or to `recovery-pending` when the owner will try to + * restore the session itself (a refresh token). + */ notifyUnauthenticated(): void; }>; diff --git a/src/application/ports/auth-session-port.ts b/src/application/ports/auth-session-port.ts index e2f56f78..324a4e6e 100644 --- a/src/application/ports/auth-session-port.ts +++ b/src/application/ports/auth-session-port.ts @@ -1,3 +1,19 @@ +/** + * 1103/09-11. The owner of the session moves it; nothing else does. + * + * - `unauthenticated` → `authenticated`: a sign-in completed (after + * `beginSignIn`, often on the page load that returns from the sign-in). + * - `authenticated` → `recovery-pending`: the credential stopped working + * (a server 401, a failed refresh) and the owner can still try to restore it. + * - `authenticated` → `unauthenticated`: `signOut`, or a 401 nothing can + * restore. + * - `recovery-pending` → `authenticated` | `unauthenticated`: a recovery ended, + * the owner's own or `recover()`'s (see there). + * - any → `integration-failed`: the owner cannot work at all. + * + * Every change of state or subject notifies subscribers once, and each one + * fences server state, so a token refresh for the same user changes neither. + */ export type SessionState = | "authenticated" | "unauthenticated" @@ -27,6 +43,16 @@ export type SessionGateway = Readonly<{ * to keep existing owners working; the transport races the signal either way, * and a recovery that answers after the request already ended is observed but * never turned into a user-visible sign-out. + * + * 1103/09-11. The state is moved before the promise settles: + * + * - `"restored"`: the state is `authenticated`, with its subject. + * - `"no-session"`: the state is `unauthenticated` (or + * `integration-failed`). Never `recovery-pending`: the screen would keep + * offering a recovery that already said no. Presentation shows sign-in + * after this answer whatever the owner reports, until it next notifies. + * - rejects: the owner could not tell (network, timeout). The state is left + * as it was, so the user can try again. */ recover( context?: CredentialOperationContext, diff --git a/src/presentation/providers/session-provider.tsx b/src/presentation/providers/session-provider.tsx index 8fafa3d8..d74dd6de 100644 --- a/src/presentation/providers/session-provider.tsx +++ b/src/presentation/providers/session-provider.tsx @@ -1,6 +1,7 @@ import { createContext, useContext, + useEffect, useMemo, useState, useSyncExternalStore, @@ -27,18 +28,35 @@ export function SessionProvider({ children, }: Readonly<{ children: ReactNode }>) { const session = useApplicationSession(); - const sessionState = useSyncExternalStore( + const ownerState = useSyncExternalStore( session.subscribe, session.getSnapshot, session.getSnapshot, ); + // 1103/09-11. "no-session" means nobody is signed in. The contract + // (`SessionGateway.recover`) has the owner leave `recovery-pending` first; + // one that does not would keep offering a recovery that already said no, so + // the answer stands until the owner next notifies. + const [recoveryDeclined, setRecoveryDeclined] = useState(false); + useEffect( + () => session.subscribe(() => setRecoveryDeclined(false)), + [session], + ); + const sessionState: SessionState = + recoveryDeclined && ownerState === "recovery-pending" + ? "unauthenticated" + : ownerState; const value = useMemo( () => Object.freeze({ sessionState, beginSignIn: session.beginSignIn, signOut: session.signOut, - recover: session.recover, + async recover() { + const answer = await session.recover(); + if (answer === "no-session") setRecoveryDeclined(true); + return answer; + }, }), [session, sessionState], ); diff --git a/tests/component/session-recovery.test.tsx b/tests/component/session-recovery.test.tsx new file mode 100644 index 00000000..7a4815f5 --- /dev/null +++ b/tests/component/session-recovery.test.tsx @@ -0,0 +1,134 @@ +// @vitest-environment jsdom + +import { render, screen, waitFor, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, expect, it, vi } from "vitest"; + +import { + createExternalAuthSessionAdapter, + type ExternalSessionOwner, +} from "../../src/adapters/auth/external-session-adapter.ts"; +import type { SessionState } from "../../src/application/ports/auth-session-port.ts"; +import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx"; +import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx"; +import { AppRouter } from "../../src/presentation/routes/app-router.tsx"; +import { createTestApplication } from "../helpers/create-test-application.ts"; + +// Same test-only feature as router.test.tsx: `/fixture/items` is session-required. +vi.mock("../../src/.generated/product-feature-index.ts", async () => ({ + DECLARED_PRODUCT_FEATURE_IDS: ["fixture-feature"], + PRODUCT_FEATURE_MODULES: [(await import("../helpers/fixture-feature.tsx")).FIXTURE_FEATURE_MODULE], +})); +vi.mock("../../src/.generated/product-context-index.ts", async () => ({ + PRODUCT_CONTEXT_MODULES: [(await import("../helpers/fixture-feature.tsx")).FIXTURE_CONTEXT_MODULE], +})); + +/** + * An owner stuck in `recovery-pending`. `recoverSession` answers as given and, + * unless `moveTo` is set, leaves the state where it was — the contract breach + * 1103/09-11 is about. + */ +function recoveringOwner( + answer: "restored" | "no-session", + moveTo?: SessionState, +) { + let state: SessionState = "recovery-pending"; + const listeners = new Set<() => void>(); + const beginSignIn = vi.fn(async (_returnTo?: string) => {}); + const owner: ExternalSessionOwner = { + readState: () => state, + readSubject: () => (state === "authenticated" ? "user-1" : null), + subscribe(listener) { + listeners.add(listener); + return () => listeners.delete(listener); + }, + beginSignIn, + signOut: async () => {}, + attachCredential: async () => ({ headers: {} }), + async recoverSession() { + if (moveTo !== undefined) { + state = moveTo; + for (const listener of listeners) listener(); + } + return answer; + }, + notifyUnauthenticated() {}, + }; + return { + session: createExternalAuthSessionAdapter(owner), + beginSignIn, + setState(next: SessionState) { + state = next; + for (const listener of listeners) listener(); + }, + }; +} + +function renderAt(url: string, session: ReturnType["session"]) { + window.history.pushState({}, "", url); + return render( + + + + + , + ); +} + +const main = () => within(screen.getByRole("main")); + +describe("1103/09-11 the recovery button uses recover()'s answer", () => { + it("offers sign-in after no-session even when the owner stays recovery-pending", async () => { + const user = userEvent.setup(); + const owner = recoveringOwner("no-session"); + renderAt("/fixture/items", owner.session); + + await user.click(await main().findByRole("button", { name: "세션 복구" })); + + const signIn = await main().findByRole("button", { name: "로그인 시작" }); + expect(main().queryByRole("button", { name: "세션 복구" })).toBeNull(); + expect(screen.getByRole("heading", { name: "세션이 필요합니다.", level: 1 })).toBeVisible(); + await user.click(signIn); + expect(owner.beginSignIn).toHaveBeenCalledWith("/fixture/items"); + }); + + it("shows the owner's own state again once it notifies", async () => { + const user = userEvent.setup(); + const owner = recoveringOwner("no-session"); + renderAt("/fixture/items", owner.session); + await user.click(await main().findByRole("button", { name: "세션 복구" })); + await main().findByRole("button", { name: "로그인 시작" }); + + // A later 401 puts the owner back into recovery: that is a new question. + owner.setState("authenticated"); + owner.setState("recovery-pending"); + + await main().findByRole("button", { name: "세션 복구" }); + }); + + it("keeps an owner that follows the contract as it is", async () => { + const user = userEvent.setup(); + const owner = recoveringOwner("no-session", "unauthenticated"); + renderAt("/fixture/items", owner.session); + + await user.click(await main().findByRole("button", { name: "세션 복구" })); + + await main().findByRole("button", { name: "로그인 시작" }); + await waitFor(() => + expect(screen.getAllByText("로그인 전").length).toBeGreaterThan(0), + ); + }); + + it("does not offer sign-in after restored", async () => { + const user = userEvent.setup(); + const owner = recoveringOwner("restored", "authenticated"); + renderAt("/fixture/items", owner.session); + + await user.click(await main().findByRole("button", { name: "세션 복구" })); + + await waitFor(() => + expect(main().queryByRole("button", { name: "로그인 시작" })).toBeNull(), + ); + expect(main().queryByRole("button", { name: "세션 복구" })).toBeNull(); + }); +});