UNPKG

everything-dev

Version:

A consolidated product package for building Module Federation apps with oRPC APIs.

151 lines (149 loc) • 7.46 kB
import { bundleUrlToStagedPath, resolveContained } from "../resolution/resolver.mjs"; import { asDigest, clearVerifiedCache, mark, verifyDocument } from "../verify/engine.mjs"; import { manifestDocumentUrl, reasonOf } from "./manifest-verify.mjs"; import { existsSync, readFileSync, readdirSync, statSync } from "node:fs"; import path, { join } from "node:path"; import { BuildEntryReportSchema, MF_MANIFEST_FILENAME } from "every-plugin/build/artifact-names"; import { WorkspaceVersionManifestSchema, composeVersionManifest } from "every-plugin/version-manifest"; //#region src/services/deploy/version-manifest.ts /** Read a workspace dist's build-report.json (ticket 01's entry-name report). */ function readBuildReport(distRoot) { const reportPath = join(distRoot, "build-report.json"); if (!existsSync(reportPath)) return null; try { return BuildEntryReportSchema.parse(JSON.parse(readFileSync(reportPath, "utf8"))); } catch { return null; } } /** * Compose the workspace's version manifest from the dist build reports and * the **server-computed** SRI map of the upload response (MAP decision 6 — * SRI is authoritative from the storage boundary, never computed * client-side). Returns null when the dist predates hashed entry names * (no report, or the SRI map lacks the entry) — the deploy leg then aborts: * uploaded workspaces must pin. */ function composeWorkspaceVersionManifest(input) { const { report, ssrReport, integrityMap, files, dir, source, gitSha } = input; const entryIntegrity = integrityMap[report.entry]; if (!entryIntegrity) return null; const ssrEntry = ssrReport?.entry; const ssrIntegrity = ssrEntry ? integrityMap[`ssr/${ssrEntry}`] : void 0; return composeVersionManifest({ ...dir ? { dir } : {}, entry: report.entry, entryIntegrity, ...ssrEntry && ssrIntegrity ? { ssr: { entry: `ssr/${ssrEntry}`, integrity: ssrIntegrity } } : {}, ...report.browserManifest && integrityMap[report.browserManifest] ? { browserManifest: { file: report.browserManifest, integrity: integrityMap[report.browserManifest] } } : {}, ...report.css && integrityMap[report.css] ? { assets: { css: integrityMap[report.css] } } : {}, ...report.shared ?? ssrReport?.shared ? { shared: report.shared ?? ssrReport?.shared } : {}, ...files ? { files } : {}, ...source ? { source } : {}, ...gitSha ? { gitSha } : {} }); } function clearRemoteVersionCache() { clearVerifiedCache(); } function remoteVersionFromManifest(base, manifest, options) { const trimmedBase = base.replace(/\/$/, ""); const fileBase = manifest.dir && !options?.ignoreDir ? `${trimmedBase}/${manifest.dir}` : trimmedBase; return { base: trimmedBase, entryUrl: `${fileBase}/${manifest.entry}`, entryIntegrity: manifest.entryIntegrity, ...manifest.dir ? { dir: manifest.dir } : {}, ...manifest.browserManifest ? { browserManifestUrl: `${fileBase}/${manifest.browserManifest.file}` } : {}, ...manifest.ssr ? { ssrEntryUrl: `${fileBase}/${manifest.ssr.entry}`, ssrIntegrity: manifest.ssr.integrity } : {}, ...manifest.shared ? { sharedVersions: manifest.shared } : {}, ...manifest.files ? { files: manifest.files } : {}, ...manifest.source ? { source: manifest.source } : {} }; } /** Every artifact URL the resolved pin attests, keyed by the URL the runtime * actually fetches (the resolved hashed entry, the ssr entry, and each file * in the pin's files map) → its SRI. Integrity-in-pipeline keying: register * these and the loader verifies bytes at fetch time (#642's fork class — * fixed-name keying beside hashed fetches — cannot reconstruct this map). */ function resolvedIntegrityMap(r) { const map = { [r.entryUrl]: r.entryIntegrity }; if (r.ssrEntryUrl && r.ssrIntegrity) map[r.ssrEntryUrl] = r.ssrIntegrity; const fileBase = r.dir ? `${r.base.replace(/\/$/, "")}/${r.dir}` : r.base.replace(/\/$/, ""); for (const [file, integrity] of Object.entries(r.files ?? {})) map[`${fileBase}/${file.replace(/^\//, "")}`] = integrity; return map; } /** * Staged-remote preference (ADR 0020/0021 self-contained tier): when a runtime * stages its own namespace under `BOS_BUNDLE_DIR`, a remote resolves from the * staged dist's own version manifest instead of the config's pin — pinned * manifest bytes that predate the image (deploy lag after a release bump) * cannot exist in the staged namespace, so their hashed files would 404 the * disk and fall through to the network, where the stale immutable bytes * still answer 200 and boot a foreign build. The staged manifest is trusted * (staged by the image build itself) and skipped entirely when the remote is * absent from the staged namespace or the pinned manifest is present (the * normal healthy case, which keeps the pin's SRI check). */ function readStagedRemoteVersion(base, digest) { const bundleDir = process.env.BOS_BUNDLE_DIR; if (!bundleDir) return null; const slotDir = bundleUrlToStagedPath(base, bundleDir); if (!slotDir || !existsSync(slotDir)) return null; const pinnedManifestPath = resolveContained(slotDir, digest.manifest); if (!pinnedManifestPath || existsSync(pinnedManifestPath)) return null; const versionsDir = path.join(slotDir, "versions"); if (!existsSync(versionsDir)) return null; const manifests = readdirSync(versionsDir).filter((name) => name.endsWith(".json")).map((name) => path.join(versionsDir, name)).filter((file) => statSync(file).isFile()).sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs || (a < b ? -1 : 1)); if (manifests.length === 0) return null; const manifestPath = manifests[0]; if (!manifestPath) return null; try { return remoteVersionFromManifest(base, WorkspaceVersionManifestSchema.parse(JSON.parse(readFileSync(manifestPath, "utf8"))), { ignoreDir: true }); } catch { return null; } } /** * The container manifest document a pinned boot registers (#874): the pin's * hashed browser manifest copy when the build emitted one — immutable in both * the CDN layout and the staged flat layout — else the fixed name under the * pin's immutable version directory (#826; CDN only — staged dists are flat * on disk), else the fixed name at the slot root. The last tier is the * legacy/dev shape, and the tier the #874 incident rode: reading the fixed * name at the mutable slot root lets a later root publish move bytes the * child's pin never named. */ function pinnedManifestDocumentUrl(fallbackUrl, resolved) { if (resolved.browserManifestUrl) return resolved.browserManifestUrl; if (resolved.dir && !process.env.BOS_BUNDLE_DIR) return `${resolved.base.replace(/\/$/, "")}/${resolved.dir}/${MF_MANIFEST_FILENAME}`; return fallbackUrl; } async function resolveRemoteVersion(input) { const staged = readStagedRemoteVersion(input.base, input.digest); if (staged) return mark(staged); const manifestUrl = manifestDocumentUrl(input.base, input.digest.manifest); try { const manifest = await verifyDocument({ url: manifestUrl, expected: asDigest(input.digest.integrity), schema: WorkspaceVersionManifestSchema, fetchImpl: input.fetchImpl }); return mark(remoteVersionFromManifest(input.base, manifest)); } catch (error) { throw new Error(`[SRI] version manifest verification failed for ${manifestUrl}: ${reasonOf(error)}`); } } //#endregion export { clearRemoteVersionCache, composeWorkspaceVersionManifest, pinnedManifestDocumentUrl, readBuildReport, resolveRemoteVersion, resolvedIntegrityMap }; //# sourceMappingURL=version-manifest.mjs.map