diff --git a/.env.example b/.env.example index 47d62975..80f19b81 100644 --- a/.env.example +++ b/.env.example @@ -5,8 +5,11 @@ # # Runtime configuration — API endpoints, auth mode, telemetry, capability # switches — is NOT here. It lives in `config/runtime/.json` and is -# materialized into `dist/config.json` at build time, so it can be changed -# without rebuilding. See the "Runtime configuration" section of README.md. +# materialized into `dist/config.json` at build time. Only the emergency +# switches (CAPABILITY_OVERRIDES, FEATURE_OVERRIDES) may be changed in a +# deployed config.json without rebuilding, by the checked procedure in +# docs/runbooks/FE-RB-001.md. See the "Runtime configuration" section of +# README.md. # # Copy to `.env.local` (git-ignored) to override locally. diff --git a/docs/operations/browser-file-storage-recovery.md b/docs/operations/browser-file-storage-recovery.md index d7ace2c2..257f0c83 100644 --- a/docs/operations/browser-file-storage-recovery.md +++ b/docs/operations/browser-file-storage-recovery.md @@ -515,7 +515,8 @@ Service Worker를 별도 선택한 조합에서만 추가. 워커의 fetch 가 스위치는 없다. 끄는 경로는 아래 둘이다. - 페이지가 부팅하면: runtime config에 `CAPABILITY_OVERRIDES.SERVICE_WORKER: - "DISABLED"`를 넣는다. 재빌드는 필요 없다. 다음 부팅 때 page controller가 scope와 + "DISABLED"`를 넣는다. 재빌드는 필요 없다. 사본을 고쳐 검사한 뒤 바꾸는 절차는 + `docs/runbooks/FE-RB-001.md`에 있다. 다음 부팅 때 page controller가 scope와 script가 정확히 일치하는 등록만 unregister하고, 새 등록은 하지 않는다 (`src/contracts/runtime-capabilities.ts` `resolveRuntimeCapabilities`, `service-worker-page-controller.ts` `start()`의 `disabledCleanup` 분기). 소유 diff --git a/docs/operations/release-cache-rollback.md b/docs/operations/release-cache-rollback.md index a7c11402..77fae814 100644 --- a/docs/operations/release-cache-rollback.md +++ b/docs/operations/release-cache-rollback.md @@ -173,7 +173,9 @@ same build as the HTML and assets it caches. next boot unregisters the owned registration and registers nothing; owned caches stay (`src/contracts/runtime-capabilities.ts` `resolveRuntimeCapabilities`, `service-worker-page-controller.ts` `start()`). - This needs a page that boots. + This needs a page that boots. Edit a copy and check it with + `check:release-admission --config --original ` before it + replaces the served file (`docs/runbooks/FE-RB-001.md`). 3. **A worker stops the page from booting.** Deploy a release whose static selection is `REMOVE_REGISTRATION`. It ships a self-unregistering `service-worker.js` (`scripts/build-frontend.ts`, diff --git a/docs/runbooks/FE-RB-001.md b/docs/runbooks/FE-RB-001.md index c40abd1e..42f53c5f 100644 --- a/docs/runbooks/FE-RB-001.md +++ b/docs/runbooks/FE-RB-001.md @@ -7,3 +7,26 @@ the release owner. Close only after a clean-session boot mounts the product root, config validation evidence passes, and repeated boot-error telemetry is absent. + +## Changing an emergency switch without a rebuild + +Only `CAPABILITY_OVERRIDES` and `FEATURE_OVERRIDES` may change in a deployed +`config.json`. Every browser validates the document on boot, so a typo there +causes this runbook's failure for every user. Change it in four steps: + +1. Download the deployed `config.json` twice, as `deployed.json` (keep it as + is) and `edited.json`. Change only the switch in `edited.json`. +2. From a checkout of the deployed commit, run + `RELEASE_TARGET= corepack pnpm check:release-admission --config /abs/edited.json --original /abs/deployed.json` + (absolute paths: pnpm runs it from the repository root). It must print + `ADMITTED`. It refuses a schema error, a target rule, and any changed field + other than the two switches, `BUILD_ID` and `RELEASE_ID` included. +3. Upload `edited.json` next to the live file and rename it over + `config.json` on the same filesystem. Never edit the live file in place. + To undo, rename `deployed.json` back the same way. +4. Boot in a clean session (new browser profile) and see the product root + mount. The switch takes effect on the next boot only. + +The served document then differs from the release record (`checksums.txt`, +the promoted archive). Note the change in the release log, and put it in the +profile (`config/runtime/.json`) for the next build. diff --git a/scripts/check-release-admission.ts b/scripts/check-release-admission.ts index 15e0299b..a5d4d9f9 100644 --- a/scripts/check-release-admission.ts +++ b/scripts/check-release-admission.ts @@ -1,5 +1,6 @@ import { mkdir, readFile, writeFile } from "node:fs/promises"; import process from "node:process"; +import { parseArgs } from "node:util"; import { DEPLOYMENT_TARGETS, @@ -29,7 +30,62 @@ import { COMPILED_PRODUCT_FEATURE_IDS } from "../src/features/installed-product- const RUNTIME_CONFIG_PATH = "dist/config.json"; const RECORD_PATH = "artifacts/release/deployment-admission.json"; +/** + * 1101/13-05. The only fields an operator may change in a deployed config.json + * without a rebuild (docs/runbooks/FE-RB-001.md). Every other field belongs to + * the build: BUILD_ID and RELEASE_ID must still match the deployed HTML and + * release manifest, or every boot stops with CONFIG_BUILD_MISMATCH. + */ +const EMERGENCY_SWITCHES: ReadonlySet = new Set([ + "CAPABILITY_OVERRIDES", + "FEATURE_OVERRIDES", +]); + +function refuse(reason: string): void { + process.stderr.write(`release admission refused: ${reason}\n`); + process.exitCode = 1; +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +async function readRuntimeConfig(file: string): Promise { + let document: unknown; + try { + document = JSON.parse(await readFile(file, "utf8")); + } catch (error) { + refuse(`${file} is unreadable: ${errorMessage(error)}`); + return null; + } + try { + return parseRuntimeConfigArtifact(document) as AdmissionInput; + } catch (error) { + refuse(`${file} is not a valid runtime config: ${errorMessage(error)}`); + return null; + } +} + +function changedBuildFields(original: object, edited: object): string[] { + const before = new Map(Object.entries(original)); + const after = new Map(Object.entries(edited)); + return [...new Set([...before.keys(), ...after.keys()])] + .filter( + (field) => + !EMERGENCY_SWITCHES.has(field) && + JSON.stringify(before.get(field)) !== JSON.stringify(after.get(field)), + ) + .sort(); +} + async function main(): Promise { + // `pnpm check:release-admission -- --config …` may pass the separator through. + const argv = process.argv.slice(2); + if (argv[0] === "--") argv.shift(); + const { values: options } = parseArgs({ + args: argv, + options: { config: { type: "string" }, original: { type: "string" } }, + }); const declared = process.env["RELEASE_TARGET"]; if (!isDeploymentTarget(declared)) { process.stderr.write( @@ -54,30 +110,30 @@ async function main(): Promise { return; } - let document: unknown; - try { - document = JSON.parse(await readFile(RUNTIME_CONFIG_PATH, "utf8")); - } catch (error) { - process.stderr.write( - `release admission refused: ${RUNTIME_CONFIG_PATH} is unreadable: ${ - error instanceof Error ? error.message : String(error) - }\n`, + // 1101/13-05. An edited copy of the deployed document is checked against + // that document, so a changed build field is refused, not just a bad value. + const editedCopy = options.config; + if (editedCopy !== undefined && options.original === undefined) { + refuse( + "--config needs --original ; " + + "BUILD_ID, RELEASE_ID and every other build field are compared with it.", ); - process.exitCode = 1; return; } - - let config: AdmissionInput; - try { - config = parseRuntimeConfigArtifact(document) as AdmissionInput; - } catch (error) { - process.stderr.write( - `release admission refused: ${RUNTIME_CONFIG_PATH} is not a valid runtime config: ${ - error instanceof Error ? error.message : String(error) - }\n`, - ); - process.exitCode = 1; - return; + const configPath = editedCopy ?? RUNTIME_CONFIG_PATH; + const config = await readRuntimeConfig(configPath); + if (config === null) return; + if (options.original !== undefined) { + const original = await readRuntimeConfig(options.original); + if (original === null) return; + const changed = changedBuildFields(original, config); + if (changed.length > 0) { + refuse( + `${configPath} changes ${changed.join(", ")}; without a rebuild only ` + + `${[...EMERGENCY_SWITCHES].join(" and ")} may change.`, + ); + return; + } } const violations = findAdmissionViolations(declared, config); @@ -93,6 +149,24 @@ async function main(): Promise { for (const warning of warnings) { process.stderr.write(`release admission warning: ${warning.field} ${warning.reason}\n`); } + if (editedCopy !== undefined) { + // The record is the build's admission evidence (a CI artifact); an + // operator's edited copy is not the build and does not replace it. + if (violations.length > 0) { + refuse( + `${editedCopy} for ${declared}:\n${violations + .map((violation) => ` ${violation.field}: ${violation.reason}`) + .join("\n")}`, + ); + return; + } + process.stdout.write( + `release admission: ${editedCopy} ADMITTED for ${declared}; no field other than ` + + `${[...EMERGENCY_SWITCHES].join(" and ")} differs from ${options.original}. ` + + "Not recorded: this checks an edited copy, not the build.\n", + ); + return; + } await mkdir("artifacts/release", { recursive: true }); await writeFile( RECORD_PATH, diff --git a/tests/unit/deployment-admission.test.ts b/tests/unit/deployment-admission.test.ts index 64ee6599..98ceb542 100644 --- a/tests/unit/deployment-admission.test.ts +++ b/tests/unit/deployment-admission.test.ts @@ -269,3 +269,73 @@ describe("runtime config profiles", () => { } }); }); + +// 1101/13-05. The emergency switches (CAPABILITY_OVERRIDES, FEATURE_OVERRIDES) +// are changed in the deployed config.json without a rebuild. A typo there stops +// every boot, so the edited copy is checked against the deployed one first. +describe("checking an edited copy of the deployed runtime config", () => { + async function check( + edit: (deployed: Record) => Record, + args: readonly string[] = ["--config", "edited.json", "--original", "deployed.json"], + ) { + const root = await mkdtemp(path.join(tmpdir(), "release-admission-copy-")); + try { + const deployed = await generateRuntimeConfig("production", { + VITE_BUILD_ID: "20260815.42", + RELEASE_ID: "r-2026.08.15-1", + }); + await writeFile(path.join(root, "deployed.json"), JSON.stringify(deployed)); + await writeFile(path.join(root, "edited.json"), JSON.stringify(edit(deployed))); + const result = spawnSync( + process.execPath, + [path.resolve("scripts/check-release-admission.ts"), ...args], + { + cwd: root, + encoding: "utf8", + env: { ...process.env, APP_PROFILE: "production", RELEASE_TARGET: "production" }, + }, + ); + const records = await readdir(path.join(root, "artifacts/release")).catch(() => []); + return { status: result.status, stderr: result.stderr, stdout: result.stdout, records }; + } finally { + await rm(root, { recursive: true, force: true }); + } + } + const withServiceWorker = (deployed: Record, value: string) => ({ + ...deployed, + CAPABILITY_OVERRIDES: { + ...(deployed["CAPABILITY_OVERRIDES"] as Record), + SERVICE_WORKER: value, + }, + }); + + it("admits a copy that only flips an emergency switch, without writing the build's record", async () => { + const result = await check((deployed) => withServiceWorker(deployed, "DISABLED")); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toContain("edited.json"); + expect(result.records).toEqual([]); + }); + + it("refuses a typo in a switch value", async () => { + const result = await check((deployed) => withServiceWorker(deployed, "DISABLE")); + expect(result.status).toBe(1); + expect(result.stderr).toMatch(/edited\.json is not a valid runtime config/u); + }); + + // A valid value, so only the comparison with the deployed copy can refuse it. + it.each([ + ["BUILD_ID", "20260815.43"], + ["RELEASE_ID", "r-2026.08.15-2"], + ["API_BASE_URL", "https://other.example.org/"], + ])("refuses a copy that changes %s, which only a build may change", async (field, value) => { + const result = await check((deployed) => ({ ...deployed, [field]: value })); + expect(result.status).toBe(1); + expect(result.stderr).toContain(`edited.json changes ${field}`); + }); + + it("refuses --config without the deployed original to compare with", async () => { + const result = await check((deployed) => deployed, ["--config", "edited.json"]); + expect(result.status).toBe(1); + expect(result.stderr).toContain("--original"); + }); +});