Files
clean-architecture-frontend…/scripts/check-optional-recipe-fixtures.ts
T
DongHyeonka 05958bbdb6 feat(recipes): 짝 백엔드 두 인증 모드의 세션 owner recipe를 더한다
문제: AUTH_MODE external은 제품이 owner 8개 메서드를 직접 써야 하는데,
짝 백엔드(JWT·Keycloak 또는 Redis session)에 맞는 owner가 src·recipes
어디에도 없다. 쿠키 owner 모양은 테스트 파일 안 스케치뿐이다. 그래서
제품마다 첫 연동 전에 토큰 획득·갱신·subject·상태 전이·401 처리를
처음부터 쓴다.

짝 백엔드(bbe944bd)에서 확인한 계약:
- jwt 모드(기본): OAuth2 resource server. iss = APP_SECURITY_JWT_ISSUER
  (local http://localhost:8081/realms/ca-skeleton), aud 필수. CSRF·세션
  없음. 그러나 realm에는 서비스용 confidential client(ca-skeleton-api,
  standard flow 꺼짐)만 있고 브라우저용 public client가 없다.
- redis-session 모드: CA_SESSION httpOnly 쿠키, CookieCsrfTokenRepository
  (XSRF-TOKEN 쿠키, X-XSRF-TOKEN 헤더, plain handler). 로그인·로그아웃·
  세션 조회·CSRF 발급 엔드포인트는 운영 코드에 없다(테스트 픽스처만).

고른 방법: recipes/session-owners/에 둘을 둔다. 제품은 src/bootstrap/로
복사해 composeProductSessionOwner에서 돌려준다.
- oidc-pkce-session-owner.ts: authorization code + PKCE S256, WebCrypto와
  context fetch만 쓴다(라이브러리 없음). 토큰은 메모리에만, sessionStorage
  에는 10분짜리 거래(verifier·state·nonce·returnTo)만 두고 콜백이 먼저
  지운다. 콜백 URL에서 code를 네트워크 호출 전에 지운다. state·RFC 9207
  iss·nonce·aud·azp·exp·sub를 검사하고, 갱신 때 sub가 바뀌면 로그아웃.
  bearer는 apiOrigins에만 보낸다. 만료 30초 전 갱신은 한 번만 하고 상태
  알림이 없다. 401이면 refresh token으로 한 번 복구하고, 그 토큰도 401이면
  로그아웃. 설정이 틀리면 integration-failed로 닫는다.
- cookie-session-owner.ts: 세션 조회·로그아웃 URL과 로그인 시작을 기본값
  없이 받는다(백엔드에 없는 엔드포인트를 지어내지 않는다). 200+subject →
  authenticated, 401 → unauthenticated, 그 밖은 reject(상태 유지).
  SESSION_COOKIE_READ/WRITE 프로필과 XSRF-TOKEN → x-xsrf-token provider.
  쿠키가 없으면 쓰기는 UNAVAILABLE로 아무것도 보내지 않는다.
- 두 owner 모두 SessionState·recover 전이 계약을 따른다.
- PRODUCTION_IMPORTS_RECIPE 검사를 recipes/session-owners에도 건다.
  recipe는 복사하지 import하지 않는다(초기 번들 밖).
버린 대안: src에 기본 owner 내장(IdP 결합이 템플릿 본체에 들어간다),
OIDC 라이브러리 의존(fetch·WebCrypto로 충분), 매뉴얼만(같은 실수 반복).

위험·한계: 실제 Keycloak·Redis session 백엔드에 붙여 보지 않았다. ID
token 서명은 검사하지 않는다(토큰 엔드포인트 직접 응답, OIDC Core
3.1.3.7 (6)); access token 서명은 백엔드가 본다. 새로고침하면 메모리
토큰이 사라져 다시 로그인한다(Keycloak SSO면 비밀번호 없이 돌아온다).
쿠키 모드는 페이지와 API가 같은 host여야 XSRF-TOKEN을 읽는다.

검증: tests/recipes 3파일 52건(구현 전 모듈 없음으로 실패 확인).
변이 15개(state·origin·401 한 번·nonce·iss·URL 정리·갱신 sub·TTL,
CSRF 헤더·401·로그아웃 실패·notify·단일 조회·subject 상한·credentials)
모두 실패로 잡힘. runtime 조립 테스트 4건이 실제 createRuntimeAdapters로
EXTERNAL_BEARER bearer, 401 뒤 갱신, 쿠키 쓰기의 x-xsrf-token을 확인.
check:optional-recipe-fixtures(regex 변경 없이는 실패 확인),
check:optional-recipes:source, check:types, eslint 통과. 두 recipe의
minify+gzip 크기 3.8 kB, 1.1 kB.

Refs: docs/reviews/2026-11-03-maturity-review/09-app-core.md 09-03
2026-11-04 20:47:24 +09:00

212 lines
6.8 KiB
TypeScript

import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { measureOptionalRecipeBundle } from "./lib/optional-recipe-bundle.ts";
import { optionalRecipeFixturesArtifactSchema } from "./contracts/release-artifacts.ts";
import {
scanOptionalRecipeSources,
scanProductionBundle,
validateRecipeCatalog,
} from "./lib/optional-recipes.ts";
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
type ReferenceRuntimeRecipe = Readonly<{
id: string;
referenceRuntime: Readonly<{
sourceRoots: readonly string[];
}>;
}>;
const catalog = JSON.parse(
await readFile("config/recipes/frontend-capability-recipes.json", "utf8"),
);
const packageDocument = JSON.parse(await readFile("package.json", "utf8"));
const catalogRecipes: unknown[] = Array.isArray(catalog.recipes)
? (catalog.recipes as unknown[])
: [];
const referenceRuntimeRecipes = catalogRecipes.filter(
(recipe: unknown): recipe is ReferenceRuntimeRecipe =>
Boolean(
recipe &&
typeof recipe === "object" &&
typeof (recipe as Record<string, unknown>).id === "string" &&
(recipe as Record<string, unknown>).referenceRuntime &&
typeof (recipe as Record<string, unknown>).referenceRuntime ===
"object" &&
Array.isArray(
(
(recipe as Record<string, unknown>)
.referenceRuntime as Record<string, unknown>
).sourceRoots,
),
),
);
const bundleBudgetFixtures = await Promise.all(
referenceRuntimeRecipes.map(async (recipe) => {
const measurement = await measureOptionalRecipeBundle({
recipeId: recipe.id,
sourceRoots: recipe.referenceRuntime.sourceRoots,
bundleBudgetGzipBytes: 1,
});
return Object.freeze({
recipeId: recipe.id,
gzipBytes: measurement.gzipBytes,
fixtureBudgetGzipBytes: measurement.bundleBudgetGzipBytes,
rejected: !measurement.passed,
});
}),
);
const cleanupCatalog = structuredClone(catalog);
cleanupCatalog.recipes.find(
(recipe: { id: string }) => recipe.id === "realtime",
).lifecycleMethods = [];
const dependencyCatalog = structuredClone(catalog);
dependencyCatalog.productionRuntimeDependencies = ["zustand"];
const workflowCatalog = structuredClone(catalog);
workflowCatalog.recipes.find(
(recipe: { id: string }) => recipe.id === "client-workflow",
).serverStatePolicy = "copied-server-state";
const sourceViolations = await scanOptionalRecipeSources(
"tests/fixtures/optional-recipes/forbidden",
{ scanProductionBoundary: false },
);
const productionViolations = await scanOptionalRecipeSources(
"tests/fixtures/optional-recipes/forbidden/production-import",
{ scanProductionBoundary: true },
);
const runtimeCompositionViolations = await scanOptionalRecipeSources(
"tests/fixtures/optional-recipes/forbidden/runtime-composition",
{ scanProductionBoundary: true },
);
const bundleFixtureRoot = ".tmp/optional-recipe-runtime-bundle";
await rm(bundleFixtureRoot, { recursive: true, force: true });
await mkdir(`${bundleFixtureRoot}/assets`, { recursive: true });
await writeFile(
`${bundleFixtureRoot}/assets/runtime.js`,
'throw new TypeError("OPFS runtime policy is invalid.");\n',
);
const bundleViolations = await scanProductionBundle(bundleFixtureRoot);
await rm(bundleFixtureRoot, { recursive: true, force: true });
const inventoryFixtureRoot =
".tmp/optional-recipe-runtime-module-inventory";
await rm(inventoryFixtureRoot, { recursive: true, force: true });
await mkdir(`${inventoryFixtureRoot}/.vite`, { recursive: true });
await writeFile(`${inventoryFixtureRoot}/.vite/manifest.json`, "{}\n");
await writeFile(
`${inventoryFixtureRoot}/.vite/module-inventory.json`,
`${JSON.stringify({
schemaVersion: 1,
chunks: [
{
fileName: "assets/application.js",
modules: [
"src/adapters/browser-files/browser-file-vault.ts",
],
},
],
})}\n`,
);
const inventoryViolations =
await scanProductionBundle(inventoryFixtureRoot);
await rm(inventoryFixtureRoot, { recursive: true, force: true });
sourceViolations.push(...productionViolations);
sourceViolations.push(...runtimeCompositionViolations);
const ruleIds = new Set(sourceViolations.map(({ ruleId }) => ruleId));
const results = [
{
id: "cleanup-omission",
passed: validateRecipeCatalog(cleanupCatalog, packageDocument).some(
(violation) => violation === "realtime:CLEANUP_CONTRACT_MISSING",
),
},
{
id: "unselected-runtime-dependency",
passed: validateRecipeCatalog(dependencyCatalog, packageDocument).includes(
"UNSELECTED_RUNTIME_DEPENDENCY",
),
},
{
id: "server-state-policy",
passed: validateRecipeCatalog(workflowCatalog, packageDocument).includes(
"client-workflow:SERVER_STATE_DUPLICATION_POLICY",
),
},
{
id: "vendor-direct-import",
passed: ruleIds.has("VENDOR_IMPORT_OUTSIDE_ADAPTER"),
},
{
id: "credential-leak",
passed: ruleIds.has("CREDENTIAL_LEAK_PATH"),
},
{
id: "server-state-source-duplication",
passed: ruleIds.has("CLIENT_STORE_DUPLICATES_SERVER_STATE"),
},
{
id: "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",
passed: ruleIds.has("REFERENCE_RUNTIME_COMPOSED_WITHOUT_SELECTION"),
},
{
id: "reference-runtime-not-bundled",
passed: bundleViolations.some((file) => file.endsWith("runtime.js")),
},
{
id: "reference-runtime-module-not-bundled",
passed: inventoryViolations.some((violation) =>
violation.includes(
"src/adapters/browser-files/browser-file-vault.ts",
),
),
},
{
id: "reference-runtime-bundle-over-budget",
passed:
bundleBudgetFixtures.length === referenceRuntimeRecipes.length &&
bundleBudgetFixtures.length > 0 &&
bundleBudgetFixtures.every(
(fixture) =>
fixture.gzipBytes > fixture.fixtureBudgetGzipBytes &&
fixture.rejected,
),
},
];
const report = optionalRecipeFixturesArtifactSchema.parse({
schemaVersion: 1,
results,
bundleBudgetFixtures,
passed: results.every(({ passed }) => passed),
});
await mkdir("artifacts/quality", { recursive: true });
await writeValidatedJsonArtifact({
path: "artifacts/quality/optional-recipe-fixtures.json",
schema: optionalRecipeFixturesArtifactSchema,
value: report,
});
if (!report.passed) {
process.stderr.write(
`Optional recipe negative fixtures failed: ${results
.filter(({ passed }) => !passed)
.map(({ id }) => id)
.join(", ")}\n`,
);
process.exit(1);
}
process.stdout.write(
`Optional recipe negative fixtures: PASS (${results.length} forbidden cases rejected)\n`,
);