Files
clean-architecture-frontend…/scripts/lib/hosting-probe.ts
T
DongHyeonka 4bce8bf379 fix(hosting): FE-GATE-019가 후보의 설정·entry와 HTTP/2·압축 전제를 대조한다
문제: (1) live probe는 배포된 release-manifest.json의 buildId·releaseId만
후보와 비교했다. 두 값은 CI run 번호로 만든 이름이라, 같은 run에서 로컬
프로필로 다시 빌드한 release(APP_ENV=local, AUTH_MODE=demo, loopback
API)를 올려도 PASS(live)였다(리뷰 실험 E-2c). 공개 대상 승인
(FE-GATE-027)을 받은 것은 후보의 config.json인데, 호스트가 내주는
config.json은 헤더만 보았다. entry script도 호스트의 두 응답끼리만
비교했다. (2) 템플릿은 HTTP/2와 압축을 전제로 초기 청크를 나누고 gzip
바이트로 예산을 재는데, 그 전제가 호스팅 계약에 없고 probe도 보지
않았다. 템플릿 nginx 예시는 http2도 gzip도 켜지 않았다.

고른 방법:
- 받은 /config.json을 후보 dist/config.json과 비교한다. 비상 스위치
  두 개(CAPABILITY_OVERRIDES, FEATURE_OVERRIDES) 밖의 필드가 다르거나
  읽을 수 없으면 FAIL. 규칙은 check-release-admission과 같은 함수
  (scripts/lib/runtime-config-switches.ts)로 옮겨 같이 쓴다.
- 받은 index.html의 entry script를 후보 index.html의 것과 비교한다.
- cache-policy.json에 transport.alpnProtocols(["h2"])와
  hashedAsset.contentEncodings(br, gzip, zstd)를 선언한다. probe는 TLS
  handshake의 ALPN(node:tls, h2와 http/1.1을 제안)과 entry script 응답의
  Content-Encoding을 본다. Node fetch는 h2를 지원하는 서버에도 HTTP/1.1로
  붙어서 프로토콜은 따로 확인해야 한다.
- nginx 예시에 http2 on과 gzip·gzip_types를 넣고, static-delivery.md와
  release-cache-rollback.md에 두 전제와 실패 조건을 적었다.
두 수정은 같은 probe 함수와 테스트를 고쳐 한 커밋에 넣었다.
버린 대안: archive SHA를 호스트에 올려 대조하기(호스트에 새 파일 규약이
생기고 일부 파일만 다른 배포는 못 잡는다). HTTP/2를 기록만 하기
(아무도 읽지 않는 경고는 청크를 묶는 결정을 부르지 못한다. 선언을 바꾸면
제품이 끌 수 있다).

위험·한계: HTTP/1.1만 되는 호스트는 이제 FE-GATE-019에서 FAIL한다. 그
제품은 cache-policy.json 선언을 바꾸고 초기 청크를 묶는다. 실제 nginx와
Gitea runner에서는 돌리지 않았다. 슬롯이 후보를 받도록 강제하는 계약
규칙은 다음 커밋(제품 overlay)에 있다.

검증: hosting-probe.test.ts에 같은 이름·다른 config.json → FAIL, 비상
스위치만 다름 → PASS, 읽을 수 없는 config.json → FAIL, 다른 entry →
FAIL, ALPN http/1.1·없음 → FAIL, 압축 없는 entry → FAIL, 정책 선언 확인을
더했다(고치기 전 실패). 33건 통과. 로컬 자체 서명 TLS 서버 실험:
http2.createSecureServer → "h2", https.createServer → "http/1.1",
인증서 이름 불일치 → ERR_TLS_CERT_ALTNAME_INVALID.
verify:hosting-headers(fixture) UNVERIFIED exit 3, deployment-admission 통과.

Refs: docs/reviews/2026-11-03-maturity-review/13-build-release-supply-chain.md 13-01, 13-02
2026-11-04 20:40:37 +09:00

357 lines
12 KiB
TypeScript

import { isIP } from "node:net";
import { connect } from "node:tls";
import type { InstalledServiceWorkerSelection } from "../../src/contracts/service-worker.ts";
import { changedRuntimeConfigBuildFields } from "./runtime-config-switches.ts";
const LOOPBACK_IPV4 = /^127(?:\.\d{1,3}){3}$/;
export type HostingMode = "live" | "invalid-live" | "fixture";
export type HostingVerdict = "PASS" | "FAIL" | "UNVERIFIED";
/**
* 13-05 (D-14). The fixture compares the declared headers with a copy of
* themselves, so it can only find a contradiction, never prove hosting. Only a
* live probe of the deployed release can PASS.
*/
export function hostingVerdict(mode: HostingMode, passed: boolean): HostingVerdict {
if (!passed) return "FAIL";
return mode === "live" ? "PASS" : "UNVERIFIED";
}
/**
* 13-05. The live probe requests the entry script the served index.html names,
* so it checks the release that is deployed rather than the first asset of a
* local build, which the deployed release may not contain.
*/
export function servedEntryScript(indexHtml: string): string | null {
for (const tag of indexHtml.match(/<script\b[^>]*>/gu) ?? []) {
if (!/\btype=["']module["']/u.test(tag)) continue;
const source = /\bsrc=["']([^"']+\.js)["']/u.exec(tag)?.[1];
if (source) return source;
}
return null;
}
export type ProbeResult = Readonly<{
surface: string;
header: string;
expected: unknown;
observed: unknown;
reason?: string;
passed: boolean;
}>;
export type ResponseHeaders = Record<string, Record<string, string>>;
export type HostingFetcher = (url: URL) => Promise<Response>;
export type ReleaseIdentity = Readonly<{ buildId: string; releaseId: string }>;
/** The promoted candidate: its manifest names and the texts of its dist/config.json and dist/index.html. */
export type CandidateRelease = ReleaseIdentity & Readonly<{ runtimeConfig: string; indexHtml: string }>;
export type ProbeTransport = Readonly<{
fetcher?: HostingFetcher;
/** The ALPN protocol the host negotiates over TLS, or null when none. */
negotiateAlpn?: (base: URL) => Promise<string | null>;
/** Accepted protocols (`transport.alpnProtocols` in config/hosting/cache-policy.json); empty skips the check. */
alpnProtocols?: readonly string[];
}>;
/**
* 1103/13-02. Node's fetch speaks HTTP/1.1 even to a host that offers h2, so
* the protocol a browser gets is read from the TLS handshake instead: the
* client offers h2 and http/1.1 and the host picks one. The certificate is
* verified as fetch verifies it.
*/
export function negotiatedAlpnProtocol(base: URL, timeoutMs = 10_000): Promise<string | null> {
return new Promise((resolve, reject) => {
const host = base.hostname.replace(/^\[|\]$/gu, "");
const socket = connect({
host,
port: Number(base.port || 443),
...(isIP(host) === 0 ? { servername: host } : {}),
ALPNProtocols: ["h2", "http/1.1"],
});
socket.setTimeout(timeoutMs, () => socket.destroy(new Error("TLS handshake timed out")));
socket.once("secureConnect", () => {
const protocol = socket.alpnProtocol;
socket.end();
resolve(typeof protocol === "string" ? protocol : null);
});
socket.once("error", reject);
});
}
function parsedJsonObject(text: string | null): object | null {
try {
const value: unknown = JSON.parse(text ?? "");
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
} catch {
return null;
}
}
/** `buildId` and `releaseId` of a release-manifest.json text, or null. */
export function releaseIdentity(manifest: string | null): ReleaseIdentity | null {
try {
const { buildId, releaseId } = JSON.parse(manifest ?? "") as Record<string, unknown>;
return typeof buildId === "string" && typeof releaseId === "string"
? { buildId, releaseId }
: null;
} catch {
return null;
}
}
/**
* 13-05 (D-14). Runs after the promoted release is deployed. Every surface must
* answer 200 without leaving the probed origin, and the hashed asset it
* requests is the entry script the served index.html names.
*
* 1101/13-04. `appRoute` is a path the build has no file for. The router uses
* browser history, so a reload or a shared link of any route reaches the host
* as such a path, and the host must answer it with the same index.html (SPA
* fallback). A 404 or any other page there fails, although `/` still works.
*
* 1101/13-01. The served release manifest must name the candidate's build and
* release. Correct headers on an earlier release are not evidence for this one.
*
* 1103/13-01. Those names come from the CI run, so a release rebuilt in the
* same run (say with the local profile) carries them too. The served
* config.json must equal the candidate's, the one release admission
* (FE-GATE-027) admitted, except for the two emergency switches FE-RB-001 may
* change; and the served index.html must name the candidate's entry script.
*
* 1103/13-02. The host must negotiate a declared protocol (HTTP/2): the
* template splits its initial chunks on that premise.
*/
export async function probeLiveRelease(
base: URL,
paths: Readonly<Record<string, string>>,
candidate: CandidateRelease,
transport: ProbeTransport = {},
): Promise<{ responses: ResponseHeaders; results: ProbeResult[] }> {
const fetcher = transport.fetcher ?? ((url: URL) => fetch(url, { redirect: "follow" }));
const negotiateAlpn = transport.negotiateAlpn ?? negotiatedAlpnProtocol;
const responses: ResponseHeaders = {};
const results: ProbeResult[] = [];
const probe = async (surface: string, pathname: string): Promise<string | null> => {
try {
const response = await fetcher(new URL(pathname, base));
const finalOrigin = new URL(response.url).origin;
results.push(
{
surface,
header: "http-status",
expected: 200,
observed: response.status,
passed: response.status === 200,
},
{
surface,
header: "final-origin",
expected: base.origin,
observed: finalOrigin,
passed: finalOrigin === base.origin,
},
);
responses[surface] = Object.fromEntries(
[...response.headers.entries()].map(([name, value]) => [name.toLowerCase(), value]),
);
return await response.text();
} catch (error: unknown) {
results.push({
surface,
header: "transport",
expected: "reachable",
observed: error instanceof Error ? error.name : "UnknownError",
passed: false,
});
return null;
}
};
const bodies: Record<string, string | null> = {};
for (const [surface, pathname] of Object.entries(paths)) {
bodies[surface] = await probe(surface, pathname);
}
const entryScript = servedEntryScript(bodies["index"] ?? "");
if (entryScript) {
await probe("hashedAsset", entryScript);
} else {
results.push({
surface: "hashedAsset",
header: "entry-script",
expected: "a module script named by the served index.html",
observed: null,
passed: false,
});
}
const served = releaseIdentity(bodies["releaseManifest"] ?? null);
for (const [field, header] of [["buildId", "build-id"], ["releaseId", "release-id"]] as const) {
results.push({
surface: "releaseManifest",
header,
expected: candidate[field],
observed: served?.[field] ?? null,
passed: served?.[field] === candidate[field],
});
}
if ("appRoute" in paths) {
const observed = servedEntryScript(bodies["appRoute"] ?? "");
results.push({
surface: "appRoute",
header: "entry-script",
expected: entryScript,
observed,
passed: entryScript !== null && observed === entryScript,
});
}
const candidateEntryScript = servedEntryScript(candidate.indexHtml);
results.push({
surface: "index",
header: "candidate-entry-script",
expected: candidateEntryScript,
observed: entryScript,
passed: candidateEntryScript !== null && entryScript === candidateEntryScript,
});
if ("runtimeConfig" in paths) {
const served = parsedJsonObject(bodies["runtimeConfig"] ?? null);
const admitted = parsedJsonObject(candidate.runtimeConfig);
const changed = served && admitted ? changedRuntimeConfigBuildFields(admitted, served) : null;
results.push({
surface: "runtimeConfig",
header: "build-fields",
expected: [],
observed: changed ?? "unreadable",
...(changed === null
? { reason: "the served or the candidate config.json is not a JSON object" }
: changed.length > 0
? { reason: "differs from the candidate's config.json beyond the emergency switches" }
: {}),
passed: changed !== null && changed.length === 0,
});
}
const alpnProtocols = transport.alpnProtocols ?? [];
if (alpnProtocols.length > 0) {
let observed: string | null;
try {
observed = await negotiateAlpn(base);
} catch (error: unknown) {
observed = error instanceof Error ? error.name : "UnknownError";
}
results.push({
surface: "transport",
header: "alpn",
expected: alpnProtocols,
observed,
...(observed !== null && alpnProtocols.includes(observed)
? {}
: { reason: "the split initial chunks assume HTTP/2 (docs/architecture/static-delivery.md)" }),
passed: observed !== null && alpnProtocols.includes(observed),
});
}
return { responses, results };
}
/** A build ships a worker script for these selections (06-03: REMOVE_REGISTRATION ships the self-unregistering one). */
export function shipsServiceWorker(selection: InstalledServiceWorkerSelection | null): boolean {
return selection?.mode === "ACTIVE" || selection?.mode === "REMOVE_REGISTRATION";
}
const PUBLIC_SERVICE_WORKER = /(?:^|\/)(?:service-worker|sw)(?:[.-][^/]*)?\.js$/i;
/**
* A built `dist` may ship a worker script only when the static selection is
* `ACTIVE` or `REMOVE_REGISTRATION` (the self-unregistering worker, 06-03), and
* then only the selected script at the app root.
*/
export function checkPublicServiceWorkers(
distFiles: readonly string[],
selection: InstalledServiceWorkerSelection | null,
) {
const found = distFiles.filter((file) => PUBLIC_SERVICE_WORKER.test(file));
const allowed: string[] =
selection && shipsServiceWorker(selection) ? [selection.scriptPath] : [];
const passed =
found.length === allowed.length &&
found.every((file) => allowed.includes(file));
return {
surface: "serviceWorker",
header: "enabled",
expected: allowed.length > 0,
observed: found.length > 0,
passed,
...(passed ? {} : { reason: `dist worker scripts: ${found.join(", ") || "none"}` }),
};
}
/**
* A release gate must not promote a local preview server as live hosting
* evidence.
*
*/
export function classifyLiveHostingBaseUrl(value: string):
| {
passed: true;
reason: null;
url: URL;
observedOrigin: string;
}
| {
passed: false;
reason: string;
url: URL | null;
observedOrigin: string | null;
} {
let url: URL;
try {
url = new URL(value);
} catch {
return {
passed: false,
reason: "HOSTING_BASE_URL must be an absolute URL",
url: null,
observedOrigin: null,
};
}
const observedOrigin = url.origin;
const hostname = url.hostname.toLowerCase().replace(/^\[|\]$/g, "");
if (url.protocol !== "https:") {
return {
passed: false,
reason: "live hosting evidence requires HTTPS",
url,
observedOrigin,
};
}
if (url.username || url.password) {
return {
passed: false,
reason: "HOSTING_BASE_URL must not contain credentials",
url,
observedOrigin,
};
}
if (
hostname === "localhost" ||
hostname.endsWith(".localhost") ||
hostname === "::1" ||
hostname === "0.0.0.0" ||
LOOPBACK_IPV4.test(hostname)
) {
return {
passed: false,
reason: "local or loopback hosts are not live deployment evidence",
url,
observedOrigin,
};
}
if (url.pathname !== "/" || url.search || url.hash) {
return {
passed: false,
reason: "HOSTING_BASE_URL must be the canonical root URL",
url,
observedOrigin,
};
}
return { passed: true, reason: null, url, observedOrigin };
}