diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0e9ae1c3..25dbe324 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -280,8 +280,15 @@ jobs: timeout-minutes: 15 steps: - uses: actions/checkout@v4 + # Build context is the repository root: the dashboard's dependencies are + # locked in the root package-lock.json. See packages/web-dashboard/Dockerfile. - name: Build the dashboard image - run: docker build -t gitwire-dashboard:ci -f packages/web-dashboard/Dockerfile packages/web-dashboard + run: docker build -t gitwire-dashboard:ci -f packages/web-dashboard/Dockerfile . + # The Dockerfile installs from the lockfile with npm ci. This proves the + # image holds what the lockfile pins: every package version inside it + # has to be in package-lock.json, or the job fails. + - name: Compare the image's packages with the lockfile + run: node scripts/compare-image-deps.mjs --image gitwire-dashboard:ci - name: Boot the dashboard and check it serves run: | docker run -d --name gitwire-dashboard-ci -p 3001:3001 \ @@ -522,7 +529,8 @@ jobs: --build-arg GITWIRE_BUILT_AT="${{ steps.meta.outputs.built_at }}" \ --build-arg GITWIRE_VERSION="${{ steps.meta.outputs.version }}" \ -t "${{ steps.meta.outputs.dashboard_tag }}" \ - packages/web-dashboard + -f packages/web-dashboard/Dockerfile \ + . - name: Verify OCI revision labels run: | @@ -536,6 +544,11 @@ jobs: echo "✓ $img OCI revision: $ACTUAL" done + # The dashboard release image is installed from the lockfile. Refuse to + # publish one that holds a package version the lockfile does not pin. + - name: Compare the dashboard release image's packages with the lockfile + run: node scripts/compare-image-deps.mjs --image "${{ steps.meta.outputs.dashboard_tag }}" + - name: Smoke-test app image (fail-closed) env: EXPECTED_SHA: ${{ steps.meta.outputs.release_sha }} @@ -800,7 +813,12 @@ jobs: --build-arg GITWIRE_BUILT_AT="${{ steps.meta.outputs.built_at }}" \ --build-arg GITWIRE_VERSION="${{ steps.meta.outputs.version }}" \ -t gitwire-dashboard:release-test \ - packages/web-dashboard + -f packages/web-dashboard/Dockerfile \ + . + + # Same check as publish-release-images, against the local release-test tag. + - name: Compare the dashboard image's packages with the lockfile + run: node scripts/compare-image-deps.mjs --image gitwire-dashboard:release-test - name: Verify OCI revision labels run: | diff --git a/docker-compose.build.yml b/docker-compose.build.yml index 99d5e07e..d2d800cf 100644 --- a/docker-compose.build.yml +++ b/docker-compose.build.yml @@ -50,8 +50,10 @@ services: dashboard: image: gitwire-dashboard:dev build: - context: packages/web-dashboard - dockerfile: Dockerfile + # The dashboard's dependencies are locked in the root package-lock.json, + # so its Dockerfile is built from the repository root. + context: . + dockerfile: packages/web-dashboard/Dockerfile args: GITWIRE_COMMIT_SHA: ${GITWIRE_COMMIT_SHA:-dev} GITWIRE_BUILT_AT: ${GITWIRE_BUILT_AT:-unknown} diff --git a/package-lock.json b/package-lock.json index a689c775..58a8d037 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12783,9 +12783,9 @@ } }, "packages/web-dashboard/node_modules/@next/env": { - "version": "16.3.3", - "resolved": "https://registry.npmjs.org/@next/env/-/env-16.3.3.tgz", - "integrity": "sha512-U2eYQRwXj+dsqxV79zFqExDdatnNY/ZWc2nsJU1p/OgT7fd3dXwlF6OjYaFQCfMoeTA19PWq+wVmYgimVA+V+g==", + "version": "16.4.6", + "resolved": "https://registry.npmjs.org/@next/env/-/env-16.4.6.tgz", + "integrity": "sha512-SunBjJ6t+oBtecS3dTjdVuMhUogP5wD/vrGL5EVuQYM1iS4O5ilL51HkiJ3sPjMzRHiCChvr4dbaSJbR7F3lxA==", "license": "MIT" }, "packages/web-dashboard/node_modules/@next/swc-darwin-arm64": { @@ -13372,7 +13372,7 @@ "integrity": "sha512-QZJiYhaZLJMo2KpkQGQIwvmd79WVsAWeYIU554a8d7zArS3si/IRy3lBNV/rtYhE70oLwdLYhPAXLPx8HwcwtA==", "license": "MIT", "dependencies": { - "@next/env": "16.3.3", + "@next/env": "16.4.6", "@swc/helpers": "0.5.23", "baseline-browser-mapping": "^2.9.19", "caniuse-lite": "^1.0.30001579", @@ -13386,15 +13386,15 @@ "node": ">=20.9.0" }, "optionalDependencies": { - "@next/swc-darwin-arm64": "16.3.3", - "@next/swc-darwin-x64": "16.3.3", - "@next/swc-linux-arm64-gnu": "16.3.3", - "@next/swc-linux-arm64-musl": "16.3.3", - "@next/swc-linux-x64-gnu": "16.3.3", - "@next/swc-linux-x64-musl": "16.3.3", - "@next/swc-win32-arm64-msvc": "16.3.3", - "@next/swc-win32-x64-msvc": "16.3.3", - "sharp": "^0.35.3" + "@next/swc-darwin-arm64": "16.4.6", + "@next/swc-darwin-x64": "16.4.6", + "@next/swc-linux-arm64-gnu": "16.4.6", + "@next/swc-linux-arm64-musl": "16.4.6", + "@next/swc-linux-x64-gnu": "16.4.6", + "@next/swc-linux-x64-musl": "16.4.6", + "@next/swc-win32-arm64-msvc": "16.4.6", + "@next/swc-win32-x64-msvc": "16.4.6", + "sharp": "^0.35.5" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0", diff --git a/packages/core/tests/compare-image-deps.test.js b/packages/core/tests/compare-image-deps.test.js new file mode 100644 index 00000000..bb3d95fa --- /dev/null +++ b/packages/core/tests/compare-image-deps.test.js @@ -0,0 +1,449 @@ +// packages/core/tests/compare-image-deps.test.js +// +// Tests for scripts/compare-image-deps.mjs +// +// Builds small image trees and lockfiles on disk and runs the script against +// them. Covers: +// - every package pinned for the workspace (pass, exit 0) +// - peer dependencies are followed; two versions of one package are a note +// - a version that is in no lockfile entry (fail, exit 1) +// - a version pinned only for another workspace, or only as a dev dependency +// (warning, exit 0) +// - workspace manifest carrying another version than the lockfile (fail) +// - scoped, nested and linked packages are listed once +// - nothing listed, an entry without a version (error, exit 2) +// - a package.json under node_modules that is not a JSON object (error, +// exit 2); a directory that holds none is passed over +// - a directory that must be examined and cannot be listed, read or +// resolved (error, exit 2), brought about by a failing fs method and, on +// POSIX as a plain user, by real permission bits +// - unreadable lockfile, lockfile without a packages map, unknown workspace, +// usage errors (error, exit 2) +// - --json report +// - --image runs the listing inside the container (POSIX runners only) + +import { describe, it, expect, beforeEach, afterEach } from "@jest/globals"; +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import path from "node:path"; +import os from "node:os"; +import { fileURLToPath } from "node:url"; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const SCRIPT = path.resolve(__dirname, "../../../scripts/compare-image-deps.mjs"); +const WORKSPACE = "packages/web-dashboard"; + +// Two workspaces share one lockfile. The dashboard's tree is: a, @scope/b with +// its own d@1.5.0, the react@19.2.8 that @scope/b takes as a peer from the +// root, and its own nested react@19.2.4. left-pad belongs to the other +// workspace, d@2.0.0 reaches neither, and eslint is a dev dependency. +const makeLock = () => ({ + name: "root", + version: "1.0.0", + lockfileVersion: 3, + requires: true, + packages: { + "": { name: "root", version: "1.0.0", devDependencies: { eslint: "^9.0.0" } }, + [WORKSPACE]: { name: "web-dashboard", version: "0.23.1", dependencies: { a: "1.0.0", "@scope/b": "^2.0.0", react: "19.2.4" } }, + "packages/other": { name: "other", version: "0.23.1", dependencies: { react: "^19.1.0", "left-pad": "1.0.0" } }, + "node_modules/a": { version: "1.0.0" }, + "node_modules/@scope/b": { version: "2.0.0", dependencies: { d: "^1.0.0" }, peerDependencies: { react: "^19.0.0" } }, + "node_modules/@scope/b/node_modules/d": { version: "1.5.0" }, + "node_modules/d": { version: "2.0.0" }, + "node_modules/react": { version: "19.2.8" }, + "node_modules/left-pad": { version: "1.0.0" }, + "node_modules/eslint": { version: "9.0.0", dev: true }, + [`${WORKSPACE}/node_modules/react`]: { version: "19.2.4" }, + }, +}); + +// What an image built from that lockfile holds: the workspace manifest and +// the packages its production tree resolves to. +const TREE_PACKAGES = [ + ["node_modules/a", "a", "1.0.0"], + ["node_modules/@scope/b", "@scope/b", "2.0.0"], + ["node_modules/@scope/b/node_modules/d", "d", "1.5.0"], + ["node_modules/react", "react", "19.2.8"], + [`${WORKSPACE}/node_modules/react`, "react", "19.2.4"], +]; + +let dir; +let image; +let lockfile; + +beforeEach(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), "compare-image-deps-")); + image = path.join(dir, "image"); + lockfile = path.join(dir, "package-lock.json"); + writeManifest(WORKSPACE, "web-dashboard", "0.23.1"); + for (const [rel, name, version] of TREE_PACKAGES) writeManifest(rel, name, version); + writeLock(makeLock()); +}); + +afterEach(() => { + fs.rmSync(dir, { recursive: true, force: true }); +}); + +function writeManifest(rel, name, version) { + const file = path.join(image, rel, "package.json"); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, JSON.stringify(version === undefined ? { name } : { name, version })); +} + +function writeLock(lock) { + fs.writeFileSync(lockfile, typeof lock === "string" ? lock : JSON.stringify(lock, null, 2)); +} + +function runScript(args, env = {}) { + try { + const stdout = execFileSync(process.execPath, [SCRIPT, ...args], { encoding: "utf8", timeout: 20000, env: { ...process.env, ...env } }); + return { status: 0, stdout, stderr: "" }; + } catch (err) { + return { status: err.status, stdout: err.stdout || "", stderr: err.stderr || "" }; + } +} + +// Lists the fixture image on disk. Later arguments win over the first two. +const run = (args) => runScript(["--dir", image, "--lockfile", lockfile, ...args]); + +// The listing runs in a child Node process. A file-system failure is brought +// about there through a module the child loads before anything else: it +// replaces one fs method so that the method fails, with the given error code, +// for every path that ends with one of `targets`. +function failInListing(method, code, targets) { + const stub = path.join(dir, `fail-${method}.cjs`); + fs.writeFileSync( + stub, + [ + "const fs = require('node:fs');", + "const targets = (process.env.FAIL_PATHS || '').split(';').filter(Boolean);", + "const method = process.env.FAIL_METHOD;", + "const real = fs[method];", + "fs[method] = function (target, ...rest) {", + " const p = String(target).split('\\\\').join('/');", + " if (targets.some((t) => p.endsWith(t))) {", + " const err = new Error(`simulated ${process.env.FAIL_CODE} for ${p}`);", + " err.code = process.env.FAIL_CODE;", + " throw err;", + " }", + " return real.call(this, target, ...rest);", + "};", + ].join("\n") + "\n", + ); + // Node reads NODE_OPTIONS with backslashes as escapes, so the path uses slashes. + const preload = stub.split(path.sep).join("/"); + return { + NODE_OPTIONS: `${process.env.NODE_OPTIONS || ""} --require "${preload}"`.trim(), + FAIL_METHOD: method, + FAIL_CODE: code, + FAIL_PATHS: targets.join(";"), + }; +} + +const runFailing = (method, code, targets) => runScript(["--dir", image, "--lockfile", lockfile], failInListing(method, code, targets)); + +describe("compare-image-deps", () => { + it("passes when every package in the image is pinned for the workspace", () => { + const result = run([]); + expect(result.status).toBe(0); + expect(result.stdout).toContain("packages listed: 5"); + expect(result.stdout).toContain("5 of 5 packages are pinned by the lockfile"); + expect(result.stdout).not.toContain("WARNING"); + expect(result.stdout).toContain("result: PASS"); + }); + + it("follows peer dependencies and notes two versions of one package", () => { + const result = run([]); + // react@19.2.8 is reachable only as @scope/b's peer dependency. + expect(result.stdout).toMatch(/OK\s+react@19\.2\.8\s+at node_modules\/react/); + expect(result.stdout).toMatch(/OK\s+react@19\.2\.4\s+at packages\/web-dashboard\/node_modules\/react/); + expect(result.stdout).toContain("react is present at 2 versions: 19.2.4, 19.2.8"); + expect(result.stdout).toContain("::notice title=compare-image-deps::react is present at 2 versions"); + }); + + it("fails when the image carries a version that is in no lockfile entry", () => { + writeManifest("node_modules/@scope/b/node_modules/d", "d", "1.5.1"); + const result = run([]); + expect(result.status).toBe(1); + expect(result.stdout).toMatch(/NOT IN LOCKFILE\s+d@1\.5\.1/); + expect(result.stdout).toContain("d@1.5.1 at node_modules/@scope/b/node_modules/d is in no lockfile entry"); + expect(result.stdout).toContain("::error title=compare-image-deps::d@1.5.1"); + expect(result.stdout).toContain("result: FAIL (1)"); + }); + + it("lists every unpinned version, not only the first", () => { + writeManifest("node_modules/a", "a", "1.0.1"); + writeManifest("node_modules/@scope/b/node_modules/d", "d", "1.5.1"); + const result = run([]); + expect(result.status).toBe(1); + expect(result.stdout).toContain("a@1.0.1 at node_modules/a is in no lockfile entry"); + expect(result.stdout).toContain("d@1.5.1 at node_modules/@scope/b/node_modules/d is in no lockfile entry"); + expect(result.stdout).toContain("result: FAIL (2)"); + }); + + it("warns, without failing, about a version pinned only for another workspace or as a dev dependency", () => { + writeManifest("node_modules/left-pad", "left-pad", "1.0.0"); + writeManifest("node_modules/eslint", "eslint", "9.0.0"); + const result = run([]); + expect(result.status).toBe(0); + expect(result.stdout).toMatch(/OUTSIDE THE WORKSPACE TREE\s+left-pad@1\.0\.0\s+at node_modules\/left-pad\s+lockfile has it at node_modules\/left-pad/); + expect(result.stdout).toMatch(/OUTSIDE THE WORKSPACE TREE\s+eslint@9\.0\.0\s+at node_modules\/eslint/); + expect(result.stdout).toContain("::warning title=compare-image-deps::2 package(s)"); + expect(result.stdout).toContain("outside the packages/web-dashboard tree: eslint@9.0.0, left-pad@1.0.0"); + expect(result.stdout).toContain("result: PASS"); + }); + + it("fails when the workspace manifest carries another version than the lockfile", () => { + writeManifest(WORKSPACE, "web-dashboard", "0.24.0"); + const result = run([]); + expect(result.status).toBe(1); + expect(result.stdout).toContain("does not carry the version the lockfile records for packages/web-dashboard"); + expect(result.stdout).toContain("result: FAIL (1)"); + }); + + it("lists a linked workspace once, under its link path", () => { + const link = path.join(image, "node_modules", "web-dashboard"); + fs.symlinkSync(path.join(image, WORKSPACE), link, "junction"); + try { + const result = run([]); + expect(result.status).toBe(0); + expect(result.stdout).toContain("packages listed: 6"); + expect(result.stdout).toMatch(/OK\s+web-dashboard@0\.23\.1\s+at node_modules\/web-dashboard/); + // The nested package is found through the link and listed exactly once. + expect(result.stdout.match(/OK\s+react@19\.2\.4\s+at /g)).toHaveLength(1); + expect(result.stdout).toMatch(/OK\s+react@19\.2\.4\s+at node_modules\/web-dashboard\/node_modules\/react/); + } finally { + fs.rmSync(link, { force: true }); // the link itself, never what it points at + } + }); + + it("writes a JSON report with the status of every package", () => { + const report = path.join(dir, "report.json"); + writeManifest("node_modules/left-pad", "left-pad", "1.0.0"); + writeManifest("node_modules/eslint", "eslint", "9.9.9"); + const result = run(["--json", report]); + expect(result.status).toBe(1); + const parsed = JSON.parse(fs.readFileSync(report, "utf8")); + expect(parsed.source).toBe(image); + expect(parsed.workspace).toBe(WORKSPACE); + expect(parsed.pass).toBe(false); + expect(parsed.packages.find((p) => p.name === "react" && p.version === "19.2.8").status).toBe("ok"); + expect(parsed.packages.find((p) => p.name === "left-pad").status).toBe("outside-tree"); + expect(parsed.packages.find((p) => p.name === "eslint").status).toBe("unpinned"); + expect(parsed.notes).toContain("react is present at 2 versions: 19.2.4, 19.2.8"); + }); + + it("exits 2 when nothing is listed", () => { + for (const [rel] of TREE_PACKAGES) fs.rmSync(path.join(image, rel), { recursive: true, force: true }); + const result = run([]); + expect(result.status).toBe(2); + expect(result.stderr).toContain("no packages were listed"); + }); + + it("exits 2 for a listed entry without a version", () => { + writeManifest("node_modules/nameless", "nameless", undefined); + const result = run([]); + expect(result.status).toBe(2); + expect(result.stderr).toContain("malformed listing entry"); + }); + + it.each([ + ["truncated JSON", '{"name": "broken",'], + ["an empty file", ""], + ["a JSON array", "[]"], + ["a JSON string", '"not a manifest"'], + ["JSON null", "null"], + ])("exits 2 when a package.json under node_modules holds %s", (_label, content) => { + // A package the check cannot read must stop the check. It must not vanish. + const file = path.join(image, "node_modules", "broken", "package.json"); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, content); + const result = run([]); + expect(result.status).toBe(2); + expect(result.stderr).toContain("1 package.json file(s) under node_modules"); + expect(result.stderr).toContain("could not be read as a JSON object: node_modules/broken"); + expect(result.stdout).not.toContain("result:"); + }); + + it("names every unreadable package.json, in a scope and in a nested node_modules", () => { + const nested = path.join(image, "node_modules", "@scope", "b", "node_modules", "broken", "package.json"); + fs.mkdirSync(path.dirname(nested), { recursive: true }); + fs.writeFileSync(nested, "{"); + const scoped = path.join(image, "node_modules", "@broken", "pkg", "package.json"); + fs.mkdirSync(path.dirname(scoped), { recursive: true }); + fs.writeFileSync(scoped, "null"); + const result = run([]); + expect(result.status).toBe(2); + expect(result.stderr).toContain("2 package.json file(s)"); + expect(result.stderr).toContain("node_modules/@broken/pkg, node_modules/@scope/b/node_modules/broken"); + }); + + it("passes over directories under node_modules that hold no package.json", () => { + for (const rel of ["node_modules/.vite/deps.json", "node_modules/tmp/x.js", "node_modules/@scope/notes.txt"]) { + const file = path.join(image, rel); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, "x"); + } + const result = run([]); + expect(result.status).toBe(0); + expect(result.stdout).toContain("packages listed: 5"); + expect(result.stdout).toContain("result: PASS"); + }); + + it("fails when the workspace's own package.json cannot be read", () => { + fs.writeFileSync(path.join(image, WORKSPACE, "package.json"), "{"); + const result = run([]); + expect(result.status).toBe(1); + expect(result.stdout).toContain("does not carry the version the lockfile records for packages/web-dashboard"); + }); + + it("exits 2 when the lockfile cannot be read", () => { + const result = run(["--lockfile", path.join(dir, "missing.json")]); + expect(result.status).toBe(2); + expect(result.stderr).toContain("could not read lockfile"); + }); + + it("exits 2 for a lockfile without a packages map", () => { + writeLock(JSON.stringify({ name: "root", version: "1.0.0" })); + const result = run([]); + expect(result.status).toBe(2); + expect(result.stderr).toContain("has no packages map"); + }); + + it("exits 2 for a workspace that is not in the lockfile", () => { + const result = run(["--workspace", "packages/nowhere"]); + expect(result.status).toBe(2); + expect(result.stderr).toContain("workspace packages/nowhere is not in the lockfile"); + }); + + it("exits 2 on a usage error", () => { + expect(runScript([]).stderr).toContain("pass exactly one of --image or --dir "); + expect(runScript(["--dir", image, "--image", "test-image:1"]).stderr).toContain("pass exactly one of --image or --dir "); + expect(runScript(["--workspace"]).stderr).toContain("--workspace needs a value"); + expect(runScript(["--bogus"]).stderr).toContain("unknown argument: --bogus"); + expect(runScript(["--bogus"]).status).toBe(2); + expect(runScript(["--bogus"]).stderr).toContain("usage: node scripts/compare-image-deps.mjs"); + }); + + // The fake docker needs a shebang, which Windows does not honour without a shell. + const itOnPosix = process.platform === "win32" ? it.skip : it; + // Permission bits do not restrict the superuser. + const itOnPosixAsUser = process.platform === "win32" || process.getuid?.() === 0 ? it.skip : it; + + const writeFakeDocker = () => { + const fakeDocker = path.join(dir, "fake-docker"); + const callLog = path.join(dir, "docker-call.txt"); + // Records its arguments, then runs what follows the image name with node, + // which is exactly what the real `docker run --entrypoint node` does. + fs.writeFileSync(fakeDocker, '#!/bin/sh\nprintf \'%s\\n\' "$*" > "$FAKE_DOCKER_CALL_LOG"\nwhile [ "$1" != "test-image:1" ] && [ "$#" -gt 0 ]; do shift; done\n[ "$#" -gt 0 ] && shift\nexec node "$@"\n'); + fs.chmodSync(fakeDocker, 0o755); + return { DOCKER: fakeDocker, FAKE_DOCKER_CALL_LOG: callLog, callLog }; + }; + + describe("a directory that cannot be examined", () => { + // An empty answer for a directory that could not be listed would let the + // check pass over packages it never saw. + it.each([ + ["the node_modules directory inside a package", ["node_modules/@scope/b/node_modules"]], + ["a scope directory", ["node_modules/@scope"]], + ["the top-level node_modules directory", ["node_modules"]], + ["a directory on the way down from the root", ["packages"]], + ])("exits 2 instead of passing when %s cannot be listed", (_label, targets) => { + const result = runFailing("readdirSync", "EACCES", targets); + expect(result.status).toBe(2); + expect(result.stderr).toContain("1 directory inside"); + expect(result.stderr).toContain("could not be examined"); + expect(result.stderr).toContain(`${targets[0]} (EACCES)`); + expect(result.stdout).not.toContain("result:"); + }); + + it("names the error it met", () => { + const result = runFailing("readdirSync", "EIO", ["node_modules/@scope/b/node_modules"]); + expect(result.status).toBe(2); + expect(result.stderr).toContain("node_modules/@scope/b/node_modules (EIO)"); + }); + + it("exits 2 when a directory's own status cannot be read", () => { + const result = runFailing("statSync", "EACCES", ["node_modules/@scope/b/node_modules"]); + expect(result.status).toBe(2); + expect(result.stderr).toContain("could not be examined"); + expect(result.stderr).toContain("node_modules/@scope/b/node_modules (EACCES)"); + }); + + it("exits 2 when a directory's real path cannot be resolved", () => { + const result = runFailing("realpathSync", "ELOOP", ["node_modules/@scope"]); + expect(result.status).toBe(2); + expect(result.stderr).toContain("node_modules/@scope (ELOOP)"); + }); + + it("exits 2 when a package's package.json is there and cannot be read", () => { + const result = runFailing("readFileSync", "EACCES", ["node_modules/react/package.json"]); + expect(result.status).toBe(2); + expect(result.stderr).toContain("could not be examined"); + expect(result.stderr).toContain("node_modules/react/package.json (EACCES)"); + }); + + it("exits 2 when the workspace's own package.json cannot be read", () => { + const result = runFailing("readFileSync", "EACCES", ["packages/web-dashboard/package.json"]); + expect(result.status).toBe(2); + expect(result.stderr).toContain("packages/web-dashboard/package.json (EACCES)"); + }); + + itOnPosixAsUser("exits 2 when the process may not list a node_modules directory inside a package", () => { + const nested = path.join(image, "node_modules", "@scope", "b", "node_modules"); + fs.chmodSync(nested, 0o000); + try { + const result = run([]); + expect(result.status).toBe(2); + expect(result.stderr).toContain("node_modules/@scope/b/node_modules (EACCES)"); + } finally { + fs.chmodSync(nested, 0o755); + } + }); + + itOnPosixAsUser("exits 2 when the process may not read a package directory", () => { + const pkg = path.join(image, "node_modules", "react"); + fs.chmodSync(pkg, 0o000); + try { + const result = run([]); + expect(result.status).toBe(2); + expect(result.stderr).toContain("node_modules/react/package.json (EACCES)"); + } finally { + fs.chmodSync(pkg, 0o755); + } + }); + + itOnPosix("passes over a symbolic link under node_modules that points at nothing", () => { + const link = path.join(image, "node_modules", "dangling"); + fs.symlinkSync(path.join(image, "nowhere"), link, "dir"); + try { + const result = run([]); + expect(result.status).toBe(0); + expect(result.stdout).toContain("packages listed: 5"); + } finally { + fs.rmSync(link, { force: true }); + } + }); + }); + + itOnPosix("lists through docker run for --image", () => { + const fake = writeFakeDocker(); + const result = runScript(["--image", "test-image:1", "--lockfile", lockfile, "--root", image], fake); + const call = fs.readFileSync(fake.callLog, "utf8"); + expect(call).toMatch(/^run --rm --pull never --network none --entrypoint node test-image:1 -e /); + expect(call).toContain("function listInstalled"); + expect(result.status).toBe(0); + expect(result.stdout).toContain("5 of 5 packages are pinned by the lockfile"); + }); + + itOnPosix("exits 2 for --image when a directory inside the image cannot be listed", () => { + const fake = writeFakeDocker(); + const result = runScript(["--image", "test-image:1", "--lockfile", lockfile, "--root", image], { + ...fake, + ...failInListing("readdirSync", "EACCES", ["node_modules/@scope/b/node_modules"]), + }); + expect(result.status).toBe(2); + expect(result.stderr).toContain("1 directory inside image test-image:1 could not be examined"); + expect(result.stderr).toContain("node_modules/@scope/b/node_modules (EACCES)"); + }); +}); diff --git a/packages/web-dashboard/Dockerfile b/packages/web-dashboard/Dockerfile index 0cbb7a32..0d16e112 100644 --- a/packages/web-dashboard/Dockerfile +++ b/packages/web-dashboard/Dockerfile @@ -1,9 +1,38 @@ # GitWire Dashboard — Next.js frontend +# +# Build context: the REPOSITORY ROOT +# docker build -f packages/web-dashboard/Dockerfile . +# The dashboard is an npm workspace and its dependencies are locked in the root +# package-lock.json, which is outside this directory. The image is installed the +# way the app image is installed: with `npm ci` from that lockfile. An +# `npm install` from this directory alone resolves ranges on build day and +# ignores the lockfile, so the image stops matching what CI audits. CI compares +# the packages inside the built image with the lockfile +# (scripts/compare-image-deps.mjs). +# +# Dockerfile.dockerignore, next to this file, stands in for the root +# .dockerignore. It admits only what the COPY lines name. FROM node:20-alpine AS builder WORKDIR /app -COPY package.json ./ -RUN npm install -COPY . . + +# The dependency manifests and the dashboard source. The source is copied +# whole, because the checks below have to see exactly what reached the builder. +COPY package.json package-lock.json ./ +COPY packages/web-dashboard ./packages/web-dashboard + +# Dockerfile.dockerignore, next to this file, lets only the paths named above +# into the build context. These checks run before anything is installed, so +# they see nothing but what came from that context, and each one fails the +# build on its own when a builder ignores that file. The repository's +# .dockerignore drops the svg public assets this image serves, and it keeps +# neither a local checkout's installed dependencies nor its build output out. +RUN test ! -e packages/web-dashboard/node_modules +RUN test ! -e packages/web-dashboard/.next +RUN ls packages/web-dashboard/public/*.svg >/dev/null + +# Strict npm ci, scoped to the dashboard workspace — no fallback to npm install. +# Lifecycle scripts are skipped, as in the app image. +RUN npm ci --workspace=packages/web-dashboard --ignore-scripts # Build-info via env vars (v0.20.2) — Next.js bundles NEXT_PUBLIC_* at build time ARG GITWIRE_VERSION=0.23.1 @@ -19,7 +48,7 @@ LABEL org.opencontainers.image.created=$GITWIRE_BUILT_AT LABEL org.opencontainers.image.version=$GITWIRE_VERSION LABEL org.opencontainers.image.source="https://github.com/Octo-Lex/GitWire" -RUN npm run build +RUN npm run build --workspace=packages/web-dashboard FROM node:20-alpine AS runner WORKDIR /app @@ -35,10 +64,13 @@ LABEL org.opencontainers.image.created=$GITWIRE_BUILT_AT LABEL org.opencontainers.image.version=$GITWIRE_VERSION LABEL org.opencontainers.image.source="https://github.com/Octo-Lex/GitWire" -COPY --from=builder /app/.next/standalone ./ -COPY --from=builder /app/.next/static ./.next/static -COPY --from=builder /app/public ./public +# The standalone output mirrors the repository layout from the tracing root +# set in next.config.ts, so server.js sits under the workspace directory. +COPY --from=builder /app/packages/web-dashboard/.next/standalone ./ +COPY --from=builder /app/packages/web-dashboard/.next/static ./packages/web-dashboard/.next/static +COPY --from=builder /app/packages/web-dashboard/public ./packages/web-dashboard/public EXPOSE 3001 ENV PORT=3001 -CMD ["node", "server.js"] +# Run from the tracing root, which is what the generated server.js expects. +CMD ["node", "packages/web-dashboard/server.js"] diff --git a/packages/web-dashboard/Dockerfile.dockerignore b/packages/web-dashboard/Dockerfile.dockerignore new file mode 100644 index 00000000..8bcee141 --- /dev/null +++ b/packages/web-dashboard/Dockerfile.dockerignore @@ -0,0 +1,30 @@ +# Read INSTEAD of the repository's .dockerignore: a builder gives the ignore +# file named after the Dockerfile precedence over the context's own. +# +# Allowlist. Nothing enters the build context except what the COPY lines in +# this Dockerfile name: the root manifests and packages/web-dashboard. The +# dashboard is an npm workspace, so its dependencies are locked in the root +# package-lock.json and that is where the image installs them from. +# +# Build from the repository root: +# docker build -f packages/web-dashboard/Dockerfile . +# +# Each rule is decided by the last pattern that matches it, so the order is: +# exclude everything, let the two directories back in, then narrow again. +* +!package.json +!package-lock.json +!packages +packages/* +!packages/web-dashboard + +# Rebuilt inside the image, or local to one developer's checkout. +packages/web-dashboard/node_modules +packages/web-dashboard/.next +packages/web-dashboard/coverage +packages/web-dashboard/tsconfig.tsbuildinfo +packages/web-dashboard/.env* +packages/web-dashboard/.ouroboros + +# The image is a production build and does not run the test suite. +packages/web-dashboard/tests diff --git a/packages/web-dashboard/README.md b/packages/web-dashboard/README.md index 6579e69f..9fd20590 100644 --- a/packages/web-dashboard/README.md +++ b/packages/web-dashboard/README.md @@ -42,13 +42,16 @@ The API backend is expected at `http://localhost:3000`. Configure via `NEXT_PUBL ## Production -The dashboard builds as a Next.js standalone Docker image: +The dashboard builds as a Next.js standalone Docker image. It is an npm workspace, so its dependencies are locked in the repository root's `package-lock.json`, and the image is built from the repository root: ```bash -docker build -t gitwire-dashboard . +# From the repository root +docker build -t gitwire-dashboard -f packages/web-dashboard/Dockerfile . docker run -p 3001:3001 gitwire-dashboard ``` +The image installs its dependencies with `npm ci` from that lockfile, and CI compares the packages inside the built image with it (`scripts/compare-image-deps.mjs`). + See the monorepo `docker-compose.yml` for the full deployment configuration. ## Testing diff --git a/packages/web-dashboard/next.config.ts b/packages/web-dashboard/next.config.ts index 172c7dc5..ff0d9951 100644 --- a/packages/web-dashboard/next.config.ts +++ b/packages/web-dashboard/next.config.ts @@ -1,8 +1,15 @@ import type { NextConfig } from "next"; +import path from "node:path"; const nextConfig: NextConfig = { output: 'standalone', basePath: '/dashboard', + // The dashboard is an npm workspace: its dependencies are installed from the + // repository root's lockfile, above this directory. Next leaves out of the + // standalone output every file outside this root, so the root has to be the + // repository root. The output then mirrors the repository layout, and + // server.js lands at packages/web-dashboard/server.js inside it. + outputFileTracingRoot: path.join(__dirname, '../../'), }; export default nextConfig; diff --git a/scripts/compare-image-deps.mjs b/scripts/compare-image-deps.mjs new file mode 100644 index 00000000..c10e0b6d --- /dev/null +++ b/scripts/compare-image-deps.mjs @@ -0,0 +1,448 @@ +#!/usr/bin/env node +// scripts/compare-image-deps.mjs +// +// Compares the packages inside a built image with the lockfile the image was +// installed from. An `npm install` that ignores the lockfile produces an image +// whose versions match nothing in it; this check makes that a build failure. +// +// Exits 0 when every package in the image is pinned by the lockfile, 1 when +// it is not, and 2 when the check itself could not run (image missing, +// unreadable lockfile, nothing listed, a package.json inside the image that +// is not a JSON object, or a directory inside the image that cannot be +// examined). Neither of the last two is ever passed over in silence. A +// package the lockfile pins only for another workspace is +// reported as a warning and does not fail the check; the standalone output +// of Next.js carries such lone manifest files. +// +// The comparison is by package name and version as declared in each +// package.json. That the file contents match those versions is what `npm ci` +// guarantees when it verifies the lockfile's integrity hashes. +// +// Usage: +// node scripts/compare-image-deps.mjs --image [options] +// node scripts/compare-image-deps.mjs --dir [options] +// +// --image image to list. It is started once with node, without a +// network and without volumes, and only its package.json +// files are read. +// --dir list this directory on disk instead of starting a container. +// --workspace lockfile path of the workspace whose dependency tree is +// expected inside the image (default packages/web-dashboard). +// --lockfile lockfile to compare with (default package-lock.json). +// --root directory to list inside the image (default /app). +// --json also write the full report to this file. + +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import path from "node:path"; + +const EXIT_PASS = 0; +const EXIT_FAIL = 1; +const EXIT_ERROR = 2; + +const USAGE = `usage: node scripts/compare-image-deps.mjs (--image | --dir ) + [--workspace ] [--lockfile ] [--root ] [--json ]`; + +class UsageError extends Error {} + +function parseArgs(argv) { + const opts = { image: null, dir: null, workspace: "packages/web-dashboard", lockfile: "package-lock.json", root: "/app", json: null }; + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + const value = () => { + if (i + 1 >= argv.length) throw new UsageError(`${arg} needs a value`); + return argv[++i]; + }; + switch (arg) { + case "--image": + opts.image = value(); + break; + case "--dir": + opts.dir = value(); + break; + case "--workspace": + opts.workspace = value(); + break; + case "--lockfile": + opts.lockfile = value(); + break; + case "--root": + opts.root = value(); + break; + case "--json": + opts.json = value(); + break; + default: + throw new UsageError(`unknown argument: ${arg}`); + } + } + if (Boolean(opts.image) === Boolean(opts.dir)) throw new UsageError("pass exactly one of --image or --dir "); + return opts; +} + +// Runs inside the image, or in a child Node process for --dir, and is sent +// there as source text: it is evaluated as CommonJS, which is why it uses +// require(), and it must not refer to anything outside its own body. It lists +// every directory that holds a package.json under any node_modules directory +// below `root`, following symbolic links once. Nothing that cannot be examined +// is passed over in silence: a package.json that is there and is not a JSON +// object is reported in `unreadable`, and a directory that must be examined +// and cannot be stops the walk and is reported in `unexamined`. +function listInstalled(root, workspace) { + const fs = require("node:fs"); + const path = require("node:path"); + const packages = []; + const unreadable = []; + const unexamined = []; + const entered = new Set(); + const relative = (dir) => path.relative(root, dir).split(path.sep).join("/"); + const codeOf = (err) => (err && typeof err.code === "string" ? err.code : String(err)); + // Raised to stop the walk. Whatever could not be examined is recorded first. + const stopWalk = () => { + const signal = new Error("a directory could not be examined"); + signal.unexamined = true; + return signal; + }; + const manifestOf = (dir) => { + const file = path.join(dir, "package.json"); + let text; + try { + text = fs.readFileSync(file, "utf8"); + } catch (err) { + const code = codeOf(err); + // No package.json there, so not a package. Any other failure, such as a + // missing permission, means the directory cannot be examined. + if (code === "ENOENT" || code === "ENOTDIR") return { manifest: null, found: false }; + return { manifest: null, found: true, failure: code }; + } + try { + const manifest = JSON.parse(text); + if (!manifest || typeof manifest !== "object" || Array.isArray(manifest)) return { manifest: null, found: true }; + return { manifest, found: true }; + } catch { + return { manifest: null, found: true }; + } + }; + // Lists a directory that enter() has just confirmed. When it cannot be + // listed, the packages under it are unknown. That is never an empty answer: + // the walk stops and the check fails with the directory's name. + const list = (dir) => { + try { + return fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); + } catch (err) { + unexamined.push(`${relative(dir)} (${codeOf(err)})`); + throw stopWalk(); + } + }; + // A directory, possibly reached through a symbolic link, not visited before. + // Returns false for what is not a directory at all. Any other failure to + // examine it stops the walk. + const enter = (dir) => { + let stats; + try { + stats = fs.statSync(dir); + } catch (err) { + const code = codeOf(err); + if (code === "ENOENT" || code === "ENOTDIR") return false; + unexamined.push(`${relative(dir)} (${code})`); + throw stopWalk(); + } + if (!stats.isDirectory()) return false; + let real; + try { + real = fs.realpathSync(dir); + } catch (err) { + unexamined.push(`${relative(dir)} (${codeOf(err)})`); + throw stopWalk(); + } + if (entered.has(real)) return false; + entered.add(real); + return true; + }; + const scanNodeModules = (dir) => { + if (!enter(dir)) return; + for (const entry of list(dir)) { + if (entry.name.startsWith(".")) continue; + const child = path.join(dir, entry.name); + if (entry.name.startsWith("@")) { + if (!enter(child)) continue; + for (const scoped of list(child)) { + if (!scoped.name.startsWith(".")) record(path.join(child, scoped.name), `${entry.name}/${scoped.name}`); + } + } else { + record(child, entry.name); + } + } + }; + const record = (dir, fallbackName) => { + const { manifest, found, failure } = manifestOf(dir); + // A directory without a package.json is not a package. + if (!found) return; + if (failure !== undefined) { + unexamined.push(`${relative(dir)}/package.json (${failure})`); + throw stopWalk(); + } + if (!manifest) { + unreadable.push(relative(dir)); + return; + } + packages.push({ + path: relative(dir), + name: typeof manifest.name === "string" ? manifest.name : fallbackName, + version: typeof manifest.version === "string" ? manifest.version : null, + }); + scanNodeModules(path.join(dir, "node_modules")); + }; + const walk = (dir) => { + if (!enter(dir)) return; + for (const entry of list(dir)) { + if (entry.name.startsWith(".")) continue; + const child = path.join(dir, entry.name); + if (entry.name === "node_modules") scanNodeModules(child); + else walk(child); + } + }; + try { + walk(root); + } catch (err) { + // The walk stopped at a directory it could not examine, which is recorded. + if (!err || err.unexamined !== true) throw err; + } + packages.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)); + const appDir = path.join(root, workspace); + const { manifest: app, failure: appFailure } = manifestOf(appDir); + if (appFailure !== undefined) unexamined.push(`${relative(appDir)}/package.json (${appFailure})`); + const identity = (m) => (m ? { name: typeof m.name === "string" ? m.name : null, version: typeof m.version === "string" ? m.version : null } : null); + unreadable.sort(); + process.stdout.write(JSON.stringify({ packages, unreadable, unexamined, app: identity(app) })); +} + +function parseListing(stdout, source) { + let listing; + try { + listing = JSON.parse(stdout); + } catch { + throw new CheckError(`could not read the package listing from ${source}: output is not JSON`); + } + if (!listing || !Array.isArray(listing.packages) || !Array.isArray(listing.unreadable) || !Array.isArray(listing.unexamined)) { + throw new CheckError(`could not read the package listing from ${source}: it has no package list`); + } + if (listing.unexamined.length > 0) { + const count = listing.unexamined.length; + throw new CheckError(`${count} ${count === 1 ? "directory" : "directories"} inside ${source} could not be examined, so the packages under ${count === 1 ? "it" : "them"} are unknown: ${listing.unexamined.join(", ")}`); + } + if (listing.unreadable.length > 0) { + throw new CheckError(`${listing.unreadable.length} package.json file(s) under node_modules in ${source} could not be read as a JSON object: ${listing.unreadable.slice(0, 10).join(", ")}${listing.unreadable.length > 10 ? ", …" : ""}`); + } + if (listing.packages.length === 0) { + throw new CheckError(`no packages were listed from ${source}: an empty image cannot pass this check`); + } + for (const p of listing.packages) { + if (typeof p.path !== "string" || typeof p.name !== "string" || typeof p.version !== "string") { + throw new CheckError(`malformed listing entry from ${source}: ${JSON.stringify(p)}`); + } + } + return listing; +} + +function listImage(opts) { + const script = `(${listInstalled})(${JSON.stringify(opts.root)}, ${JSON.stringify(opts.workspace)})`; + const docker = process.env.DOCKER || "docker"; + try { + return parseListing( + execFileSync(docker, ["run", "--rm", "--pull", "never", "--network", "none", "--entrypoint", "node", opts.image, "-e", script], { + encoding: "utf8", + maxBuffer: 64 * 1024 * 1024, + stdio: ["ignore", "pipe", "pipe"], + }), + `image ${opts.image}`, + ); + } catch (err) { + if (err instanceof CheckError) throw err; + const detail = String(err.stderr || err.message || err).trim().split("\n").slice(-5).join(" | "); + throw new CheckError(`could not list image ${opts.image} with \`${docker} run\`: ${detail}`); + } +} + +function listDirectory(opts) { + const root = path.resolve(opts.dir); + if (!fs.existsSync(root)) throw new CheckError(`directory to list does not exist: ${opts.dir}`); + const script = `(${listInstalled})(${JSON.stringify(root)}, ${JSON.stringify(opts.workspace)})`; + try { + return parseListing(execFileSync(process.execPath, ["-e", script], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] }), `directory ${opts.dir}`); + } catch (err) { + if (err instanceof CheckError) throw err; + throw new CheckError(`could not list directory ${opts.dir}: ${String(err.stderr || err.message).trim().split("\n").slice(-5).join(" | ")}`); + } +} + +class CheckError extends Error {} + +// ── Lockfile side ───────────────────────────────────────────────────────── + +const lockName = (key) => key.slice(key.lastIndexOf("node_modules/") + "node_modules/".length); + +// Resolves a dependency the way Node does: from the dependency's own +// directory first, then from each directory above it. +function resolveFrom(packages, from, name) { + let dir = from; + for (;;) { + const key = `${dir ? `${dir}/` : ""}node_modules/${name}`; + const entry = packages[key]; + if (entry) { + // A link entry stands for the workspace that provides the package. + if (entry.link) return packages[entry.resolved] ? { key: entry.resolved, entry: packages[entry.resolved] } : null; + return { key, entry }; + } + if (!dir) return null; + if (dir.startsWith("node_modules/")) { + const cut = dir.lastIndexOf("/node_modules/"); + dir = cut === -1 ? "" : dir.slice(0, cut); + } else { + const cut = dir.lastIndexOf("/"); + dir = cut === -1 ? "" : dir.slice(0, cut); + } + } +} + +// Dependencies npm installs alongside a package: regular, optional, and peer +// dependencies that are not marked optional. +function dependencyNames(entry) { + const names = new Set(); + for (const section of ["optionalDependencies", "dependencies"]) for (const name of Object.keys(entry[section] || {})) names.add(name); + for (const name of Object.keys(entry.peerDependencies || {})) { + if (!entry.peerDependenciesMeta?.[name]?.optional) names.add(name); + } + return names; +} + +// Every lockfile entry the workspace's production tree can reach, keyed by +// lock path. The workspace itself counts as part of the tree: npm links it +// into node_modules under its name. +function productionTree(packages, workspace) { + const root = packages[workspace]; + if (!root) throw new CheckError(`workspace ${workspace} is not in the lockfile`); + const tree = new Map([[workspace, root]]); + const queue = [[workspace, root]]; + while (queue.length) { + const [from, entry] = queue.pop(); + for (const name of dependencyNames(entry)) { + const resolved = resolveFrom(packages, from, name); + if (!resolved || tree.has(resolved.key)) continue; + tree.set(resolved.key, resolved.entry); + queue.push([resolved.key, resolved.entry]); + } + } + return tree; +} + +function loadLockfile(lockfilePath) { + let lock; + try { + lock = JSON.parse(fs.readFileSync(lockfilePath, "utf8")); + } catch (err) { + throw new CheckError(`could not read lockfile ${lockfilePath}: ${err.message}`); + } + if (!lock || typeof lock.packages !== "object" || lock.packages === null) { + throw new CheckError(`lockfile ${lockfilePath} has no packages map (lockfileVersion 2 or 3 is required)`); + } + return lock.packages; +} + +// ── Comparison ──────────────────────────────────────────────────────────── + +function compare(listing, packages, workspace) { + const tree = productionTree(packages, workspace); + // Every lockfile entry by the name and version it provides. + const pinned = new Map(); + for (const [key, entry] of Object.entries(packages)) { + if (typeof entry.version !== "string") continue; + const name = typeof entry.name === "string" ? entry.name : lockName(key); + const id = `${name}@${entry.version}`; + if (!pinned.has(id)) pinned.set(id, []); + pinned.get(id).push(key); + } + const rows = listing.packages.map((p) => { + const id = `${p.name}@${p.version}`; + const keys = pinned.get(id) || []; + const inTree = keys.filter((k) => tree.has(k)); + const status = keys.length === 0 ? "unpinned" : inTree.length === 0 ? "outside-tree" : "ok"; + return { ...p, status, lockPaths: inTree.length > 0 ? inTree : keys }; + }); + // One package shipped at several versions is worth a look even when each + // copy is pinned: it usually means two copies of a library such as react. + const versions = new Map(); + for (const p of listing.packages) { + if (!versions.has(p.name)) versions.set(p.name, new Set()); + versions.get(p.name).add(p.version); + } + const notes = [...versions] + .filter(([, v]) => v.size > 1) + .map(([name, v]) => `${name} is present at ${v.size} versions: ${[...v].sort().join(", ")}`) + .sort(); + const expected = packages[workspace]; + const appOk = listing.app && expected ? listing.app.version === expected.version : false; + return { rows, notes, appOk, treeSize: tree.size }; +} + +const LABEL = { ok: "OK", "outside-tree": "OUTSIDE THE WORKSPACE TREE", unpinned: "NOT IN LOCKFILE" }; + +function report(result, listing, opts) { + const out = (line) => console.log(line); + const rows = result.rows; + const source = opts.image || opts.dir; + out(`packages listed: ${rows.length} (from ${source})`); + out(`lockfile ${opts.lockfile}: ${result.treeSize} packages in the production tree of ${opts.workspace}`); + out(""); + for (const r of rows) { + const detail = r.status === "outside-tree" ? ` lockfile has it at ${r.lockPaths.join(", ")}` : ""; + out(` ${LABEL[r.status].padEnd(24)} ${r.name}@${r.version} at ${r.path}${detail}`); + } + for (const note of result.notes) { + out(` ${"NOTE".padEnd(24)} ${note}`); + console.log(`::notice title=compare-image-deps::${note} (${source})`); + } + out(""); + const count = (status) => rows.filter((r) => r.status === status).length; + out(` ${"OK".padEnd(24)} ${count("ok")} of ${rows.length} packages are pinned by the lockfile and belong to the workspace tree`); + const outside = rows.filter((r) => r.status === "outside-tree"); + if (outside.length > 0) { + const text = `${outside.length} package(s) in ${source} are pinned by the lockfile but outside the ${opts.workspace} tree: ${outside.map((r) => `${r.name}@${r.version}`).join(", ")}`; + out(` ${"WARNING".padEnd(24)} ${text}`); + console.log(`::warning title=compare-image-deps::${text}`); + } + const failures = rows.filter((r) => r.status === "unpinned").map((r) => ({ text: `${r.name}@${r.version} at ${r.path} is in no lockfile entry` })); + if (!result.appOk) { + failures.push({ text: `the workspace manifest under ${opts.root}/${opts.workspace} does not carry the version the lockfile records for ${opts.workspace} (found ${JSON.stringify(listing.app)})` }); + } + for (const f of failures) { + out(` ${"FAILED".padEnd(24)} ${f.text}`); + console.log(`::error title=compare-image-deps::${f.text}`); + } + out(""); + out(failures.length === 0 ? "result: PASS" : `result: FAIL (${failures.length})`); + return failures.length === 0 ? EXIT_PASS : EXIT_FAIL; +} + +function main() { + let opts; + let result; + let listing; + try { + opts = parseArgs(process.argv.slice(2)); + listing = opts.image ? listImage(opts) : listDirectory(opts); + result = compare(listing, loadLockfile(opts.lockfile), opts.workspace); + } catch (err) { + if (err instanceof UsageError) console.error(USAGE); + if (!(err instanceof UsageError || err instanceof CheckError)) throw err; + console.error(`::error title=compare-image-deps::${err.message}`); + process.exit(EXIT_ERROR); + } + if (opts.json) { + const pass = result.rows.every((r) => r.status !== "unpinned") && result.appOk; + fs.writeFileSync(opts.json, JSON.stringify({ source: opts.image || opts.dir, lockfile: opts.lockfile, workspace: opts.workspace, packages: result.rows, notes: result.notes, workspaceManifestMatchesLockfile: result.appOk, pass }, null, 2) + "\n"); + } + process.exit(report(result, listing, opts)); +} + +main();