Files
clean-architecture-frontend…/src/contracts/rest-profiles.ts
T
DongHyeonka 12f3bb7862 refactor(contracts)!: V2 API 행을 지우고 FE-REG-API를 HTTP descriptor에서 뽑는다
문제
기능 하나가 같은 HTTP API를 두 번 적는다. *-api-contract.ts의 V2 행
(defineRestOperation)은 check:registries(FE-REG-API)가 검사하는 선언이고,
contract contribution의 V3 descriptor가 실제로 실행된다. 둘이 어긋나지 않게
http-operation-v2-v3-parity 테스트를 따로 둔다. 048f490으로 V2 클라이언트가
없어져 V2 행을 읽는 실행 코드는 없고, 검사만 남은 두 번째 사본이다. V2 행을
위한 기능별 runtimeSchemas·mappers 레지스트리와 V2 보안 프로필 해석
(resolveRestSecurityProfiles)도 같이 남아 있다. 사용자 지시: 최신 경로 하나만
남기고, 레지스트리 기준선 재승인을 승인했다.

고른 방법
- src/contracts/api-operations.ts를 projectApiOperationRows 하나로 바꿨다.
  조립된 contribution의 descriptor마다 operationId, featureId, method, path,
  authProfileId, retrySemantics, requestBody, responseBody, responseEnvelope,
  request/response/problemSchema(검증기 schemaId) 행을 만든다. FE-REG-API는
  같은 export(API_OPERATIONS)를 읽고, governance 정의를 이 필드로 바꿨다.
  requestSchema·responseSchema는 그대로 FE-REG-SCHEMA를 참조한다.
- FeatureRuntime은 apiContract 대신 schemas(FE-REG-SCHEMA 행)만 받는다.
  installed-feature-runtime-registries는 schemas로 스키마 레지스트리를 만들고
  FE-REG-API 행을 descriptor에서 뽑는다. RUNTIME_SCHEMA_CODECS, MAPPER_REGISTRY,
  REST_PROFILE_BINDINGS_VALID, API_RUNTIME_BINDINGS_VALID를 지웠다.
- realtime snapshot 바인딩은 ApiOperationRow를 받고 method GET과
  retrySemantics SAFE·IDEMPOTENT를 본다(V2의 contractVersion·semantics·
  replayPolicy 대신).
- rest-profiles.ts에서 V2 행용 provider·CSRF 프로필 해석을 지웠다. V3는 조립
  때 auth profile을 검사하고 자격증명 헤더를 프로필로 거른다.
- 참조 기능: reference-api-contract.ts를 reference-schema-metadata.ts로
  바꾸고(스키마 행만), V2 runtime codec·operation mapper·레지스트리 mapper를
  지웠다. V3 descriptor가 쓰지 않는 NoRequest 스키마 행도 지웠다.
- create:feature: <base>-api-contract.ts 대신 <base>-schema-metadata.ts를
  만든다. codec·mapper 레지스트리 행과 그 테스트를 만들지 않는다.
- 레지스트리 기준선을 update:registry-baseline으로 다시 만들고 승인했다
  (digest 16f72742…, 승인자 DongHyeonka, 이유에 사용자 승인을 적음).
- 매뉴얼 01·02·reference, starter-experience, 계약 문서의 V2 설명을 지웠다.

버린 대안
- V2 행을 남기고 V3에서 생성하기: 생성 단계와 생성물이 하나 더 생긴다. 행은
  실행되지 않으므로 메모리에서 뽑아 검사하면 충분하다.
- 스키마 메타데이터(FE-REG-SCHEMA 행)도 검증기에서 뽑기: boundary·
  unknownFieldPolicy·owner는 검증기에 없고, 라우트 스키마도 같은 레지스트리를
  쓴다. 이 행은 V2가 아니라 스키마 레지스트리라 남겼다.

위험·한계
- BREAKING: FeatureRuntime 모양, contracts·rest-profiles·loaded-feature-runtimes
  의 이름이 바뀌거나 없어졌다. memento-frontend의 memento-web이 V2 행을 쓴다.
  옮기는 법은 CHANGELOG에 적는다.
- V2 보안 프로필 일관성 검사(auth "none"과 ANONYMOUS, 쿠키 프로필의 CSRF
  모드)가 사라졌다. V3 descriptor에는 그 칸이 없다.
- BoundedPollOperationContract(realtime polling recipe)는 contractVersion: 2
  필드를 갖지만 자체 계약이라 바꾸지 않았다.

검증
- check:types, lint, check:architecture, check:registries(11 registries PASS,
  compatibility=none), check:ci, check:diagnostics, check:adapter-inventory,
  verify:documentation 통과.
- test:unit 2,566(새 tests/unit/api-operation-rows.test.ts 3건 포함),
  test:integration 114, test:component 245, test:contract 23,
  test:runtime-schema 56, tests/features 99 통과.
- tests/unit/second-api-feature-registries.test.ts: V3 descriptor만 가진 두
  번째 기능을 복사본에 넣으면 기준선을 고치지 않고 check:registries가 통과한다.
- check:bundle 통과. 초기 JS 201,598 → 200,911 B.
- test:feature-scaffold 16개, test:sample-removal 23개 검사 통과.

BREAKING CHANGE: FeatureRuntime이 apiContract 대신 schemas를 받는다.
defineRestOperation, ApiOperation, RestOperationV2, composeApiOperations,
validateApiRuntimeBindings, getApiOperation, contracts의 API_OPERATIONS,
createRestProviderProfile, RestProviderProfile, resolveRestSecurityProfiles,
validateRestProfileBindings, REST_CSRF_PROFILES, RestCsrfProfile,
loaded-feature-runtimes의 RUNTIME_SCHEMA_CODECS, MAPPER_REGISTRY,
REST_PROFILE_BINDINGS_VALID, API_RUNTIME_BINDINGS_VALID가 없어졌다. 기능은
operation을 contract contribution에만 적고, schemas 행을 feature-runtime에
넘긴다.
2026-11-03 21:37:48 +09:00

223 lines
7.6 KiB
TypeScript

import {
createReadOnlyRegistry,
type ReadOnlyRegistry,
} from "./read-only-registry.ts";
import { snapshotExactArray, snapshotExactObject } from "./exact-snapshot.ts";
import { PRODUCT_REST_AUTH_PROFILES } from "./product-contracts.ts";
export type FetchCredentialsMode = "omit" | "same-origin" | "include";
/**
* VD-23. The complete closed set of headers a credential owner may contribute.
* Transport-owned headers (`accept`, `content-type`, `idempotency-key`) and
* every forbidden request header are deliberately absent.
*
* `x-xsrf-token` is the paired backend's default CSRF header (Spring
* `CookieCsrfTokenRepository`, `APP_SESSION_CSRF_HEADER_NAME`). A profile
* still has to name it in its own allowed set before a provider may send it.
*/
export const CREDENTIAL_HEADER_NAMES = Object.freeze([
"authorization",
"x-csrf-token",
"x-xsrf-token",
"x-tenant-context",
] as const);
export type CredentialHeaderName = (typeof CREDENTIAL_HEADER_NAMES)[number];
export type RestAuthProfile = Readonly<{
authProfileId: string;
transport: "ANONYMOUS" | "BEARER_HEADER" | "SAME_ORIGIN_COOKIE";
credentials: FetchCredentialsMode;
allowedCredentialHeaders: readonly CredentialHeaderName[];
/**
* Proof headers the transport must observe before dispatch. A missing entry
* fails closed with zero `fetch()` calls rather than sending an anonymous
* request under an authenticated profile.
*/
requiredCredentialHeaders: readonly CredentialHeaderName[];
}>;
/**
* LIVE-02. A read facade over a private store, never a `Map`. The executor
* resolves a profile on every request, so a post-installation `clear()` would
* otherwise turn every authenticated call into `UNKNOWN_AUTH_PROFILE`.
*/
export type InstalledRestAuthProfiles = ReadOnlyRegistry<
string,
RestAuthProfile
>;
const EXTERNAL_BEARER = Object.freeze({
authProfileId: "EXTERNAL_BEARER",
transport: "BEARER_HEADER",
credentials: "omit",
allowedCredentialHeaders: Object.freeze(["authorization"] as const),
requiredCredentialHeaders: Object.freeze(["authorization"] as const),
});
export const REST_AUTH_PROFILES = Object.freeze({
EXTERNAL_BEARER,
/**
* @deprecated 16-03: use `EXTERNAL_BEARER`. Same transport and headers under
* the sample's old name, kept for one release so a downstream operation that
* still names it resolves. Remove it in the next minor release with a
* CHANGELOG [계약] entry (owner: frontend-platform).
*/
REFERENCE_EXTERNAL_BEARER: Object.freeze({ ...EXTERNAL_BEARER, authProfileId: "REFERENCE_EXTERNAL_BEARER" }),
ANONYMOUS: Object.freeze({
authProfileId: "ANONYMOUS",
transport: "ANONYMOUS",
credentials: "omit",
allowedCredentialHeaders: Object.freeze([]),
requiredCredentialHeaders: Object.freeze([]),
}),
} satisfies Readonly<Record<string, RestAuthProfile>>);
function isCredentialHeaderName(value: unknown): value is CredentialHeaderName {
return (
typeof value === "string" &&
(CREDENTIAL_HEADER_NAMES as readonly string[]).includes(value)
);
}
function exactHeaderSet(
source: unknown,
label: string,
): readonly CredentialHeaderName[] {
// Q-6.7-6. Copied by index, so the set that is checked is the set installed.
const names = snapshotExactArray(source);
if (!names) {
throw new TypeError(`REST auth profile ${label} must be an array.`);
}
const seen = new Set<string>();
for (const name of names) {
if (!isCredentialHeaderName(name) || seen.has(name)) {
throw new TypeError(`REST auth profile ${label} is not an exact set.`);
}
seen.add(name);
}
return names as readonly CredentialHeaderName[];
}
const AUTH_PROFILE_KEYS = Object.freeze([
"authProfileId",
"transport",
"credentials",
"allowedCredentialHeaders",
"requiredCredentialHeaders",
] as const);
/**
* §7.7 / VD-23. Installs the composition-owned auth profile registry once.
*
* The registry — not a credential collaborator — owns Fetch `credentials` and
* the exact allowed/required credential-header sets. An incoherent profile is a
* composition failure, never a runtime downgrade.
*/
export function installRestAuthProfileRegistry(
profiles: Readonly<Record<string, RestAuthProfile>> = REST_AUTH_PROFILES,
): InstalledRestAuthProfiles {
const installed = new Map<string, RestAuthProfile>();
for (const [key, source] of Object.entries(profiles)) {
// Q-6.7-6. Every check reads one owned snapshot, never the caller's row.
const candidate = snapshotExactObject(source, {
allowed: AUTH_PROFILE_KEYS,
required: AUTH_PROFILE_KEYS,
}) as RestAuthProfile | null;
if (!candidate) {
throw new TypeError(
`REST auth profile ${key} is not an exact own-data object.`,
);
}
const authProfileId = candidate.authProfileId;
if (
typeof authProfileId !== "string" ||
authProfileId.length === 0 ||
authProfileId !== key
) {
throw new TypeError(`REST auth profile ${key} has a mismatched identity.`);
}
const allowed = exactHeaderSet(
candidate.allowedCredentialHeaders,
"allowedCredentialHeaders",
);
const required = exactHeaderSet(
candidate.requiredCredentialHeaders,
"requiredCredentialHeaders",
);
if (!required.every((name) => allowed.includes(name))) {
throw new TypeError(
`REST auth profile ${key} requires a header it does not allow.`,
);
}
const credentials = candidate.credentials;
if (!["omit", "same-origin", "include"].includes(credentials)) {
throw new TypeError(`REST auth profile ${key} has invalid credentials.`);
}
switch (candidate.transport) {
case "ANONYMOUS":
if (
credentials !== "omit" ||
allowed.length > 0 ||
required.length > 0
) {
throw new TypeError(
`Anonymous REST auth profile ${key} cannot carry credentials.`,
);
}
break;
case "BEARER_HEADER":
if (credentials !== "omit" || !required.includes("authorization")) {
throw new TypeError(
`Bearer REST auth profile ${key} must require authorization with omitted credentials.`,
);
}
break;
case "SAME_ORIGIN_COOKIE":
if (credentials === "omit" || allowed.includes("authorization")) {
throw new TypeError(
`Cookie REST auth profile ${key} must send ambient credentials without a bearer header.`,
);
}
break;
default:
throw new TypeError(`REST auth profile ${key} has unknown transport.`);
}
installed.set(
authProfileId,
Object.freeze({
authProfileId,
transport: candidate.transport,
credentials,
allowedCredentialHeaders: allowed,
requiredCredentialHeaders: required,
}),
);
}
if (installed.size === 0) {
throw new TypeError("REST auth profile registry cannot be empty.");
}
return createReadOnlyRegistry(installed);
}
function withProductProfiles(): Readonly<Record<string, RestAuthProfile>> {
const reused = Object.keys(PRODUCT_REST_AUTH_PROFILES).find((id) =>
Object.hasOwn(REST_AUTH_PROFILES, id),
);
if (reused !== undefined) {
throw new TypeError(
`Product REST auth profile ${reused} reuses a template profile id.`,
);
}
return { ...REST_AUTH_PROFILES, ...PRODUCT_REST_AUTH_PROFILES };
}
/**
* The single installed registry every composition root shares. 09-02. It
* holds the product's profiles (`product-contracts.ts`) too, under the same
* checks.
*/
export const INSTALLED_REST_AUTH_PROFILES: InstalledRestAuthProfiles =
installRestAuthProfileRegistry(withProductProfiles());