문제
유일한 bearer 인증 프로필 이름이 샘플 이름 REFERENCE_EXTERNAL_BEARER다.
세션이 필요한 제품 기능은 지운 샘플의 이름을 계속 쓰거나 템플릿 소유
파일에 프로필을 더해야 한다. 샘플 제거 드릴의 잔여 검사 정규식도 이
이름을 잡지 않아 샘플을 지운 제품에 그대로 남는다. 리뷰 (2) 오류
메시지는 abf3ce5가 했고 (1) 이름 변경이 남았다.
고른 방법 (2026-11-03 결정)
- 프로필 이름을 EXTERNAL_BEARER로 바꿨다. 참조 기능의 V2 operation 3개와
V3 descriptor 3개, external-session-adapter 주석, 테스트, VD-23 문서를
새 이름으로 옮겼다.
- 옛 이름은 한 릴리스 동안 REST_AUTH_PROFILES에 별칭 한 줄로 남기고
JSDoc @deprecated를 붙였다. 레지스트리는 키와 authProfileId가 같아야
하므로 별칭은 EXTERNAL_BEARER를 펼치고 id만 옛 이름으로 둔 객체다.
그래서 옛 이름을 적은 다운스트림 operation도 같은 transport·헤더로
해석된다.
- scripts/scale의 PLATFORM_TOKENS에서 이 이름을 뺐다. 참조 기능에 더는
"REFERENCE"가 든 프로필 이름이 없어 이름 바꾸기에서 보호할 것이 없다.
- 새 테스트 두 개: 별칭이 id만 빼고 EXTERNAL_BEARER와 같게 설치되는지,
src에 옛 이름이 별칭 한 줄 외에 없는지(완료 기준).
버린 대안
- 별칭 없이 바로 바꾸기: 옛 이름을 쓰는 다운스트림 기능이 모듈 로드에서
바로 실패한다. 공개 이름을 깨는 변경은 BREAKING 결정이 있을 때만 한다.
- 조회 시점의 이름 매핑(alias 표): resolve·executor·composition 세 곳이
매핑을 알아야 한다. 프로필 항목 하나가 더 작다.
위험·한계
- 설치된 프로필이 셋이 된다. 같은 설정이 두 id로 있을 뿐 권한이 넓어지지
않는다. 별칭은 다음 minor에서 지우고 CHANGELOG [계약] 행을 남긴다.
그때 "src only on the alias line" 테스트의 기대값을 빈 목록으로 바꾼다.
- 다운스트림 문자열 id("REFERENCE_EXTERNAL_BEARER")에는 @deprecated 표시가
보이지 않는다. CHANGELOG로 알린다.
- FE-REG-API 행 3개의 authProfileId가 바뀐다. breakingFields가 아니라
behavior-change이므로 증거 없이 게이트를 통과한다. 기준선 재승인은 이번
작업 묶음 끝에서 한 번에 한다.
- 초기 JS gzip(초기 청크 파일별 gzip 합) 203,818 → 203,840 B(+22 B). 별칭
항목이 rest-profiles가 있는 초기 청크에 실린다. 참조 기능 계약은 lazy
청크라 초기 크기에 영향이 없다.
검증
- RED(수정 전): rest-profile-contract.test.ts 새 사례 2건 실패("expected
undefined to match object { transport: 'BEARER_HEADER', …(1) }",
"expected [ …(9) ] to deeply equal [ Array(1) ]").
- GREEN: 같은 파일 10/10 통과. check-registries "11 registries PASS"
(FE-REG-API authProfileId 3건 behavior-change).
- 회귀: tests/{unit,integration,features,contract,runtime-schema}
207 파일 2,366건 통과(pnpm·corepack을 띄우는 6개 제외:
http-scenario-evidence, ci-workflow-generation, lab-performance,
fixture-node-modules, deployment-admission, security-followup-archive).
tsc app·test·node rc=0, 바꾼 파일 eslint rc=0. vite build 성공.
- 미실행: check:architecture, test:sample-removal(pnpm 필요), e2e.
Refs: docs/reviews/2026-11-01-maturity-review/16-structure-patterns.md
382 lines
13 KiB
TypeScript
382 lines
13 KiB
TypeScript
import {
|
|
createReadOnlyRegistry,
|
|
type ReadOnlyRegistry,
|
|
} from "./read-only-registry.ts";
|
|
import { snapshotExactArray, snapshotExactObject } from "./exact-snapshot.ts";
|
|
import { isLoopbackHostname } from "./deployment-admission.ts";
|
|
|
|
export type FetchCredentialsMode = "omit" | "same-origin" | "include";
|
|
|
|
export type RestProviderProfile = Readonly<{
|
|
providerId: string;
|
|
baseUrl: string;
|
|
allowedCredentialsModes: readonly FetchCredentialsMode[];
|
|
redirect: "error";
|
|
referrerPolicy: "no-referrer";
|
|
}>;
|
|
|
|
/**
|
|
* 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.
|
|
*/
|
|
export const CREDENTIAL_HEADER_NAMES = Object.freeze([
|
|
"authorization",
|
|
"x-csrf-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
|
|
>;
|
|
|
|
export type RestCsrfProfile = Readonly<{
|
|
csrfProfileId: string;
|
|
mode: "NONE" | "HEADER";
|
|
headerName: "x-csrf-token" | null;
|
|
}>;
|
|
|
|
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.");
|
|
}
|
|
const registry = createReadOnlyRegistry(installed);
|
|
INSTALLED_REGISTRIES.add(registry);
|
|
return registry;
|
|
}
|
|
|
|
/** Registries this module installed, as opposed to look-alike objects. */
|
|
const INSTALLED_REGISTRIES = new WeakSet<object>();
|
|
|
|
/**
|
|
* REST auth profiles as accepted by resolve: the installed registry, or a raw
|
|
* record that is installed (validated) before any lookup.
|
|
*/
|
|
export type RestAuthProfileSource =
|
|
| InstalledRestAuthProfiles
|
|
| Readonly<Record<string, RestAuthProfile>>;
|
|
|
|
/**
|
|
* Q-6.7-9. Composition, the V3 executor and V2 resolve answer from one
|
|
* validated registry. A raw record never reaches a lookup unvalidated, so a
|
|
* profile installation would refuse cannot be resolved either.
|
|
*/
|
|
function installedAuthProfiles(
|
|
profiles: RestAuthProfileSource,
|
|
): InstalledRestAuthProfiles {
|
|
return INSTALLED_REGISTRIES.has(profiles)
|
|
? (profiles as InstalledRestAuthProfiles)
|
|
: installRestAuthProfileRegistry(
|
|
profiles as Readonly<Record<string, RestAuthProfile>>,
|
|
);
|
|
}
|
|
|
|
/** The single installed registry every composition root shares. */
|
|
export const INSTALLED_REST_AUTH_PROFILES: InstalledRestAuthProfiles =
|
|
installRestAuthProfileRegistry();
|
|
|
|
export const REST_CSRF_PROFILES = Object.freeze({
|
|
NO_CSRF_BEARER: Object.freeze({
|
|
csrfProfileId: "NO_CSRF_BEARER",
|
|
mode: "NONE",
|
|
headerName: null,
|
|
}),
|
|
} satisfies Readonly<Record<string, RestCsrfProfile>>);
|
|
|
|
export function createRestProviderProfile(
|
|
providerId: string,
|
|
baseUrl: string,
|
|
allowedCredentialsModes: readonly FetchCredentialsMode[] = ["omit"],
|
|
): RestProviderProfile {
|
|
const parsed = new URL(baseUrl);
|
|
const localHttp =
|
|
parsed.protocol === "http:" &&
|
|
isLoopbackHostname(parsed.hostname);
|
|
if (
|
|
!providerId ||
|
|
(parsed.protocol !== "https:" && !localHttp) ||
|
|
parsed.username ||
|
|
parsed.password ||
|
|
parsed.search ||
|
|
parsed.hash ||
|
|
allowedCredentialsModes.length === 0 ||
|
|
new Set(allowedCredentialsModes).size !== allowedCredentialsModes.length
|
|
) {
|
|
throw new TypeError("Invalid REST provider profile.");
|
|
}
|
|
return Object.freeze({
|
|
providerId,
|
|
baseUrl: parsed.href,
|
|
allowedCredentialsModes: Object.freeze([...allowedCredentialsModes]),
|
|
redirect: "error",
|
|
referrerPolicy: "no-referrer",
|
|
});
|
|
}
|
|
|
|
export function resolveRestSecurityProfiles(
|
|
operation: Readonly<{
|
|
operationId?: string;
|
|
method: string;
|
|
auth: "none" | "external-session";
|
|
authProfileId?: string;
|
|
csrfProfileId?: string;
|
|
}>,
|
|
provider: RestProviderProfile,
|
|
authProfiles: RestAuthProfileSource = INSTALLED_REST_AUTH_PROFILES,
|
|
csrfProfiles: Readonly<Record<string, RestCsrfProfile>> = REST_CSRF_PROFILES,
|
|
): Readonly<{ auth: RestAuthProfile; csrf: RestCsrfProfile }> {
|
|
const authProfileId = operation.authProfileId ?? "";
|
|
const auth = installedAuthProfiles(authProfiles).get(authProfileId);
|
|
const csrfProfileId = operation.csrfProfileId ?? "";
|
|
const csrf = Object.hasOwn(csrfProfiles, csrfProfileId)
|
|
? csrfProfiles[csrfProfileId]
|
|
: undefined;
|
|
const unsafe = !["GET", "HEAD", "OPTIONS"].includes(operation.method);
|
|
// 16-03. Every broken condition is named, with the operation and profile
|
|
// ids, so a renamed or missing profile does not have to be found by
|
|
// comparing each rule by hand.
|
|
const broken = [
|
|
!auth && `unknown authProfileId ${authProfileId || "(none)"}`,
|
|
!csrf && `unknown csrfProfileId ${csrfProfileId || "(none)"}`,
|
|
auth &&
|
|
!provider.allowedCredentialsModes.includes(auth.credentials) &&
|
|
`provider ${provider.providerId} does not allow credentials "${auth.credentials}" of ${authProfileId}`,
|
|
auth &&
|
|
operation.auth === "none" &&
|
|
auth.transport !== "ANONYMOUS" &&
|
|
`auth "none" needs an ANONYMOUS profile, ${authProfileId} is ${auth.transport}`,
|
|
auth &&
|
|
operation.auth === "external-session" &&
|
|
auth.transport === "ANONYMOUS" &&
|
|
`auth "external-session" cannot use the ANONYMOUS profile ${authProfileId}`,
|
|
auth?.transport === "BEARER_HEADER" &&
|
|
csrf &&
|
|
csrf.mode !== "NONE" &&
|
|
`bearer profile ${authProfileId} cannot use CSRF mode ${csrf.mode} of ${csrfProfileId}`,
|
|
unsafe &&
|
|
auth?.transport === "SAME_ORIGIN_COOKIE" &&
|
|
csrf &&
|
|
csrf.mode !== "HEADER" &&
|
|
`${operation.method} with cookie profile ${authProfileId} needs a HEADER CSRF profile, ${csrfProfileId} is ${csrf.mode}`,
|
|
].filter((condition): condition is string => typeof condition === "string");
|
|
if (!auth || !csrf || broken.length > 0) {
|
|
throw new TypeError(
|
|
`REST security profiles are incoherent for ${operation.operationId ?? "an operation"}: ${broken.join("; ")}.`,
|
|
);
|
|
}
|
|
return Object.freeze({ auth, csrf });
|
|
}
|
|
|
|
export function validateRestProfileBindings(
|
|
operations: Readonly<
|
|
Record<
|
|
string,
|
|
Readonly<{
|
|
contractVersion?: number;
|
|
operationId: string;
|
|
method: string;
|
|
auth: "none" | "external-session";
|
|
providerId?: string;
|
|
authProfileId?: string;
|
|
csrfProfileId?: string;
|
|
}>
|
|
>
|
|
>,
|
|
providerCredentialModes: Readonly<
|
|
Record<string, readonly FetchCredentialsMode[]>
|
|
>,
|
|
authProfiles: RestAuthProfileSource = INSTALLED_REST_AUTH_PROFILES,
|
|
csrfProfiles: Readonly<Record<string, RestCsrfProfile>> = REST_CSRF_PROFILES,
|
|
): true {
|
|
const installed = installedAuthProfiles(authProfiles);
|
|
for (const operation of Object.values(operations)) {
|
|
if (operation.contractVersion !== 2) continue;
|
|
const allowed = providerCredentialModes[operation.providerId ?? ""];
|
|
if (!allowed) {
|
|
throw new TypeError(
|
|
`Unregistered REST provider binding: ${operation.operationId}`,
|
|
);
|
|
}
|
|
resolveRestSecurityProfiles(
|
|
operation,
|
|
Object.freeze({
|
|
providerId: operation.providerId ?? "",
|
|
baseUrl: "https://contract.invalid/",
|
|
allowedCredentialsModes: allowed,
|
|
redirect: "error",
|
|
referrerPolicy: "no-referrer",
|
|
}),
|
|
installed,
|
|
csrfProfiles,
|
|
);
|
|
}
|
|
return true;
|
|
}
|