Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(app): verify Worker runtime in the packed tarball (#551)

Gener929361a187f7
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index db02f11f3..f89ed3bf0 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -32,6 +32,7 @@ jobs:
run_rust: ${{ steps.scope.outputs.run_rust }}
run_lighthouse: ${{ steps.scope.outputs.run_lighthouse }}
run_knip: ${{ steps.scope.outputs.run_knip }}
+ run_app_packed_artifact: ${{ steps.scope.outputs.run_app_packed_artifact }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
@@ -249,6 +250,47 @@ jobs:
TURBO_SCM_HEAD: ${{ needs.scope.outputs.head_sha }}
run: pnpm turbo run test --affected --filter=@alook/cli --filter=@alook/app --filter=@alook/shared
+ app-packed-artifact:
+ name: App Packed Artifact
+ needs: scope
+ if: needs.scope.outputs.run_app_packed_artifact == 'true'
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ - uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6
+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
+ with:
+ bun-version: 1.3.11
+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
+ with:
+ node-version: 22
+ cache: pnpm
+ - run: pnpm install --frozen-lockfile
+ - name: Pack once and verify Worker closure
+ run: node src/app/scripts/app-packed-artifact.mjs --output-dir "$RUNNER_TEMP/alook-app-packed-artifact"
+ - name: Require complete app artifact evidence
+ if: always()
+ run: |
+ shopt -s nullglob
+ tarballs=("$RUNNER_TEMP"/alook-app-packed-artifact/*.tgz)
+ [[ ${#tarballs[@]} -eq 1 ]]
+ test -f "$RUNNER_TEMP/alook-app-packed-artifact/manifest.json"
+ test -f "$RUNNER_TEMP/alook-app-packed-artifact/artifact-verification/positive-wrangler.log"
+ test -f "$RUNNER_TEMP/alook-app-packed-artifact/artifact-verification/negative-wrangler.log"
+ - name: Upload app packed artifact evidence
+ if: always()
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
+ with:
+ name: app-packed-artifact-${{ github.sha }}
+ path: |
+ ${{ runner.temp }}/alook-app-packed-artifact/*.tgz
+ ${{ runner.temp }}/alook-app-packed-artifact/manifest.json
+ ${{ runner.temp }}/alook-app-packed-artifact/artifact-verification/positive-wrangler.log
+ ${{ runner.temp }}/alook-app-packed-artifact/artifact-verification/negative-wrangler.log
+ if-no-files-found: error
+ retention-days: 7
+
e2e:
name: E2E Tests
needs: scope
@@ -359,6 +401,7 @@ jobs:
- static-checks
- test-linux
- test-windows
+ - app-packed-artifact
- e2e
- desktop-rust
- lighthouse
@@ -372,6 +415,7 @@ jobs:
{"name":"static-checks","expected":${{ needs.scope.outputs.run_code_checks == 'true' }},"result":"${{ needs.static-checks.result }}"},
{"name":"test-linux","expected":${{ needs.scope.outputs.run_code_checks == 'true' }},"result":"${{ needs.test-linux.result }}"},
{"name":"test-windows","expected":${{ needs.scope.outputs.run_windows == 'true' }},"result":"${{ needs.test-windows.result }}"},
+ {"name":"app-packed-artifact","expected":${{ needs.scope.outputs.run_app_packed_artifact == 'true' }},"result":"${{ needs.app-packed-artifact.result }}"},
{"name":"e2e","expected":${{ needs.scope.outputs.run_e2e == 'true' && github.event_name != 'push' }},"result":"${{ needs.e2e.result }}"},
{"name":"desktop-rust","expected":${{ needs.scope.outputs.run_rust == 'true' }},"result":"${{ needs.desktop-rust.result }}"},
{"name":"lighthouse","expected":${{ needs.scope.outputs.run_lighthouse == 'true' && github.event_name != 'push' }},"result":"${{ needs.lighthouse.result }}"}
diff --git a/scripts/ci/changed-scopes.mjs b/scripts/ci/changed-scopes.mjs
index 80cbf8fc8..eaf5aa24a 100644
--- a/scripts/ci/changed-scopes.mjs
+++ b/scripts/ci/changed-scopes.mjs
@@ -92,6 +92,16 @@ export function classifyPaths(inputPaths, options = {}) {
const codeChanged =
full || paths.some((path) => !isMarkdownPath(path) && !isBlogPath(path))
const runCodeChecks = codeChanged && !effectiveBlogOnly && !effectiveDocsOnly
+ const appPackedArtifactInput = paths.some(
+ (path) =>
+ path.startsWith("src/app/") ||
+ path.startsWith("src/daemon/") ||
+ path.startsWith("src/shared/") ||
+ path.startsWith("src/email-worker/") ||
+ path.startsWith("src/ws-do/") ||
+ path.startsWith("src/wake-worker/") ||
+ (path.startsWith("src/web/") && !isBlogPath(path))
+ )
return {
paths,
@@ -106,6 +116,7 @@ export function classifyPaths(inputPaths, options = {}) {
run_rust: runCodeChecks && (full || desktop),
run_lighthouse: runCodeChecks && (full || web),
run_knip: runCodeChecks && (full || app || cli || shared || web || worker),
+ run_app_packed_artifact: full || appPackedArtifactInput,
}
}
diff --git a/scripts/ci/changed-scopes.test.ts b/scripts/ci/changed-scopes.test.ts
index e4cd1d27a..cdde4a03c 100644
--- a/scripts/ci/changed-scopes.test.ts
+++ b/scripts/ci/changed-scopes.test.ts
@@ -48,6 +48,38 @@ describe("classifyPaths", () => {
expect(result.run_ui_e2e).toBe(true)
expect(result.run_lighthouse).toBe(true)
expect(result.run_e2e).toBe(true)
+ expect(result.run_app_packed_artifact).toBe(true)
+ })
+
+ it("fails closed for every app bundle input while excluding stripped blog-only inputs", () => {
+ for (const path of [
+ "src/app/src/index.ts",
+ "src/app/README.md",
+ "src/daemon/src/index.ts",
+ "src/daemon/agent-driver/src/index.ts",
+ "src/daemon/README.md",
+ "src/web/custom-worker.ts",
+ "src/web/src/lib/worker-runtime.ts",
+ "src/web/wrangler.toml",
+ "src/web/migrations/0001.sql",
+ "src/web/README.md",
+ "src/shared/src/index.ts",
+ "src/shared/README.md",
+ "src/email-worker/src/index.ts",
+ "src/email-worker/README.md",
+ "src/ws-do/src/index.ts",
+ "src/ws-do/README.md",
+ "src/wake-worker/src/index.ts",
+ "src/wake-worker/README.md",
+ "pnpm-lock.yaml",
+ ".github/workflows/publish-app.yml",
+ ]) {
+ expect(classifyPaths([path]).run_app_packed_artifact, path).toBe(true)
+ }
+ expect(classifyPaths(["src/web/src/content/example.mdx"]).run_app_packed_artifact).toBe(false)
+ expect(classifyPaths(["src/web/public/blog/example/hero.webp"]).run_app_packed_artifact).toBe(false)
+ expect(classifyPaths(["README.md"]).run_app_packed_artifact).toBe(false)
+ expect(classifyPaths(["src/app/README.md"]).run_code_checks).toBe(false)
})
it("routes CLI and daemon integration test changes through Linux E2E", () => {
@@ -95,6 +127,7 @@ describe("classifyPaths", () => {
expect(result.full).toBe(true)
expect(result.blog_only).toBe(false)
expect(result.run_windows).toBe(true)
+ expect(result.run_app_packed_artifact).toBe(true)
})
})
@@ -124,6 +157,7 @@ describe("runCli", () => {
expect(values).toContain("full=true")
expect(values).toContain("run_windows=true")
expect(values).toContain("run_ui_e2e=true")
+ expect(values).toContain("run_app_packed_artifact=true")
} finally {
rmSync(directory, { recursive: true, force: true })
}
diff --git a/scripts/ci/workflow-contract.test.ts b/scripts/ci/workflow-contract.test.ts
index b81937e63..fe167ac7d 100644
--- a/scripts/ci/workflow-contract.test.ts
+++ b/scripts/ci/workflow-contract.test.ts
@@ -91,6 +91,14 @@ const daemonPackage = JSON.parse(
readFileSync(resolve(repositoryRoot, "src/daemon/package.json"), "utf8"),
) as { devDependencies?: Record<string, string> }
const workspaceManifest = readFileSync(resolve(repositoryRoot, "pnpm-workspace.yaml"), "utf8")
+const appPackedArtifactScript = readFileSync(
+ resolve(repositoryRoot, "src/app/scripts/app-packed-artifact.mjs"),
+ "utf8",
+)
+const packedArtifactVerifier = readFileSync(
+ resolve(repositoryRoot, "src/app/scripts/verify-packed-artifact.mjs"),
+ "utf8",
+)
function ciJob(name: string): string {
const start = ciWorkflow.indexOf(`\n ${name}:\n`)
@@ -151,7 +159,7 @@ describe("Bun workflow setup", () => {
})
it("installs pinned Bun in every CI job that builds a daemon package fixture", () => {
- const bunJobs = ["static-checks", "test-linux", "test-windows"]
+ const bunJobs = ["static-checks", "test-linux", "test-windows", "app-packed-artifact"]
expect(ciWorkflow.match(/oven-sh\/setup-bun/g)).toHaveLength(bunJobs.length)
for (const job of bunJobs) {
expect(ciJob(job)).toContain("oven-sh/setup-bun")
@@ -188,7 +196,7 @@ describe("CI workflow graph", () => {
it("gates the consolidated jobs under the stable CI Gate", () => {
const gate = ciJob("ci-gate")
- for (const job of ["static-checks", "test-linux", "test-windows"]) {
+ for (const job of ["static-checks", "test-linux", "test-windows", "app-packed-artifact"]) {
expect(gate).toContain(`- ${job}`)
expect(gate).toContain(`"name":"${job}"`)
}
@@ -197,6 +205,57 @@ describe("CI workflow graph", () => {
expect(gate).not.toContain(`"name":"${removed}"`)
}
})
+
+ it("gates the fail-closed exact-tarball app artifact check", () => {
+ const scope = ciJob("scope")
+ const artifact = ciJob("app-packed-artifact")
+ const gate = ciJob("ci-gate")
+ expect(scope).toContain(
+ "run_app_packed_artifact: ${{ steps.scope.outputs.run_app_packed_artifact }}",
+ )
+ expect(artifact).toContain("if: needs.scope.outputs.run_app_packed_artifact == 'true'")
+ expect(artifact).toContain("timeout-minutes: 15")
+ expect(artifact).toContain("node src/app/scripts/app-packed-artifact.mjs --output-dir")
+ expect(artifact).toContain("if: always()")
+ expect(artifact).toContain("if-no-files-found: error")
+ expect(artifact).toContain('tarballs=("$RUNNER_TEMP"/alook-app-packed-artifact/*.tgz)')
+ expect(artifact).toContain("[[ ${#tarballs[@]} -eq 1 ]]")
+ for (const evidence of [
+ "*.tgz",
+ "manifest.json",
+ "artifact-verification/positive-wrangler.log",
+ "artifact-verification/negative-wrangler.log",
+ ]) {
+ expect(artifact).toContain(evidence)
+ }
+ for (const excluded of [
+ "artifact-verification/extracted",
+ "artifact-verification/negative/package",
+ "artifact-verification/positive-wrangler/**",
+ "artifact-verification/negative-wrangler/**",
+ ]) {
+ expect(artifact).not.toContain(excluded)
+ }
+ expect(gate).toContain("- app-packed-artifact")
+ expect(gate).toContain('"name":"app-packed-artifact"')
+ })
+})
+
+describe("App packed artifact CI contract", () => {
+ it("packs once and verifies those exact bytes without lifecycle or publishing", () => {
+ expect(appPackedArtifactScript.match(/execFileSync\("npm", \[\s*"pack"/g)).toHaveLength(1)
+ expect(appPackedArtifactScript).toContain("verifyPackedArtifact(tarball")
+ expect(appPackedArtifactScript).not.toContain("self-hosted")
+ expect(appPackedArtifactScript).not.toContain("onboard")
+ expect(appPackedArtifactScript).not.toContain("npm publish")
+ })
+
+ it("derives the negative from the extracted candidate and requires the missing runtime", () => {
+ expect(packedArtifactVerifier).toContain("cpSync(packageRoot, negativePackageRoot")
+ expect(packedArtifactVerifier).toContain("rmSync(negativeRuntime)")
+ expect(packedArtifactVerifier).toContain('negativeOutput.includes("worker-runtime")')
+ expect(packedArtifactVerifier).toContain("Packed artifact Wrangler dry-run produced no output")
+ })
})
describe("Private agent driver package", () => {
diff --git a/src/app/scripts/app-packed-artifact.mjs b/src/app/scripts/app-packed-artifact.mjs
new file mode 100644
index 000000000..246cea5c6
--- /dev/null
+++ b/src/app/scripts/app-packed-artifact.mjs
@@ -0,0 +1,87 @@
+#!/usr/bin/env node
+import { execFileSync } from "node:child_process";
+import { createHash } from "node:crypto";
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { verifyPackedArtifact } from "./verify-packed-artifact.mjs";
+
+const scriptPath = fileURLToPath(import.meta.url);
+const appRoot = resolve(dirname(scriptPath), "..");
+
+function parseArgs(argv) {
+ const result = { skipBuild: false };
+ for (let index = 0; index < argv.length; index += 1) {
+ const arg = argv[index];
+ if (arg === "--skip-build") result.skipBuild = true;
+ else if (arg === "--output-dir") result.outputDir = argv[++index];
+ else throw new Error(`unexpected argument: ${arg}`);
+ }
+ return result;
+}
+
+function run(command, args, cwd) {
+ execFileSync(command, args, { cwd, env: { ...process.env, CI: "true" }, stdio: "inherit" });
+}
+
+function digest(path, algorithm, encoding = "hex") {
+ return createHash(algorithm).update(readFileSync(path)).digest(encoding);
+}
+
+export function runAppPackedArtifact(options) {
+ const outputDir = resolve(options.outputDir);
+ mkdirSync(outputDir, { recursive: true });
+ if (!options.skipBuild) {
+ run("pnpm", ["run", "bundle"], appRoot);
+ run("pnpm", ["run", "build"], appRoot);
+ }
+ const packed = JSON.parse(execFileSync("npm", [
+ "pack",
+ "--json",
+ "--ignore-scripts",
+ "--pack-destination",
+ outputDir,
+ ], { cwd: appRoot, encoding: "utf8", env: { ...process.env, CI: "true" } }));
+ if (!Array.isArray(packed) || packed.length !== 1 || typeof packed[0].filename !== "string") {
+ throw new Error("npm pack did not return exactly one artifact");
+ }
+ const tarball = join(outputDir, packed[0].filename);
+ if (!existsSync(tarball)) throw new Error(`npm pack artifact missing: ${tarball}`);
+ const integrity = `sha512-${digest(tarball, "sha512", "base64")}`;
+ if (packed[0].integrity && packed[0].integrity !== integrity) {
+ throw new Error("npm pack integrity does not match the exact tarball bytes");
+ }
+ const verification = verifyPackedArtifact(tarball, {
+ scratchRoot: join(outputDir, "artifact-verification"),
+ });
+ const manifest = {
+ package: packed[0].name,
+ version: packed[0].version,
+ tarball,
+ filename: packed[0].filename,
+ integrity,
+ sha256: digest(tarball, "sha256"),
+ verification: {
+ positiveWrangler: "passed",
+ negativeWrangler: "failed-missing-worker-runtime",
+ positiveLog: verification.positiveLog,
+ negativeLog: verification.negativeLog,
+ },
+ };
+ const manifestPath = join(outputDir, "manifest.json");
+ writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
+ return { ...manifest, manifestPath };
+}
+
+if (process.argv[1] === scriptPath) {
+ try {
+ const args = parseArgs(process.argv.slice(2));
+ if (!args.outputDir) {
+ throw new Error("Usage: app-packed-artifact.mjs --output-dir <directory> [--skip-build]");
+ }
+ console.log(JSON.stringify(runAppPackedArtifact(args), null, 2));
+ } catch (error) {
+ console.error(error instanceof Error ? error.message : String(error));
+ process.exitCode = 1;
+ }
+}
diff --git a/src/app/scripts/bundle.ts b/src/app/scripts/bundle.ts
index 881216243..7c4508490 100644
--- a/src/app/scripts/bundle.ts
+++ b/src/app/scripts/bundle.ts
@@ -98,6 +98,11 @@ cpSync(join(webSrc, ".open-next"), join(webDest, ".open-next"), { recursive: tru
rewriteAbsolutePaths(webDest);
cpSync(join(webSrc, "wrangler.toml"), join(webDest, "wrangler.toml"));
cpSync(join(webSrc, "custom-worker.ts"), join(webDest, "custom-worker.ts"));
+mkdirSync(join(webDest, "src", "lib"), { recursive: true });
+cpSync(
+ join(webSrc, "src", "lib", "worker-runtime.ts"),
+ join(webDest, "src", "lib", "worker-runtime.ts"),
+);
cpSync(join(webSrc, "migrations"), join(webDest, "migrations"), { recursive: true });
// --- Build Email Worker ---
diff --git a/src/app/scripts/verify-packed-artifact.mjs b/src/app/scripts/verify-packed-artifact.mjs
new file mode 100644
index 000000000..603840fba
--- /dev/null
+++ b/src/app/scripts/verify-packed-artifact.mjs
@@ -0,0 +1,133 @@
+import { execFileSync, spawnSync } from "node:child_process";
+import { createRequire } from "node:module";
+import {
+ cpSync,
+ existsSync,
+ mkdtempSync,
+ mkdirSync,
+ readdirSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const require = createRequire(import.meta.url);
+const scriptPath = fileURLToPath(import.meta.url);
+
+function wranglerBin() {
+ return join(dirname(require.resolve("wrangler/package.json")), "bin", "wrangler.js");
+}
+
+function runWrangler(webRoot, outdir) {
+ return spawnSync(
+ process.execPath,
+ [wranglerBin(), "deploy", "--dry-run", "--outdir", outdir, "--config", join(webRoot, "wrangler.toml")],
+ {
+ cwd: webRoot,
+ encoding: "utf8",
+ env: { ...process.env, CI: "true" },
+ },
+ );
+}
+
+function outputOf(result) {
+ return `${result.stdout ?? ""}${result.stderr ?? ""}`;
+}
+
+export function extractPackage(tarball, destination) {
+ mkdirSync(destination, { recursive: true });
+ execFileSync("tar", ["-xzf", tarball, "-C", destination], { stdio: "pipe" });
+ const packageRoot = join(destination, "package");
+ if (!existsSync(join(packageRoot, "package.json"))) {
+ throw new Error(`Packed artifact did not extract to ${packageRoot}`);
+ }
+ return packageRoot;
+}
+
+export function verifyExtractedPackage(packageRoot, scratchRoot) {
+ const webRoot = join(packageRoot, "bundled", "web");
+ const runtimePath = join(webRoot, "src", "lib", "worker-runtime.ts");
+ const entryPath = join(webRoot, "custom-worker.ts");
+ if (!existsSync(entryPath)) throw new Error(`Packed artifact is missing ${entryPath}`);
+ if (!existsSync(runtimePath)) throw new Error(`Packed artifact is missing ${runtimePath}`);
+
+ const negativePackageRoot = join(scratchRoot, "negative", "package");
+ cpSync(packageRoot, negativePackageRoot, { recursive: true });
+ const negativeRuntime = join(negativePackageRoot, "bundled", "web", "src", "lib", "worker-runtime.ts");
+ rmSync(negativeRuntime);
+
+ const negativeOut = join(scratchRoot, "negative-wrangler");
+ const negative = runWrangler(join(negativePackageRoot, "bundled", "web"), negativeOut);
+ const negativeOutput = outputOf(negative);
+ writeFileSync(join(scratchRoot, "negative-wrangler.log"), negativeOutput);
+ if (negative.status === 0) {
+ throw new Error("0.1.18-shaped negative artifact unexpectedly passed Wrangler dry-run");
+ }
+ if (!negativeOutput.includes("worker-runtime")) {
+ throw new Error(`Negative artifact failed for the wrong reason:\n${negativeOutput}`);
+ }
+
+ const positiveOut = join(scratchRoot, "positive-wrangler");
+ const positive = runWrangler(webRoot, positiveOut);
+ const positiveOutput = outputOf(positive);
+ writeFileSync(join(scratchRoot, "positive-wrangler.log"), positiveOutput);
+ if (positive.status !== 0) {
+ throw new Error(`Packed artifact Wrangler dry-run failed:\n${positiveOutput}`);
+ }
+ if (!existsSync(positiveOut) || readdirSync(positiveOut).length === 0) {
+ throw new Error("Packed artifact Wrangler dry-run produced no output");
+ }
+
+ return {
+ entryPath,
+ runtimePath,
+ negativeLog: join(scratchRoot, "negative-wrangler.log"),
+ positiveLog: join(scratchRoot, "positive-wrangler.log"),
+ positiveOut,
+ };
+}
+
+export function verifyPackedArtifact(tarball, options = {}) {
+ const artifact = resolve(tarball);
+ if (!existsSync(artifact)) throw new Error(`Packed artifact not found: ${artifact}`);
+ const ownedScratch = !options.scratchRoot;
+ const scratchRoot = options.scratchRoot
+ ? resolve(options.scratchRoot)
+ : mkdtempSync(join(tmpdir(), "alook-app-packed-artifact-"));
+ mkdirSync(scratchRoot, { recursive: true });
+ let completed = false;
+
+ try {
+ const packageRoot = extractPackage(artifact, join(scratchRoot, "extracted"));
+ const result = { artifact, scratchRoot, ...verifyExtractedPackage(packageRoot, scratchRoot) };
+ completed = true;
+ return result;
+ } catch (error) {
+ if (ownedScratch) {
+ console.error(`Packed artifact evidence retained at ${scratchRoot}`);
+ }
+ throw error;
+ } finally {
+ if (ownedScratch && completed && process.env.ALOOK_KEEP_PACKAGE_EVIDENCE !== "1") {
+ rmSync(scratchRoot, { recursive: true, force: true });
+ }
+ }
+}
+
+if (process.argv[1] === scriptPath) {
+ const tarball = process.argv[2];
+ if (!tarball) {
+ console.error("Usage: node scripts/verify-packed-artifact.mjs <package.tgz> [scratch-dir]");
+ process.exitCode = 2;
+ } else {
+ try {
+ const result = verifyPackedArtifact(tarball, { scratchRoot: process.argv[3] });
+ console.log(JSON.stringify(result, null, 2));
+ } catch (error) {
+ console.error(error instanceof Error ? error.message : String(error));
+ process.exitCode = 1;
+ }
+ }
+}
diff --git a/src/app/test/packed-artifact.test.ts b/src/app/test/packed-artifact.test.ts
new file mode 100644
index 000000000..3f329304b
--- /dev/null
+++ b/src/app/test/packed-artifact.test.ts
@@ -0,0 +1,104 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+const mocks = vi.hoisted(() => ({
+ spawnSync: vi.fn(),
+}));
+
+vi.mock("node:child_process", async (importOriginal) => {
+ const original = await importOriginal<typeof import("node:child_process")>();
+ return { ...original, spawnSync: mocks.spawnSync };
+});
+
+const { verifyExtractedPackage } = await import("../scripts/verify-packed-artifact.mjs");
+
+const scratchRoots: string[] = [];
+
+function fixture() {
+ const root = mkdtempSync(join(tmpdir(), "alook-packed-artifact-test-"));
+ scratchRoots.push(root);
+ const packageRoot = join(root, "candidate");
+ const webRoot = join(packageRoot, "bundled", "web");
+ mkdirSync(join(webRoot, "src", "lib"), { recursive: true });
+ writeFileSync(join(packageRoot, "package.json"), "{}");
+ writeFileSync(join(webRoot, "wrangler.toml"), 'main = "custom-worker.ts"\n');
+ writeFileSync(join(webRoot, "custom-worker.ts"), 'import "./src/lib/worker-runtime";\n');
+ writeFileSync(join(webRoot, "src", "lib", "worker-runtime.ts"), "export {};\n");
+ return { root, packageRoot, scratchRoot: join(root, "scratch") };
+}
+
+afterEach(() => {
+ mocks.spawnSync.mockReset();
+ for (const root of scratchRoots.splice(0)) rmSync(root, { recursive: true, force: true });
+});
+
+describe("packed artifact verifier", () => {
+ it("copies the Worker runtime into the packaged entry's relative import path", async () => {
+ const execSync = vi.fn();
+ const cpSync = vi.fn();
+ const mkdirSync = vi.fn();
+ const bundleFs = {
+ cpSync,
+ existsSync: vi.fn(() => false),
+ mkdirSync,
+ readFileSync: vi.fn(() => 'main = "src/index.ts"'),
+ readdirSync: vi.fn(() => []),
+ rmSync: vi.fn(),
+ writeFileSync: vi.fn(),
+ };
+
+ vi.doMock("fs", () => bundleFs);
+ vi.doMock("node:fs", () => bundleFs);
+ vi.doMock("child_process", () => ({ execSync }));
+ vi.doMock("node:child_process", () => ({ execSync }));
+ vi.resetModules();
+
+ try {
+ await import("../scripts/bundle.ts");
+ } finally {
+ vi.doUnmock("fs");
+ vi.doUnmock("node:fs");
+ vi.doUnmock("child_process");
+ vi.doUnmock("node:child_process");
+ }
+
+ const appRoot = join(import.meta.dirname, "..");
+ const monoRoot = join(appRoot, "..", "..");
+ const webDest = join(appRoot, "bundled", "web");
+ expect(mkdirSync).toHaveBeenCalledWith(join(webDest, "src", "lib"), { recursive: true });
+ expect(cpSync).toHaveBeenCalledWith(
+ join(monoRoot, "src", "web", "src", "lib", "worker-runtime.ts"),
+ join(webDest, "src", "lib", "worker-runtime.ts"),
+ );
+ });
+
+ it("derives the missing-runtime negative control from the candidate and validates both outcomes", () => {
+ const { packageRoot, scratchRoot } = fixture();
+ mocks.spawnSync
+ .mockReturnValueOnce({ status: 1, stdout: "", stderr: 'Could not resolve "./src/lib/worker-runtime"' })
+ .mockImplementationOnce((_command, args: string[]) => {
+ const outdir = args[args.indexOf("--outdir") + 1];
+ mkdirSync(outdir, { recursive: true });
+ writeFileSync(join(outdir, "index.js"), "export default {};\n");
+ return { status: 0, stdout: "dry-run complete", stderr: "" };
+ });
+
+ const result = verifyExtractedPackage(packageRoot, scratchRoot);
+
+ expect(existsSync(join(packageRoot, "bundled", "web", "src", "lib", "worker-runtime.ts"))).toBe(true);
+ expect(existsSync(join(scratchRoot, "negative", "package", "bundled", "web", "src", "lib", "worker-runtime.ts"))).toBe(false);
+ expect(existsSync(result.positiveOut)).toBe(true);
+ expect(mocks.spawnSync).toHaveBeenCalledTimes(2);
+ });
+
+ it("rejects a negative control that Wrangler accepts", () => {
+ const { packageRoot, scratchRoot } = fixture();
+ mocks.spawnSync.mockReturnValueOnce({ status: 0, stdout: "unexpected", stderr: "" });
+
+ expect(() => verifyExtractedPackage(packageRoot, scratchRoot)).toThrow(
+ "0.1.18-shaped negative artifact unexpectedly passed Wrangler dry-run",
+ );
+ });
+});