From 86f1ccddeb53e1cc3f7ae4cf5f2770475a678c58 Mon Sep 17 00:00:00 2001 From: Jerred Shepherd Date: Wed, 2 Dec 2026 19:41:15 -0800 Subject: [PATCH] fix(temporal): verify structured Renovate pins and Bun integrity Why The production preview rejected unchanged ranked pins. Version-catalog pins are structured entries, and npm registry integrity lives in Bun lock records. What Match the exact managed catalog entry and compare the whole modified catalog. Verify npm resolutions against the exact ranked version and SHA-512 in the tracked Bun lockfile after a frozen install. Verification Replayed real production candidates. Nine of eleven catalog entries and thirteen formerly rejected npm manifests now match. A real vec3 update verified the regenerated Bun lock and installed package. Focused tests and typecheck passed. A production preview and review PR still need live verification. --- .../activities/renovate/bundle-bun.test.ts | 159 +++++++++++++++ .../src/activities/renovate/bundle-bun.ts | 183 +++++++++++++++++ .../renovate/bundle-catalog-pins.test.ts | 191 ++++++++++++++++++ .../renovate/bundle-catalog-pins.ts | 84 ++++++++ .../src/activities/renovate/bundle-pins.ts | 14 +- .../src/activities/renovate/bundle-verify.ts | 48 +---- .../activities/renovate/ranking-versions.ts | 48 ++++- 7 files changed, 672 insertions(+), 55 deletions(-) create mode 100644 packages/temporal/src/activities/renovate/bundle-bun.test.ts create mode 100644 packages/temporal/src/activities/renovate/bundle-bun.ts create mode 100644 packages/temporal/src/activities/renovate/bundle-catalog-pins.test.ts create mode 100644 packages/temporal/src/activities/renovate/bundle-catalog-pins.ts diff --git a/packages/temporal/src/activities/renovate/bundle-bun.test.ts b/packages/temporal/src/activities/renovate/bundle-bun.test.ts new file mode 100644 index 0000000000..0585cb0409 --- /dev/null +++ b/packages/temporal/src/activities/renovate/bundle-bun.test.ts @@ -0,0 +1,159 @@ +import type { RenovateTarget } from "@shepherdjerred/ops-model/renovate-ranking.ts"; +import { createScratchWorkspace } from "#activities/remediation/codex-pr-remediation-git.ts"; +import { describe, expect, test } from "vitest"; +import { assertRankedBunIntegrity } from "./bundle-bun.ts"; +import { actualPinFile, expectedPinFile } from "./bundle-pins.ts"; + +const digest = `sha512-${"A".repeat(86)}==`; +const otherDigest = `sha512-B${"A".repeat(85)}==`; +const path = "packages/app/package.json"; +const catalogRange = "^1.2.0"; + +function target(fields: Partial = {}): RenovateTarget { + return { + manager: "bun", + datasource: "npm", + packageName: "example", + filePath: path, + currentValue: "^1.0.0", + targetValue: catalogRange, + currentVersion: "1.0.0", + targetVersion: "1.2.3", + currentDigest: null, + digest, + ...fields, + }; +} + +function resolution(version = "1.2.3", integrity = digest) { + return [`example@${version}`, "", {}, integrity]; +} + +async function verify(lock: Record, proposal: RenovateTarget) { + const scratch = await createScratchWorkspace("bundle-bun-integrity"); + try { + await Bun.write( + `${scratch.repoDir}/bun.lock`, + JSON.stringify({ lockfileVersion: 2, ...lock }), + { createPath: true }, + ); + await assertRankedBunIntegrity( + { repoDir: scratch.repoDir, trackedPaths: new Set(["bun.lock"]) }, + [proposal], + ); + } finally { + await scratch.cleanup(); + } +} + +describe("Bun npm tarball integrity", () => { + test("matches the manifest without inserting the registry digest", () => { + const before = '{"dependencies":{"example":"^1.0.0"}}'; + const after = '{"dependencies":{"example":"^1.2.0"}}'; + expect(expectedPinFile(path, before, [target()])).toBe( + actualPinFile(path, after), + ); + expect( + expectedPinFile(path, before, [target({ digest: "sha256:old" })]), + ).toBeUndefined(); + expect( + expectedPinFile(path, before, [ + target({ digest: `sha512-${"A".repeat(85)}B==` }), + ]), + ).toBeUndefined(); + expect( + expectedPinFile(path, before, [target({ datasource: "docker" })]), + ).toBeUndefined(); + }); + + test("requires the exact local workspace resolution and integrity", async () => { + const lock = { + workspaces: { + "": { name: "root", dependencies: { example: "^1.0.0" } }, + "packages/app": { + name: "@app/main", + dependencies: { example: catalogRange }, + }, + }, + packages: { + example: resolution(), + "@app/main/example": resolution(), + }, + }; + await expect(verify(lock, target())).resolves.toBeUndefined(); + for (const invalid of [ + resolution("1.2.4"), + resolution("1.2.3", otherDigest), + ]) { + await expect( + verify( + { + ...lock, + packages: { ...lock.packages, "@app/main/example": invalid }, + }, + target(), + ), + ).rejects.toThrow("did not match the exact ranked version"); + } + await expect( + verify(lock, target({ filePath: "packages/unknown/package.json" })), + ).rejects.toThrow("did not match the exact ranked version"); + }); + + test("matches every catalog consumer and rejects unused catalog entries", async () => { + const lock = { + workspaces: { + "": { name: "repo" }, + "packages/app": { + name: "@app/main", + dependencies: { example: "catalog:" }, + }, + "packages/next": { + name: "@app/next", + devDependencies: { example: "catalog:" }, + }, + }, + catalog: { example: catalogRange }, + packages: { example: resolution() }, + }; + const proposal = target({ filePath: "package.json" }); + await expect(verify(lock, proposal)).resolves.toBeUndefined(); + await expect( + verify( + { + ...lock, + packages: { + ...lock.packages, + "@app/next/example": resolution("1.2.3", otherDigest), + }, + }, + proposal, + ), + ).rejects.toThrow("did not match the exact ranked version"); + await expect( + verify({ ...lock, workspaces: { "": { name: "repo" } } }, proposal), + ).rejects.toThrow("did not match the exact ranked version"); + }); + + test("uses unscoped override resolutions for transitive or platform-specific packages", async () => { + const lock = { + workspaces: { "": { name: "root" } }, + overrides: { example: catalogRange }, + packages: { "native-parent/example": resolution() }, + }; + const proposal = target({ filePath: "package.json" }); + await expect(verify(lock, proposal)).resolves.toBeUndefined(); + await expect( + verify( + { + ...lock, + packages: { + ...lock.packages, + "another-parent/example": resolution("1.0.0"), + }, + }, + proposal, + ), + ).rejects.toThrow("did not match the exact ranked version"); + }); +}); diff --git a/packages/temporal/src/activities/renovate/bundle-bun.ts b/packages/temporal/src/activities/renovate/bundle-bun.ts new file mode 100644 index 0000000000..abfc94390e --- /dev/null +++ b/packages/temporal/src/activities/renovate/bundle-bun.ts @@ -0,0 +1,183 @@ +import { realpath } from "node:fs/promises"; +import nodePath from "node:path"; +import type { RenovateTarget } from "@shepherdjerred/ops-model/renovate-ranking.ts"; +import { z } from "zod/v4"; +import { + bunLockOccurrence, + bunWorkspaceDependencySpecs, + parseBunLock, + type BunLock, +} from "./ranking-versions.ts"; + +const { posix } = nodePath; + +function isBunManifestTarget(target: RenovateTarget): boolean { + return ( + (target.manager === "bun" || target.manager === "npm") && + target.datasource === "npm" && + posix.basename(target.filePath) === "package.json" + ); +} + +// npm SHA-512 SRI encodes exactly 64 bytes using canonical, padded Base64. +const NPM_SHA512 = /^sha512-[A-Za-z0-9+/]{85}[AQgw]==$/u; + +export function rankedNpmIntegrity(target: RenovateTarget): string | undefined { + return isBunManifestTarget(target) && + target.targetVersion !== null && + target.currentDigest === null && + target.digest !== null && + NPM_SHA512.test(target.digest) + ? target.digest + : undefined; +} + +type LockOccurrence = BunLock["packages"][string] | undefined; + +function catalogReferences(lock: BunLock, target: RenovateTarget): string[] { + const name = target.packageName; + const references = Object.entries(lock.catalogs ?? {}) + .filter(([, catalog]) => catalog[name] === target.targetValue) + .map(([catalog]) => `catalog:${catalog}`); + if (lock.catalog?.[name] === target.targetValue) references.push("catalog:"); + return references; +} + +function verifiedCatalogOccurrences( + lock: BunLock, + target: RenovateTarget, + references: readonly string[], +): LockOccurrence[] { + return references.flatMap((reference) => { + const consumers = Object.entries(lock.workspaces).filter(([, workspace]) => + bunWorkspaceDependencySpecs(workspace, target.packageName).includes( + reference, + ), + ); + return consumers.length === 0 + ? [undefined] + : consumers.map(([path]) => + bunLockOccurrence(lock, path, target.packageName), + ); + }); +} + +function targetOccurrences( + lock: BunLock, + target: RenovateTarget, +): LockOccurrence[] { + const { filePath, packageName, targetValue } = target; + const project = posix.dirname(filePath); + const path = project === "." ? "" : project; + const workspace = lock.workspaces[path]; + const occurrences: LockOccurrence[] = []; + if ( + workspace !== undefined && + bunWorkspaceDependencySpecs(workspace, packageName).includes(targetValue) + ) { + occurrences.push(bunLockOccurrence(lock, path, packageName)); + } + if (path === "") { + occurrences.push( + ...verifiedCatalogOccurrences( + lock, + target, + catalogReferences(lock, target), + ), + ); + // An unscoped root override covers every occurrence, including transitive + // dependencies and optional packages for other platforms. + if (lock.overrides?.[packageName] === targetValue) { + const prefix = `${packageName}@`; + const overrides = Object.values(lock.packages).filter(([resolution]) => + resolution.startsWith(prefix), + ); + occurrences.push(...(overrides.length === 0 ? [undefined] : overrides)); + } + } + return occurrences; +} + +export async function assertRankedBunIntegrity( + input: { + readonly repoDir: string; + readonly trackedPaths: ReadonlySet; + }, + targets: readonly RenovateTarget[], +): Promise { + const evidence = targets.flatMap((target) => { + const digest = rankedNpmIntegrity(target); + return digest === undefined || target.targetVersion === null + ? [] + : [{ target, digest, version: target.targetVersion }]; + }); + if (evidence.length === 0) return; + if (!input.trackedPaths.has("bun.lock")) { + throw new Error("Ranked npm integrity requires the tracked Bun lockfile."); + } + // The frozen install verifies the regenerated lock against the manifests and + // checks the downloaded package. Bind that proof to the exact ranked pin and + // integrity rather than accepting another version that satisfies the range. + const lock = parseBunLock(await Bun.file(`${input.repoDir}/bun.lock`).text()); + for (const { target, digest, version } of evidence) { + const occurrences = targetOccurrences(lock, target); + const expected = `${target.lookupName ?? target.packageName}@${version}`; + if ( + occurrences.length === 0 || + occurrences.some( + (occurrence) => + occurrence?.[0] !== expected || occurrence[3] !== digest, + ) + ) { + throw new Error( + `Bun lockfile evidence for ${target.packageName} in ${target.filePath} did not match the exact ranked version and npm integrity.`, + ); + } + } +} + +const InstalledManifestSchema = z.object({ version: z.string() }); + +export async function assertInstalledBunVersions( + repoDir: string, + targets: readonly RenovateTarget[], +): Promise { + for (const target of targets) { + if ( + target.targetVersion === null || + (target.manager !== "npm" && !isBunManifestTarget(target)) + ) + continue; + const project = posix.dirname(target.filePath); + if ( + !/^(?:@[\w.-]+\/)?[\w.-]+$/u.test(target.packageName) || + target.packageName + .split("/") + .some((segment) => segment === "." || segment === "..") + ) { + throw new Error( + "The installed npm package name could not be verified safely.", + ); + } + const installedFile = `${repoDir}/${project}/node_modules/${target.packageName}/package.json`; + const resolved = Bun.file(installedFile); + // Root overrides and peers may have no direct installation at the + // declaring workspace. The frozen install still validates their lockfile. + if (!(await resolved.exists())) continue; + const resolvedPath = nodePath.relative( + await realpath(repoDir), + await realpath(installedFile), + ); + if (nodePath.isAbsolute(resolvedPath) || resolvedPath.startsWith("..")) { + throw new Error( + `The installed npm package ${target.packageName} resolves outside the checkout.`, + ); + } + const manifest = InstalledManifestSchema.parse(await resolved.json()); + if (manifest.version !== target.targetVersion) { + throw new Error( + `The installed version of ${target.packageName} in ${project} is different from the exact ranked target ${target.targetVersion}.`, + ); + } + } +} diff --git a/packages/temporal/src/activities/renovate/bundle-catalog-pins.test.ts b/packages/temporal/src/activities/renovate/bundle-catalog-pins.test.ts new file mode 100644 index 0000000000..17785dcee8 --- /dev/null +++ b/packages/temporal/src/activities/renovate/bundle-catalog-pins.test.ts @@ -0,0 +1,191 @@ +import type { RenovateTarget } from "@shepherdjerred/ops-model/renovate-ranking.ts"; +import { describe, expect, test } from "vitest"; + +import { expectedVersionCatalog } from "./bundle-catalog-pins.ts"; +import { actualPinFile, expectedPinFile } from "./bundle-pins.ts"; + +const filePath = "packages/version-catalog/src/catalog.json"; +const oldDigest = + "sha256:d3c53deb09f6b8fffd1476c7154da538394193955d1e909f3b126068102fb7cf"; +const newDigest = + "sha256:7ca2e262712700ae28ca5b32f9cebf1168e3ea3bfcd97a8da6e040f5ca6227a5"; +const image = { + name: "linuxserver/tautulli", + category: "upstream", + artifactType: "image", + management: { + managed: true, + datasource: "docker", + registryUrl: "https://ghcr.io", + versioning: "docker", + }, + value: `2.18.2@${oldDigest}`, + notes: ["Keep catalog metadata and unrelated entries intact."], +}; +const source = { + name: "adyanth/cloudflare-operator", + category: "upstream", + artifactType: "source", + management: { + managed: true, + datasource: "github-releases", + versioning: "semver", + }, + value: "v0.13.0", +}; + +function catalog(entries: readonly unknown[]) { + return { + $schema: "./schema.json", + schemaVersion: 1, + entries, + }; +} + +function dockerTarget(overrides: Partial = {}): RenovateTarget { + return { + manager: "custom.regex", + datasource: "docker", + packageName: image.name, + lookupName: image.name, + filePath, + currentValue: "2.18.2", + currentVersion: "2.18.2", + targetValue: "2.18.2", + targetVersion: null, + currentDigest: oldDigest, + digest: newDigest, + ...overrides, + }; +} + +describe("exact catalog pins", () => { + test("applies digest-only and version-only proposals by entry identity", () => { + const before = catalog([image, source]); + const output = expectedVersionCatalog(JSON.stringify(before, null, 2), [ + dockerTarget(), + dockerTarget({ + datasource: "github-releases", + packageName: source.name, + lookupName: source.name, + currentValue: "v0.13.0", + currentVersion: "v0.13.0", + targetValue: "v0.14.0", + targetVersion: "v0.14.0", + currentDigest: null, + digest: null, + }), + ]); + expect(output).toEqual( + catalog([ + { ...image, value: `2.18.2@${newDigest}` }, + { ...source, value: "v0.14.0" }, + ]), + ); + }); + + test("requires the upstream alias and both exact values for an OCI chart", () => { + const chart = { + ...image, + name: "chart-alias", + artifactType: "helm-chart", + management: { ...image.management, packageName: "owner/chart" }, + }; + const before = JSON.stringify(catalog([chart])); + const target = dockerTarget({ + packageName: "chart-alias", + lookupName: "owner/chart", + targetValue: "2.19.0", + targetVersion: "2.19.0", + }); + expect(expectedVersionCatalog(before, [target])).toEqual( + catalog([{ ...chart, value: `2.19.0@${newDigest}` }]), + ); + expect( + expectedVersionCatalog(before, [ + { ...target, lookupName: "other/chart" }, + ]), + ).toBeUndefined(); + }); + + test("compares the complete catalog at the exact manifest path", () => { + const before = JSON.stringify(catalog([image, source])); + const proposedImage = { ...image, value: `2.18.2@${newDigest}` }; + const after = JSON.stringify(catalog([proposedImage, source]), null, 2); + const expected = expectedPinFile(filePath, before, [dockerTarget()]); + + expect(expected).toBeDefined(); + expect(actualPinFile(filePath, after)).toBe(expected); + expect( + actualPinFile( + filePath, + JSON.stringify( + catalog([proposedImage, { ...source, value: "v0.20.0" }]), + ), + ), + ).not.toBe(expected); + expect( + expectedPinFile("fixture/catalog.json", before, [dockerTarget()]), + ).toBeUndefined(); + }); + + test.each([ + { currentValue: "2.18.1" }, + { currentDigest: newDigest }, + { digest: null }, + { digest: oldDigest }, + { digest: newDigest.slice("sha256:".length) }, + { datasource: "helm" }, + ])("holds exact pin mismatches and no-op proposals (%o)", (overrides) => { + const before = JSON.stringify(catalog([image])); + expect( + expectedVersionCatalog(before, [dockerTarget(overrides)]), + ).toBeUndefined(); + }); + + test("rejects duplicate catalog entries and competing targets", () => { + const repeated = JSON.stringify(catalog([image, image])); + expect(expectedVersionCatalog(repeated, [dockerTarget()])).toBeUndefined(); + const before = JSON.stringify(catalog([image])); + expect( + expectedVersionCatalog(before, [ + dockerTarget(), + dockerTarget({ + currentDigest: newDigest, + targetValue: "2.19.0", + digest: oldDigest, + }), + ]), + ).toBeUndefined(); + }); + + test("holds unmanaged entries and Helm index checksums", () => { + const unmanaged = { ...image, management: { managed: false } }; + expect( + expectedVersionCatalog(JSON.stringify(catalog([unmanaged])), [ + dockerTarget(), + ]), + ).toBeUndefined(); + const chart = { + ...image, + name: "mc-router", + artifactType: "helm-chart", + management: { ...image.management, datasource: "helm" }, + value: "1.5.0", + }; + expect( + expectedVersionCatalog(JSON.stringify(catalog([chart])), [ + dockerTarget({ + datasource: "helm", + packageName: chart.name, + lookupName: chart.name, + currentValue: "1.5.0", + targetValue: "1.5.1", + currentDigest: null, + digest: + "a1d4ec4ac31bc031b326261f31fd9f41771f77b99d8bdc5a5e61c0c2e8d73e10", + }), + ]), + ).toBeUndefined(); + }); +}); diff --git a/packages/temporal/src/activities/renovate/bundle-catalog-pins.ts b/packages/temporal/src/activities/renovate/bundle-catalog-pins.ts new file mode 100644 index 0000000000..87fbf6d19e --- /dev/null +++ b/packages/temporal/src/activities/renovate/bundle-catalog-pins.ts @@ -0,0 +1,84 @@ +import type { RenovateTarget } from "@shepherdjerred/ops-model/renovate-ranking.ts"; +import { z } from "zod/v4"; + +const CatalogEntrySchema = z.looseObject({ + name: z.string().min(1), + value: z.string().min(1), + artifactType: z.enum(["image", "helm-chart", "package", "source"]), + management: z.discriminatedUnion("managed", [ + z.looseObject({ managed: z.literal(false) }), + z.looseObject({ + managed: z.literal(true), + datasource: z.string().min(1), + packageName: z.string().min(1).optional(), + }), + ]), +}); + +const CatalogSchema = z.looseObject({ + schemaVersion: z.literal(1), + entries: z.array(CatalogEntrySchema).min(1), +}); + +type CatalogEntry = z.infer; +const CATALOG_VERSION = /^[^@\s]+$/u; +const OCI_DIGEST = /^sha256:[a-f0-9]{64}$/u; + +function catalogValue( + version: string | null, + digest: string | null, +): string | undefined { + if (version === null || !CATALOG_VERSION.test(version)) return undefined; + if (digest === null) return version; + return OCI_DIGEST.test(digest) ? `${version}@${digest}` : undefined; +} + +function replacementValue( + entry: CatalogEntry, + target: RenovateTarget, +): string | undefined { + const { management, artifactType } = entry; + const { datasource, currentDigest, digest } = target; + if ( + !management.managed || + management.datasource !== datasource || + (management.packageName ?? entry.name) !== + (target.lookupName ?? target.packageName) + ) { + return undefined; + } + if (datasource === "docker") { + if ( + currentDigest === null || + digest === null || + (artifactType !== "image" && artifactType !== "helm-chart") + ) { + return undefined; + } + } else if (currentDigest !== null || digest !== null) { + // A registry checksum without a stored digest needs independent proof. + return undefined; + } + const current = catalogValue(target.currentValue, currentDigest); + const next = catalogValue(target.targetValue, digest); + return next !== current && current === entry.value ? next : undefined; +} + +export function expectedVersionCatalog( + before: string, + targets: readonly RenovateTarget[], +): Record | undefined { + const catalog = CatalogSchema.parse(JSON.parse(before)); + const entries = new Map(catalog.entries.map((entry) => [entry.name, entry])); + if (targets.length === 0 || entries.size !== catalog.entries.length) + return undefined; + for (const target of targets) { + const entry = entries.get(target.packageName); + if (entry === undefined) return undefined; + const next = replacementValue(entry, target); + if (next === undefined) return undefined; + entry.value = next; + entries.delete(target.packageName); + } + return catalog; +} diff --git a/packages/temporal/src/activities/renovate/bundle-pins.ts b/packages/temporal/src/activities/renovate/bundle-pins.ts index 2e16e55acd..84ad557557 100644 --- a/packages/temporal/src/activities/renovate/bundle-pins.ts +++ b/packages/temporal/src/activities/renovate/bundle-pins.ts @@ -1,9 +1,12 @@ import nodePath from "node:path"; import { z } from "zod/v4"; import type { RenovateTarget } from "@shepherdjerred/ops-model/renovate-ranking.ts"; +import { rankedNpmIntegrity } from "./bundle-bun.ts"; +import { expectedVersionCatalog } from "./bundle-catalog-pins.ts"; import { dependencyFields } from "./bundle-policy.ts"; const ManifestSchema = z.record(z.string(), z.unknown()); +const VERSION_CATALOG_FILE = "packages/version-catalog/src/catalog.json"; function sortJson(value: unknown): unknown { if (Array.isArray(value)) return value.map((item) => sortJson(item)); @@ -55,7 +58,7 @@ function expectedPackageManifest( if ( target.currentValue === null || target.currentValue === target.targetValue || - target.digest !== null || + (target.digest !== null && rankedNpmIntegrity(target) === undefined) || replaceManifestDependency(dependencies, target) === 0 ) { return undefined; @@ -194,13 +197,20 @@ export function expectedPinFile( before: string, targets: readonly RenovateTarget[], ): string | undefined { + if (file === VERSION_CATALOG_FILE) { + const expected = expectedVersionCatalog(before, targets); + return expected === undefined + ? undefined + : JSON.stringify(sortJson(expected)); + } return nodePath.posix.basename(file) === "package.json" ? expectedPackageManifest(before, targets) : expectedTextManifest(before, targets); } export function actualPinFile(file: string, after: string): string { - return nodePath.posix.basename(file) === "package.json" + return file === VERSION_CATALOG_FILE || + nodePath.posix.basename(file) === "package.json" ? JSON.stringify(sortJson(ManifestSchema.parse(JSON.parse(after)))) : after.replaceAll("\r\n", "\n"); } diff --git a/packages/temporal/src/activities/renovate/bundle-verify.ts b/packages/temporal/src/activities/renovate/bundle-verify.ts index d5da68c02a..ebf22220bc 100644 --- a/packages/temporal/src/activities/renovate/bundle-verify.ts +++ b/packages/temporal/src/activities/renovate/bundle-verify.ts @@ -1,4 +1,4 @@ -import { lstat, realpath } from "node:fs/promises"; +import { lstat } from "node:fs/promises"; import nodePath from "node:path"; import { z } from "zod/v4"; import type { @@ -8,6 +8,10 @@ import type { import { rootInstallWithoutHooks } from "#activities/bot-clone.ts"; import { listDirtyRepoPaths } from "#activities/remediation/codex-pr-remediation-git.ts"; import type { GitCommandRunner } from "#activities/scout/scout-season-refresh-git.ts"; +import { + assertInstalledBunVersions, + assertRankedBunIntegrity, +} from "./bundle-bun.ts"; import { actualPinFile, expectedPinFile, @@ -322,47 +326,6 @@ async function verifiedChangedFiles( return changedFiles; } -async function assertInstalledBunVersions( - repoDir: string, - targets: readonly RenovateTarget[], -): Promise { - for (const target of targets) { - if (target.targetVersion === null || target.manager !== "npm") continue; - const project = posix.dirname(target.filePath); - const workspace = `${repoDir}/${project}`; - if ( - !/^(?:@[\w.-]+\/)?[\w.-]+$/u.test(target.packageName) || - target.packageName - .split("/") - .some((segment) => segment === "." || segment === "..") - ) { - throw new Error( - "The installed npm package name could not be verified safely.", - ); - } - const installedFile = `${workspace}/node_modules/${target.packageName}/package.json`; - const resolved = Bun.file(installedFile); - // Root overrides and peer constraints have no direct installation at the - // declaring workspace. The frozen install still validates their lockfile. - if (!(await resolved.exists())) continue; - const resolvedPath = nodePath.relative( - await realpath(repoDir), - await realpath(installedFile), - ); - if (nodePath.isAbsolute(resolvedPath) || resolvedPath.startsWith("..")) { - throw new Error( - `The installed npm package ${target.packageName} resolves outside the checkout.`, - ); - } - const manifest = ManifestSchema.parse(await resolved.json()); - if (manifest["version"] !== target.targetVersion) { - throw new Error( - `The installed version of ${target.packageName} in ${project} is different from the exact ranked target ${target.targetVersion}.`, - ); - } - } -} - export async function readBundleDiff( repoDir: string, files: readonly string[], @@ -442,6 +405,7 @@ export async function verifyPreparedRenovateBundle( await rootInstallWithoutHooks(input.repoDir, (args, { cwd, env }) => runCheck(args, { cwd, ...(env === undefined ? {} : { env }) }), ); + await assertRankedBunIntegrity(input, targets); if (input.verificationSandbox) await assertInstalledBunVersions(input.repoDir, targets); const commands = [ diff --git a/packages/temporal/src/activities/renovate/ranking-versions.ts b/packages/temporal/src/activities/renovate/ranking-versions.ts index 2fb84d7bd9..41a4dc36c3 100644 --- a/packages/temporal/src/activities/renovate/ranking-versions.ts +++ b/packages/temporal/src/activities/renovate/ranking-versions.ts @@ -21,10 +21,40 @@ const BunLockSchema = z.object({ ), catalog: DependencySpecsSchema.optional(), catalogs: z.record(z.string(), DependencySpecsSchema).optional(), + overrides: z.record(z.string(), z.unknown()).optional(), packages: z.record(z.string(), z.tuple([z.string()], z.unknown())), }); -type BunLock = z.infer; +export type BunLock = z.infer; + +export function parseBunLock(lockText: string): BunLock { + return BunLockSchema.parse(Bun.JSONC.parse(lockText)); +} + +export function bunWorkspaceDependencySpecs( + workspace: BunLock["workspaces"][string], + packageName: string, +): string[] { + return DependencyTypeSchema.options.flatMap((depType) => { + const spec = workspace[depType]?.[packageName]; + return spec === undefined ? [] : [spec]; + }); +} + +export function bunLockOccurrence( + lock: BunLock, + workspacePath: string, + packageName: string, +): BunLock["packages"][string] | undefined { + if (!Object.hasOwn(lock.workspaces, workspacePath)) return undefined; + if (workspacePath === "") return lock.packages[packageName]; + // Bun stores a workspace-local override under workspace-name/dependency + // and uses the root package slot when the workspace shares a resolution. + const name = lock.workspaces[workspacePath]?.name; + return name === undefined + ? undefined + : (lock.packages[`${name}/${packageName}`] ?? lock.packages[packageName]); +} type Occurrence = { readonly filePath: string; @@ -67,7 +97,7 @@ function declaredRange( export function bunInstalledVersionResolver( lockText: string, ): (input: Occurrence) => string | null { - const lock = BunLockSchema.parse(Bun.JSONC.parse(lockText)); + const lock = parseBunLock(lockText); return (input) => { const depType = DependencyTypeSchema.safeParse(input.depType); if (!depType.success) return null; @@ -80,15 +110,11 @@ export function bunInstalledVersionResolver( const range = declaredRange(lock, input, declaration); if (range === undefined) return null; - // Bun stores a workspace-local override under workspace-name/dependency - // and uses the root package slot when the workspace shares a resolution. - const workspaceName = workspace?.name; - if (workspacePath !== "" && workspaceName === undefined) return null; - const workspaceSlot = - workspacePath === "" || workspaceName === undefined - ? undefined - : lock.packages[`${workspaceName}/${input.packageName}`]; - const resolution = (workspaceSlot ?? lock.packages[input.packageName])?.[0]; + const resolution = bunLockOccurrence( + lock, + workspacePath, + input.packageName, + )?.[0]; const prefix = `${input.lookupName}@`; if (typeof resolution !== "string" || !resolution.startsWith(prefix)) return null;