Files
clean-architecture-frontend…/recipes/session-owners/cookie-session-owner.ts
T
DongHyeonka 00076992f7 fix(recipes): 쿠키 세션 모드의 서버 401을 템플릿 세션에 잇는다
문제: 짝 백엔드 Redis session 모드를 쿠키 recipe와 매뉴얼 04 4.3대로
이으면 서버 401이 세션에 닿지 않는다. 1103/09-01 수정 뒤 조립 루트는
제품 provider 프로필의 401을 제품의 선택 hook `onCredentialRejected`에만
알린다. 쿠키 모드의 operation은 모두 제품 프로필(SESSION_COOKIE_*)인데
매뉴얼 예시는 그 hook을 잇지 않았고, recipe와 매뉴얼은 "서버 401 →
unauthenticated"라고 적었다. 이으려 해도 ProductCompositionContext에
세션에 알릴 길이 없었다. 리뷰 09-cookie401에서 세션 만료 뒤에도 상태가
authenticated, 이전 scope가 current로 남았다.

고른 방법: 두 가지를 더했다.
- ProductCompositionContext.notifySessionUnauthenticated(): 템플릿 세션의
  자기 401과 같은 판정(authSession.onUnauthenticated)을 제품이 부를 수
  있게 한다(리뷰 안 C).
- recipe의 createSessionCookieRejectionHandler(context): SESSION_COOKIE_*
  프로필의 401만 세션에 넘긴다. 다른 제품 프로필의 401은 넘기지 않으므로
  1103/09-01의 완료 기준(세션과 무관한 provider의 401은 로그아웃시키지
  않는다)은 그대로다.
매뉴얼 04 4.3 예시에 `onCredentialRejected` 한 줄을 넣고, recipe 주석,
매뉴얼 04 흐름도, 매뉴얼 02 5절과 7절 업로드 예시(BACKEND_SESSION 쿠키
세션)를 맞췄다. 버린 대안: recipe가 owner와 provider를 한 번에 만드는
함수(안 B). owner는 composeProductSessionOwner, provider는 composeProduct
에서 따로 만들어져 모듈 변수가 필요하다. provider 선언에 "세션 자격
증명" 표시를 두는 안(D)은 계약 칸이 늘고 판정이 선언과 hook 둘로 갈린다.

위험·한계: 제품이 이 한 줄을 빼면 여전히 세션 만료를 모른다. 이것을
막는 검사는 없다(매뉴얼과 recipe 주석이 적는다). 이미 recipe를 복사한
다운스트림은 handler를 복사본에 옮기고 composeProduct에 한 줄을 더해야
한다. ProductCompositionContext에 칸이 하나 늘었다. 이 context는 템플릿만
만들므로 제품 코드는 깨지지 않는다. 실제 Redis 백엔드에는 붙이지
않았다(1103/09-03 남은 부분).

검증: desktop batch에서 확인.
node scripts/run-vitest.ts run tests/recipes/session-owners-runtime.test.ts tests/recipes/cookie-session-owner.test.ts
조립 루트를 지나는 테스트가 매뉴얼 4.3 연결로 쿠키 읽기·쓰기 401 뒤
세션 unauthenticated, 이전 scope not current를 본다.

Refs: 1105/09-02
2026-11-05 22:26:27 +09:00

226 lines
9.1 KiB
TypeScript

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 {
ProductComposition,
ProductCompositionContext,
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. That 401 reaches the session only through
* `createSessionCookieRejectionHandler` as the product's
* `onCredentialRejected` (1105/09-02): the template tells a product
* provider's 401 to the product, not to the session.
*
* Copy this file into `src/bootstrap/`, the profiles into
* `PRODUCT_REST_AUTH_PROFILES`, the providers into `credentialProviders` and
* the handler into `onCredentialRejected`;
* `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<Record<string, RestAuthProfile>>);
/** 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<void>;
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. Its 401 reaches the owner through
* `createSessionCookieRejectionHandler`, not through these.
*/
export function createSessionCookieCredentialProviders(
options: Readonly<{
readCookie(name: string): string | undefined;
csrfCookieName?: string;
}>,
): Readonly<Record<keyof typeof SESSION_COOKIE_AUTH_PROFILES, ProductCredentialProvider>> {
const ready = (headers: Readonly<Record<string, string>>): 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 });
},
});
}
/**
* 1105/09-02. The `onCredentialRejected` that goes with these providers. The
* template tells a 401 to whoever supplied the rejected credential
* (1103/09-01), and for a SESSION_COOKIE_* request that is the product. The
* credential is still the session's own cookie, so a 401 means the server
* session ended (TTL, signed out in another tab or on the server): the
* template session hears it, signs out and fences server state. A 401 on any
* other product profile is left to that profile's provider.
*/
export function createSessionCookieRejectionHandler(
context: Pick<ProductCompositionContext, "notifySessionUnauthenticated">,
): NonNullable<ProductComposition["onCredentialRejected"]> {
return (binding) => {
if (Object.hasOwn(SESSION_COOKIE_AUTH_PROFILES, binding.authProfileId)) {
context.notifySessionUnauthenticated();
}
};
}