everything-dev
Version:
A consolidated product package for building Module Federation apps with oRPC APIs.
223 lines (221 loc) • 7.23 kB
JavaScript
import { asDigest, fetchVerified, isVerifyError, verifyDocument } from "./engine.mjs";
import { manifestDocumentUrl } from "../deploy/manifest-verify.mjs";
import { walkRemotes } from "../remotes.mjs";
import { verifyManifestSignature } from "../deploy/manifest-signature.mjs";
import { ZodError } from "zod";
import { WorkspaceVersionManifestSchema, signaturePayloadOf } from "every-plugin/version-manifest";
//#region src/services/verify/chain.ts
function collectPinnedRemotes(config) {
const remotes = [];
walkRemotes(config, ({ remote, entry }) => {
if (entry && typeof entry === "object") remotes.push({
remote,
ref: entry
});
});
return remotes;
}
function digestOf(ref) {
const manifest = typeof ref.digest?.manifest === "string" ? ref.digest.manifest : void 0;
const integrity = typeof ref.digest?.integrity === "string" ? ref.digest.integrity : void 0;
return manifest && integrity ? {
manifest,
integrity
} : null;
}
/** Every pinned remote with both a production base and a verifiable pin. */
function collectRemoteDescriptors(config) {
return collectPinnedRemotes(config).map(({ remote, ref }) => {
const digest = digestOf(ref);
const base = typeof ref.production === "string" ? ref.production : void 0;
return digest && base ? {
remote,
base,
digest
} : null;
}).filter((entry) => entry !== null);
}
const VERIFY_CONCURRENCY = 8;
const messageOf = (cause) => cause instanceof Error ? cause.message : String(cause);
const manifestLegReason = (error) => {
if (!isVerifyError(error)) return messageOf(error);
if (error._tag === "IntegrityMismatch") return `manifest SRI mismatch — pin ${error.expected}, served ${error.actual}`;
if (error._tag === "ProvenanceUnknown") {
if (error.cause instanceof ZodError) return `manifest schema: ${error.cause.message}`;
if (error.status !== void 0) return `manifest GET ${error.status}`;
return `manifest fetch failed: ${messageOf(error.cause)}`;
}
return `manifest signature: ${error.reason}`;
};
const entryLegReason = (error) => {
if (!isVerifyError(error)) return messageOf(error);
if (error._tag === "IntegrityMismatch") return `entry SRI mismatch — pin ${error.expected}, served ${error.actual}`;
if (error._tag === "ProvenanceUnknown") {
if (error.status !== void 0) return `entry GET ${error.status}`;
return `entry fetch failed: ${messageOf(error.cause)}`;
}
return `entry signature: ${error.reason}`;
};
const fileBaseOf = (base, dir) => dir ? `${base.replace(/\/$/, "")}/${dir}` : base.replace(/\/$/, "");
async function walkRemotePin(descriptor, depth, fetchImpl, verification) {
const manifestUrl = manifestDocumentUrl(descriptor.base, descriptor.digest.manifest);
const remote = {
remote: descriptor.remote,
base: descriptor.base,
manifest: descriptor.digest.manifest,
manifestOk: false,
legacy: true,
filesChecked: 0,
mismatches: []
};
const entryResults = [];
let manifest;
try {
manifest = await verifyDocument({
url: manifestUrl,
expected: asDigest(descriptor.digest.integrity),
schema: WorkspaceVersionManifestSchema,
fetchImpl,
cache: false
});
} catch (error) {
remote.manifestReason = manifestLegReason(error);
return {
remote,
entryResults
};
}
remote.manifestOk = true;
if (manifest.dir) {
remote.dir = manifest.dir;
remote.legacy = false;
}
if (verification && verification !== "off") try {
verifyManifestSignature(signaturePayloadOf(manifest), manifest.signature, verification.publicKey);
remote.signature = { ok: true };
} catch (error) {
remote.signature = {
ok: false,
reason: manifestLegReason(error)
};
}
const fileBase = fileBaseOf(descriptor.base, manifest.dir);
if (depth === "entries") {
const targets = [{
url: `${fileBase}/${manifest.entry}`,
integrity: manifest.entryIntegrity
}, ...manifest.ssr ? [{
url: `${fileBase}/${manifest.ssr.entry}`,
integrity: manifest.ssr.integrity
}] : []];
for (const target of targets) try {
await fetchVerified({
url: target.url,
expected: asDigest(target.integrity),
fetchImpl,
cache: false
});
entryResults.push({
remote: descriptor.remote,
url: target.url,
ok: true
});
} catch (error) {
entryResults.push({
remote: descriptor.remote,
url: target.url,
ok: false,
reason: entryLegReason(error)
});
}
}
if (depth === "files") {
const entries = Object.entries(manifest.files ?? {});
remote.filesChecked = entries.length;
const check = async ([path, expected]) => {
try {
await fetchVerified({
url: `${fileBase}/${path}`,
expected: asDigest(expected),
fetchImpl,
cache: false
});
return null;
} catch (error) {
if (isVerifyError(error)) {
if (error._tag === "IntegrityMismatch") return {
file: path,
expected,
actual: error.actual
};
if (error._tag === "ProvenanceUnknown") return {
file: path,
expected,
error: error.status !== void 0 ? `GET ${error.status}` : messageOf(error.cause)
};
return {
file: path,
expected,
error: error.reason
};
}
return {
file: path,
expected,
error: messageOf(error)
};
}
};
const mismatches = [];
let cursor = 0;
const workers = Array.from({ length: Math.min(VERIFY_CONCURRENCY, entries.length) }, async () => {
while (cursor < entries.length) {
const entry = entries[cursor++];
if (!entry) continue;
const mismatch = await check(entry);
if (mismatch) mismatches.push(mismatch);
}
});
await Promise.all(workers);
remote.mismatches = mismatches.sort((a, b) => a.file.localeCompare(b.file));
}
return {
remote,
entryResults
};
}
async function verifyChain(input) {
const descriptors = collectRemoteDescriptors(input.config);
const remotes = [];
const entries = [];
const fetchImpl = input.fetchImpl ?? fetch;
const verification = input.config.publish?.verification;
for (const descriptor of descriptors) {
const walk = await walkRemotePin(descriptor, input.depth, fetchImpl, verification);
remotes.push(walk.remote);
entries.push(...walk.entryResults);
}
const ok = remotes.every((remote) => remote.manifestOk && remote.mismatches.length === 0 && remote.signature?.ok !== false) && entries.every((entry) => entry.ok);
return {
depth: input.depth,
remotes,
entries,
ok
};
}
function formatChainFailures(result) {
const lines = [];
for (const remote of result.remotes) {
if (!remote.manifestOk) lines.push(`${remote.remote}: ${remote.manifestReason}`);
if (remote.signature && !remote.signature.ok) lines.push(`${remote.remote}: signature — ${remote.signature.reason}`);
for (const mismatch of remote.mismatches) {
const detail = mismatch.actual ? `expected ${mismatch.expected}, served ${mismatch.actual}` : mismatch.error ?? "mismatch";
lines.push(`${remote.remote}/${mismatch.file}: ${detail}`);
}
}
for (const entry of result.entries) if (!entry.ok) lines.push(`${entry.remote} entry: ${entry.url} — ${entry.reason}`);
return lines.join("\n");
}
//#endregion
export { collectPinnedRemotes, collectRemoteDescriptors, digestOf, formatChainFailures, verifyChain };
//# sourceMappingURL=chain.mjs.map