From d7c6cb4fd25c1119e162f20813fe9742d97a3cd8 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:23:22 +0900 Subject: [PATCH 1/4] =?UTF-8?q?fix(auth):=20=EC=84=B8=EC=85=98=20=EB=B3=B5?= =?UTF-8?q?=EA=B5=AC=EA=B0=80=20no-session=EC=9D=B4=EB=A9=B4=20=EB=A1=9C?= =?UTF-8?q?=EA=B7=B8=EC=9D=B8=20=EB=B2=84=ED=8A=BC=EC=9D=84=20=EB=B3=B4?= =?UTF-8?q?=EC=9D=B8=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 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 --- src/adapters/auth/external-session-adapter.ts | 10 ++ src/application/ports/auth-session-port.ts | 26 ++++ .../providers/session-provider.tsx | 22 ++- tests/component/session-recovery.test.tsx | 134 ++++++++++++++++++ 4 files changed, 190 insertions(+), 2 deletions(-) create mode 100644 tests/component/session-recovery.test.tsx 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(); + }); +}); From d02efe7bc9debde538e813d8f69f253a93f02df0 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:26:48 +0900 Subject: [PATCH 2/4] =?UTF-8?q?feat(bootstrap):=20=EC=84=B8=EC=85=98=20own?= =?UTF-8?q?er=20context=EC=97=90=20=EC=8B=9C=EA=B0=84=20=EC=A0=9C=ED=95=9C?= =?UTF-8?q?=20=EC=9E=88=EB=8A=94=20fetch=EC=99=80=20=ED=8E=98=EC=9D=B4?= =?UTF-8?q?=EC=A7=80=EB=A5=BC=20=EC=A4=80=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: composeProductSessionOwner는 config와 raw fetcher만 받는다. owner는 http보다 먼저 만들어져 세션 조회·토큰 호출을 직접 해야 하는데, 응답하지 않는 호출 하나가 세션을 recovery-pending에 영원히 둔다. 픽스처의 쿠키 owner 스케치가 바로 그렇게 쓴다. 로그인 리다이렉트에 필요한 페이지 (location·history)와 sessionStorage도 bootstrap lint가 전역 접근을 막아 제품 파일에서 얻을 길이 없다. 고른 방법: ProductSessionOwnerContext에 넷을 더한다. - fetch: 헤더와 본문 전체에 마감 하나(REQUEST_TIMEOUT_MS가 상한, 호출이 줄일 수만 있다). 본문은 64 KiB까지 메모리로 읽어 새 Response로 준다. redirect는 항상 error. fetcher가 signal을 무시해도 경합으로 끝난다. - readCookie: composeProduct와 같은 host cookie 읽기. - page: href·replaceUrl·assign. host에 없으면 throw로 닫힌다. replaceUrl은 라우터의 history state를 그대로 둔다. - redirectStorage: host sessionStorage. 토큰이 아니라 리다이렉트 한 번 동안의 상태만 둔다고 계약에 적었다. 조립은 새 파일 product-session-owner-context.ts에 두고 runtime-adapters.ts는 호출 한 곳만 바꿨다. fetch 구현 (session-owner-fetch.ts)은 처음 쓸 때 동적 import로 읽는다. 초기 번들 여유가 3 KB 남짓이라 demo 모드나 owner 없는 제품이 이 코드를 내려받지 않게 했다. 버린 대안: - platform 커널 createAbortableOperation 사용. 커널이 boot가 이미 읽는 배럴과 같은 청크로 묶여 지연 청크로 빼도 초기 번들에 남았다(빌드로 확인). 그래서 read-bounded-boot-json.ts와 같은 마감 방식을 쓴다. - 마감만 주고 본문은 owner가 읽게 두기. 본문이 멈추면 다시 무한 대기다. 위험·한계: fetch는 필수 필드라 ProductSessionOwnerContext를 직접 만드는 제품 테스트는 컴파일이 깨진다. 기존 fetcher는 그대로 둔다. 지연 청크 적재 시간은 마감에 들어가지 않는다(라우트 청크와 같다). 검증: tests/unit/product-session-owner-context.test.ts 12건(구현 전 모듈 없음으로 실패 확인), product-composition-fixture·runtime-adapters 테스트 통과, check:types, eslint 통과. build + check:bundle: initial JS 202,242 / 204,800 B gzip(09-11 포함, 기준 201,848), 지연 청크 session-owner-fetch 0.81 kB gzip. Refs: docs/reviews/2026-11-03-maturity-review/09-app-core.md 09-03 --- src/bootstrap/product-composition-contract.ts | 34 +++ .../product-session-owner-context.ts | 102 +++++++ src/bootstrap/runtime-adapters.ts | 14 +- src/bootstrap/session-owner-fetch.ts | 134 +++++++++ .../product-session-owner-context.test.ts | 273 ++++++++++++++++++ 5 files changed, 553 insertions(+), 4 deletions(-) create mode 100644 src/bootstrap/product-session-owner-context.ts create mode 100644 src/bootstrap/session-owner-fetch.ts create mode 100644 tests/unit/product-session-owner-context.test.ts diff --git a/src/bootstrap/product-composition-contract.ts b/src/bootstrap/product-composition-contract.ts index 0f5190b3..747967b9 100644 --- a/src/bootstrap/product-composition-contract.ts +++ b/src/bootstrap/product-composition-contract.ts @@ -12,6 +12,28 @@ import type { RuntimeConfig } from "./runtime-config-schema.ts"; * profiles and runtime-config keys) and never edits `runtime-adapters.ts`. */ +/** + * 1103/09-03. A fetch with one deadline over the whole exchange (at most + * `REQUEST_TIMEOUT_MS`; `timeoutMs` may shorten it) and the body read into + * memory, at most 64 KiB. Rejects with a `TimeoutError` or `AbortError` + * DOMException, or a `RangeError` for a larger body. Redirects are refused. + */ +export type SessionOwnerFetch = ( + input: string | URL, + init?: Omit & + Readonly<{ signal?: AbortSignal; timeoutMs?: number }>, +) => Promise; + +/** The page a sign-in redirect leaves and returns to. Each throws without one. */ +export type ProductSessionOwnerPage = Readonly<{ + /** The current URL. */ + href(): string; + /** Replaces the current entry without loading, e.g. to drop a sign-in callback query. */ + replaceUrl(url: string): void; + /** Loads another page: the identity provider's sign-in or sign-out. */ + assign(url: string): void; +}>; + /** * What a product session owner is built from. It is asked first, before * `http` exists (`http` needs the session), so it gets no capability. @@ -19,7 +41,19 @@ import type { RuntimeConfig } from "./runtime-config-schema.ts"; export type ProductSessionOwnerContext = Readonly<{ /** Validated runtime config, product keys included. */ config: RuntimeConfig; + /** Unbounded; prefer `fetch`. */ fetcher?: typeof fetch; + /** 1103/09-03. Use this one: a probe or token call cannot hang the session. */ + fetch: SessionOwnerFetch; + /** A cookie of the page (double-submit CSRF), read when called. */ + readCookie(name: string): string | undefined; + page: ProductSessionOwnerPage; + /** + * The page's session storage, when there is one: what must survive a + * sign-in redirect and nothing longer. Never a token (`AUTH_TOKEN` is + * `forbidden` in `src/contracts/storage-keys.ts`). + */ + redirectStorage?: Pick; }>; /** diff --git a/src/bootstrap/product-session-owner-context.ts b/src/bootstrap/product-session-owner-context.ts new file mode 100644 index 00000000..7014c542 --- /dev/null +++ b/src/bootstrap/product-session-owner-context.ts @@ -0,0 +1,102 @@ +import type { + ProductSessionOwnerContext, + ProductSessionOwnerPage, + SessionOwnerFetch, +} from "./product-composition-contract.ts"; +import type { RuntimeConfig } from "./runtime-config-schema.ts"; + +/** + * 1103/09-03. What the composition root hands a product session owner. The + * owner is asked at boot, before `http` exists, so it talks to its session + * endpoint or identity provider itself; these are the host facilities it needs + * for that, each bounded or fail-closed. + */ + +/** + * `session-owner-fetch.ts` on first use. The initial bundle has no headroom + * for code only an external-mode product owner runs; the chunk is the size of + * a route chunk and loads the same way. + */ +function lazySessionOwnerFetch( + options: Readonly<{ fetcher?: typeof fetch; timeoutMs: number }>, +): SessionOwnerFetch { + let loaded: Promise | null = null; + return (input, init) => { + loaded ??= import("./session-owner-fetch.ts").then( + ({ createSessionOwnerFetch }) => createSessionOwnerFetch(options), + (error: unknown) => { + loaded = null; + throw error; + }, + ); + return loaded.then((bounded) => bounded(input, init)); + }; +} + +function hostMember(target: unknown, name: string): unknown { + if (!target || typeof target !== "object") return undefined; + try { + return Reflect.get(target, name); + } catch { + return undefined; + } +} + +/** + * The page, read from the host when called. A host without `location` or + * `history` (a worker, a test) throws, so an owner that needs the page fails + * closed instead of signing in somewhere else. + */ +function hostPage(host: Record): ProductSessionOwnerPage { + const unavailable = (): never => { + throw new TypeError("The page is unavailable to the session owner."); + }; + const location = () => hostMember(host, "location"); + return Object.freeze({ + href() { + const href = hostMember(location(), "href"); + return typeof href === "string" ? href : unavailable(); + }, + replaceUrl(url: string) { + const history = hostMember(host, "history"); + const replaceState = hostMember(history, "replaceState"); + if (typeof replaceState !== "function") unavailable(); + // The router keeps its own entry state; replacing it would lose its index. + Reflect.apply(replaceState as (...args: unknown[]) => void, history, [ + hostMember(history, "state") ?? null, + "", + url, + ]); + }, + assign(url: string) { + const page = location(); + const assign = hostMember(page, "assign"); + if (typeof assign !== "function") unavailable(); + Reflect.apply(assign as (url: string) => void, page, [url]); + }, + }); +} + +export function createProductSessionOwnerContext( + host: Record, + input: Readonly<{ + config: RuntimeConfig; + fetcher?: typeof fetch; + readCookie(name: string): string | undefined; + redirectStorage?: Storage; + }>, +): ProductSessionOwnerContext { + return Object.freeze({ + config: input.config, + ...(input.fetcher === undefined ? {} : { fetcher: input.fetcher }), + fetch: lazySessionOwnerFetch({ + ...(input.fetcher === undefined ? {} : { fetcher: input.fetcher }), + timeoutMs: input.config.REQUEST_TIMEOUT_MS, + }), + readCookie: input.readCookie, + page: hostPage(host), + ...(input.redirectStorage === undefined + ? {} + : { redirectStorage: input.redirectStorage }), + }); +} diff --git a/src/bootstrap/runtime-adapters.ts b/src/bootstrap/runtime-adapters.ts index d419621b..fc9d8e57 100644 --- a/src/bootstrap/runtime-adapters.ts +++ b/src/bootstrap/runtime-adapters.ts @@ -63,6 +63,7 @@ import { composeProductSessionOwner, } from "./product-composition.ts"; import type { ProductComposition } from "./product-composition-contract.ts"; +import { createProductSessionOwnerContext } from "./product-session-owner-context.ts"; import { createInstalledContractRegistry } from "../features/installed-contract-contributions.ts"; import { indexInvalidationRegistry, @@ -284,10 +285,15 @@ export async function createRuntimeAdapters( const externalOwner = config.AUTH_MODE === "demo" ? null - : (composeProductSessionOwner({ - config, - ...(context.fetcher === undefined ? {} : { fetcher: context.fetcher }), - }) ?? externalOwnerFrom(host)); + : (composeProductSessionOwner( + // 1103/09-03. A bounded fetch, the page and its cookies. + createProductSessionOwnerContext(host, { + config, + ...(context.fetcher === undefined ? {} : { fetcher: context.fetcher }), + readCookie: (name) => hostCookie(host, name), + redirectStorage: storageOrUndefined(hostValue(host, "sessionStorage")), + }), + ) ?? externalOwnerFrom(host)); const authSession = config.AUTH_MODE === "demo" ? createDemoSessionAdapter() diff --git a/src/bootstrap/session-owner-fetch.ts b/src/bootstrap/session-owner-fetch.ts new file mode 100644 index 00000000..e775456e --- /dev/null +++ b/src/bootstrap/session-owner-fetch.ts @@ -0,0 +1,134 @@ +import type { SessionOwnerFetch } from "./product-composition-contract.ts"; + +/** + * 1103/09-03. The fetch a product session owner gets. Loaded on first use, + * from `product-session-owner-context.ts`, so it costs the initial bundle + * nothing in demo mode or without a product owner. It does not use the + * platform kernel's `createAbortableOperation`: the kernel shares a chunk + * with the barrel boot already imports, so it would land in the initial + * bundle after all. The deadline is the one `read-bounded-boot-json.ts` uses. + */ + +/** A session or token response is a few KiB; this is the most an owner buffers. */ +export const SESSION_OWNER_FETCH_MAXIMUM_BYTES = 65_536; + +/** Statuses whose `Response` cannot carry a body. */ +const NULL_BODY_STATUSES: ReadonlySet = new Set([101, 103, 204, 205, 304]); + +/** + * One deadline over the whole exchange, headers and body. The body is read + * into memory up to `maximumBytes` and handed back as a fresh `Response`, so + * the owner reads it without a second, unbounded wait. `timeoutMs` is a + * ceiling: a call may shorten it, never extend it. Redirects are refused: a + * session endpoint that redirects to a sign-in page must not read as an + * answer. + */ +export function createSessionOwnerFetch( + options: Readonly<{ + fetcher?: typeof fetch; + timeoutMs: number; + maximumBytes?: number; + }>, +): SessionOwnerFetch { + const fetcher = options.fetcher ?? fetch; + const maximumBytes = options.maximumBytes ?? SESSION_OWNER_FETCH_MAXIMUM_BYTES; + return async (input, init = {}) => { + const { signal, timeoutMs, ...request } = init; + const controller = new AbortController(); + let timedOut = false; + const timer = setTimeout( + () => { + timedOut = true; + controller.abort(); + }, + Math.min(timeoutMs ?? options.timeoutMs, options.timeoutMs), + ); + const forwardAbort = () => controller.abort(); + if (signal?.aborted) controller.abort(); + else signal?.addEventListener("abort", forwardAbort, { once: true }); + // Raced, not only signalled: a fetcher that ignores the signal is still + // bounded, and so is a body stream that stops sending. + const stopped = new Promise((_, reject) => { + const stop = () => + reject( + timedOut + ? new DOMException("The session owner request timed out.", "TimeoutError") + : new DOMException("The session owner request was aborted.", "AbortError"), + ); + if (controller.signal.aborted) stop(); + else controller.signal.addEventListener("abort", stop, { once: true }); + }); + stopped.catch(() => undefined); + const sending = Promise.resolve().then(() => + fetcher(input, { + cache: "no-store", + ...request, + redirect: "error", + signal: controller.signal, + }), + ); + // A response that lands after the deadline is released, not left open. + void sending.then( + (late) => { + if (controller.signal.aborted) void late.body?.cancel().catch(() => undefined); + }, + () => undefined, + ); + try { + const response = await Promise.race([sending, stopped]); + const reading = readBody(response, maximumBytes, controller.signal); + reading.catch(() => undefined); + const bytes = await Promise.race([reading, stopped]); + return new Response(NULL_BODY_STATUSES.has(response.status) ? null : bytes, { + status: response.status, + statusText: response.statusText, + headers: response.headers, + }); + } finally { + clearTimeout(timer); + signal?.removeEventListener("abort", forwardAbort); + } + }; +} + +async function readBody( + response: Response, + maximumBytes: number, + signal: AbortSignal, +): Promise> { + const declared = Number(response.headers.get("content-length")); + if (Number.isFinite(declared) && declared > maximumBytes) { + void response.body?.cancel().catch(() => undefined); + throw new RangeError("The session owner response is too large."); + } + const body = response.body; + if (!body) return new Uint8Array(0); + const reader = body.getReader(); + // The deadline releases the stream even when the fetcher ignored the signal. + signal.addEventListener("abort", () => void reader.cancel().catch(() => undefined), { + once: true, + }); + const chunks: Uint8Array[] = []; + let total = 0; + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + total += value.byteLength; + if (total > maximumBytes) { + throw new RangeError("The session owner response is too large."); + } + chunks.push(value); + } + } catch (error) { + void reader.cancel().catch(() => undefined); + throw error; + } + const bytes = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + return bytes; +} diff --git a/tests/unit/product-session-owner-context.test.ts b/tests/unit/product-session-owner-context.test.ts new file mode 100644 index 00000000..769c4e3b --- /dev/null +++ b/tests/unit/product-session-owner-context.test.ts @@ -0,0 +1,273 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +import type { ProductSessionOwnerContext } from "../../src/bootstrap/product-composition-contract.ts"; +import { + createSessionOwnerFetch, + SESSION_OWNER_FETCH_MAXIMUM_BYTES, +} from "../../src/bootstrap/session-owner-fetch.ts"; +import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts"; +import { validateRuntimeConfig } from "../../src/bootstrap/runtime-config-schema.ts"; + +/** + * 1103/09-03. A session owner is asked for at boot, before `http` exists, and + * the shipped context gave it a raw `fetcher`: a session probe or a token call + * that never answered left the session `recovery-pending` for good. The + * context now carries a fetch with one deadline over the whole exchange. + */ + +const fixture = vi.hoisted(() => ({ + context: undefined as ProductSessionOwnerContext | undefined, +})); + +vi.mock("../../src/bootstrap/product-composition.ts", () => ({ + composeProductSessionOwner(context: ProductSessionOwnerContext) { + fixture.context = context; + return null; + }, + composeProduct: () => ({ capabilities: {}, credentialProviders: {} }), +})); + +const never = () => new Promise(() => {}); + +/** A body that sends one chunk and then nothing. */ +function stalledBody(): ReadableStream { + return new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode("{")); + }, + }); +} + +describe("createSessionOwnerFetch", () => { + it("answers with the whole body read, status and headers kept", async () => { + const fetcher = vi.fn(async () => + Response.json({ sub: "user-1" }, { status: 201, headers: { "x-extra": "1" } }), + ); + const bounded = createSessionOwnerFetch({ fetcher, timeoutMs: 1_000 }); + + const response = await bounded("https://idp.example/token", { + method: "POST", + credentials: "omit", + }); + + expect(response.status).toBe(201); + expect(response.headers.get("x-extra")).toBe("1"); + await expect(response.json()).resolves.toEqual({ sub: "user-1" }); + const [, init] = fetcher.mock.calls[0] as unknown as [string, RequestInit]; + expect(init).toMatchObject({ + method: "POST", + credentials: "omit", + cache: "no-store", + redirect: "error", + }); + expect(init.signal).toBeInstanceOf(AbortSignal); + }); + + it("refuses to follow a redirect even when asked", async () => { + const fetcher = vi.fn(async () => new Response("{}")); + const bounded = createSessionOwnerFetch({ fetcher, timeoutMs: 1_000 }); + + await bounded("https://api.example/session", { + redirect: "follow", + } as unknown as Parameters[1]); + + expect((fetcher.mock.calls[0] as unknown as [string, RequestInit])[1].redirect).toBe("error"); + }); + + it("times out a request that never answers", async () => { + const bounded = createSessionOwnerFetch({ fetcher: never, timeoutMs: 20 }); + + await expect(bounded("https://api.example/session")).rejects.toMatchObject({ + name: "TimeoutError", + }); + }); + + it("times out a body that stops arriving: the deadline covers the body", async () => { + const bounded = createSessionOwnerFetch({ + fetcher: async () => new Response(stalledBody()), + timeoutMs: 20, + }); + + await expect(bounded("https://api.example/session")).rejects.toMatchObject({ + name: "TimeoutError", + }); + }); + + it("lets one call shorten the deadline but never extend it", async () => { + const shorter = createSessionOwnerFetch({ fetcher: never, timeoutMs: 10_000 }); + const started = Date.now(); + await expect( + shorter("https://api.example/session", { timeoutMs: 20 }), + ).rejects.toMatchObject({ name: "TimeoutError" }); + expect(Date.now() - started).toBeLessThan(5_000); + + const capped = createSessionOwnerFetch({ fetcher: never, timeoutMs: 20 }); + await expect( + capped("https://api.example/session", { timeoutMs: 60_000 }), + ).rejects.toMatchObject({ name: "TimeoutError" }); + }); + + it("stops when the caller aborts", async () => { + const bounded = createSessionOwnerFetch({ fetcher: never, timeoutMs: 10_000 }); + const caller = new AbortController(); + + const pending = bounded("https://api.example/session", { signal: caller.signal }); + caller.abort(); + + await expect(pending).rejects.toMatchObject({ name: "AbortError" }); + }); + + it("refuses a body over the cap and cancels it", async () => { + const cancel = vi.fn(); + const chunk = new Uint8Array(SESSION_OWNER_FETCH_MAXIMUM_BYTES); + const body = new ReadableStream({ + pull(controller) { + controller.enqueue(chunk); + }, + cancel, + }); + const bounded = createSessionOwnerFetch({ + fetcher: async () => new Response(body), + timeoutMs: 1_000, + }); + + await expect(bounded("https://api.example/session")).rejects.toBeInstanceOf(RangeError); + expect(cancel).toHaveBeenCalled(); + }); + + it("passes the fetcher's own rejection through", async () => { + const bounded = createSessionOwnerFetch({ + fetcher: async () => { + throw new TypeError("Failed to fetch"); + }, + timeoutMs: 1_000, + }); + + await expect(bounded("https://api.example/session")).rejects.toThrow("Failed to fetch"); + }); + + it("answers a body-less status without a body", async () => { + const bounded = createSessionOwnerFetch({ + fetcher: async () => new Response(null, { status: 204 }), + timeoutMs: 1_000, + }); + + const response = await bounded("https://api.example/sign-out", { method: "POST" }); + + expect(response.status).toBe(204); + expect(response.body).toBeNull(); + }); +}); + +const CONFIG = { + APP_ENV: "local", + API_BASE_URL: "http://localhost:8080", + REQUEST_TIMEOUT_MS: 150, + TELEMETRY_ENABLED: false, + AUTH_MODE: "external", + CONFIG_SCHEMA_VERSION: "2.0", + RELEASE_MANIFEST_URL: "/release-manifest.json", + CAPABILITY_OVERRIDES: { + REALTIME: "DEFAULT", + WEB_WORKER: "DEFAULT", + SERVICE_WORKER: "DEFAULT", + OFFLINE_COMMANDS: "DEFAULT", + }, + FEATURE_OVERRIDES: {}, +} as const; + +describe("the session owner context the composition root builds", () => { + let dispose: (() => void) | undefined; + afterEach(() => { + dispose?.(); + dispose = undefined; + fixture.context = undefined; + }); + + async function compose(host: Record, fetcher: typeof fetch) { + const validated = validateRuntimeConfig(CONFIG); + if (!validated.success) throw new Error(JSON.stringify(validated.issues)); + const adapters = await createRuntimeAdapters({ + runtime: { + config: validated.data, + configSchema: "V2", + build: { + buildId: "build-a", + commitSha: "abc123", + routerBasePath: "/", + runtimeConfigUrl: "/config.json", + }, + validationDurationMs: 0, + }, + release: { + schemaVersion: 2, + appVersion: "0.1.0", + buildId: "build-a", + commitSha: "abc123", + configSchemaVersion: "2.0", + contractSet: { + setAlgorithm: "CA_CONTRACT_SET_V1", + setDigest: `sha256:${"0".repeat(64)}`, + packages: [], + }, + assetManifestHash: "hash-a", + releaseId: "release-a", + builtAt: "2026-07-25T00:00:00Z", + routeChunks: { "route-home": "assets/home.js" }, + }, + host, + fetcher, + }); + dispose = () => adapters.infrastructure.dispose(); + const context = fixture.context; + if (!context) throw new Error("the session owner was not asked"); + return context; + } + + it("bounds the owner's fetch by REQUEST_TIMEOUT_MS", async () => { + const context = await compose({}, never as unknown as typeof fetch); + + await expect(context.fetch("http://localhost:8080/session")).rejects.toMatchObject({ + name: "TimeoutError", + }); + }); + + it("reads the page, its session storage and its cookies through the host", async () => { + const replaceState = vi.fn(); + const assign = vi.fn(); + const storage = new Map(); + const sessionStorage = { + getItem: (key: string) => storage.get(key) ?? null, + setItem: (key: string, value: string) => void storage.set(key, value), + removeItem: (key: string) => void storage.delete(key), + }; + const context = await compose( + { + location: { href: "http://localhost:5173/callback?code=c&state=s", assign }, + history: { state: { idx: 3 }, replaceState }, + sessionStorage, + document: { cookie: "theme=dark; XSRF-TOKEN=xsrf-1" }, + }, + (async () => new Response("{}")) as unknown as typeof fetch, + ); + + expect(context.page.href()).toBe("http://localhost:5173/callback?code=c&state=s"); + context.page.replaceUrl("/items?limit=1"); + // The router's own history state is kept, so its index survives. + expect(replaceState).toHaveBeenCalledWith({ idx: 3 }, "", "/items?limit=1"); + context.page.assign("https://idp.example/auth"); + expect(assign).toHaveBeenCalledWith("https://idp.example/auth"); + context.redirectStorage?.setItem("k", "v"); + expect(storage.get("k")).toBe("v"); + expect(context.readCookie("XSRF-TOKEN")).toBe("xsrf-1"); + }); + + it("fails closed when the host has no page", async () => { + const context = await compose({}, (async () => new Response("{}")) as unknown as typeof fetch); + + expect(context.redirectStorage).toBeUndefined(); + expect(() => context.page.href()).toThrow("page is unavailable"); + expect(() => context.page.assign("https://idp.example/auth")).toThrow("page is unavailable"); + expect(context.readCookie("XSRF-TOKEN")).toBeUndefined(); + }); +}); From 05958bbdb639efafa3a46dd0bbcd63e7e48f488e Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:47:24 +0900 Subject: [PATCH 3/4] =?UTF-8?q?feat(recipes):=20=EC=A7=9D=20=EB=B0=B1?= =?UTF-8?q?=EC=97=94=EB=93=9C=20=EB=91=90=20=EC=9D=B8=EC=A6=9D=20=EB=AA=A8?= =?UTF-8?q?=EB=93=9C=EC=9D=98=20=EC=84=B8=EC=85=98=20owner=20recipe?= =?UTF-8?q?=EB=A5=BC=20=EB=8D=94=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: AUTH_MODE external은 제품이 owner 8개 메서드를 직접 써야 하는데, 짝 백엔드(JWT·Keycloak 또는 Redis session)에 맞는 owner가 src·recipes 어디에도 없다. 쿠키 owner 모양은 테스트 파일 안 스케치뿐이다. 그래서 제품마다 첫 연동 전에 토큰 획득·갱신·subject·상태 전이·401 처리를 처음부터 쓴다. 짝 백엔드(bbe944bd)에서 확인한 계약: - jwt 모드(기본): OAuth2 resource server. iss = APP_SECURITY_JWT_ISSUER (local http://localhost:8081/realms/ca-skeleton), aud 필수. CSRF·세션 없음. 그러나 realm에는 서비스용 confidential client(ca-skeleton-api, standard flow 꺼짐)만 있고 브라우저용 public client가 없다. - redis-session 모드: CA_SESSION httpOnly 쿠키, CookieCsrfTokenRepository (XSRF-TOKEN 쿠키, X-XSRF-TOKEN 헤더, plain handler). 로그인·로그아웃· 세션 조회·CSRF 발급 엔드포인트는 운영 코드에 없다(테스트 픽스처만). 고른 방법: recipes/session-owners/에 둘을 둔다. 제품은 src/bootstrap/로 복사해 composeProductSessionOwner에서 돌려준다. - oidc-pkce-session-owner.ts: authorization code + PKCE S256, WebCrypto와 context fetch만 쓴다(라이브러리 없음). 토큰은 메모리에만, sessionStorage 에는 10분짜리 거래(verifier·state·nonce·returnTo)만 두고 콜백이 먼저 지운다. 콜백 URL에서 code를 네트워크 호출 전에 지운다. state·RFC 9207 iss·nonce·aud·azp·exp·sub를 검사하고, 갱신 때 sub가 바뀌면 로그아웃. bearer는 apiOrigins에만 보낸다. 만료 30초 전 갱신은 한 번만 하고 상태 알림이 없다. 401이면 refresh token으로 한 번 복구하고, 그 토큰도 401이면 로그아웃. 설정이 틀리면 integration-failed로 닫는다. - cookie-session-owner.ts: 세션 조회·로그아웃 URL과 로그인 시작을 기본값 없이 받는다(백엔드에 없는 엔드포인트를 지어내지 않는다). 200+subject → authenticated, 401 → unauthenticated, 그 밖은 reject(상태 유지). SESSION_COOKIE_READ/WRITE 프로필과 XSRF-TOKEN → x-xsrf-token provider. 쿠키가 없으면 쓰기는 UNAVAILABLE로 아무것도 보내지 않는다. - 두 owner 모두 SessionState·recover 전이 계약을 따른다. - PRODUCTION_IMPORTS_RECIPE 검사를 recipes/session-owners에도 건다. recipe는 복사하지 import하지 않는다(초기 번들 밖). 버린 대안: src에 기본 owner 내장(IdP 결합이 템플릿 본체에 들어간다), OIDC 라이브러리 의존(fetch·WebCrypto로 충분), 매뉴얼만(같은 실수 반복). 위험·한계: 실제 Keycloak·Redis session 백엔드에 붙여 보지 않았다. ID token 서명은 검사하지 않는다(토큰 엔드포인트 직접 응답, OIDC Core 3.1.3.7 (6)); access token 서명은 백엔드가 본다. 새로고침하면 메모리 토큰이 사라져 다시 로그인한다(Keycloak SSO면 비밀번호 없이 돌아온다). 쿠키 모드는 페이지와 API가 같은 host여야 XSRF-TOKEN을 읽는다. 검증: tests/recipes 3파일 52건(구현 전 모듈 없음으로 실패 확인). 변이 15개(state·origin·401 한 번·nonce·iss·URL 정리·갱신 sub·TTL, CSRF 헤더·401·로그아웃 실패·notify·단일 조회·subject 상한·credentials) 모두 실패로 잡힘. runtime 조립 테스트 4건이 실제 createRuntimeAdapters로 EXTERNAL_BEARER bearer, 401 뒤 갱신, 쿠키 쓰기의 x-xsrf-token을 확인. check:optional-recipe-fixtures(regex 변경 없이는 실패 확인), check:optional-recipes:source, check:types, eslint 통과. 두 recipe의 minify+gzip 크기 3.8 kB, 1.1 kB. Refs: docs/reviews/2026-11-03-maturity-review/09-app-core.md 09-03 --- .../session-owners/cookie-session-owner.ts | 199 ++++++ .../session-owners/oidc-pkce-session-owner.ts | 651 ++++++++++++++++++ scripts/check-optional-recipe-fixtures.ts | 9 +- scripts/lib/optional-recipes.ts | 5 +- .../src/bad-session-owner.ts | 3 + tests/recipes/cookie-session-owner.test.ts | 241 +++++++ tests/recipes/oidc-pkce-session-owner.test.ts | 503 ++++++++++++++ tests/recipes/session-owners-runtime.test.ts | 396 +++++++++++ 8 files changed, 2005 insertions(+), 2 deletions(-) create mode 100644 recipes/session-owners/cookie-session-owner.ts create mode 100644 recipes/session-owners/oidc-pkce-session-owner.ts create mode 100644 tests/fixtures/optional-recipes/forbidden/production-import/src/bad-session-owner.ts create mode 100644 tests/recipes/cookie-session-owner.test.ts create mode 100644 tests/recipes/oidc-pkce-session-owner.test.ts create mode 100644 tests/recipes/session-owners-runtime.test.ts diff --git a/recipes/session-owners/cookie-session-owner.ts b/recipes/session-owners/cookie-session-owner.ts new file mode 100644 index 00000000..ca602495 --- /dev/null +++ b/recipes/session-owners/cookie-session-owner.ts @@ -0,0 +1,199 @@ +import type { ExternalSessionOwner } from "../../src/adapters/auth/index.ts"; +import type { CredentialPatchOutcome } from "../../src/adapters/http/index.ts"; +import type { SessionState } from "../../src/application/ports/auth-session-port.ts"; +import type { + ProductCredentialProvider, + SessionOwnerFetch, +} from "../../src/bootstrap/product-composition-contract.ts"; +import type { RestAuthProfile } from "../../src/contracts/rest-profiles.ts"; + +/** + * 1103/09-03. A session owner and CSRF credential providers for the paired + * backend's Redis session mode (`APP_SECURITY_AUTH_MODE=redis-session`). The + * backend's filter chain (`SecurityConfig` in its inbound web adapter) gives: + * + * - the session as an httpOnly, Secure, SameSite=Lax cookie (`CA_SESSION`), + * which the browser sends and script never reads; + * - Spring's `CookieCsrfTokenRepository`: a readable `XSRF-TOKEN` cookie whose + * value goes back unchanged (plain, not XOR-masked) in `X-XSRF-TOKEN` on + * every state-changing request. + * + * It gives no endpoint to sign in, sign out or ask who is signed in; its + * tests use fixture controllers. Those three are the product's, so this owner + * takes their URLs and the sign-in start with no defaults. The session + * endpoint must read the CSRF token (in Spring, `CsrfToken.getToken()`), since + * the deferred token sets no cookie until something reads it. + * + * The `XSRF-TOKEN` cookie is readable only on the API's host, so the page + * and the API share a host: same origin behind one proxy, or `localhost` on + * two ports in development. + * + * State transitions follow `SessionState` in + * `src/application/ports/auth-session-port.ts`. The cookie is the credential + * and the server is the judge: a server 401 signs out, and nothing is + * refreshed here. + * + * Copy this file into `src/bootstrap/`, the profiles into + * `PRODUCT_REST_AUTH_PROFILES` and the providers into `credentialProviders`; + * `docs/manual/04-paired-backend-session.md` shows the wiring. + */ + +const cookieProfile = ( + authProfileId: string, + headers: readonly ("x-xsrf-token" | "x-csrf-token")[], +): RestAuthProfile => + Object.freeze({ + authProfileId, + transport: "SAME_ORIGIN_COOKIE", + // `include`, not `same-origin`: development serves the page and the API + // from two ports of `localhost`, which is same-site but cross-origin. + credentials: "include", + allowedCredentialHeaders: Object.freeze([...headers]), + requiredCredentialHeaders: Object.freeze([...headers]), + }); + +/** + * Reads go with the cookie alone; writes must carry the CSRF header, and the + * executor sends nothing without it. Header names are the backend's default + * (`APP_SESSION_CSRF_HEADER_NAME`). + */ +export const SESSION_COOKIE_AUTH_PROFILES = Object.freeze({ + SESSION_COOKIE_READ: cookieProfile("SESSION_COOKIE_READ", []), + SESSION_COOKIE_WRITE: cookieProfile("SESSION_COOKIE_WRITE", ["x-xsrf-token"]), +} satisfies Readonly>); + +/** The backend's defaults (`APP_SESSION_CSRF_COOKIE_NAME`, `..._HEADER_NAME`). */ +const CSRF_COOKIE = "XSRF-TOKEN"; +const CSRF_HEADER = "x-xsrf-token"; +const MAX_SUBJECT_LENGTH = 255; + +export type CookieSessionOwnerOptions = Readonly<{ + /** The product's GET endpoint: 200 when signed in (body read by `subjectFrom`), 401 when not. */ + sessionUrl: string; + /** The opaque, stable id of who is signed in, from the 200 body; `null` for nobody. */ + subjectFrom(body: unknown): string | null; + /** The product's POST endpoint that ends the session. */ + signOutUrl: string; + /** Starts the product's sign-in: its login page, or a Spring `oauth2Login` redirect. */ + beginSignIn(returnTo?: string): Promise; + fetch: SessionOwnerFetch; + readCookie(name: string): string | undefined; + csrfCookieName?: string; +}>; + +export function createCookieSessionOwner( + options: CookieSessionOwnerOptions, +): ExternalSessionOwner { + let state: SessionState = "recovery-pending"; + let subject: string | null = null; + let probing: Promise<"restored" | "no-session"> | null = null; + const listeners = new Set<() => void>(); + + function publish(nextState: SessionState, nextSubject: string | null): void { + if (nextState === state && nextSubject === subject) return; + state = nextState; + subject = nextSubject; + for (const listener of [...listeners]) { + try { + listener(); + } catch { + // One subscriber cannot stop the others hearing the change. + } + } + } + + /** Who is signed in, asked of the server; one question at a time. */ + function probe(): Promise<"restored" | "no-session"> { + probing ??= (async () => { + // A rejection here (network, timeout, a body over the cap) leaves the + // state as it is, so a recovering session can be retried. + const response = await options.fetch(options.sessionUrl, { + method: "GET", + credentials: "include", + headers: { accept: "application/json" }, + }); + if (response.status === 401) { + publish("unauthenticated", null); + return "no-session" as const; + } + if (response.status !== 200) { + throw new Error(`The session endpoint answered ${response.status}.`); + } + const named = options.subjectFrom(await response.json()); + if (typeof named !== "string" || named.length === 0 || named.length > MAX_SUBJECT_LENGTH) { + publish("unauthenticated", null); + return "no-session" as const; + } + publish("authenticated", named); + return "restored" as const; + })().finally(() => { + probing = null; + }); + return probing; + } + + void probe().catch(() => { + // Unreachable at boot: stay recovering, and the user can retry. + }); + + return Object.freeze({ + readState: () => state, + readSubject: () => (state === "authenticated" ? subject : null), + subscribe(listener: () => void) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + beginSignIn: (returnTo?: string) => options.beginSignIn(returnTo), + async signOut() { + const token = options.readCookie(options.csrfCookieName ?? CSRF_COOKIE); + const response = await options.fetch(options.signOutUrl, { + method: "POST", + credentials: "include", + headers: token === undefined ? {} : { [CSRF_HEADER]: token }, + }); + // 401: already gone. Anything else but success leaves the server session + // alive, so this page must not claim it ended. + if (!response.ok && response.status !== 401) { + throw new Error(`The sign-out endpoint answered ${response.status}.`); + } + publish("unauthenticated", null); + }, + async attachCredential() { + throw new TypeError( + "A cookie session sends no bearer header; give the operation a SESSION_COOKIE_* profile.", + ); + }, + recoverSession: probe, + notifyUnauthenticated() { + publish("unauthenticated", null); + }, + }); +} + +/** + * The providers for `SESSION_COOKIE_AUTH_PROFILES`. They read the CSRF cookie + * when the request goes, since the backend may issue a new one at any answer. + * They do not ask the session state: the cookie is the proof and the server + * decides, and its 401 reaches the owner. + */ +export function createSessionCookieCredentialProviders( + options: Readonly<{ + readCookie(name: string): string | undefined; + csrfCookieName?: string; + }>, +): Readonly> { + const ready = (headers: Readonly>): CredentialPatchOutcome => + Object.freeze({ kind: "READY" as const, headers: Object.freeze(headers) }); + return Object.freeze({ + SESSION_COOKIE_READ: async () => ready({}), + SESSION_COOKIE_WRITE: async () => { + const token = options.readCookie(options.csrfCookieName ?? CSRF_COOKIE); + // Without it Spring answers 403; fail closed with nothing sent. + return token === undefined || token.length === 0 + ? Object.freeze({ kind: "UNAVAILABLE" as const }) + : ready({ [CSRF_HEADER]: token }); + }, + }); +} diff --git a/recipes/session-owners/oidc-pkce-session-owner.ts b/recipes/session-owners/oidc-pkce-session-owner.ts new file mode 100644 index 00000000..72301076 --- /dev/null +++ b/recipes/session-owners/oidc-pkce-session-owner.ts @@ -0,0 +1,651 @@ +import type { ExternalSessionOwner } from "../../src/adapters/auth/index.ts"; +import type { + CredentialPatch, + SessionState, +} from "../../src/application/ports/auth-session-port.ts"; +import type { + ProductSessionOwnerContext, + ProductSessionOwnerPage, + SessionOwnerFetch, +} from "../../src/bootstrap/product-composition-contract.ts"; + +/** + * 1103/09-03. A session owner for the paired backend's JWT mode + * (`APP_SECURITY_AUTH_MODE=jwt`, the default): a Spring resource server that + * accepts a Keycloak access token whose `iss` is `APP_SECURITY_JWT_ISSUER` and + * whose `aud` names `APP_SECURITY_JWT_AUDIENCE`. Operations keep the + * template's `EXTERNAL_BEARER` profile. + * + * The owner signs in with the OAuth 2.0 authorization code flow and PKCE + * (S256) against a public client, with WebCrypto and the context's bounded + * fetch; there is no library. + * + * - Tokens live in memory only. A reload signs out; a Keycloak SSO session + * makes the next sign-in a redirect without a password. + * - `redirectStorage` (sessionStorage) holds one sign-in transaction — the + * PKCE verifier, `state`, `nonce` and the return path — for at most ten + * minutes, and the callback deletes it before anything else. + * - The bearer goes only to `apiOrigins`. + * - The ID token's claims are checked, not its signature: it comes straight + * from the token endpoint over the context's fetch (OIDC Core 3.1.3.7 (6)). + * The backend verifies the access token's signature. + * + * State transitions follow `SessionState` in + * `src/application/ports/auth-session-port.ts`. + * + * The backend's realm (`infra/keycloak/realms/ca-skeleton-realm.json` there) + * has only a confidential service client; a product registers the public + * client this owner signs in with. Copy this file into `src/bootstrap/` and + * return it from `composeProductSessionOwner`; `docs/manual/04-paired-backend-session.md` + * shows the realm client and the wiring. + */ + +/** `buildPhysicalKey("auth", 1, "oidc-pkce-transaction")`; never a token. */ +export const OIDC_PKCE_TRANSACTION_KEY = "ca-frontend:auth:v1:oidc-pkce-transaction"; + +export type OidcPkceSessionOwnerOptions = Readonly<{ + /** Exact issuer, e.g. `http://localhost:8081/realms/ca-skeleton`. HTTPS off this machine. */ + issuer: string; + /** The public client (standard flow, PKCE S256) registered for this app. */ + clientId: string; + /** + * The app's base URL, origin plus router base path, registered as the + * client's redirect URI. The sign-in returns here and the owner then + * replaces the URL with the return path under this base. + */ + redirectUri: string; + /** Default `openid`. */ + scope?: string; + /** Origins the bearer may go to: normally `new URL(API_BASE_URL).origin`. */ + apiOrigins: readonly string[]; + /** Registered post-logout redirect URI; without it sign-out stays local. */ + postLogoutRedirectUri?: string; + fetch: SessionOwnerFetch; + page: ProductSessionOwnerPage; + redirectStorage: ProductSessionOwnerContext["redirectStorage"]; + /** Defaults to the page's WebCrypto. */ + crypto?: Readonly<{ + getRandomValues(array: Uint8Array): Uint8Array; + subtle: Pick; + }>; + /** Epoch milliseconds. */ + now?: () => number; + /** Refresh this long before the access token expires. Default 30 s. */ + refreshLeewayMs?: number; +}>; + +const TRANSACTION_TTL_MS = 10 * 60_000; +const MAX_SUBJECT_LENGTH = 255; +/** RFC 6750 b64token, and short enough for the 8 KiB credential header cap. */ +const TOKEN_PATTERN = /^[A-Za-z0-9\-._~+/]+=*$/u; +const MAX_TOKEN_LENGTH = 8_000; +/** Authorization response parameters; anything else in the query is the app's. */ +const CALLBACK_PARAMETERS = [ + "code", + "state", + "iss", + "session_state", + "error", + "error_description", + "error_uri", +] as const; + +type Endpoints = Readonly<{ + authorization: string; + token: string; + endSession?: string; +}>; + +type Transaction = Readonly<{ + state: string; + nonce: string; + verifier: string; + returnTo: string; + createdAt: number; +}>; + +type Tokens = Readonly<{ + accessToken: string; + expiresAt: number; + refreshToken?: string; +}>; + +/** `definitive`: the IdP said no; anything else could answer differently later. */ +class OwnerFailure extends Error { + constructor( + message: string, + readonly definitive: boolean, + ) { + super(message); + } +} + +const isRecord = (value: unknown): value is Record => + Boolean(value) && typeof value === "object" && !Array.isArray(value); + +function isLoopback(url: URL): boolean { + return ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname); +} + +/** HTTPS, or HTTP on this machine for local Keycloak. */ +function endpointUrl(value: unknown): URL | null { + if (typeof value !== "string") return null; + try { + const url = new URL(value); + const secure = + url.protocol === "https:" || (url.protocol === "http:" && isLoopback(url)); + return secure && url.username === "" && url.password === "" && url.hash === "" + ? url + : null; + } catch { + return null; + } +} + +function base64Url(bytes: Uint8Array): string { + let binary = ""; + for (const byte of bytes) binary += String.fromCharCode(byte); + return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, ""); +} + +function claimsOf(token: string): Record | null { + const payload = token.split(".")[1]; + if (payload === undefined || token.split(".").length !== 3) return null; + try { + const base64 = payload.replaceAll("-", "+").replaceAll("_", "/"); + const binary = atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, "=")); + const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0)); + const claims: unknown = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)); + return isRecord(claims) ? claims : null; + } catch { + return null; + } +} + +/** A path of this app: one leading slash, no scheme, no host, no control character. */ +function appPath(value: unknown): string | null { + return typeof value === "string" && + value.length <= 2_048 && + /^\/(?![/\\])/u.test(value) && + !value.includes("\\") && + ![...value].some((character) => { + const code = character.charCodeAt(0); + return code < 0x20 || code === 0x7f; + }) + ? value + : null; +} + +function readTransaction( + storage: OidcPkceSessionOwnerOptions["redirectStorage"], +): Transaction | null { + try { + const raw = storage?.getItem(OIDC_PKCE_TRANSACTION_KEY); + if (!raw) return null; + const value: unknown = JSON.parse(raw); + if ( + !isRecord(value) || + value.v !== 1 || + typeof value.state !== "string" || + typeof value.nonce !== "string" || + typeof value.verifier !== "string" || + typeof value.createdAt !== "number" || + appPath(value.returnTo) === null + ) { + return null; + } + return value as unknown as Transaction; + } catch { + return null; + } +} + +/** The same owner shape, closed: nothing can sign in. */ +function misconfiguredOwner(): ExternalSessionOwner { + return Object.freeze({ + readState: () => "integration-failed" as const, + readSubject: () => null, + subscribe: () => () => {}, + beginSignIn: async () => { + throw new TypeError("The OIDC session owner is misconfigured."); + }, + signOut: async () => {}, + attachCredential: async () => { + throw new TypeError("The OIDC session owner is misconfigured."); + }, + recoverSession: async () => "no-session" as const, + notifyUnauthenticated: () => {}, + }); +} + +export function createOidcPkceSessionOwner( + options: OidcPkceSessionOwnerOptions, +): ExternalSessionOwner { + const issuer = endpointUrl(options.issuer); + const redirect = endpointUrl(options.redirectUri); + const apiOrigins = new Set(options.apiOrigins); + const storage = options.redirectStorage; + if ( + issuer === null || + issuer.search !== "" || + redirect === null || + options.clientId.length === 0 || + storage === undefined || + apiOrigins.size === 0 || + [...apiOrigins].some((origin) => endpointUrl(origin)?.origin !== origin) + ) { + return misconfiguredOwner(); + } + const issuerId = options.issuer; + const clientId = options.clientId; + const crypto: NonNullable = + options.crypto ?? globalThis.crypto; + const now = options.now ?? Date.now; + const leewayMs = options.refreshLeewayMs ?? 30_000; + const basePath = redirect.pathname.replace(/\/$/u, ""); + + let state: SessionState = "unauthenticated"; + let subject: string | null = null; + /** Who signed in, kept while a 401 recovers: a refresh must give the same one back. */ + let lastSubject: string | null = null; + let tokens: Tokens | null = null; + /** Set by a 401's automatic refresh; a second 401 then signs out. */ + let refreshedAfter401 = false; + let discovery: Promise | null = null; + let refreshing: Promise | null = null; + let recovering: Promise<"restored" | "no-session"> | null = null; + const listeners = new Set<() => void>(); + + function publish(nextState: SessionState, nextSubject: string | null): void { + if (nextState === state && nextSubject === subject) return; + state = nextState; + subject = nextSubject; + for (const listener of [...listeners]) { + try { + listener(); + } catch { + // One subscriber cannot stop the others hearing the change. + } + } + } + + function signedOut(): void { + tokens = null; + lastSubject = null; + refreshedAfter401 = false; + publish("unauthenticated", null); + } + + async function readJson(response: Response): Promise> { + const type = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase(); + if (type !== "application/json") { + throw new OwnerFailure("The identity provider did not answer JSON.", true); + } + try { + const value: unknown = await response.json(); + if (isRecord(value)) return value; + } catch { + // Falls through to the same refusal. + } + throw new OwnerFailure("The identity provider answered malformed JSON.", true); + } + + async function send(url: string, init: Parameters[1]): Promise { + try { + return await options.fetch(url, { credentials: "omit", ...init }); + } catch (error) { + // A body over the cap is the IdP misbehaving, not the network. + throw new OwnerFailure("The identity provider could not be reached.", error instanceof RangeError); + } + } + + function discover(): Promise { + discovery ??= (async () => { + const response = await send( + `${issuerId.replace(/\/$/u, "")}/.well-known/openid-configuration`, + { method: "GET", headers: { accept: "application/json" } }, + ); + if (!response.ok) { + throw new OwnerFailure("OIDC discovery failed.", response.status < 500); + } + const document = await readJson(response); + const authorization = endpointUrl(document.authorization_endpoint); + const token = endpointUrl(document.token_endpoint); + const endSession = endpointUrl(document.end_session_endpoint); + // OIDC Discovery 4.3: the document must name exactly this issuer. + if (document.issuer !== issuerId || authorization === null || token === null) { + throw new OwnerFailure("OIDC discovery named another issuer.", true); + } + return Object.freeze({ + authorization: authorization.href, + token: token.href, + ...(endSession === null ? {} : { endSession: endSession.href }), + }); + })(); + discovery.catch(() => { + discovery = null; + }); + return discovery; + } + + /** Token endpoint call; the answer is checked before anything is kept. */ + async function requestTokens( + form: Readonly>, + expected: Readonly<{ nonce?: string; subject?: string }>, + ): Promise> { + const endpoints = await discover(); + const response = await send(endpoints.token, { + method: "POST", + headers: { accept: "application/json" }, + body: new URLSearchParams(form), + }); + if (!response.ok) { + // 400 invalid_grant / 401 invalid_client: this grant will never work. + throw new OwnerFailure("The identity provider refused the grant.", response.status < 500); + } + const body = await readJson(response); + const accessToken = body.access_token; + const refreshToken = body.refresh_token; + const expiresIn = body.expires_in; + if ( + typeof accessToken !== "string" || + accessToken.length > MAX_TOKEN_LENGTH || + !TOKEN_PATTERN.test(accessToken) || + typeof body.token_type !== "string" || + body.token_type.toLowerCase() !== "bearer" || + typeof expiresIn !== "number" || + !Number.isFinite(expiresIn) || + expiresIn <= 0 || + (refreshToken !== undefined && + (typeof refreshToken !== "string" || refreshToken.length === 0)) + ) { + throw new OwnerFailure("The token response is not a bearer token.", true); + } + const idSubject = checkIdToken(body.id_token, expected); + const nextSubject = idSubject ?? expected.subject; + if (nextSubject === undefined) { + throw new OwnerFailure("The token response names nobody.", true); + } + return { + subject: nextSubject, + tokens: Object.freeze({ + accessToken, + expiresAt: now() + expiresIn * 1_000, + ...(typeof refreshToken === "string" ? { refreshToken } : {}), + }), + }; + } + + /** OIDC Core 3.1.3.7 and 12.2, without the signature (see the file comment). */ + function checkIdToken( + idToken: unknown, + expected: Readonly<{ nonce?: string; subject?: string }>, + ): string | undefined { + if (idToken === undefined && expected.nonce === undefined) return undefined; + const claims = typeof idToken === "string" ? claimsOf(idToken) : null; + const audience = claims?.aud; + const sub = claims?.sub; + if ( + claims === null || + claims.iss !== issuerId || + !(audience === clientId || (Array.isArray(audience) && audience.includes(clientId))) || + (claims.azp !== undefined && claims.azp !== clientId) || + typeof claims.exp !== "number" || + claims.exp * 1_000 <= now() || + typeof sub !== "string" || + sub.length === 0 || + sub.length > MAX_SUBJECT_LENGTH || + (expected.nonce !== undefined && claims.nonce !== expected.nonce) || + (expected.subject !== undefined && sub !== expected.subject) + ) { + throw new OwnerFailure("The ID token is not for this sign-in.", true); + } + return sub; + } + + /** One refresh at a time; every caller waits for the same one. */ + function refresh(): Promise { + refreshing ??= (async () => { + const refreshToken = tokens?.refreshToken; + const expectedSubject = lastSubject; + if (refreshToken === undefined || expectedSubject === null) { + throw new OwnerFailure("There is no session to refresh.", true); + } + const answer = await requestTokens( + { grant_type: "refresh_token", refresh_token: refreshToken, client_id: clientId }, + { subject: expectedSubject }, + ); + tokens = Object.freeze({ + ...answer.tokens, + // Keycloak may rotate the refresh token; without a new one the old one stays. + ...(answer.tokens.refreshToken === undefined ? { refreshToken } : {}), + }); + lastSubject = answer.subject; + publish("authenticated", answer.subject); + })().finally(() => { + refreshing = null; + }); + return refreshing; + } + + function recover(): Promise<"restored" | "no-session"> { + recovering ??= (async () => { + try { + await refresh(); + return "restored" as const; + } catch (error) { + if (error instanceof OwnerFailure && error.definitive) { + signedOut(); + return "no-session" as const; + } + throw error; + } + })().finally(() => { + recovering = null; + }); + return recovering; + } + + /** The page load that returns from the IdP. Synchronous up to the exchange. */ + function completeSignIn(): void { + let url: URL; + try { + url = new URL(options.page.href()); + } catch { + return; + } + const params = url.searchParams; + const atRedirect = + url.origin === redirect!.origin && + url.pathname.replace(/\/$/u, "") === basePath; + if (!atRedirect || !params.has("state") || !(params.has("code") || params.has("error"))) { + return; + } + const transaction = readTransaction(storage); + try { + storage?.removeItem(OIDC_PKCE_TRANSACTION_KEY); + } catch { + // A transaction that cannot be removed is still never used twice here. + } + const code = params.get("code"); + const valid = + transaction !== null && + code !== null && + params.get("state") === transaction.state && + !params.has("error") && + // RFC 9207: a response from another issuer is a mix-up, not a sign-in. + (!params.has("iss") || params.get("iss") === issuerId) && + now() - transaction.createdAt <= TRANSACTION_TTL_MS && + now() >= transaction.createdAt; + // The code leaves the URL before any network call, so a reload or a copied + // address cannot replay it. + if (transaction !== null) { + options.page.replaceUrl(`${basePath}${transaction.returnTo}`); + } else { + for (const name of CALLBACK_PARAMETERS) params.delete(name); + options.page.replaceUrl(`${url.pathname}${url.search}${url.hash}`); + } + if (!valid || code === null || transaction === null) return; + state = "recovery-pending"; + recovering = (async () => { + try { + const answer = await requestTokens( + { + grant_type: "authorization_code", + code, + redirect_uri: options.redirectUri, + client_id: clientId, + code_verifier: transaction.verifier, + }, + { nonce: transaction.nonce }, + ); + tokens = answer.tokens; + lastSubject = answer.subject; + refreshedAfter401 = false; + publish("authenticated", answer.subject); + return "restored" as const; + } catch { + // The code is single-use and the verifier is gone: nothing to retry. + signedOut(); + return "no-session" as const; + } + })().finally(() => { + recovering = null; + }); + } + + completeSignIn(); + + return Object.freeze({ + readState: () => state, + readSubject: () => (state === "authenticated" ? subject : null), + subscribe(listener: () => void) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + async beginSignIn(returnTo?: string) { + const endpoints = await discover(); + const random = (size: number) => base64Url(crypto.getRandomValues(new Uint8Array(size))); + const verifier = random(32); + const transaction = { + v: 1, + state: random(16), + nonce: random(16), + verifier, + returnTo: appPath(returnTo) ?? "/", + createdAt: now(), + }; + const challenge = base64Url( + new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))), + ); + storage.setItem(OIDC_PKCE_TRANSACTION_KEY, JSON.stringify(transaction)); + const authorize = new URL(endpoints.authorization); + for (const [name, value] of [ + ["response_type", "code"], + ["client_id", clientId], + ["redirect_uri", options.redirectUri], + ["scope", options.scope ?? "openid"], + ["state", transaction.state], + ["nonce", transaction.nonce], + ["code_challenge", challenge], + ["code_challenge_method", "S256"], + ] as const) { + authorize.searchParams.set(name, value); + } + options.page.assign(authorize.href); + }, + async signOut() { + // Local first: the tokens are gone even if the IdP never answers. + signedOut(); + try { + storage.removeItem(OIDC_PKCE_TRANSACTION_KEY); + } catch { + // Nothing of the session is in it once the tokens are gone. + } + if (options.postLogoutRedirectUri === undefined) return; + const endSession = await discover().then( + (endpoints) => endpoints.endSession, + () => undefined, + ); + if (endSession === undefined) return; + // No `id_token_hint`: an ID token does not belong in a URL. Keycloak then + // asks the user to confirm the sign-out. + const logout = new URL(endSession); + logout.searchParams.set("client_id", clientId); + logout.searchParams.set("post_logout_redirect_uri", options.postLogoutRedirectUri); + options.page.assign(logout.href); + }, + async attachCredential(binding, context): Promise { + if (!apiOrigins.has(binding.origin)) { + throw new TypeError("The bearer token goes to the API origin only."); + } + if (state !== "authenticated" || tokens === null) { + throw new TypeError("Nobody is signed in."); + } + if (tokens.expiresAt - leewayMs <= now()) { + try { + await raceSignal(refresh(), context?.signal); + refreshedAfter401 = false; + } catch (error) { + if (error instanceof OwnerFailure && error.definitive) signedOut(); + // A refresh that could not be reached leaves a token still inside its life. + if (tokens === null || tokens.expiresAt <= now() || !(error instanceof OwnerFailure)) { + throw error; + } + } + } + if (tokens === null) throw new TypeError("Nobody is signed in."); + return Object.freeze({ + headers: Object.freeze({ authorization: `Bearer ${tokens.accessToken}` }), + }); + }, + recoverSession() { + if (recovering !== null) return recovering; + if (state === "authenticated" && tokens !== null && tokens.expiresAt - leewayMs > now()) { + return Promise.resolve("restored" as const); + } + if (tokens?.refreshToken === undefined) { + signedOut(); + return Promise.resolve("no-session" as const); + } + return recover(); + }, + notifyUnauthenticated() { + if (state !== "authenticated") return; + const refreshToken = tokens?.refreshToken; + if (refreshToken === undefined || refreshedAfter401) { + signedOut(); + return; + } + // The access token was refused; only the refresh token is worth keeping. + refreshedAfter401 = true; + tokens = Object.freeze({ accessToken: "", expiresAt: 0, refreshToken }); + publish("recovery-pending", null); + void recover().catch(() => { + // Unreachable IdP: stay recovering, and the user can retry. + }); + }, + }); +} + +/** Waits for `work`, or stops waiting when the request ends; `work` goes on. */ +function raceSignal(work: Promise, signal: AbortSignal | undefined): Promise { + if (signal === undefined) return work; + if (signal.aborted) return Promise.reject(new DOMException("Aborted", "AbortError")); + return new Promise((resolve, reject) => { + const onAbort = () => reject(new DOMException("Aborted", "AbortError")); + signal.addEventListener("abort", onAbort, { once: true }); + work.then( + (value) => { + signal.removeEventListener("abort", onAbort); + resolve(value); + }, + (error: unknown) => { + signal.removeEventListener("abort", onAbort); + reject(error); + }, + ); + }); +} diff --git a/scripts/check-optional-recipe-fixtures.ts b/scripts/check-optional-recipe-fixtures.ts index 6647ee0c..e2956a0d 100644 --- a/scripts/check-optional-recipe-fixtures.ts +++ b/scripts/check-optional-recipe-fixtures.ts @@ -148,7 +148,14 @@ const results = [ }, { id: "production-imports-recipe", - passed: ruleIds.has("PRODUCTION_IMPORTS_RECIPE"), + // 1103/09-03. Both recipe folders, one fixture each. + passed: ["bad.ts", "bad-session-owner.ts"].every((file) => + productionViolations.some( + (violation) => + violation.ruleId === "PRODUCTION_IMPORTS_RECIPE" && + violation.path.endsWith(`/src/${file}`), + ), + ), }, { id: "reference-runtime-not-composed", diff --git a/scripts/lib/optional-recipes.ts b/scripts/lib/optional-recipes.ts index 38244793..9434ad05 100644 --- a/scripts/lib/optional-recipes.ts +++ b/scripts/lib/optional-recipes.ts @@ -261,7 +261,10 @@ export async function scanOptionalRecipeSources( (path.basename(path.resolve(root)) === "src" && !relativeToRoot.startsWith(".."))) && imports.some((specifier) => - /(?:^|\/)recipes\/frontend-capabilities(?:\/|$)/.test(specifier), + // 1103/09-03. Session owner recipes are copied too, never imported. + /(?:^|\/)recipes\/(?:frontend-capabilities|session-owners)(?:\/|$)/.test( + specifier, + ), ) ) { violations.push({ ruleId: "PRODUCTION_IMPORTS_RECIPE", path: relative }); diff --git a/tests/fixtures/optional-recipes/forbidden/production-import/src/bad-session-owner.ts b/tests/fixtures/optional-recipes/forbidden/production-import/src/bad-session-owner.ts new file mode 100644 index 00000000..d9de6148 --- /dev/null +++ b/tests/fixtures/optional-recipes/forbidden/production-import/src/bad-session-owner.ts @@ -0,0 +1,3 @@ +import { createCookieSessionOwner } from "../../../../../../recipes/session-owners/cookie-session-owner.ts"; + +export const sessionOwnerRecipeInProduction = createCookieSessionOwner; diff --git a/tests/recipes/cookie-session-owner.test.ts b/tests/recipes/cookie-session-owner.test.ts new file mode 100644 index 00000000..00575f51 --- /dev/null +++ b/tests/recipes/cookie-session-owner.test.ts @@ -0,0 +1,241 @@ +import { describe, expect, it, vi } from "vitest"; + +import type { SessionOwnerFetch } from "../../src/bootstrap/product-composition-contract.ts"; +import { installRestAuthProfileRegistry } from "../../src/contracts/rest-profiles.ts"; +import { + createCookieSessionOwner, + createSessionCookieCredentialProviders, + SESSION_COOKIE_AUTH_PROFILES, + type CookieSessionOwnerOptions, +} from "../../recipes/session-owners/cookie-session-owner.ts"; + +/** + * 1103/09-03. The paired backend's Redis session mode + * (`APP_SECURITY_AUTH_MODE=redis-session`): an httpOnly `CA_SESSION` cookie, + * and Spring's `CookieCsrfTokenRepository` with the `XSRF-TOKEN` cookie and + * the `X-XSRF-TOKEN` header. The backend template ships no sign-in, sign-out + * or session endpoint, so their URLs are the product's and have no default. + */ + +const SESSION_URL = "http://localhost:8080/api/session"; +const SIGN_OUT_URL = "http://localhost:8080/api/session/sign-out"; + +/** The product's session endpoint answers the backend's Envelope. */ +const subjectFrom: CookieSessionOwnerOptions["subjectFrom"] = (body) => { + const data = (body as { data?: { subject?: unknown } } | null)?.data; + return typeof data?.subject === "string" ? data.subject : null; +}; + +function harness( + answers: Array<() => Response | Promise> = [], + cookie: Record = { "XSRF-TOKEN": "xsrf-1" }, +) { + const fetch = vi.fn(async (input) => { + const answer = answers.shift(); + if (!answer) throw new TypeError(`unexpected ${String(input)}`); + return answer(); + }); + const beginSignIn = vi.fn(async (_returnTo?: string) => {}); + const options: CookieSessionOwnerOptions = { + sessionUrl: SESSION_URL, + signOutUrl: SIGN_OUT_URL, + subjectFrom, + beginSignIn, + fetch, + readCookie: (name) => cookie[name], + }; + return { options, fetch, beginSignIn, answers, cookie }; +} + +const signedIn = (subject = "user-1") => () => + Response.json({ success: true, data: { subject } }); +const status = (code: number) => () => + Response.json({ success: false, error: { code: "AUTH" } }, { status: code }); + +describe("cookie session owner: state", () => { + it("asks the session endpoint at boot with the cookie and recovers until it answers", async () => { + const setup = harness([signedIn()]); + const owner = createCookieSessionOwner(setup.options); + + expect(owner.readState()).toBe("recovery-pending"); + await vi.waitFor(() => expect(owner.readState()).toBe("authenticated")); + expect(owner.readSubject()).toBe("user-1"); + expect(setup.fetch).toHaveBeenCalledWith(SESSION_URL, { + method: "GET", + credentials: "include", + headers: { accept: "application/json" }, + }); + }); + + it("is signed out when the session endpoint answers 401", async () => { + const setup = harness([status(401)]); + const owner = createCookieSessionOwner(setup.options); + + await vi.waitFor(() => expect(owner.readState()).toBe("unauthenticated")); + expect(owner.readSubject()).toBeNull(); + }); + + it("is signed out when the 200 names nobody", async () => { + const setup = harness([() => Response.json({ success: true, data: {} })]); + const owner = createCookieSessionOwner(setup.options); + + await vi.waitFor(() => expect(owner.readState()).toBe("unauthenticated")); + }); + + it("stays recovering when the endpoint cannot answer, and recovers on request", async () => { + const setup = harness([ + () => { + throw new DOMException("timed out", "TimeoutError"); + }, + status(503), + signedIn(), + ]); + const owner = createCookieSessionOwner(setup.options); + + // The first joins the boot probe, which times out; the second gets a 503. + await expect(owner.recoverSession()).rejects.toThrow("timed out"); + await expect(owner.recoverSession()).rejects.toThrow("503"); + expect(owner.readState()).toBe("recovery-pending"); + await expect(owner.recoverSession()).resolves.toBe("restored"); + expect(setup.fetch).toHaveBeenCalledTimes(3); + expect(owner.readState()).toBe("authenticated"); + }); + + it("answers no-session already signed out, never still recovering", async () => { + const setup = harness([status(401), status(401)]); + const owner = createCookieSessionOwner(setup.options); + await vi.waitFor(() => expect(owner.readState()).toBe("unauthenticated")); + + await expect(owner.recoverSession()).resolves.toBe("no-session"); + expect(owner.readState()).toBe("unauthenticated"); + }); + + it("shares one probe between boot and a recovery that starts meanwhile", async () => { + const setup = harness([signedIn()]); + const owner = createCookieSessionOwner(setup.options); + + await expect(owner.recoverSession()).resolves.toBe("restored"); + expect(setup.fetch).toHaveBeenCalledTimes(1); + }); + + it("signs out on a server 401 and notifies once per change", async () => { + const setup = harness([signedIn()]); + const owner = createCookieSessionOwner(setup.options); + await vi.waitFor(() => expect(owner.readState()).toBe("authenticated")); + const listener = vi.fn(); + owner.subscribe(listener); + + owner.notifyUnauthenticated(); + owner.notifyUnauthenticated(); + + expect(owner.readState()).toBe("unauthenticated"); + expect(listener).toHaveBeenCalledTimes(1); + }); + + it("refuses an over-long or empty subject", async () => { + const setup = harness([signedIn("x".repeat(256))]); + const owner = createCookieSessionOwner(setup.options); + + await vi.waitFor(() => expect(owner.readState()).toBe("unauthenticated")); + }); +}); + +describe("cookie session owner: sign-in, sign-out, credentials", () => { + it("hands sign-in to the product", async () => { + const setup = harness([status(401)]); + const owner = createCookieSessionOwner(setup.options); + + await owner.beginSignIn("/items"); + + expect(setup.beginSignIn).toHaveBeenCalledWith("/items"); + }); + + it("signs out with the CSRF header and is signed out after the server agrees", async () => { + const setup = harness([signedIn(), () => new Response(null, { status: 204 })]); + const owner = createCookieSessionOwner(setup.options); + await vi.waitFor(() => expect(owner.readState()).toBe("authenticated")); + + await owner.signOut(); + + expect(setup.fetch).toHaveBeenLastCalledWith(SIGN_OUT_URL, { + method: "POST", + credentials: "include", + headers: { "x-xsrf-token": "xsrf-1" }, + }); + expect(owner.readState()).toBe("unauthenticated"); + }); + + it("keeps the session when the server did not sign it out", async () => { + const setup = harness([signedIn(), status(403)]); + const owner = createCookieSessionOwner(setup.options); + await vi.waitFor(() => expect(owner.readState()).toBe("authenticated")); + + await expect(owner.signOut()).rejects.toThrow(); + expect(owner.readState()).toBe("authenticated"); + }); + + it("sends no bearer header: operations use the cookie profiles", async () => { + const setup = harness([signedIn()]); + const owner = createCookieSessionOwner(setup.options); + + await expect( + owner.attachCredential({ origin: "http://localhost:8080", method: "GET", operationId: "X" }), + ).rejects.toThrow("SESSION_COOKIE_"); + }); +}); + +describe("session cookie credential providers", () => { + const operation = (authProfileId: string, method = "POST") => + Object.freeze({ operationId: "WRITE", authProfileId, method }); + const context = Object.freeze({ + signal: new AbortController().signal, + deadlineAtMonotonicMs: 0, + }); + + it("installs as product auth profiles under the template's checks", () => { + const registry = installRestAuthProfileRegistry(SESSION_COOKIE_AUTH_PROFILES); + + expect(registry.get("SESSION_COOKIE_READ")).toMatchObject({ + transport: "SAME_ORIGIN_COOKIE", + credentials: "include", + requiredCredentialHeaders: [], + }); + expect(registry.get("SESSION_COOKIE_WRITE")).toMatchObject({ + transport: "SAME_ORIGIN_COOKIE", + credentials: "include", + allowedCredentialHeaders: ["x-xsrf-token"], + requiredCredentialHeaders: ["x-xsrf-token"], + }); + }); + + it("sends the XSRF-TOKEN cookie as X-XSRF-TOKEN on writes", async () => { + const providers = createSessionCookieCredentialProviders({ + readCookie: (name) => (name === "XSRF-TOKEN" ? "xsrf-1" : undefined), + }); + + await expect( + providers.SESSION_COOKIE_WRITE(operation("SESSION_COOKIE_WRITE"), context), + ).resolves.toEqual({ kind: "READY", headers: { "x-xsrf-token": "xsrf-1" } }); + await expect( + providers.SESSION_COOKIE_READ(operation("SESSION_COOKIE_READ", "GET"), context), + ).resolves.toEqual({ kind: "READY", headers: {} }); + }); + + it("fails a write closed without the cookie, so nothing is sent", async () => { + const providers = createSessionCookieCredentialProviders({ readCookie: () => undefined }); + + await expect( + providers.SESSION_COOKIE_WRITE(operation("SESSION_COOKIE_WRITE"), context), + ).resolves.toEqual({ kind: "UNAVAILABLE" }); + }); + + it("reads the cookie when the request goes, not when composed", async () => { + let token: string | undefined; + const providers = createSessionCookieCredentialProviders({ readCookie: () => token }); + token = "xsrf-2"; + + await expect( + providers.SESSION_COOKIE_WRITE(operation("SESSION_COOKIE_WRITE"), context), + ).resolves.toEqual({ kind: "READY", headers: { "x-xsrf-token": "xsrf-2" } }); + }); +}); diff --git a/tests/recipes/oidc-pkce-session-owner.test.ts b/tests/recipes/oidc-pkce-session-owner.test.ts new file mode 100644 index 00000000..d05a2610 --- /dev/null +++ b/tests/recipes/oidc-pkce-session-owner.test.ts @@ -0,0 +1,503 @@ +import { createHash } from "node:crypto"; + +import { describe, expect, it, vi } from "vitest"; + +import type { SessionOwnerFetch } from "../../src/bootstrap/product-composition-contract.ts"; +import { + createOidcPkceSessionOwner, + OIDC_PKCE_TRANSACTION_KEY, + type OidcPkceSessionOwnerOptions, +} from "../../recipes/session-owners/oidc-pkce-session-owner.ts"; + +/** + * 1103/09-03. The paired backend's JWT mode: a Spring resource server that + * checks a Keycloak access token's issuer and audience. This owner gets that + * token in the browser with the authorization code flow and PKCE, keeps it in + * memory only, and follows the session state contract on `SessionState`. + */ + +// The backend's local issuer (application-local.yml, APP_SECURITY_JWT_ISSUER). +const ISSUER = "http://localhost:8081/realms/ca-skeleton"; +const CLIENT_ID = "ca-frontend"; +const APP = "http://localhost:5173"; +const API_ORIGIN = "http://localhost:8080"; +const AUTHORIZE = `${ISSUER}/protocol/openid-connect/auth`; +const TOKEN = `${ISSUER}/protocol/openid-connect/token`; +const END_SESSION = `${ISSUER}/protocol/openid-connect/logout`; + +const encode = (value: unknown) => + Buffer.from(JSON.stringify(value)).toString("base64url"); +/** The owner reads claims; it does not verify the signature (OIDC Core 3.1.3.7 (6)). */ +const jwt = (claims: Record) => + `${encode({ alg: "RS256", typ: "JWT" })}.${encode(claims)}.signature`; + +type Call = Readonly<{ url: string; init: Parameters[1] }>; + +function harness( + overrides: Partial = {}, + setup: Readonly<{ href?: string; storage?: Record }> = {}, +) { + let now = Date.parse("2026-11-04T00:00:00Z"); + let href = setup.href ?? `${APP}/`; + const storage = new Map(Object.entries(setup.storage ?? {})); + const calls: Call[] = []; + const tokenAnswers: Array<() => Response | Promise> = []; + let tokenCounter = 0; + // The nonce of the sign-in this page load returns from, as Keycloak echoes it. + const nonce = (() => { + try { + return (JSON.parse(storage.get(OIDC_PKCE_TRANSACTION_KEY) ?? "null") as { nonce?: string } | null) + ?.nonce; + } catch { + return undefined; + } + })(); + const idToken = (claims: Record = {}) => + jwt({ + iss: ISSUER, + aud: CLIENT_ID, + sub: "user-1", + exp: Math.floor(now / 1000) + 300, + ...(nonce === undefined ? {} : { nonce }), + ...claims, + }); + /** A token response as Keycloak sends one. */ + const tokens = ( + fields: Record = {}, + claims: Record = {}, + ) => { + tokenCounter += 1; + return Response.json({ + access_token: `access-${tokenCounter}`, + token_type: "Bearer", + expires_in: 300, + refresh_token: `refresh-${tokenCounter}`, + id_token: idToken(claims), + ...fields, + }); + }; + const discovery = { value: () => Response.json({ + issuer: ISSUER, + authorization_endpoint: AUTHORIZE, + token_endpoint: TOKEN, + end_session_endpoint: END_SESSION, + }) }; + const fetch = vi.fn(async (input, init) => { + const url = String(input); + calls.push({ url, init }); + if (url === `${ISSUER}/.well-known/openid-configuration`) return discovery.value(); + if (url === TOKEN) { + const answer = tokenAnswers.shift(); + return answer ? answer() : tokens(); + } + throw new TypeError(`unexpected ${url}`); + }); + const page = { + href: () => href, + replaceUrl: vi.fn((url: string) => { + href = new URL(url, href).href; + }), + assign: vi.fn((url: string) => { + href = url; + }), + }; + const redirectStorage = { + getItem: (key: string) => storage.get(key) ?? null, + setItem: (key: string, value: string) => void storage.set(key, value), + removeItem: (key: string) => void storage.delete(key), + }; + const create = () => + createOidcPkceSessionOwner({ + issuer: ISSUER, + clientId: CLIENT_ID, + redirectUri: `${APP}/`, + apiOrigins: [API_ORIGIN], + postLogoutRedirectUri: `${APP}/`, + fetch, + page, + redirectStorage, + now: () => now, + ...overrides, + }); + return { + create, + fetch, + calls, + page, + storage, + tokens, + tokenAnswers, + discovery, + idToken, + advance(ms: number) { + now += ms; + }, + tokenRequests: () => + calls + .filter((call) => call.url === TOKEN) + .map((call) => Object.fromEntries(call.init?.body as URLSearchParams)), + }; +} + +/** Starts a sign-in on one page and returns the callback URL the IdP sends back. */ +async function signInRedirect( + setup: ReturnType, + returnTo = "/items?limit=1", + params: Readonly> = {}, +) { + const owner = setup.create(); + await owner.beginSignIn(returnTo); + const authorize = new URL(setup.page.assign.mock.calls.at(-1)![0]); + const callback = new URL(`${APP}/`); + callback.searchParams.set("code", "code-1"); + callback.searchParams.set("state", authorize.searchParams.get("state")!); + callback.searchParams.set("iss", ISSUER); + for (const [name, value] of Object.entries(params)) callback.searchParams.set(name, value); + return { authorize, callback: callback.href, storage: Object.fromEntries(setup.storage) }; +} + +/** A signed-in owner, as on the page load that returns from Keycloak. */ +async function signedIn(overrides: Partial = {}) { + const first = harness(overrides); + const { callback, storage } = await signInRedirect(first); + const setup = harness(overrides, { href: callback, storage }); + const owner = setup.create(); + await expect(owner.recoverSession()).resolves.toBe("restored"); + return { ...setup, owner }; +} + +const binding = (origin = API_ORIGIN) => + Object.freeze({ origin, method: "GET", operationId: "LIST" }); + +describe("OIDC PKCE session owner: sign-in", () => { + it("starts the code flow with PKCE S256 and keeps only the transaction", async () => { + const setup = harness(); + const owner = setup.create(); + expect(owner.readState()).toBe("unauthenticated"); + + await owner.beginSignIn("/items?limit=1"); + + const authorize = new URL(setup.page.assign.mock.calls[0]![0]); + expect(`${authorize.origin}${authorize.pathname}`).toBe(AUTHORIZE); + const transaction = JSON.parse(setup.storage.get(OIDC_PKCE_TRANSACTION_KEY)!); + expect(Object.fromEntries(authorize.searchParams)).toEqual({ + response_type: "code", + client_id: CLIENT_ID, + redirect_uri: `${APP}/`, + scope: "openid", + state: transaction.state, + nonce: transaction.nonce, + code_challenge: s256(transaction.verifier), + code_challenge_method: "S256", + }); + expect(transaction.returnTo).toBe("/items?limit=1"); + expect(transaction.verifier).toMatch(/^[A-Za-z0-9_-]{43}$/u); + expect(setup.storage.size).toBe(1); + }); + + it("returns only to a path of this app", async () => { + for (const returnTo of ["//evil.example/x", "https://evil.example/", "/\\evil", "items"]) { + const setup = harness(); + await setup.create().beginSignIn(returnTo); + expect(JSON.parse(setup.storage.get(OIDC_PKCE_TRANSACTION_KEY)!).returnTo).toBe("/"); + } + }); + + it("exchanges the code on the page load that returns, and drops it from the URL first", async () => { + const first = harness(); + const { callback, storage } = await signInRedirect(first); + const setup = harness({}, { href: callback, storage }); + + const owner = setup.create(); + + // Before any network answer: the code is out of the URL and the + // transaction is spent, so a reload cannot replay it. + expect(owner.readState()).toBe("recovery-pending"); + expect(setup.page.replaceUrl).toHaveBeenCalledWith("/items?limit=1"); + expect(setup.storage.has(OIDC_PKCE_TRANSACTION_KEY)).toBe(false); + await expect(owner.recoverSession()).resolves.toBe("restored"); + expect(owner.readState()).toBe("authenticated"); + expect(owner.readSubject()).toBe("user-1"); + expect(setup.tokenRequests()).toEqual([ + { + grant_type: "authorization_code", + code: "code-1", + redirect_uri: `${APP}/`, + client_id: CLIENT_ID, + code_verifier: JSON.parse(storage[OIDC_PKCE_TRANSACTION_KEY]!).verifier, + }, + ]); + const tokenCall = setup.calls.find((call) => call.url === TOKEN)!; + expect(tokenCall.init).toMatchObject({ method: "POST", credentials: "omit" }); + }); + + it("returns under the router base path", async () => { + const overrides = { redirectUri: `${APP}/app/` }; + const first = harness(overrides); + const { callback, storage } = await signInRedirect(first, "/items"); + const setup = harness(overrides, { href: callback.replace(`${APP}/`, `${APP}/app/`), storage }); + + setup.create(); + + expect(setup.page.replaceUrl).toHaveBeenCalledWith("/app/items"); + }); + + it.each([ + ["a state that is not the one sent", { state: "forged" }], + ["an error from the IdP", { error: "access_denied" }], + ["another issuer (RFC 9207)", { iss: "http://evil.example/realms/x" }], + ])("signs nobody in on %s", async (_case, params) => { + const first = harness(); + const { callback, storage } = await signInRedirect(first, "/items", params); + const setup = harness({}, { href: callback, storage }); + + const owner = setup.create(); + + expect(owner.readState()).toBe("unauthenticated"); + await expect(owner.recoverSession()).resolves.toBe("no-session"); + expect(setup.tokenRequests()).toEqual([]); + expect(setup.page.replaceUrl).toHaveBeenCalled(); + expect(setup.storage.has(OIDC_PKCE_TRANSACTION_KEY)).toBe(false); + }); + + it("signs nobody in from a transaction older than ten minutes", async () => { + const first = harness(); + const { callback, storage } = await signInRedirect(first); + const setup = harness({}, { href: callback, storage }); + setup.advance(10 * 60_000 + 1); + + expect(setup.create().readState()).toBe("unauthenticated"); + expect(setup.tokenRequests()).toEqual([]); + }); + + it.each([ + ["a nonce that is not the one sent", { nonce: "other" }], + ["an id token for another client", { aud: "other-client" }], + ["an id token from another issuer", { iss: "http://evil.example" }], + ["an id token without a subject", { sub: "" }], + ])("refuses %s", async (_case, claims) => { + const first = harness(); + const { callback, storage } = await signInRedirect(first); + const setup = harness({}, { href: callback, storage }); + const nonce = JSON.parse(storage[OIDC_PKCE_TRANSACTION_KEY]!).nonce; + setup.tokenAnswers.push(() => setup.tokens({}, { nonce, ...claims })); + + const owner = setup.create(); + + await expect(owner.recoverSession()).resolves.toBe("no-session"); + expect(owner.readState()).toBe("unauthenticated"); + expect(owner.readSubject()).toBeNull(); + }); + + it("refuses a token response that is not a bearer token", async () => { + const first = harness(); + const { callback, storage } = await signInRedirect(first); + const setup = harness({}, { href: callback, storage }); + setup.tokenAnswers.push(() => setup.tokens({ token_type: "DPoP" })); + + await expect(setup.create().recoverSession()).resolves.toBe("no-session"); + }); + + it("leaves a page that is not a sign-in callback alone", () => { + const setup = harness({}, { href: `${APP}/items?code=x&state=y` }); + + expect(setup.create().readState()).toBe("unauthenticated"); + expect(setup.page.replaceUrl).not.toHaveBeenCalled(); + }); + + it("refuses a discovery document for another issuer", async () => { + const setup = harness(); + setup.discovery.value = () => + Response.json({ issuer: "http://evil.example", authorization_endpoint: AUTHORIZE, token_endpoint: TOKEN }); + + await expect(setup.create().beginSignIn("/")).rejects.toThrow(); + expect(setup.page.assign).not.toHaveBeenCalled(); + expect(setup.storage.size).toBe(0); + }); + + it("keeps tokens out of storage", async () => { + const { storage, owner } = await signedIn(); + await owner.attachCredential(binding()); + + expect([...storage.values()].join("")).not.toMatch(/access-|refresh-/u); + }); +}); + +describe("OIDC PKCE session owner: credentials", () => { + it("sends the access token to the API origin and nowhere else", async () => { + const { owner } = await signedIn(); + + await expect(owner.attachCredential(binding())).resolves.toEqual({ + headers: { authorization: "Bearer access-1" }, + }); + await expect(owner.attachCredential(binding("https://other.example"))).rejects.toThrow( + "API origin", + ); + }); + + it("has no credential while signed out", async () => { + const setup = harness(); + + await expect(setup.create().attachCredential(binding())).rejects.toThrow(); + }); + + it("refreshes once before expiry, for every waiting request, without a notification", async () => { + const setup = await signedIn(); + const listener = vi.fn(); + setup.owner.subscribe(listener); + setup.advance(290_000); + + const patches = await Promise.all([ + setup.owner.attachCredential(binding()), + setup.owner.attachCredential(binding()), + ]); + + expect(patches.map((patch) => patch.headers.authorization)).toEqual([ + "Bearer access-2", + "Bearer access-2", + ]); + expect(setup.tokenRequests().at(-1)).toEqual({ + grant_type: "refresh_token", + refresh_token: "refresh-1", + client_id: CLIENT_ID, + }); + expect(setup.tokenRequests()).toHaveLength(2); + expect(setup.owner.readState()).toBe("authenticated"); + expect(setup.owner.readSubject()).toBe("user-1"); + expect(listener).not.toHaveBeenCalled(); + }); + + it("signs out when the refresh token is refused", async () => { + const setup = await signedIn(); + setup.advance(290_000); + setup.tokenAnswers.push(() => Response.json({ error: "invalid_grant" }, { status: 400 })); + + await expect(setup.owner.attachCredential(binding())).rejects.toThrow(); + expect(setup.owner.readState()).toBe("unauthenticated"); + expect(setup.owner.readSubject()).toBeNull(); + }); + + it("keeps a still-valid token when the refresh cannot be reached", async () => { + const setup = await signedIn(); + setup.advance(290_000); + setup.tokenAnswers.push(() => { + throw new DOMException("timed out", "TimeoutError"); + }); + + await expect(setup.owner.attachCredential(binding())).resolves.toEqual({ + headers: { authorization: "Bearer access-1" }, + }); + expect(setup.owner.readState()).toBe("authenticated"); + }); + + it("signs out when a refresh names another subject", async () => { + const setup = await signedIn(); + setup.advance(290_000); + setup.tokenAnswers.push(() => setup.tokens({}, { sub: "user-2" })); + + await expect(setup.owner.attachCredential(binding())).rejects.toThrow(); + expect(setup.owner.readState()).toBe("unauthenticated"); + }); +}); + +describe("OIDC PKCE session owner: 401 and recovery", () => { + it("restores the session with the refresh token after a 401, once", async () => { + const setup = await signedIn(); + const states: string[] = []; + setup.owner.subscribe(() => states.push(setup.owner.readState())); + + setup.owner.notifyUnauthenticated(); + + expect(setup.owner.readState()).toBe("recovery-pending"); + expect(setup.owner.readSubject()).toBeNull(); + await expect(setup.owner.recoverSession()).resolves.toBe("restored"); + expect(setup.owner.readSubject()).toBe("user-1"); + await expect(setup.owner.attachCredential(binding())).resolves.toEqual({ + headers: { authorization: "Bearer access-2" }, + }); + + // The fresh token is refused too: a refresh will not help. + setup.owner.notifyUnauthenticated(); + + expect(setup.owner.readState()).toBe("unauthenticated"); + expect(states).toEqual(["recovery-pending", "authenticated", "unauthenticated"]); + expect(setup.tokenRequests()).toHaveLength(2); + }); + + it("signs out on a 401 when nothing can restore the session", async () => { + const withoutRefresh = harness(); + const { callback, storage } = await signInRedirect(withoutRefresh); + const bare = harness({}, { href: callback, storage }); + bare.tokenAnswers.push(() => bare.tokens({ refresh_token: undefined })); + const owner = bare.create(); + await owner.recoverSession(); + + owner.notifyUnauthenticated(); + + expect(owner.readState()).toBe("unauthenticated"); + await expect(owner.recoverSession()).resolves.toBe("no-session"); + }); + + it("answers no-session from unauthenticated, never leaving it recovering", async () => { + const owner = harness().create(); + + await expect(owner.recoverSession()).resolves.toBe("no-session"); + expect(owner.readState()).toBe("unauthenticated"); + }); + + it("rejects and stays recovering when the IdP cannot be reached", async () => { + const setup = await signedIn(); + setup.tokenAnswers.push(() => Response.json({ error: "temporarily_unavailable" }, { status: 503 })); + + setup.owner.notifyUnauthenticated(); + + await vi.waitFor(() => expect(setup.tokenRequests()).toHaveLength(2)); + expect(setup.owner.readState()).toBe("recovery-pending"); + await expect(setup.owner.recoverSession()).resolves.toBe("restored"); + }); + + it("answers no-session after a refused refresh, signed out", async () => { + const setup = await signedIn(); + setup.tokenAnswers.push(() => Response.json({ error: "invalid_grant" }, { status: 400 })); + + setup.owner.notifyUnauthenticated(); + + await vi.waitFor(() => expect(setup.owner.readState()).toBe("unauthenticated")); + await expect(setup.owner.recoverSession()).resolves.toBe("no-session"); + }); +}); + +describe("OIDC PKCE session owner: sign-out and configuration", () => { + it("forgets the tokens and ends the IdP session without an id token in the URL", async () => { + const setup = await signedIn(); + + await setup.owner.signOut(); + + expect(setup.owner.readState()).toBe("unauthenticated"); + await expect(setup.owner.attachCredential(binding())).rejects.toThrow(); + const logout = new URL(setup.page.assign.mock.calls.at(-1)![0]); + expect(`${logout.origin}${logout.pathname}`).toBe(END_SESSION); + expect(Object.fromEntries(logout.searchParams)).toEqual({ + client_id: CLIENT_ID, + post_logout_redirect_uri: `${APP}/`, + }); + }); + + it.each([ + ["a plain-HTTP issuer off this machine", { issuer: "http://idp.example/realms/x" }], + ["no client id", { clientId: "" }], + ["an API origin that is not an origin", { apiOrigins: ["http://localhost:8080/api"] }], + ["no storage to survive the redirect", { redirectStorage: undefined }], + ])("fails closed as integration-failed with %s", async (_case, overrides) => { + const owner = harness(overrides as Partial).create(); + + expect(owner.readState()).toBe("integration-failed"); + await expect(owner.beginSignIn("/")).rejects.toThrow(); + await expect(owner.recoverSession()).resolves.toBe("no-session"); + expect(owner.readState()).toBe("integration-failed"); + }); +}); + +function s256(verifier: string): string { + return createHash("sha256").update(verifier).digest("base64url"); +} diff --git a/tests/recipes/session-owners-runtime.test.ts b/tests/recipes/session-owners-runtime.test.ts new file mode 100644 index 00000000..460e92ab --- /dev/null +++ b/tests/recipes/session-owners-runtime.test.ts @@ -0,0 +1,396 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +import type { InstalledHttpOperationExecutor } from "../../src/adapters/http/index.ts"; +import type { + ProductCompositionContext, + ProductSessionOwnerContext, +} from "../../src/bootstrap/product-composition-contract.ts"; +import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts"; +import { OIDC_PKCE_TRANSACTION_KEY } from "../../recipes/session-owners/oidc-pkce-session-owner.ts"; +import { TEST_LIST_HTTP_CONTRACT } from "../helpers/external-contract-fixture.ts"; + +/** + * 1103/09-03 completion check, short of the real backend: each recipe wired + * the way docs/manual/04-paired-backend-session.md tells a product to, through + * the template's real composition root. Only the two product-owned files, the + * installed contract set (adds the operations) and the feature-input composer + * (to reach the `http` capability) are replaced. + */ + +const ISSUER = "http://localhost:8081/realms/ca-skeleton"; +const APP = "http://localhost:5173"; +const API = "http://localhost:8080"; + +const fixture = vi.hoisted(() => ({ + mode: "oidc" as "oidc" | "cookie", + http: undefined as InstalledHttpOperationExecutor | undefined, + withProfile( + contract: T, + operationId: string, + authProfileId: string, + ): T { + return { + ...contract, + contract: { ...contract.contract, operationId }, + frontend: { ...contract.frontend, authProfileId }, + }; + }, +})); + +/** The product's `src/contracts/product-contracts.ts` for the cookie mode. */ +vi.mock("../../src/contracts/product-contracts.ts", async () => { + const { SESSION_COOKIE_AUTH_PROFILES } = await import( + "../../recipes/session-owners/cookie-session-owner.ts" + ); + return { + PRODUCT_RUNTIME_CONFIG_FIELDS: Object.freeze({}), + PRODUCT_ENV_REGISTRY: Object.freeze({}), + PRODUCT_REST_AUTH_PROFILES: SESSION_COOKIE_AUTH_PROFILES, + }; +}); + +/** The product's `src/bootstrap/product-composition.ts`, one mode at a time. */ +vi.mock("../../src/bootstrap/product-composition.ts", async () => { + const { createOidcPkceSessionOwner } = await import( + "../../recipes/session-owners/oidc-pkce-session-owner.ts" + ); + const { createCookieSessionOwner, createSessionCookieCredentialProviders } = await import( + "../../recipes/session-owners/cookie-session-owner.ts" + ); + return { + composeProductSessionOwner(context: ProductSessionOwnerContext) { + const api = new URL(context.config.API_BASE_URL); + return fixture.mode === "oidc" + ? createOidcPkceSessionOwner({ + issuer: ISSUER, + clientId: "ca-frontend", + redirectUri: `${APP}/`, + apiOrigins: [api.origin], + fetch: context.fetch, + page: context.page, + redirectStorage: context.redirectStorage, + }) + : createCookieSessionOwner({ + sessionUrl: new URL("api/session", api).href, + signOutUrl: new URL("api/session/sign-out", api).href, + subjectFrom: (body) => + (body as { data?: { subject?: string } }).data?.subject ?? null, + beginSignIn: async () => context.page.assign(`${APP}/login`), + fetch: context.fetch, + readCookie: context.readCookie, + }); + }, + composeProduct(context: ProductCompositionContext) { + return { + capabilities: {}, + credentialProviders: createSessionCookieCredentialProviders({ + readCookie: context.readCookie, + }), + }; + }, + }; +}); + +const OPERATIONS = vi.hoisted(() => ({ + bearer: ["LIST_BEARER", "EXTERNAL_BEARER"], + cookieRead: ["LIST_COOKIE_READ", "SESSION_COOKIE_READ"], + cookieWrite: ["LIST_COOKIE_WRITE", "SESSION_COOKIE_WRITE"], +} as const)); + +vi.mock("../../src/features/installed-contract-contributions.ts", async (importOriginal) => { + const original = + await importOriginal(); + const { TEST_CONTRACT_CONTRIBUTION: contribution, TEST_LIST_HTTP_CONTRACT: list } = + await import("../helpers/external-contract-fixture.ts"); + const source = contribution.source; + if (source.kind !== "EXTERNAL_PACKAGE") throw new Error("fixture source changed"); + return { + ...original, + createInstalledContractRegistry: () => { + const registry = original.createInstalledContractRegistry([ + ...original.EXPECTED_CONTRACT_SET_PACKAGES, + source.package, + ]); + registry.install(contribution.featureId, [ + { + ...contribution, + http: Object.values(OPERATIONS).map(([operationId, authProfileId]) => + fixture.withProfile(list, operationId, authProfileId), + ) as unknown as typeof contribution.http, + }, + ]); + return registry; + }, + }; +}); + +vi.mock("../../src/features/installed-feature-adapters.ts", async (importOriginal) => { + const original = + await importOriginal(); + return { + ...original, + createInstalledFeatureLoaders: ( + ...args: Parameters + ) => { + fixture.http = Reflect.get(args[0], "http") as InstalledHttpOperationExecutor; + return original.createInstalledFeatureLoaders(...args); + }, + }; +}); + +const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url"); +const jwt = (claims: Record) => + `${encode({ alg: "RS256" })}.${encode(claims)}.signature`; + +let dispose: (() => void) | undefined; +afterEach(() => { + dispose?.(); + dispose = undefined; + fixture.http = undefined; +}); + +async function compose( + host: Record, + respond: (url: string, init: RequestInit) => Response, +) { + const fetcher = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => + respond(String(input), init ?? {}), + ); + const adapters = await createRuntimeAdapters({ + runtime: { + config: { + APP_ENV: "local", + API_BASE_URL: `${API}/`, + TELEMETRY_ENABLED: false, + AUTH_MODE: "external", + REQUEST_TIMEOUT_MS: 10_000, + MAX_RETRY_ATTEMPTS: 0, + RELEASE_MANIFEST_URL: "/release-manifest.json", + CONFIG_SCHEMA_VERSION: "2.0", + CAPABILITY_OVERRIDES: { + REALTIME: "DEFAULT", + WEB_WORKER: "DEFAULT", + SERVICE_WORKER: "DEFAULT", + OFFLINE_COMMANDS: "DEFAULT", + }, + FEATURE_OVERRIDES: {}, + }, + configSchema: "V2", + build: { + buildId: "build-a", + commitSha: "abc123", + routerBasePath: "/", + runtimeConfigUrl: "/config.json", + }, + validationDurationMs: 0, + }, + release: { + schemaVersion: 2, + appVersion: "0.1.0", + buildId: "build-a", + commitSha: "abc123", + configSchemaVersion: "2.0", + contractSet: { + setAlgorithm: "CA_CONTRACT_SET_V1", + setDigest: `sha256:${"0".repeat(64)}`, + packages: [], + }, + assetManifestHash: "hash-a", + releaseId: "release-a", + builtAt: "2026-07-25T00:00:00Z", + routeChunks: { "route-home": "assets/home.js" }, + }, + host, + fetcher: fetcher as unknown as typeof fetch, + }); + dispose = () => adapters.infrastructure.dispose(); + const http = fixture.http; + if (!http) throw new Error("The http capability was not composed"); + return { adapters, http, fetcher }; +} + +const operation = (entry: readonly [string, string]) => + fixture.withProfile(TEST_LIST_HTTP_CONTRACT, ...entry); + +function apiCalls(fetcher: ReturnType) { + return fetcher.mock.calls + .map(([url, init]) => ({ url: String(url), init: (init ?? {}) as RequestInit })) + .filter((call) => call.url.startsWith(`${API}/api/test-entities`)); +} + +describe("OIDC PKCE owner in the composition root (JWT mode)", () => { + function signInReturn() { + const storage = new Map([ + [ + OIDC_PKCE_TRANSACTION_KEY, + JSON.stringify({ + v: 1, + state: "state-1", + nonce: "nonce-1", + verifier: "v".repeat(43), + returnTo: "/items", + createdAt: Date.now(), + }), + ], + ]); + const replaceState = vi.fn(); + const host = { + location: { href: `${APP}/?code=code-1&state=state-1&iss=${encodeURIComponent(ISSUER)}`, assign: vi.fn() }, + history: { state: null, replaceState }, + sessionStorage: { + getItem: (key: string) => storage.get(key) ?? null, + setItem: (key: string, value: string) => void storage.set(key, value), + removeItem: (key: string) => void storage.delete(key), + }, + }; + let issued = 0; + let apiStatus = 200; + const respond = (url: string) => { + if (url.endsWith("/.well-known/openid-configuration")) { + return Response.json({ + issuer: ISSUER, + authorization_endpoint: `${ISSUER}/protocol/openid-connect/auth`, + token_endpoint: `${ISSUER}/protocol/openid-connect/token`, + }); + } + if (url === `${ISSUER}/protocol/openid-connect/token`) { + issued += 1; + return Response.json({ + access_token: `access-${issued}`, + token_type: "Bearer", + expires_in: 300, + refresh_token: `refresh-${issued}`, + id_token: jwt({ + iss: ISSUER, + aud: "ca-frontend", + sub: "user-1", + nonce: "nonce-1", + exp: Math.floor(Date.now() / 1000) + 300, + }), + }); + } + if (apiStatus === 401) { + apiStatus = 200; + return Response.json( + { success: false, error: { code: "AUTH_TOKEN_EXPIRED" } }, + { status: 401, headers: { "www-authenticate": "Bearer" } }, + ); + } + return Response.json([{ id: "entity-1", name: "Entity" }]); + }; + return { + host, + storage, + replaceState, + respond, + failNextApiCall() { + apiStatus = 401; + }, + }; + } + + it("signs in on the returning page load and sends the bearer on EXTERNAL_BEARER", async () => { + fixture.mode = "oidc"; + const page = signInReturn(); + const { adapters, http, fetcher } = await compose(page.host, page.respond); + const session = adapters.outputPorts.session; + + expect(page.replaceState).toHaveBeenCalledWith(null, "", "/items"); + expect(page.storage.size).toBe(0); + await vi.waitFor(() => expect(session.getState()).toBe("authenticated")); + expect(session.getSubject()).toBe("user-1"); + await vi.waitFor(() => + expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"), + ); + + const outcome = await http.execute(operation(OPERATIONS.bearer), { limit: 1 }, { routeId: "R" }); + + expect(outcome.kind).toBe("SUCCESS"); + const [call] = apiCalls(fetcher); + expect(new Headers(call!.init.headers).get("authorization")).toBe("Bearer access-1"); + expect(call!.init.credentials).toBe("omit"); + }); + + it("turns a server 401 into one refresh and keeps the same subject", async () => { + fixture.mode = "oidc"; + const page = signInReturn(); + const { adapters, http, fetcher } = await compose(page.host, page.respond); + const session = adapters.outputPorts.session; + await vi.waitFor(() => expect(session.getState()).toBe("authenticated")); + await vi.waitFor(() => + expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"), + ); + page.failNextApiCall(); + + await expect( + http.execute(operation(OPERATIONS.bearer), { limit: 1 }, { routeId: "R" }), + ).resolves.toMatchObject({ kind: "UNAUTHENTICATED" }); + + await vi.waitFor(() => expect(session.getState()).toBe("authenticated")); + expect(session.getSubject()).toBe("user-1"); + await vi.waitFor(() => + expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"), + ); + await http.execute(operation(OPERATIONS.bearer), { limit: 1 }, { routeId: "R" }); + expect(new Headers(apiCalls(fetcher).at(-1)!.init.headers).get("authorization")).toBe( + "Bearer access-2", + ); + }); +}); + +describe("cookie owner and CSRF providers in the composition root (Redis session mode)", () => { + function cookiePage(signedIn = true) { + const host = { + location: { href: `${APP}/items`, assign: vi.fn() }, + history: { state: null, replaceState: vi.fn() }, + document: { cookie: "XSRF-TOKEN=xsrf-1" }, + }; + const respond = (url: string) => { + if (url === `${API}/api/session`) { + return signedIn + ? Response.json({ success: true, data: { subject: "user-1" } }) + : Response.json({ success: false }, { status: 401 }); + } + return Response.json([{ id: "entity-1", name: "Entity" }]); + }; + return { host, respond }; + } + + it("asks the session at boot and sends writes with the cookie and X-XSRF-TOKEN", async () => { + fixture.mode = "cookie"; + const page = cookiePage(); + const { adapters, http, fetcher } = await compose(page.host, page.respond); + const session = adapters.outputPorts.session; + expect(session.getState()).toBe("recovery-pending"); + await vi.waitFor(() => expect(session.getState()).toBe("authenticated")); + expect(fetcher.mock.calls[0]?.[1]).toMatchObject({ credentials: "include", redirect: "error" }); + await vi.waitFor(() => + expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"), + ); + + await expect( + http.execute(operation(OPERATIONS.cookieWrite), { limit: 1 }, { routeId: "R" }), + ).resolves.toMatchObject({ kind: "SUCCESS" }); + await expect( + http.execute(operation(OPERATIONS.cookieRead), { limit: 1 }, { routeId: "R" }), + ).resolves.toMatchObject({ kind: "SUCCESS" }); + + const [write, read] = apiCalls(fetcher); + expect(write!.init.credentials).toBe("include"); + expect(new Headers(write!.init.headers).get("x-xsrf-token")).toBe("xsrf-1"); + expect(read!.init.credentials).toBe("include"); + expect(new Headers(read!.init.headers).has("x-xsrf-token")).toBe(false); + expect(new Headers(read!.init.headers).has("authorization")).toBe(false); + }); + + it("is signed out when the session endpoint says nobody is", async () => { + fixture.mode = "cookie"; + const page = cookiePage(false); + const { adapters } = await compose(page.host, page.respond); + + await vi.waitFor(() => + expect(adapters.outputPorts.session.getState()).toBe("unauthenticated"), + ); + await expect(adapters.outputPorts.session.recover()).resolves.toBe("no-session"); + }); +}); From f3fd10f17cdb0959f4f52bbb0044412803683005 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:51:51 +0900 Subject: [PATCH 4/4] =?UTF-8?q?docs(manual):=20=EC=A7=9D=20=EB=B0=B1?= =?UTF-8?q?=EC=97=94=EB=93=9C=EC=97=90=20=EC=B2=98=EC=9D=8C=20=EB=B6=99?= =?UTF-8?q?=EC=9D=B4=EA=B8=B0=20=EC=A0=88=EC=9D=84=20=EB=8D=94=ED=95=9C?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 제품이 짝 백엔드에 처음 붙을 때 볼 문서가 없다. owner 작성자는 SessionGateway 주석, subject·scope fence 규칙, R-3.2, recover 규약을 여러 파일에서 모아야 하고, 백엔드가 무엇을 주고 무엇을 안 주는지(realm의 브라우저 client, 로그인·로그아웃·세션 엔드포인트)는 백엔드 코드를 읽어야 안다. 고른 방법: docs/manual/04-paired-backend-session.md를 새로 둔다. - 두 모드 비교표와 근거 위치(백엔드 bbe944bd의 SecurityConfig, security.yml, application-local.yml, realm JSON). - 공통 준비: AUTH_MODE external, 백엔드 local CORS 출처 http://localhost:3000에 맞춘 dev 포트, owner context 필드, recipe는 복사(import 금지). - jwt: 흐름도, realm에 더할 public client JSON(audience mapper 포함), 제품 설정 키 OIDC_ISSUER·OIDC_CLIENT_ID, product-composition 예시, 하지 않는 것(새로고침 로그아웃, ID token 서명, id_token_hint). - redis-session: 흐름도, 제품이 더할 엔드포인트 셋과 CSRF 토큰 읽기, 프로필을 product-contracts.ts에 옮겨 적는 이유, 예시, 같은 host 조건. - 상태 전이 표, 확인 방법(실제 백엔드 e2e는 아직 없음), 증상별 원인. 매뉴얼 README·02 §5, starter-experience·foundation·optional-adapter- recipes에는 위치만 가리키는 줄을 더했다. 백엔드 표는 복사하지 않고 위치만 적었다(매뉴얼 README 규칙). 위험·한계: 백엔드 설정이 바뀌면 이 문서가 낡는다. 기준 커밋을 문서 첫머리에 적었다. Keycloak client JSON은 실제 Keycloak에 넣어 보지 않았다. 검증: verify:documentation PASS_SCOPED(새 문서와 고친 문서 모두 경로· 명령·게이트 ID 누락 0). Refs: docs/reviews/2026-11-03-maturity-review/09-app-core.md 09-03 --- .../frontend-application-foundation.md | 5 +- docs/architecture/optional-adapter-recipes.md | 1 + docs/architecture/starter-experience.md | 12 + docs/manual/02-decision-tables.md | 1 + docs/manual/04-paired-backend-session.md | 298 ++++++++++++++++++ docs/manual/README.md | 2 + 6 files changed, 318 insertions(+), 1 deletion(-) create mode 100644 docs/manual/04-paired-backend-session.md diff --git a/docs/architecture/frontend-application-foundation.md b/docs/architecture/frontend-application-foundation.md index d9fe275e..428774e1 100644 --- a/docs/architecture/frontend-application-foundation.md +++ b/docs/architecture/frontend-application-foundation.md @@ -181,7 +181,10 @@ the session itself (a BFF whose session is an httpOnly cookie) returns its session owner from `composeProductSessionOwner` in the same file. It is asked first, before `http` exists, only when `AUTH_MODE` is `external`, and it comes before the host's `__CA_FRONTEND_AUTH_OWNER__`; `null` leaves the session to -that global. Product auth profiles, runtime-config keys and the keys' +that global. Its context (`src/bootstrap/product-session-owner-context.ts`) +carries a `fetch` with one deadline over the whole exchange, the page for a +sign-in redirect, the page's session storage for that redirect only, and +`readCookie`. Product auth profiles, runtime-config keys and the keys' FE-REG-ENV rows go in `src/contracts/product-contracts.ts`; each joins the template's registry under the same checks (`tests/unit/product-composition-fixture.test.ts`). diff --git a/docs/architecture/optional-adapter-recipes.md b/docs/architecture/optional-adapter-recipes.md index 4281ddba..3760bad9 100644 --- a/docs/architecture/optional-adapter-recipes.md +++ b/docs/architecture/optional-adapter-recipes.md @@ -22,6 +22,7 @@ production readiness를 뜻하지 않는다. | file/IndexedDB/OPFS/Cache 심층 계약. reference runtime이 있는 port는 복사하지 않고 `src/application/ports`의 port를 다시 내보낸다([0929] 05-03) | `recipes/frontend-capabilities/browser-file-storage-contracts.ts` | 아니오 | | 심층 deterministic fake. file·storage durability·OPFS fake는 `src` port를 `implements`한다 | `recipes/frontend-capabilities/browser-file-storage-fakes.ts` | 아니오 | | 심층 contract test | `tests/recipes/browser-file-storage-contracts.test.ts` | 아니오 | +| 짝 백엔드 세션 owner(JWT·Keycloak PKCE, Redis session 쿠키+CSRF). catalog 밖이고 복사해서 쓴다. src가 import하면 `PRODUCTION_IMPORTS_RECIPE` | `recipes/session-owners/`, 테스트 `tests/recipes/oidc-pkce-session-owner.test.ts`, `tests/recipes/cookie-session-owner.test.ts`, `tests/recipes/session-owners-runtime.test.ts`, 절차 `docs/manual/04-paired-backend-session.md` | 아니오 | | browser data current-status ledger | `docs/architecture/browser-data-capability-completion-ledger.md` | 문서만 | | 심층 설계/ADR | `docs/architecture/browser-file-and-origin-storage.md`, `decisions/VD-11-browser-file-and-origin-storage.md` | 문서만 | | client cache scope/persistence 설계 | `docs/architecture/client-cache-and-storage.md`, `decisions/VD-13-client-cache-scope-and-persistence.md` | 문서만 | diff --git a/docs/architecture/starter-experience.md b/docs/architecture/starter-experience.md index 0a4512dc..af25901e 100644 --- a/docs/architecture/starter-experience.md +++ b/docs/architecture/starter-experience.md @@ -51,6 +51,18 @@ An external owner implements `readState`, `readSubject`, `subscribe`, lacks any of these methods is rejected, and the session fails closed as `integration-failed`. +The state transitions an owner makes, and what `recover()` leaves behind for +each answer, are written on `SessionState` and `SessionGateway.recover` in +`src/application/ports/auth-session-port.ts`. For the paired backend's two +authentication modes there are owners to copy, not to write: +`recipes/session-owners/oidc-pkce-session-owner.ts` (JWT mode: Keycloak, +authorization code with PKCE, `EXTERNAL_BEARER`) and +`recipes/session-owners/cookie-session-owner.ts` (Redis session mode: the +session cookie, plus `SESSION_COOKIE_*` profiles and the `X-XSRF-TOKEN` +provider). `docs/manual/04-paired-backend-session.md` wires them and lists +what the backend template does not ship (a browser client in its realm; the +sign-in, sign-out and session endpoints). + `readSubject()` is required. The server-state cache is cleared only when the session state or the subject changes, so a token refresh for the same user keeps cached data. `readSubject()` must return: diff --git a/docs/manual/02-decision-tables.md b/docs/manual/02-decision-tables.md index 96fe6213..b4bfb867 100644 --- a/docs/manual/02-decision-tables.md +++ b/docs/manual/02-decision-tables.md @@ -191,6 +191,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 - `REFERENCE_EXTERNAL_BEARER`는 `EXTERNAL_BEARER`의 옛 이름이다. `@deprecated`이고 한 릴리스 뒤 지운다. 새 코드는 쓰지 않는다. - 제품 프로필 ID는 템플릿 프로필 ID와 겹치면 안 된다. - 쿠키 인증과 CSRF 헤더는 인증 프로필의 헤더 집합으로 표현한다. 예제: `tests/unit/product-composition-fixture.test.ts`. +- 짝 백엔드에 붙일 때 세션 owner와 프로필은 [04 문서](04-paired-backend-session.md)가 모드별로 정한다. JWT 모드는 `EXTERNAL_BEARER`, Redis session 모드는 `SESSION_COOKIE_READ`·`SESSION_COOKIE_WRITE`다. **기준**: 백엔드가 그 API에 요구하는 인증을 따른다. 새 프로필은 템플릿 파일이 아니라 제품 소유 파일 두 곳에만 더한다. diff --git a/docs/manual/04-paired-backend-session.md b/docs/manual/04-paired-backend-session.md new file mode 100644 index 00000000..c9a6c965 --- /dev/null +++ b/docs/manual/04-paired-backend-session.md @@ -0,0 +1,298 @@ +# 04. 짝 백엔드에 처음 붙이기 — 세션 owner + +핵심: 짝 백엔드(`clean-architecture-backend-template`)는 인증 방식이 둘이다. 한 배포는 하나만 쓴다. +프론트는 그 방식에 맞는 세션 owner를 `recipes/session-owners/`에서 골라 복사하고, `composeProductSessionOwner`에서 돌려준다. + +- 세션 owner: 지금 누가 로그인했는지 알고, 요청에 붙일 자격 증명을 주는 객체다. 계약은 `src/adapters/auth/external-session-adapter.ts`의 `ExternalSessionOwner`다. +- 템플릿에는 demo owner만 있다. demo는 `APP_ENV=local`에서만 켜지고, 그 표식 토큰은 백엔드 JWT 검증을 통과하지 못한다. +- `AUTH_MODE: "external"`인데 owner가 없으면 세션은 `integration-failed`로 닫히고, 인증이 필요한 화면은 "로그인 연동이 필요합니다"를 보인다. + +이 문서의 백엔드 사실은 백엔드 `bbe944bd` 기준이다. 백엔드가 인증 설정을 바꾸면 이 문서와 recipe를 함께 맞춘다. + +--- + +## 1. 어느 쪽인가 + +백엔드의 `APP_SECURITY_AUTH_MODE`가 정한다. 기본값은 `jwt`다. + +| | `jwt` | `redis-session` | +|---|---|---| +| 백엔드가 받는 것 | `Authorization: Bearer ` | `CA_SESSION` 쿠키. 쓰기에는 `X-XSRF-TOKEN` 헤더도 | +| 프론트 recipe | `recipes/session-owners/oidc-pkce-session-owner.ts` | `recipes/session-owners/cookie-session-owner.ts` | +| operation 인증 프로필 | `EXTERNAL_BEARER` (템플릿. 생성 뼈대 기본값) | `SESSION_COOKIE_READ`, `SESSION_COOKIE_WRITE` (제품 프로필. recipe에 있다) | +| 백엔드 템플릿에 없어서 제품이 더하는 것 | Keycloak realm의 브라우저용 public client, 사용자 | 로그인·로그아웃·세션 조회 엔드포인트 | +| 브라우저에 남는 것 | 없음. 토큰은 메모리에만 | httpOnly 쿠키. 스크립트는 못 읽는다 | + +백엔드 근거 위치: + +- 두 모드의 보안 체인: `clean-architecture-backend-template/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/SecurityConfig.java` +- 쿠키·CSRF 이름과 모드 기본값: `clean-architecture-backend-template/src/app-bootstrap/src/main/resources/config/security.yml` +- local issuer·audience·CORS: `clean-architecture-backend-template/src/app-bootstrap/src/main/resources/application-local.yml` +- realm: `clean-architecture-backend-template/infra/keycloak/realms/ca-skeleton-realm.json` + +--- + +## 2. 공통 준비 + +1. `config/runtime/local.json`의 `AUTH_MODE`를 `"external"`로 바꾼다. + - `demo`로 두면 owner를 묻지 않는다. 백엔드에 실제로 붙지 않는다. +2. 백엔드 local 프로필의 CORS 허용 출처는 `http://localhost:3000`이다. 프론트를 그 포트로 띄운다. + - `corepack pnpm dev --port 3000` + - 다른 포트를 쓰면 백엔드의 CORS 허용 출처를 그 출처로 바꾼다. +3. owner는 `ProductSessionOwnerContext`(`src/bootstrap/product-composition-contract.ts`)에서 만든다. + - `fetch`: 요청 하나에 마감이 있다(`REQUEST_TIMEOUT_MS`가 상한). 본문은 64 KiB까지 읽는다. redirect는 따라가지 않는다. + - `fetcher`는 마감이 없다. owner에서 쓰지 않는다. 응답하지 않는 호출 하나가 세션을 "복구 중"에 영원히 둔다. + - `page`: 지금 URL, URL 바꾸기, 다른 페이지로 이동. 로그인 리다이렉트에 쓴다. + - `redirectStorage`: 페이지의 sessionStorage. 리다이렉트 한 번 동안의 상태만 둔다. 토큰은 두지 않는다(`AUTH_TOKEN`은 `src/contracts/storage-keys.ts`에서 `forbidden`이다). + - `readCookie`: 페이지 쿠키 읽기. +4. recipe는 `src/bootstrap/` 아래로 **복사**한다. import하지 않는다. + - `src`가 `recipes/`를 import하면 `check:optional-recipes`가 `PRODUCTION_IMPORTS_RECIPE`로 막는다. + - 복사한 파일의 import 경로에서 `../../src/`를 `../`로 바꾼다. + - 템플릿이 recipe를 고치면 CHANGELOG에 적는다. 복사본에 같은 diff를 옮긴다. + +--- + +## 3. `jwt` 모드 — OIDC PKCE owner + +```text +로그인 버튼 → beginSignIn(returnTo) + → owner가 verifier·state·nonce를 만들어 redirectStorage에 둔다 (10분) + → Keycloak 로그인 화면 (code_challenge = SHA-256(verifier)) + → 앱 기본 주소로 돌아온다 (?code=…&state=…&iss=…) + → owner가 저장한 거래를 지우고, URL에서 code를 지우고 returnTo로 바꾼다 [recovery-pending] + → 토큰 엔드포인트에서 code + verifier를 토큰으로 바꾼다 + → ID token의 iss·aud·nonce·exp·sub를 확인한다 [authenticated, subject = sub] + +요청 → attachCredential → Authorization: Bearer (API origin에만) +만료 30초 전 → refresh token으로 한 번 갱신. 상태 알림이 없어 서버 상태 캐시가 남는다 +서버 401 → refresh로 한 번 복구 → 새 토큰도 401이면 로그아웃 [unauthenticated] +``` + +- PKCE: 로그인 시작 때 만든 비밀값(verifier)의 해시를 보내고, 토큰을 받을 때 원래 값을 보내는 방식이다. 중간에서 code를 가로채도 토큰으로 바꾸지 못한다. +- 라이브러리는 없다. WebCrypto와 context `fetch`만 쓴다. + +### 3.1 Keycloak에 브라우저용 client를 더한다 + +백엔드 realm에는 서비스용 confidential client `ca-skeleton-api` 하나뿐이다. 그 client는 브라우저 로그인(standard flow)이 꺼져 있다. 그래서 브라우저가 로그인할 public client를 제품이 더한다. + +realm JSON의 `clients`에 넣거나 Keycloak 관리 화면에서 같은 값으로 만든다. + +```json +{ + "clientId": "ca-frontend", + "enabled": true, + "protocol": "openid-connect", + "publicClient": true, + "standardFlowEnabled": true, + "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, + "redirectUris": ["http://localhost:3000/*"], + "webOrigins": ["http://localhost:3000"], + "attributes": { + "pkce.code.challenge.method": "S256", + "post.logout.redirect.uris": "http://localhost:3000/*" + }, + "protocolMappers": [ + { + "name": "ca-skeleton-api-audience", + "protocol": "openid-connect", + "protocolMapper": "oidc-audience-mapper", + "config": { + "included.client.audience": "ca-skeleton-api", + "id.token.claim": "false", + "access.token.claim": "true" + } + } + ] +} +``` + +- audience mapper가 꼭 있어야 한다. 백엔드는 access token의 `aud`에 `APP_SECURITY_JWT_AUDIENCE`(local 기본 `ca-skeleton-api`)가 없으면 401 `AUTH_AUDIENCE_MISMATCH`로 거부한다. +- `webOrigins`는 브라우저가 토큰 엔드포인트를 부를 때의 CORS 허용이다. +- realm에는 사람 사용자가 없다. local에서는 관리 화면에서 사용자를 하나 만들고 realm role `user`를 준다. +- 백엔드 권한은 `realm_access.roles`와 `resource_access.ca-skeleton-api.roles`에서 온다. 쓰기 권한이 필요하면 그 사용자에게 `ca-skeleton-api`의 client role을 준다(`clean-architecture-backend-template/docs/manual/07-authorization.md`). + +### 3.2 제품 설정 키를 더한다 + +issuer와 client id는 환경마다 다르다. 그래서 런타임 설정 키로 둔다. `src/contracts/product-contracts.ts`: + +```ts +import { z } from "./zod.ts"; + +export const PRODUCT_RUNTIME_CONFIG_FIELDS = Object.freeze({ + OIDC_ISSUER: z.url().optional(), + OIDC_CLIENT_ID: z.string().min(1).optional(), +}); + +export const PRODUCT_ENV_REGISTRY = Object.freeze({ + OIDC_ISSUER: { phase: "runtime", classification: "public", required: false }, + OIDC_CLIENT_ID: { phase: "runtime", classification: "public", required: false }, +} as const); +``` + +- `.optional()`로 둔다. 값이 비면 owner는 `integration-failed`로 닫힌다. 잘못된 곳으로 로그인하지 않는다. +- `config/runtime/local.json`에 `"OIDC_ISSUER": "http://localhost:8081/realms/ca-skeleton"`, `"OIDC_CLIENT_ID": "ca-frontend"`를 더한다. +- `OIDC_ISSUER`는 백엔드 `APP_SECURITY_JWT_ISSUER`와 글자 하나까지 같아야 한다. 끝의 `/`도 같아야 한다. +- 원격 issuer는 HTTPS만 받는다. HTTP는 `localhost`, `127.0.0.1`, `[::1]`에서만 받는다. + +### 3.3 owner를 돌려준다 + +recipe를 `src/bootstrap/` 아래로 복사한 뒤(예: 같은 이름 oidc-pkce-session-owner.ts) `src/bootstrap/product-composition.ts`: + +```ts +import { createOidcPkceSessionOwner } from "./oidc-pkce-session-owner.ts"; + +export function composeProductSessionOwner( + context: ProductSessionOwnerContext, +): ProductSessionOwner { + const app = new URL(context.page.href()); + return createOidcPkceSessionOwner({ + issuer: context.config.OIDC_ISSUER ?? "", + clientId: context.config.OIDC_CLIENT_ID ?? "", + // 앱 기본 주소: origin + 라우터 base path. client의 redirect URI와 같아야 한다. + redirectUri: new URL("/", app.origin).href, + postLogoutRedirectUri: new URL("/", app.origin).href, + apiOrigins: [new URL(context.config.API_BASE_URL).origin], + fetch: context.fetch, + page: context.page, + redirectStorage: context.redirectStorage, + }); +} +``` + +- 라우터 base path가 `/`가 아니면 `redirectUri`에 그 경로를 넣는다. 돌아온 뒤 owner가 그 경로 아래의 `returnTo`로 URL을 바꾼다. +- operation은 `EXTERNAL_BEARER` 그대로 둔다. 바꿀 것이 없다. +- 배포 CSP `connect-src 'self' https:`는 HTTPS Keycloak을 이미 허용한다(`config/hosting/security-headers.json`). + +### 3.4 이 owner가 하지 않는 것 + +- **새로고침하면 로그아웃된다.** 토큰이 메모리에만 있기 때문이다. Keycloak SSO 세션이 살아 있으면 로그인 버튼 한 번이 비밀번호 없이 돌아온다. + - 새로고침에도 로그인을 유지하려면 `prompt=none` 리다이렉트를 더하는 것은 제품의 결정이다. 토큰을 storage에 두는 방법은 쓰지 않는다. +- **ID token 서명은 보지 않는다.** 토큰 엔드포인트에서 직접 받은 응답이라 TLS가 출처를 보증한다(OIDC Core 3.1.3.7 (6)). access token 서명은 백엔드가 확인한다. +- **로그아웃 URL에 ID token을 넣지 않는다.** 그래서 Keycloak이 "로그아웃할까요?"를 한 번 묻는다. + +--- + +## 4. `redis-session` 모드 — 쿠키 owner와 CSRF provider + +```text +부팅 → owner가 세션 엔드포인트를 묻는다 (GET, 쿠키 포함) [recovery-pending] + → 200 + subject → [authenticated] + → 401 → [unauthenticated] + → 그 밖·시간 초과 → 그대로 recovery-pending. "세션 복구" 버튼이 다시 묻는다 + +읽기 요청 (SESSION_COOKIE_READ) → 쿠키만 +쓰기 요청 (SESSION_COOKIE_WRITE) → 쿠키 + X-XSRF-TOKEN: +서버 401 → [unauthenticated] +``` + +- CSRF: 다른 사이트가 사용자의 쿠키로 쓰기를 보내는 공격이다. 백엔드는 스크립트가 읽을 수 있는 `XSRF-TOKEN` 쿠키를 주고, 쓰기 요청의 `X-XSRF-TOKEN` 헤더가 그 값과 같은지 본다. 다른 사이트의 스크립트는 이 쿠키를 읽지 못한다. +- 백엔드는 plain 방식이다(`CsrfTokenRequestAttributeHandler`). 쿠키 값을 그대로 헤더에 넣는다. + +### 4.1 백엔드에 엔드포인트 셋을 더한다 + +백엔드 템플릿의 운영 코드에는 로그인·로그아웃·세션 조회 엔드포인트가 없다. 테스트 픽스처(`SecurityModeWebContractTest.java`의 `/csrf`, `/login-test`, `/whoami`)만 있다. 그래서 recipe는 이 셋의 주소를 기본값 없이 받는다. + +- **세션 조회 (GET)**: 로그인했으면 200과 subject, 아니면 401. + - subject: 사용자마다 다르고 바뀌지 않는 불투명한 id다. 토큰이나 이메일을 쓰지 않는다. + - 이 엔드포인트가 CSRF 토큰을 읽어야 한다(Spring이면 `CsrfToken.getToken()`). Spring Security는 6부터 GET 요청에서 토큰을 읽을 때까지 `XSRF-TOKEN` 쿠키를 쓰지 않는다. +- **로그아웃 (POST)**: 세션을 끝낸다. CSRF 헤더가 필요하다. +- **로그인**: 로그인 화면 POST든 `oauth2Login` 리다이렉트든 제품이 정한다. 끝나면 페이지가 `recover()`를 불러 owner가 세션을 다시 묻게 한다. + +### 4.2 인증 프로필 두 개를 더한다 + +`cookie-session-owner.ts`의 `SESSION_COOKIE_AUTH_PROFILES` 두 행을 `src/contracts/product-contracts.ts`의 `PRODUCT_REST_AUTH_PROFILES`에 그대로 옮겨 적는다. + +- import하지 않고 옮겨 적는 이유: `src/contracts`는 `src/bootstrap`을 import하지 못한다(`check:architecture`의 `contracts-do-not-know-presentation-or-bootstrap`). +- 읽기 operation은 `SESSION_COOKIE_READ`, 쓰기 operation은 `SESSION_COOKIE_WRITE`를 `frontend.authProfileId`에 적는다. +- `SESSION_COOKIE_WRITE`는 `x-xsrf-token`을 요구한다. 쿠키가 없으면 executor가 요청을 하나도 보내지 않고 `AUTH_INTEGRATION_FAILURE`로 닫는다. + +### 4.3 owner와 provider를 돌려준다 + +recipe를 `src/bootstrap/` 아래로 복사한 뒤 `src/bootstrap/product-composition.ts`: + +```ts +import { + createCookieSessionOwner, + createSessionCookieCredentialProviders, +} from "./cookie-session-owner.ts"; + +export function composeProductSessionOwner( + context: ProductSessionOwnerContext, +): ProductSessionOwner { + const api = new URL(context.config.API_BASE_URL); + return createCookieSessionOwner({ + sessionUrl: new URL("api/session", api).href, + signOutUrl: new URL("api/session/sign-out", api).href, + // 백엔드 Envelope: { success: true, data: { subject } } + subjectFrom: (body) => { + const data = (body as { data?: { subject?: unknown } } | null)?.data; + return typeof data?.subject === "string" ? data.subject : null; + }, + beginSignIn: async () => context.page.assign(new URL("/login", context.page.href()).href), + fetch: context.fetch, + readCookie: context.readCookie, + }); +} + +export function composeProduct(context: ProductCompositionContext) { + return { + capabilities: {}, + credentialProviders: createSessionCookieCredentialProviders({ + readCookie: context.readCookie, + }), + } satisfies ProductComposition; +} +``` + +- 위 경로(`api/session` 등)는 예시다. 4.1에서 만든 엔드포인트 주소를 쓴다. +- provider는 세션 상태를 묻지 않는다. 쿠키가 증명이고 서버가 판정한다. 서버의 401은 owner에게 간다. + +### 4.4 페이지와 API는 같은 host여야 한다 + +- `XSRF-TOKEN` 쿠키는 그 쿠키를 준 host에서만 스크립트가 읽는다. 페이지 host와 API host가 다르면 쓰기가 늘 실패한다. +- 운영: 프록시 하나 뒤에 페이지와 API를 같은 origin으로 둔다. +- local: 쿠키는 포트를 가리지 않는다. 그래서 `localhost:3000`의 페이지가 `localhost:8080`이 준 쿠키를 읽는다. 백엔드 local 프로필은 CORS `allow-credentials: true`다. +- 백엔드는 세션 쿠키를 `Secure`로만 준다. 브라우저가 `http://localhost`를 안전한 출처로 볼 때만 저장된다. 저장되지 않으면 https 개발 서버를 쓴다. + +--- + +## 5. owner가 지킬 상태 전이 + +정본: `src/application/ports/auth-session-port.ts`의 `SessionState`와 `SessionGateway.recover` 주석. 두 recipe 모두 이를 따른다. + +| `recover()` 답 | 답할 때의 상태 | +|---|---| +| `"restored"` | `authenticated`, subject 있음 | +| `"no-session"` | `unauthenticated` (또는 `integration-failed`). `recovery-pending`이 아니다 | +| reject | 바꾸지 않는다. 사용자가 다시 시도한다 | + +- 같은 사용자의 토큰 갱신은 상태도 subject도 바꾸지 않는다. 바꾸면 서버 상태 캐시가 비워진다. +- 계약을 어기고 `"no-session"` 뒤에도 `recovery-pending`이면 화면은 owner가 다시 알릴 때까지 로그인 버튼을 보인다. + +--- + +## 6. 확인 + +- `corepack pnpm test:recipes`: 두 recipe의 단위 테스트와, 템플릿 조립 루트에 실제로 붙인 테스트(`tests/recipes/session-owners-runtime.test.ts`). +- 아직 없는 것: 실제 Keycloak·Redis session 백엔드에 붙인 e2e. 처음 붙일 때 손으로 확인한다. + - `jwt`: 로그인 한 번, `EXTERNAL_BEARER` operation 한 번이 200. + - `redis-session`: 로그인 한 번, `SESSION_COOKIE_WRITE` operation 한 번이 성공하고 요청에 `X-XSRF-TOKEN`이 있다. + +--- + +## 7. 틀리면 + +- **"로그인 연동이 필요합니다"** (`integration-failed`) + - `AUTH_MODE`가 `external`인데 `composeProductSessionOwner`가 `null`을 돌려준다. + - OIDC 설정이 틀렸다: `OIDC_ISSUER`·`OIDC_CLIENT_ID`가 비었다, 원격 issuer가 HTTP다, `apiOrigins`가 origin이 아니다, `redirectStorage`가 없다. +- **Keycloak이 `Invalid parameter: redirect_uri`를 보인다**: client `redirectUris`에 앱 기본 주소가 없다. +- **토큰 교환에서 CORS 오류**: client `webOrigins`에 앱 origin이 없다. +- **로그인했는데 API가 401**: 백엔드 응답의 `error.code`를 본다(목록: `clean-architecture-backend-template/src/adapter/inbound/web/README.md`의 `SecurityErrorClassifier`). + - `AUTH_AUDIENCE_MISMATCH`: 3.1의 audience mapper가 없다. + - `AUTH_ISSUER_MISMATCH`: `OIDC_ISSUER`와 `APP_SECURITY_JWT_ISSUER`가 다르다. 컨테이너 안의 백엔드는 `localhost`로 Keycloak에 닿지 못한다는 점도 본다(백엔드 `application-local.yml` 주석). + - `AUTH_JWKS_UNAVAILABLE` (503): 백엔드가 Keycloak에 닿지 못한다. +- **401 뒤 바로 로그아웃된다**: refresh token이 없거나(client 설정), 갱신한 토큰도 401이다. 후자는 갱신으로 풀리지 않는 거부(audience, issuer)다. +- **부팅 뒤 계속 "세션을 복구하고 있습니다"** (쿠키 모드): 세션 엔드포인트가 응답하지 않거나 200·401 말고 다른 status를 준다. +- **쓰기가 `AUTH_INTEGRATION_FAILURE`이고 요청이 0번** (쿠키 모드): `XSRF-TOKEN` 쿠키가 없다. 세션 엔드포인트가 CSRF 토큰을 읽지 않았거나, 페이지와 API host가 다르다. +- **쓰기가 403** (쿠키 모드): 헤더 값이 쿠키와 다르거나, 백엔드가 `APP_SESSION_CSRF_HEADER_NAME`을 바꿨다. 바꿨다면 프로필과 provider의 헤더 이름을 같이 바꾼다. 템플릿이 허용하는 이름은 `x-xsrf-token`, `x-csrf-token`이다(`src/contracts/rest-profiles.ts`의 `CREDENTIAL_HEADER_NAMES`). diff --git a/docs/manual/README.md b/docs/manual/README.md index 5c61e1be..8550e843 100644 --- a/docs/manual/README.md +++ b/docs/manual/README.md @@ -21,6 +21,7 @@ README (이 문서) → 01 작업 순서 (처음부터 끝까지 한 번) → 02 결정표 (단계 중 "무엇을 고를지" 막힐 때) → 03 기능 폴더 밖 파일 (폴더 밖을 고쳐야 할 때) + → 04 짝 백엔드에 처음 붙이기 (로그인이 필요한 API를 처음 부를 때) → reference/ (명령 인자, 전역 ID, 패턴, 오류 메시지를 찾아볼 때) ``` @@ -29,6 +30,7 @@ README (이 문서) | [`01-add-a-feature.md`](01-add-a-feature.md) | 0~11단계. 단계마다 정할 것, 판단 기준, 잡는 검사와 못 잡는 것, 쓸 스킬 | | [`02-decision-tables.md`](02-decision-tables.md) | context 경계, 계약 출처, 재시도 의미, 결과 불명, 인증, 페이지 템플릿 | | [`03-outside-feature-folder.md`](03-outside-feature-folder.md) | 기능 폴더 밖 파일. 생성 명령이 하는 것과 사람이 하는 것 | +| [`04-paired-backend-session.md`](04-paired-backend-session.md) | 짝 백엔드의 두 인증 모드(JWT·Keycloak, Redis session)에 맞는 세션 owner를 붙이는 법 | | [`reference/create-feature.md`](reference/create-feature.md) | `create:feature`의 인자, 만드는 파일, 거부 조건, 출력 | | [`reference/global-ids.md`](reference/global-ids.md) | 전역 ID 종류, 생성 명령이 만드는 값, 유일성 검사 | | [`reference/patterns.md`](reference/patterns.md) | 기능 개발 패턴과 예제 위치. 예제가 없는 패턴은 "없음" |