문제
제품이 http·telemetry·indexedDb 밖의 capability, 세션 밖 자격증명(BFF
쿠키 XSRF, Studio CSRF), 제품 런타임 설정 키를 넣으려면
runtime-adapters.ts, feature-adapter-contribution.ts, rest-profiles.ts,
release-artifacts.ts, runtime-config-schema.ts를 직접 고쳐야 한다. 이
파일들은 템플릿이 보안·계약 수정을 자주 넣는 곳이라, 동기화 때마다
fail-closed 코드를 손으로 병합한다(memento +61줄, tech-log +118줄).
고른 방법 (리뷰 09 4.2의 (B))
- FeaturePlatformCapabilities를 interface로 바꾼다. 제품은 이 repo의
FeatureIndexedDbRepositories·ApplicationFeatureInputs와 같은
declaration merging으로 capability를 더한다.
- 제품 소유 파일 둘을 빈 구현으로 둔다.
- src/bootstrap/product-composition.ts: 추가 capability와 "인증 프로필
id → 자격증명 제공자" 표. 계약 타입은 템플릿 소유
product-composition-contract.ts에 둔다.
- src/contracts/product-contracts.ts: 제품 인증 프로필과 런타임 설정
zod 조각. 프로필 레지스트리와 strict 설정 스키마는 contracts 층에
있고 빌드 스크립트도 읽는다. contracts는 bootstrap을 import할 수
없어서 파일을 하나로 합치지 못했다.
- 판단 순서는 조립 루트가 쥔다: scope fence → ANONYMOUS 프로필 → 제품
제공자 → 세션 → 응답 뒤 fence 재확인. 제공자가 throw하면 executor가
CREDENTIAL_OWNER_FAILED로 닫는다. 나가는 헤더는 여전히 프로필 허용
목록이 정한다.
- 제공자 계약은 기존 attachCredentials 시그니처를 그대로 쓴다.
- 제품 composition은 http capability가 생긴 뒤에 부른다. tech-log가
두었던 전방 참조 stub이 필요 없다.
- 제품에 host 전체를 넘기지 않고 readCookie(name)만 넘긴다. host를 객체에
담으면 browser-data-boundary/no-capability-alias가 막는다.
- http·telemetry는 spread 뒤에 둬서 제품이 바꿀 수 없다(타입에서도 뺀다).
제품 프로필 id나 설정 키가 템플릿 이름과 겹치면 모듈 로드 때 throw한다.
버린 대안
- (A) 현 상태: 템플릿 비용은 0이지만 제품마다 동기화 비용이 반복된다.
- (C) 기능 계약 기여가 인증 프로필과 제공자를 함께 가져온다: 인증
정책이 기능마다 흩어져 보안 리뷰 범위가 넓어진다.
- 제공자에 응답 관찰 훅 추가: tech-log의 401/403 토큰 폐기는 제품
capability가 http를 감싸서 표현된다(픽스처). 제공자 계약을 작게 둔다.
위험·한계
- memento의 x-xsrf-token은 닫힌 자격증명 헤더 목록(VD-23,
CREDENTIAL_HEADER_NAMES)에 없다. 그 이름을 쓰려면 여전히
rest-profiles.ts를 고치거나 백엔드가 x-csrf-token을 받아야 한다.
픽스처는 x-csrf-token으로 표현했다.
- 제품 설정 키의 FE-REG-ENV 행(src/contracts/env.ts)은 이 변경 밖이다.
그 행을 요구하는 검사는 없다.
- tech-log가 부트 전에 BFF 세션 owner를 설치하는 코드
(create-runtime-composition.ts)는 이 확장 지점 밖이다.
- 제공자 응답 뒤 fence 재확인은 executor가 같은 fence로 먼저 전송을
끊어서 조립 루트 경유 테스트로는 따로 보이지 않는다. 세션 경로와 같은
이중 방어로 둔다.
- V1 설정 문서도 제품 키를 받는다(없으면 기본값). V1은 한 릴리스 동안만
쓰는 리더다.
- 초기 JS gzip 203,818 → 204,178 B(+360, 예산 204,800).
검증
- RED: tests/unit/runtime-adapters-credential-order.test.ts 7행 중 제품
제공자를 기대하는 4행 실패(세션이 먼저 답해 UNAUTHENTICATED, owner가
먼저 답해 SUCCESS). fence·ANONYMOUS·세션 3행은 통과.
- GREEN: 같은 파일 7/7. tests/unit/product-composition-fixture.test.ts
9/9(가짜 제품 파일 두 개로 offsetUpload, runtime, BFF 쿠키 XSRF 읽기·
쓰기, Studio CSRF 발급·403 폐기, 제품 설정 키, 이름 충돌 거절). 09-01
tests/unit/runtime-adapters-auth-profile.test.ts 12/12.
- 회귀: tests/unit·contract·runtime-schema 182 files 2590 tests 통과.
integration·component 47 files 386 tests 통과(pnpm을 띄우는
security-followup-archive 제외). tsc app·test·node·recipes·web-worker·
service-worker 통과. 바꾼 파일 eslint 통과. check:registries PASS
(compatibility=breaking은 기존 route·storage 행). verify:documentation
PASS_SCOPED. check:adapter-inventory PASS. check:architecture는 pnpm 대신
exec 전용 shim으로 그래프·fixture PASS. 템플릿 런타임 설정 JSON
schema는 baseline과 같다.
332 lines
10 KiB
TypeScript
332 lines
10 KiB
TypeScript
import { z } from "./zod.ts";
|
|
|
|
import { contractSetSchema } from "./contract-set.ts";
|
|
import { PRODUCT_RUNTIME_CONFIG_FIELDS } from "./product-contracts.ts";
|
|
|
|
const versionSchema = z.string().regex(/^\d+(?:\.\d+){0,2}$/);
|
|
|
|
function assertEndpointUrl(
|
|
value: string,
|
|
local: boolean,
|
|
options: Readonly<{ trailingSlashPath?: boolean }> = {},
|
|
): void {
|
|
const parsed = new URL(value);
|
|
if (
|
|
(parsed.protocol !== "http:" && parsed.protocol !== "https:") ||
|
|
parsed.username ||
|
|
parsed.password ||
|
|
parsed.hash ||
|
|
parsed.search ||
|
|
(!local && parsed.protocol !== "https:")
|
|
) {
|
|
throw new TypeError("invalid");
|
|
}
|
|
if (options.trailingSlashPath && !parsed.pathname.endsWith("/")) {
|
|
throw new TypeError("invalid");
|
|
}
|
|
}
|
|
|
|
export function isValidReleaseManifestUrl(value: string): boolean {
|
|
if (!value.startsWith("/") || value.startsWith("//")) return false;
|
|
if (new TextEncoder().encode(value).byteLength > 256) return false;
|
|
if (value.includes("?") || value.includes("#") || value.includes("\\")) {
|
|
return false;
|
|
}
|
|
if (/%2f|%5c/i.test(value)) return false;
|
|
if (value.split("/").some((segment) => segment === "." || segment === "..")) {
|
|
return false;
|
|
}
|
|
// R-7.3. The URL parser strips tab/CR/LF and resolves `%2e` dot segments, so
|
|
// "/\t/evil.example/m.json" becomes a cross-origin URL. The path must
|
|
// resolve to exactly itself on the page's origin.
|
|
const base = "https://release-manifest.invalid";
|
|
try {
|
|
const resolved = new URL(value, base);
|
|
return resolved.origin === base && resolved.pathname === value;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export const capabilityOverrideArtifactSchema = z
|
|
.object({
|
|
REALTIME: z.enum(["DEFAULT", "DISABLED"]).default("DEFAULT"),
|
|
WEB_WORKER: z.enum(["DEFAULT", "DISABLED"]).default("DEFAULT"),
|
|
SERVICE_WORKER: z.enum(["DEFAULT", "DISABLED"]).default("DEFAULT"),
|
|
OFFLINE_COMMANDS: z.enum(["DEFAULT", "DISABLED"]).default("DEFAULT"),
|
|
})
|
|
.strict()
|
|
.default({
|
|
REALTIME: "DEFAULT",
|
|
WEB_WORKER: "DEFAULT",
|
|
SERVICE_WORKER: "DEFAULT",
|
|
OFFLINE_COMMANDS: "DEFAULT",
|
|
});
|
|
|
|
/**
|
|
* §3.5 / §6.1. A runtime switch that can take an installed feature out of
|
|
* service without a rebuild.
|
|
*
|
|
* Values are `DEFAULT | DISABLED` for the same reason `CAPABILITY_OVERRIDES`
|
|
* is: a configuration document may subtract from what the build installed and
|
|
* may never add to it. Keys are feature ids; naming a feature this build does
|
|
* not contain is inert rather than an error, so a shared configuration
|
|
* document can cover several builds.
|
|
*/
|
|
export const featureOverrideArtifactSchema = z
|
|
.record(
|
|
z.string().regex(/^[a-z][a-z0-9-]{0,63}$/u, "feature id is invalid"),
|
|
z.enum(["DEFAULT", "DISABLED"]),
|
|
)
|
|
.default({});
|
|
|
|
type RuntimeConfigArtifactDraft = Readonly<{
|
|
APP_ENV: "local" | "development" | "staging" | "production";
|
|
API_BASE_URL: string;
|
|
TELEMETRY_ENABLED: boolean;
|
|
TELEMETRY_ENDPOINT?: string;
|
|
AUTH_MODE: "external" | "demo";
|
|
RELEASE_MANIFEST_URL: string;
|
|
}>;
|
|
|
|
function runtimeConfigArtifactInvariants(
|
|
config: RuntimeConfigArtifactDraft,
|
|
context: z.RefinementCtx,
|
|
): void {
|
|
const local = config.APP_ENV === "local" || config.APP_ENV === "development";
|
|
if (config.TELEMETRY_ENABLED && !config.TELEMETRY_ENDPOINT) {
|
|
context.addIssue({
|
|
code: "custom",
|
|
path: ["TELEMETRY_ENDPOINT"],
|
|
message: "required when telemetry is enabled",
|
|
});
|
|
}
|
|
if (!local && config.AUTH_MODE === "demo") {
|
|
context.addIssue({
|
|
code: "custom",
|
|
path: ["AUTH_MODE"],
|
|
message: "demo authentication is limited to local environments",
|
|
});
|
|
}
|
|
try {
|
|
assertEndpointUrl(config.API_BASE_URL, local, { trailingSlashPath: true });
|
|
} catch {
|
|
context.addIssue({
|
|
code: "custom",
|
|
path: ["API_BASE_URL"],
|
|
message:
|
|
"absolute credential-free URL ending in / is required; HTTPS outside local",
|
|
});
|
|
}
|
|
if (config.TELEMETRY_ENDPOINT) {
|
|
try {
|
|
assertEndpointUrl(config.TELEMETRY_ENDPOINT, local);
|
|
} catch {
|
|
context.addIssue({
|
|
code: "custom",
|
|
path: ["TELEMETRY_ENDPOINT"],
|
|
message:
|
|
"absolute credential-free URL is required; HTTPS outside local",
|
|
});
|
|
}
|
|
}
|
|
if (!isValidReleaseManifestUrl(config.RELEASE_MANIFEST_URL)) {
|
|
context.addIssue({
|
|
code: "custom",
|
|
path: ["RELEASE_MANIFEST_URL"],
|
|
message: "same-origin absolute path without query, hash or traversal",
|
|
});
|
|
}
|
|
}
|
|
|
|
const runtimeConfigArtifactFields = {
|
|
APP_ENV: z.enum(["local", "development", "staging", "production"]),
|
|
API_BASE_URL: z.url(),
|
|
REQUEST_TIMEOUT_MS: z.int().min(100).max(60_000).default(10_000),
|
|
MAX_RETRY_ATTEMPTS: z.int().min(0).max(2).default(2),
|
|
TELEMETRY_ENABLED: z.boolean(),
|
|
TELEMETRY_ENDPOINT: z.url().optional(),
|
|
AUTH_MODE: z.enum(["external", "demo"]),
|
|
RELEASE_MANIFEST_URL: z.string().min(1).default("/release-manifest.json"),
|
|
RELEASE_ID: z.string().min(1).optional(),
|
|
BUILD_ID: z.string().min(1).optional(),
|
|
} as const;
|
|
|
|
/**
|
|
* 09-02. The product's keys (`product-contracts.ts`) join the strict document
|
|
* and are validated with it. A product key cannot take a template key's name.
|
|
*/
|
|
function withProductFields<Shape extends Record<string, z.ZodType>>(
|
|
shape: Shape,
|
|
) {
|
|
const reused = Object.keys(PRODUCT_RUNTIME_CONFIG_FIELDS).find((key) =>
|
|
Object.hasOwn(shape, key),
|
|
);
|
|
if (reused !== undefined) {
|
|
throw new TypeError(`Product runtime config key ${reused} is a template key.`);
|
|
}
|
|
return { ...shape, ...PRODUCT_RUNTIME_CONFIG_FIELDS };
|
|
}
|
|
|
|
/**
|
|
* @deprecated V1 reader kept for one release after the V2-only writer
|
|
* (change evidence `FE-REG-ENV:API_CONTRACT_VERSION:*:removed`, 2026-09-24).
|
|
* Remove it and its re-export in `src/bootstrap/runtime-config-schema.ts`
|
|
* once no deployed `/config.json` still carries `CONFIG_SCHEMA_VERSION: "1"`
|
|
* (owner: frontend-platform).
|
|
*/
|
|
export const runtimeConfigV1ArtifactSchema = z
|
|
.object(
|
|
withProductFields({
|
|
...runtimeConfigArtifactFields,
|
|
CONFIG_SCHEMA_VERSION: z.literal("1"),
|
|
API_CONTRACT_VERSION: versionSchema,
|
|
}),
|
|
)
|
|
.strict()
|
|
.superRefine(runtimeConfigArtifactInvariants);
|
|
|
|
export const runtimeConfigV2ArtifactSchema = z
|
|
.object(
|
|
withProductFields({
|
|
...runtimeConfigArtifactFields,
|
|
CONFIG_SCHEMA_VERSION: z.literal("2.0"),
|
|
CAPABILITY_OVERRIDES: capabilityOverrideArtifactSchema,
|
|
FEATURE_OVERRIDES: featureOverrideArtifactSchema,
|
|
}),
|
|
)
|
|
.strict()
|
|
.superRefine(runtimeConfigArtifactInvariants);
|
|
|
|
export const runtimeConfigArtifactSchema = z.discriminatedUnion(
|
|
"CONFIG_SCHEMA_VERSION",
|
|
[
|
|
runtimeConfigV1ArtifactSchema,
|
|
runtimeConfigV2ArtifactSchema,
|
|
],
|
|
);
|
|
|
|
const releaseManifestArtifactFields = {
|
|
appVersion: z.string().min(1),
|
|
buildId: z.string().min(1),
|
|
commitSha: z.string().min(1),
|
|
assetManifestHash: z.string().min(1),
|
|
releaseId: z.string().min(1),
|
|
builtAt: z.string().min(1),
|
|
routeChunks: z.record(z.string().min(1), z.string().min(1)),
|
|
} as const;
|
|
|
|
/**
|
|
* @deprecated V1 reader kept for one release after the V2-only writer
|
|
* (change evidence `FE-REG-ENV:API_CONTRACT_VERSION:*:removed`, 2026-09-24).
|
|
* Remove it and its re-export in `src/bootstrap/load-release-manifest.ts`
|
|
* once no deployed `/release-manifest.json` still carries `schemaVersion: 1`
|
|
* (owner: frontend-platform).
|
|
*/
|
|
export const releaseManifestV1ArtifactSchema = z
|
|
.object({
|
|
schemaVersion: z.literal(1),
|
|
...releaseManifestArtifactFields,
|
|
configSchemaVersion: versionSchema,
|
|
apiContractVersion: versionSchema,
|
|
})
|
|
.strict();
|
|
|
|
export const releaseManifestV2ArtifactSchema = z
|
|
.object({
|
|
schemaVersion: z.literal(2),
|
|
...releaseManifestArtifactFields,
|
|
configSchemaVersion: z.literal("2.0"),
|
|
contractSet: contractSetSchema,
|
|
})
|
|
.strict();
|
|
|
|
export const releaseManifestArtifactSchema = z.discriminatedUnion(
|
|
"schemaVersion",
|
|
[releaseManifestV1ArtifactSchema, releaseManifestV2ArtifactSchema],
|
|
);
|
|
|
|
export const buildManifestArtifactSchema = z
|
|
.object({
|
|
schemaVersion: z.literal(1),
|
|
buildId: z.string().min(1),
|
|
commitSha: z.string().min(1),
|
|
releaseId: z.string().min(1),
|
|
moduleInventoryHash: z.string().min(1),
|
|
generatedAt: z.string().min(1),
|
|
buildContext: z
|
|
.object({
|
|
nodeVersion: z.string().min(1),
|
|
packageManagerVersion: z.string().min(1),
|
|
runnerImage: z.string().min(1),
|
|
sourceDateEpoch: z.string().min(1).nullable(),
|
|
})
|
|
.strict(),
|
|
outputs: z
|
|
.object({
|
|
directory: z.string().min(1),
|
|
viteManifest: z.string().min(1),
|
|
moduleInventory: z.string().min(1),
|
|
routeChunks: z.record(z.string().min(1), z.string().min(1)),
|
|
runtimeConfigSchema: z.string().min(1),
|
|
})
|
|
.strict(),
|
|
})
|
|
.strict();
|
|
|
|
export type RuntimeConfigV1Artifact = z.output<
|
|
typeof runtimeConfigV1ArtifactSchema
|
|
>;
|
|
export type RuntimeConfigV2Artifact = z.output<
|
|
typeof runtimeConfigV2ArtifactSchema
|
|
>;
|
|
export type CapabilityOverrideArtifact = z.output<
|
|
typeof capabilityOverrideArtifactSchema
|
|
>;
|
|
export type RuntimeConfigArtifact = z.output<typeof runtimeConfigArtifactSchema>;
|
|
export type ReleaseManifestV1Artifact = z.output<
|
|
typeof releaseManifestV1ArtifactSchema
|
|
>;
|
|
export type ReleaseManifestV2Artifact = z.output<
|
|
typeof releaseManifestV2ArtifactSchema
|
|
>;
|
|
export type ReleaseArtifact = z.output<typeof releaseManifestArtifactSchema>;
|
|
export type BuildManifestArtifact = z.output<typeof buildManifestArtifactSchema>;
|
|
|
|
export function parseReleaseArtifact(value: unknown): ReleaseArtifact {
|
|
return releaseManifestArtifactSchema.parse(value);
|
|
}
|
|
|
|
export function parseRuntimeConfigArtifact(value: unknown): RuntimeConfigArtifact {
|
|
return runtimeConfigArtifactSchema.parse(value);
|
|
}
|
|
|
|
export function parseBuildManifestArtifact(value: unknown): BuildManifestArtifact {
|
|
return buildManifestArtifactSchema.parse(value);
|
|
}
|
|
|
|
export function projectReleaseTokens(release: ReleaseArtifact) {
|
|
const common = {
|
|
schemaVersion: release.schemaVersion,
|
|
appVersion: release.appVersion,
|
|
buildId: release.buildId,
|
|
commitSha: release.commitSha,
|
|
configSchemaVersion: release.configSchemaVersion,
|
|
assetManifestHash: release.assetManifestHash,
|
|
releaseId: release.releaseId,
|
|
builtAt: release.builtAt,
|
|
} as const;
|
|
|
|
return release.schemaVersion === 1
|
|
? Object.freeze({
|
|
...common,
|
|
schemaVersion: 1 as const,
|
|
apiContractVersion: release.apiContractVersion,
|
|
})
|
|
: Object.freeze({
|
|
...common,
|
|
schemaVersion: 2 as const,
|
|
contractSetDigest: release.contractSet.setDigest,
|
|
});
|
|
}
|