chore(review): 1103 세션 owner 조치 브랜치를 합친다
Refs: docs/reviews/2026-11-03-maturity-review/README.md 09-03 09-11 # Conflicts: # docs/manual/02-decision-tables.md
This commit is contained in:
@@ -185,7 +185,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`).
|
||||
|
||||
@@ -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` | 문서만 |
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -193,6 +193,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기
|
||||
- 제품 프로필 ID는 템플릿 프로필 ID와 겹치면 안 된다.
|
||||
- 쿠키 인증과 CSRF 헤더는 인증 프로필의 헤더 집합으로 표현한다. 예제: `tests/unit/product-composition-fixture.test.ts`.
|
||||
- 서버가 401을 주면 그 요청의 자격 증명을 낸 쪽만 안다. `ANONYMOUS` 요청의 401은 세션을 바꾸지 않는다. 템플릿 세션이 낸 자격 증명이면 세션이 로그아웃된다. 제품 `credentialProviders`가 낸 자격 증명이면 세션은 그대로이고 `composeProduct`가 돌려준 `onCredentialRejected`가 불린다(선택).
|
||||
- 짝 백엔드에 붙일 때 세션 owner와 프로필은 [04 문서](04-paired-backend-session.md)가 모드별로 정한다. JWT 모드는 `EXTERNAL_BEARER`, Redis session 모드는 `SESSION_COOKIE_READ`·`SESSION_COOKIE_WRITE`다.
|
||||
|
||||
**기준**: 백엔드가 그 API에 요구하는 인증을 따른다. 새 프로필은 템플릿 파일이 아니라 제품 소유 파일 두 곳에만 더한다.
|
||||
|
||||
|
||||
@@ -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 <Keycloak access token>` | `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 <access token> (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: <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`).
|
||||
@@ -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) | 기능 개발 패턴과 예제 위치. 예제가 없는 패턴은 "없음" |
|
||||
|
||||
@@ -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<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, and its 401 reaches the owner.
|
||||
*/
|
||||
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 });
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -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<ArrayBuffer>): Uint8Array<ArrayBuffer>;
|
||||
subtle: Pick<SubtleCrypto, "digest">;
|
||||
}>;
|
||||
/** 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<string, unknown> =>
|
||||
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<string, unknown> | 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<OidcPkceSessionOwnerOptions["crypto"]> =
|
||||
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<Endpoints> | null = null;
|
||||
let refreshing: Promise<void> | 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<Record<string, unknown>> {
|
||||
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<SessionOwnerFetch>[1]): Promise<Response> {
|
||||
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<Endpoints> {
|
||||
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<Record<string, string>>,
|
||||
expected: Readonly<{ nonce?: string; subject?: string }>,
|
||||
): Promise<Readonly<{ tokens: Tokens; subject: string }>> {
|
||||
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<void> {
|
||||
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<CredentialPatch> {
|
||||
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<T>(work: Promise<T>, signal: AbortSignal | undefined): Promise<T> {
|
||||
if (signal === undefined) return work;
|
||||
if (signal.aborted) return Promise.reject(new DOMException("Aborted", "AbortError"));
|
||||
return new Promise<T>((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);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -22,7 +22,17 @@ export type ExternalSessionOwner = Readonly<{
|
||||
binding: CredentialRequestBinding,
|
||||
context?: CredentialOperationContext,
|
||||
): Promise<CredentialPatch>;
|
||||
/**
|
||||
* Moves the state as `SessionGateway.recover` says before it settles:
|
||||
* `"restored"` → `authenticated`, `"no-session"` → `unauthenticated`, a
|
||||
* rejection leaves it. The transitions are listed on `SessionState`.
|
||||
*/
|
||||
recoverSession(): Promise<"restored" | "no-session">;
|
||||
/**
|
||||
* The runtime read a server 401 as a session verdict (R-3.2). Move to
|
||||
* `unauthenticated`, or to `recovery-pending` when the owner will try to
|
||||
* restore the session itself (a refresh token).
|
||||
*/
|
||||
notifyUnauthenticated(): void;
|
||||
}>;
|
||||
|
||||
|
||||
@@ -1,3 +1,19 @@
|
||||
/**
|
||||
* 1103/09-11. The owner of the session moves it; nothing else does.
|
||||
*
|
||||
* - `unauthenticated` → `authenticated`: a sign-in completed (after
|
||||
* `beginSignIn`, often on the page load that returns from the sign-in).
|
||||
* - `authenticated` → `recovery-pending`: the credential stopped working
|
||||
* (a server 401, a failed refresh) and the owner can still try to restore it.
|
||||
* - `authenticated` → `unauthenticated`: `signOut`, or a 401 nothing can
|
||||
* restore.
|
||||
* - `recovery-pending` → `authenticated` | `unauthenticated`: a recovery ended,
|
||||
* the owner's own or `recover()`'s (see there).
|
||||
* - any → `integration-failed`: the owner cannot work at all.
|
||||
*
|
||||
* Every change of state or subject notifies subscribers once, and each one
|
||||
* fences server state, so a token refresh for the same user changes neither.
|
||||
*/
|
||||
export type SessionState =
|
||||
| "authenticated"
|
||||
| "unauthenticated"
|
||||
@@ -27,6 +43,16 @@ export type SessionGateway = Readonly<{
|
||||
* to keep existing owners working; the transport races the signal either way,
|
||||
* and a recovery that answers after the request already ended is observed but
|
||||
* never turned into a user-visible sign-out.
|
||||
*
|
||||
* 1103/09-11. The state is moved before the promise settles:
|
||||
*
|
||||
* - `"restored"`: the state is `authenticated`, with its subject.
|
||||
* - `"no-session"`: the state is `unauthenticated` (or
|
||||
* `integration-failed`). Never `recovery-pending`: the screen would keep
|
||||
* offering a recovery that already said no. Presentation shows sign-in
|
||||
* after this answer whatever the owner reports, until it next notifies.
|
||||
* - rejects: the owner could not tell (network, timeout). The state is left
|
||||
* as it was, so the user can try again.
|
||||
*/
|
||||
recover(
|
||||
context?: CredentialOperationContext,
|
||||
|
||||
@@ -13,6 +13,28 @@ import type { RuntimeConfig } from "./runtime-config-schema.ts";
|
||||
* for the types of its capabilities) 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<RequestInit, "signal" | "redirect"> &
|
||||
Readonly<{ signal?: AbortSignal; timeoutMs?: number }>,
|
||||
) => Promise<Response>;
|
||||
|
||||
/** 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.
|
||||
@@ -20,7 +42,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<Storage, "getItem" | "setItem" | "removeItem">;
|
||||
}>;
|
||||
|
||||
/**
|
||||
|
||||
@@ -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<SessionOwnerFetch> | 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<string, unknown>): 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<string, unknown>,
|
||||
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 }),
|
||||
});
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -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<number> = 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<never>((_, 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<Uint8Array<ArrayBuffer>> {
|
||||
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;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
createContext,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
useSyncExternalStore,
|
||||
@@ -27,18 +28,35 @@ export function SessionProvider({
|
||||
children,
|
||||
}: Readonly<{ children: ReactNode }>) {
|
||||
const session = useApplicationSession();
|
||||
const sessionState = useSyncExternalStore(
|
||||
const ownerState = useSyncExternalStore(
|
||||
session.subscribe,
|
||||
session.getSnapshot,
|
||||
session.getSnapshot,
|
||||
);
|
||||
// 1103/09-11. "no-session" means nobody is signed in. The contract
|
||||
// (`SessionGateway.recover`) has the owner leave `recovery-pending` first;
|
||||
// one that does not would keep offering a recovery that already said no, so
|
||||
// the answer stands until the owner next notifies.
|
||||
const [recoveryDeclined, setRecoveryDeclined] = useState(false);
|
||||
useEffect(
|
||||
() => session.subscribe(() => setRecoveryDeclined(false)),
|
||||
[session],
|
||||
);
|
||||
const sessionState: SessionState =
|
||||
recoveryDeclined && ownerState === "recovery-pending"
|
||||
? "unauthenticated"
|
||||
: ownerState;
|
||||
const value = useMemo<SessionContextValue>(
|
||||
() =>
|
||||
Object.freeze({
|
||||
sessionState,
|
||||
beginSignIn: session.beginSignIn,
|
||||
signOut: session.signOut,
|
||||
recover: session.recover,
|
||||
async recover() {
|
||||
const answer = await session.recover();
|
||||
if (answer === "no-session") setRecoveryDeclined(true);
|
||||
return answer;
|
||||
},
|
||||
}),
|
||||
[session, sessionState],
|
||||
);
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
createExternalAuthSessionAdapter,
|
||||
type ExternalSessionOwner,
|
||||
} from "../../src/adapters/auth/external-session-adapter.ts";
|
||||
import type { SessionState } from "../../src/application/ports/auth-session-port.ts";
|
||||
import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx";
|
||||
import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx";
|
||||
import { AppRouter } from "../../src/presentation/routes/app-router.tsx";
|
||||
import { createTestApplication } from "../helpers/create-test-application.ts";
|
||||
|
||||
// Same test-only feature as router.test.tsx: `/fixture/items` is session-required.
|
||||
vi.mock("../../src/.generated/product-feature-index.ts", async () => ({
|
||||
DECLARED_PRODUCT_FEATURE_IDS: ["fixture-feature"],
|
||||
PRODUCT_FEATURE_MODULES: [(await import("../helpers/fixture-feature.tsx")).FIXTURE_FEATURE_MODULE],
|
||||
}));
|
||||
vi.mock("../../src/.generated/product-context-index.ts", async () => ({
|
||||
PRODUCT_CONTEXT_MODULES: [(await import("../helpers/fixture-feature.tsx")).FIXTURE_CONTEXT_MODULE],
|
||||
}));
|
||||
|
||||
/**
|
||||
* An owner stuck in `recovery-pending`. `recoverSession` answers as given and,
|
||||
* unless `moveTo` is set, leaves the state where it was — the contract breach
|
||||
* 1103/09-11 is about.
|
||||
*/
|
||||
function recoveringOwner(
|
||||
answer: "restored" | "no-session",
|
||||
moveTo?: SessionState,
|
||||
) {
|
||||
let state: SessionState = "recovery-pending";
|
||||
const listeners = new Set<() => void>();
|
||||
const beginSignIn = vi.fn(async (_returnTo?: string) => {});
|
||||
const owner: ExternalSessionOwner = {
|
||||
readState: () => state,
|
||||
readSubject: () => (state === "authenticated" ? "user-1" : null),
|
||||
subscribe(listener) {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
},
|
||||
beginSignIn,
|
||||
signOut: async () => {},
|
||||
attachCredential: async () => ({ headers: {} }),
|
||||
async recoverSession() {
|
||||
if (moveTo !== undefined) {
|
||||
state = moveTo;
|
||||
for (const listener of listeners) listener();
|
||||
}
|
||||
return answer;
|
||||
},
|
||||
notifyUnauthenticated() {},
|
||||
};
|
||||
return {
|
||||
session: createExternalAuthSessionAdapter(owner),
|
||||
beginSignIn,
|
||||
setState(next: SessionState) {
|
||||
state = next;
|
||||
for (const listener of listeners) listener();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function renderAt(url: string, session: ReturnType<typeof recoveringOwner>["session"]) {
|
||||
window.history.pushState({}, "", url);
|
||||
return render(
|
||||
<ApplicationProvider application={createTestApplication({ session })}>
|
||||
<PreferenceProviders>
|
||||
<AppRouter />
|
||||
</PreferenceProviders>
|
||||
</ApplicationProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
const main = () => within(screen.getByRole("main"));
|
||||
|
||||
describe("1103/09-11 the recovery button uses recover()'s answer", () => {
|
||||
it("offers sign-in after no-session even when the owner stays recovery-pending", async () => {
|
||||
const user = userEvent.setup();
|
||||
const owner = recoveringOwner("no-session");
|
||||
renderAt("/fixture/items", owner.session);
|
||||
|
||||
await user.click(await main().findByRole("button", { name: "세션 복구" }));
|
||||
|
||||
const signIn = await main().findByRole("button", { name: "로그인 시작" });
|
||||
expect(main().queryByRole("button", { name: "세션 복구" })).toBeNull();
|
||||
expect(screen.getByRole("heading", { name: "세션이 필요합니다.", level: 1 })).toBeVisible();
|
||||
await user.click(signIn);
|
||||
expect(owner.beginSignIn).toHaveBeenCalledWith("/fixture/items");
|
||||
});
|
||||
|
||||
it("shows the owner's own state again once it notifies", async () => {
|
||||
const user = userEvent.setup();
|
||||
const owner = recoveringOwner("no-session");
|
||||
renderAt("/fixture/items", owner.session);
|
||||
await user.click(await main().findByRole("button", { name: "세션 복구" }));
|
||||
await main().findByRole("button", { name: "로그인 시작" });
|
||||
|
||||
// A later 401 puts the owner back into recovery: that is a new question.
|
||||
owner.setState("authenticated");
|
||||
owner.setState("recovery-pending");
|
||||
|
||||
await main().findByRole("button", { name: "세션 복구" });
|
||||
});
|
||||
|
||||
it("keeps an owner that follows the contract as it is", async () => {
|
||||
const user = userEvent.setup();
|
||||
const owner = recoveringOwner("no-session", "unauthenticated");
|
||||
renderAt("/fixture/items", owner.session);
|
||||
|
||||
await user.click(await main().findByRole("button", { name: "세션 복구" }));
|
||||
|
||||
await main().findByRole("button", { name: "로그인 시작" });
|
||||
await waitFor(() =>
|
||||
expect(screen.getAllByText("로그인 전").length).toBeGreaterThan(0),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not offer sign-in after restored", async () => {
|
||||
const user = userEvent.setup();
|
||||
const owner = recoveringOwner("restored", "authenticated");
|
||||
renderAt("/fixture/items", owner.session);
|
||||
|
||||
await user.click(await main().findByRole("button", { name: "세션 복구" }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(main().queryByRole("button", { name: "로그인 시작" })).toBeNull(),
|
||||
);
|
||||
expect(main().queryByRole("button", { name: "세션 복구" })).toBeNull();
|
||||
});
|
||||
});
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import { createCookieSessionOwner } from "../../../../../../recipes/session-owners/cookie-session-owner.ts";
|
||||
|
||||
export const sessionOwnerRecipeInProduction = createCookieSessionOwner;
|
||||
@@ -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<Response>> = [],
|
||||
cookie: Record<string, string> = { "XSRF-TOKEN": "xsrf-1" },
|
||||
) {
|
||||
const fetch = vi.fn<SessionOwnerFetch>(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" } });
|
||||
});
|
||||
});
|
||||
@@ -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<string, unknown>) =>
|
||||
`${encode({ alg: "RS256", typ: "JWT" })}.${encode(claims)}.signature`;
|
||||
|
||||
type Call = Readonly<{ url: string; init: Parameters<SessionOwnerFetch>[1] }>;
|
||||
|
||||
function harness(
|
||||
overrides: Partial<OidcPkceSessionOwnerOptions> = {},
|
||||
setup: Readonly<{ href?: string; storage?: Record<string, string> }> = {},
|
||||
) {
|
||||
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<Response>> = [];
|
||||
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<string, unknown> = {}) =>
|
||||
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<string, unknown> = {},
|
||||
claims: Record<string, unknown> = {},
|
||||
) => {
|
||||
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<SessionOwnerFetch>(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<typeof harness>,
|
||||
returnTo = "/items?limit=1",
|
||||
params: Readonly<Record<string, string>> = {},
|
||||
) {
|
||||
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<OidcPkceSessionOwnerOptions> = {}) {
|
||||
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<OidcPkceSessionOwnerOptions>).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");
|
||||
}
|
||||
@@ -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<T extends { contract: object; frontend: object }>(
|
||||
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<typeof import("../../src/features/installed-contract-contributions.ts")>();
|
||||
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<typeof import("../../src/features/installed-feature-adapters.ts")>();
|
||||
return {
|
||||
...original,
|
||||
createInstalledFeatureLoaders: (
|
||||
...args: Parameters<typeof original.createInstalledFeatureLoaders>
|
||||
) => {
|
||||
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<string, unknown>) =>
|
||||
`${encode({ alg: "RS256" })}.${encode(claims)}.signature`;
|
||||
|
||||
let dispose: (() => void) | undefined;
|
||||
afterEach(() => {
|
||||
dispose?.();
|
||||
dispose = undefined;
|
||||
fixture.http = undefined;
|
||||
});
|
||||
|
||||
async function compose(
|
||||
host: Record<string, unknown>,
|
||||
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<typeof vi.fn>) {
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -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<Response>(() => {});
|
||||
|
||||
/** A body that sends one chunk and then nothing. */
|
||||
function stalledBody(): ReadableStream<Uint8Array> {
|
||||
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<typeof bounded>[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<Uint8Array>({
|
||||
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<string, unknown>, 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<string, string>();
|
||||
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();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user