fix(auth): 세션 복구가 no-session이면 로그인 버튼을 보인다
문제: useSessionAction이 recover()의 결과를 버린다. owner가 "no-session"을 돌려주고 상태를 recovery-pending으로 두면 보호 라우트와 셸은 계속 "세션 복구" 버튼만 보이고, 로그인으로 갈 길이 없다. owner가 지켜야 할 상태 전이도 어디에도 적혀 있지 않아 owner 작성자가 화면 코드를 읽고 추론해야 했다. 고른 방법: 두 가지를 함께 한다. - SessionState·SessionGateway.recover·ExternalSessionOwner에 전이 계약을 적는다. restored면 authenticated, no-session이면 unauthenticated(또는 integration-failed), reject면 상태 유지. - SessionProvider가 recover()의 답을 쓴다. no-session을 받았는데 owner가 아직 recovery-pending이면, owner가 다음에 알릴 때까지 화면에 unauthenticated로 보인다. 그래서 라우트 문과 셸 모두 로그인 버튼을 보인다. 버린 대안: 어댑터가 전이를 검사해 throw. 그러면 화면은 "작업 실패"만 보이고 여전히 로그인 버튼이 없다. 어댑터가 상태를 덮어쓰는 것은 구독 알림을 새로 만들어야 해서 scope fence와 얽힌다. 위험·한계: 계약을 어기는 owner의 상태를 화면에서만 바로잡는다. application·scope fence는 owner의 상태를 그대로 본다. 검증: tests/component/session-recovery.test.tsx 4건(수정 전 2건 실패 확인), router·app-shell·route-status-surfaces·auth-session-adapter 테스트 통과, check:types, eslint 통과. Refs: docs/reviews/2026-11-03-maturity-review/09-app-core.md 09-11
This commit is contained in:
@@ -22,7 +22,17 @@ export type ExternalSessionOwner = Readonly<{
|
||||
binding: CredentialRequestBinding,
|
||||
context?: CredentialOperationContext,
|
||||
): Promise<CredentialPatch>;
|
||||
/**
|
||||
* 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;
|
||||
}>;
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<SessionContextValue>(
|
||||
() =>
|
||||
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],
|
||||
);
|
||||
|
||||
@@ -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<typeof recoveringOwner>["session"]) {
|
||||
window.history.pushState({}, "", url);
|
||||
return render(
|
||||
<ApplicationProvider application={createTestApplication({ session })}>
|
||||
<PreferenceProviders>
|
||||
<AppRouter />
|
||||
</PreferenceProviders>
|
||||
</ApplicationProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user