Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
159 changes: 159 additions & 0 deletions packages/temporal/src/activities/renovate/bundle-bun.test.ts
Original file line number Diff line number Diff line change
@@ -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> = {}): 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<string, unknown>, 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");
});
});
183 changes: 183 additions & 0 deletions packages/temporal/src/activities/renovate/bundle-bun.ts
Original file line number Diff line number Diff line change
@@ -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<string>;
},
targets: readonly RenovateTarget[],
): Promise<void> {
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<void> {
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}.`,
);
}
}
}
Loading