Files
clean-architecture-frontend…/src/contracts/env.ts
T
DongHyeonka a144b575e5 fix(contracts): FE-REG-ENV 런타임 행의 필수 여부·기본값을 스키마와 맞춘다
문제
FE-REG-ENV 런타임 행 13개 중 5개의 required·defaultValue가 실제 V2
runtime config 스키마(runtimeConfigV2ArtifactSchema)와 다르다.
- TELEMETRY_ENABLED: 행 기본값 false / 스키마 필수, 기본값 없음
- AUTH_MODE: 행 기본값 "external" / 스키마 기본값 없음
- RELEASE_MANIFEST_URL: 행 required true / 스키마 선택(기본값 있음)
- CAPABILITY_OVERRIDES: 행 기본값 null / 스키마 기본값 네 항목 DEFAULT
- FEATURE_OVERRIDES: 행 기본값 null / 스키마 기본값 {}
d0414c8의 테스트는 스키마 키마다 행이 있는지만 본다. 스키마에 없는 런타임
행도, 값이 다른 행도 통과한다. 이 레지스트리는 기준선 호환 검사 대상이라
틀린 값이 계약으로 굳는다. AUTH_MODE를 빼도 external이 된다고 읽으면
부팅이 스키마 오류로 멈춘다.

고른 방법
- env-registry-coverage에 두 방향을 더한다. 스키마가 읽지 않는 런타임 행은
  실패한다. 각 행의 required·defaultValue는 스키마 필드에 undefined를 넣은
  결과(실패 = 필수·기본값 없음, 성공 = 선택·그 값)와 같아야 한다. 차이는
  키·행 값·스키마 값을 한 줄로 보인다. 제품 키(PRODUCT_*)도 같은 검사를
  받는다.
- 5개 행을 스키마에 맞춘다. 두 override 기본값은 객체라 governance의
  defaultValue 타입에 object를 더했다.
- ENV_REGISTRY 주석에 두 칸의 뜻(null = 스키마가 기본값을 주지 않음)을
  적었다.

버린 대안
- 행의 required·defaultValue를 스키마에서 계산해 채우기: 손으로 맞출 일이
  사라지지만 env.ts가 zod 스키마를 import해야 한다. env.ts는 부팅 경로
  (getBuildConfig)에 있어 초기 청크에 zod 스키마가 끌려 들어간다.

위험·한계
- RELEASE_MANIFEST_URL required true→false는 breaking 칸 변경이고
  governance fieldTypes도 바뀌어 기준선을 다시 승인했다.
- 스키마 superRefine의 조건부 필수(TELEMETRY_ENABLED면 TELEMETRY_ENDPOINT)는
  행에 표현하지 않는다.

검증
- RED: 새 대조 테스트가 위 5개 행을 정확히 보고하며 실패했다.
- GREEN: env-registry-coverage 3건 통과. 변이: 스키마 REQUEST_TIMEOUT_MS
  기본값만 20,000으로 바꾸면 실패, 스키마 필드 없는 제품 행을 더하면 실패.
- check:registries(재승인 뒤 compatibility=none), run-vitest related
  (env.ts, governance) 18파일 154건, registry-governance·product-composition
  23건, check:types, eslint 통과.

Refs: docs/reviews/2026-11-03-maturity-review/13-build-release-supply-chain.md 13-04
Refs: docs/reviews/2026-11-03-maturity-review/07-contracts.md P-07-05
2026-11-04 20:27:35 +09:00

182 lines
6.6 KiB
TypeScript

import { PRODUCT_ENV_REGISTRY } from "./product-contracts.ts";
/**
* §6.3. Case-insensitive key fragments that can never appear in a client
* configuration document.
*/
const FORBIDDEN_CONFIG_NAME_FRAGMENTS = Object.freeze([
"PASSWORD",
"SECRET",
"TOKEN",
"PRIVATE_KEY",
"CLIENT_SECRET",
"ACCESS_KEY",
"REFRESH_TOKEN",
"COOKIE",
"AUTHORIZATION",
]);
/**
* Exact top-level keys whose fragment match is a semantic enum name, not a
* credential. The allowlist is exact-key only; it is never applied to arbitrary
* nested keys.
*/
const SEMANTIC_KEY_ALLOWLIST = Object.freeze(
new Set(["AUTH_MODE", "TELEMETRY_ENABLED"]),
);
/**
* R-7.2. Exact top-level keys whose own keys are feature ids (data), not
* configuration names: `cookie-consent` or `token-wallet` is a feature, not a
* credential. Only the map keys are exempt; anything nested below them is
* still checked.
*/
const FEATURE_ID_KEYED_MAPS = Object.freeze(new Set(["FEATURE_OVERRIDES"]));
export type EnvironmentPhase = "build" | "runtime";
export type EnvironmentDefinition = Readonly<{
phase: EnvironmentPhase;
classification: string;
required: boolean;
defaultValue: unknown;
}>;
/**
* FE-REG-ENV. A runtime row states its key as `runtimeConfigV2ArtifactSchema`
* (`release-artifacts.ts`) reads it: `required` when config.json must carry
* the key, and `defaultValue` the value the schema gives an absent key, or
* `null` when it gives none (1103/13-04, tests/unit/env-registry-coverage).
*/
export const ENV_REGISTRY = Object.freeze(withProductRows({
// F-6. Required: a staging or production build fails without it
// (scripts/generate-runtime-config.ts). Local and development builds fall
// back to the placeholder, which admission refuses for public targets.
VITE_BUILD_ID: build("public-metadata", true, "local-build"),
VITE_COMMIT_SHA: build("public-metadata", false, "local"),
VITE_ROUTER_BASE_PATH: build("compile-time", true, "/"),
VITE_RUNTIME_CONFIG_URL: build("compile-time", true, "/config.json"),
APP_ENV: runtime("public", true, null),
API_BASE_URL: runtime("public-sensitive", true, null),
REQUEST_TIMEOUT_MS: runtime("public", false, 10_000),
MAX_RETRY_ATTEMPTS: runtime("public", false, 2),
TELEMETRY_ENABLED: runtime("public", true, null),
TELEMETRY_ENDPOINT: runtime("public-sensitive", false, null),
AUTH_MODE: runtime("public", true, null),
CONFIG_SCHEMA_VERSION: runtime("public", true, null),
RELEASE_MANIFEST_URL: runtime("public", false, "/release-manifest.json"),
// F-6. The release identity the build writes into config.json. It must match
// the deployed HTML and release manifest, or boot stops with
// CONFIG_BUILD_MISMATCH (scripts/check-release-admission.ts).
RELEASE_ID: runtime("public-metadata", false, null),
BUILD_ID: runtime("public-metadata", false, null),
// §3.5: overrides may only disable an installed capability, never enable one.
CAPABILITY_OVERRIDES: runtime("public", false, Object.freeze({
REALTIME: "DEFAULT",
WEB_WORKER: "DEFAULT",
SERVICE_WORKER: "DEFAULT",
OFFLINE_COMMANDS: "DEFAULT",
})),
// §3.5: likewise for features — subtractive, keyed by installed feature id.
FEATURE_OVERRIDES: runtime("public", false, Object.freeze({})),
// §3.5: build-time narrowing of the product manifest, applied by
// scripts/generate-product-feature-index.ts (09-02). A feature left out here
// is not imported by any registry and never reaches the bundle.
VITE_PRODUCT_FEATURES: build("compile-time", false, null),
}));
/**
* 09-02. The product's rows (`product-contracts.ts`) join FE-REG-ENV and are
* checked with it. A product row cannot take a template key's name.
*/
function withProductRows<Rows extends Readonly<Record<string, EnvironmentDefinition>>>(
rows: Rows,
) {
const product: Readonly<Record<string, EnvironmentDefinition>> =
PRODUCT_ENV_REGISTRY;
const reused = Object.keys(product).find((name) => Object.hasOwn(rows, name));
if (reused !== undefined) {
throw new TypeError(`Product env key ${reused} is a template key.`);
}
return { ...rows, ...product };
}
function build(
classification: string,
required: boolean,
defaultValue: unknown,
): EnvironmentDefinition {
return Object.freeze({ phase: "build", classification, required, defaultValue });
}
function runtime(
classification: string,
required: boolean,
defaultValue: unknown,
): EnvironmentDefinition {
return Object.freeze({ phase: "runtime", classification, required, defaultValue });
}
export function assertSafeConfigNames(
config: Readonly<Record<string, unknown>>,
depth = 0,
): void {
if (depth > 4) {
throw new Error("Client configuration nesting exceeds its bound");
}
for (const [name, value] of Object.entries(config)) {
const allowlisted = depth === 0 && SEMANTIC_KEY_ALLOWLIST.has(name);
if (!allowlisted && isForbiddenConfigName(name)) {
throw new Error(`Forbidden client configuration key: ${name}`);
}
if (!isPlainNested(value)) continue;
if (depth === 0 && FEATURE_ID_KEYED_MAPS.has(name)) {
for (const entry of Object.values(value)) {
if (isPlainNested(entry)) assertSafeConfigNames(entry, depth + 2);
}
} else {
assertSafeConfigNames(value, depth + 1);
}
}
}
function isPlainNested(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function isForbiddenConfigName(name: string): boolean {
const upper = name.toUpperCase();
return FORBIDDEN_CONFIG_NAME_FRAGMENTS.some((fragment) =>
upper.includes(fragment),
);
}
export type BuildEnvironment = Readonly<{
VITE_BUILD_ID?: string;
VITE_COMMIT_SHA?: string;
VITE_ROUTER_BASE_PATH?: string;
VITE_RUNTIME_CONFIG_URL?: string;
}>;
/**
* 13-06. Each variable is read by key so Vite replaces it on its own. Passing
* `import.meta.env` whole made Vite inline every loaded VITE_* value, read or
* not, into this module's chunk.
*/
export function getBuildConfig(
environment: BuildEnvironment = {
VITE_BUILD_ID: import.meta.env.VITE_BUILD_ID,
VITE_COMMIT_SHA: import.meta.env.VITE_COMMIT_SHA,
VITE_ROUTER_BASE_PATH: import.meta.env.VITE_ROUTER_BASE_PATH,
VITE_RUNTIME_CONFIG_URL: import.meta.env.VITE_RUNTIME_CONFIG_URL,
},
) {
const buildId = environment.VITE_BUILD_ID || "local-build";
const commitSha = environment.VITE_COMMIT_SHA || "local";
const routerBasePath = environment.VITE_ROUTER_BASE_PATH || "/";
// 13-07. dist is served under the base path, so the default follows it.
const runtimeConfigUrl =
environment.VITE_RUNTIME_CONFIG_URL || `${routerBasePath}config.json`;
return Object.freeze({ buildId, commitSha, routerBasePath, runtimeConfigUrl });
}