From 8def80fed44f99e3ab369cb4b3cb053d5287d416 Mon Sep 17 00:00:00 2001 From: Alajmah <55954113+Alajmah@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:39:47 +0300 Subject: [PATCH] fix(dashboard): build the image from the lockfile and compare it in CI The dashboard image ran `npm install` inside packages/web-dashboard with only that package.json in the build context. It resolved dependency ranges on build day and ignored package-lock.json. The image now in production holds three package versions that appear in no lockfile entry: @next/env 16.4.6, semver 6.3.2 and semver 7.8.6. Why @next/env differed: the lockfile entry for the dashboard's next 16.4.6 recorded the dependency ranges of 16.3.3, and the @next/env entry beside it was still 16.3.3. `npm ci` and `npm ls` accept that, because they compare the recorded ranges with the lockfile, not with the registry. package-lock.json: two entries repaired from npm's own resolution of the same versions. In the next 16.4.6 entry, @next/env and the eight @next/swc-* ranges go from 16.3.3 to 16.4.6 and sharp from ^0.35.3 to ^0.35.5. The @next/env entry goes from 16.3.3 to 16.4.6. The lockfile keeps its 1018 entries; nothing is added or removed. A full regeneration was not used: with the stale entries removed, npm moves the whole Next family from the dashboard's node_modules to the repository root (11 entries added, 12 removed). packages/web-dashboard/Dockerfile: the build context is the repository root and the dependencies are installed with `npm ci --workspace=packages/web-dashboard --ignore-scripts`. The source is copied before the install, and three checks that run in between fail the build when the ignore file is not honoured: the repository's .dockerignore drops the svg public assets and keeps a local checkout's node_modules and .next in. The standalone output is read from the workspace directory. packages/web-dashboard/Dockerfile.dockerignore: an allowlist holding only what the Dockerfile copies. It replaces the root .dockerignore, which excludes the svg files under public that the image serves. packages/web-dashboard/next.config.ts: outputFileTracingRoot is the repository root. Next drops every traced file outside that root, and the dashboard's dependencies are installed from the repository root's node_modules. scripts/compare-image-deps.mjs and its tests: list every package.json under node_modules in the built image and fail when a version is in no lockfile entry. A version the lockfile pins only for another workspace is reported as a warning. .github/workflows/ci.yml: the three dashboard builds use the root context. The image is compared with the lockfile in docker-build-dashboard, in release-tooling-validation, and in publish-release-images before the image is pushed. docker-compose.build.yml and the dashboard README describe the same build context. Signed-off-by: Alajmah <55954113+Alajmah@users.noreply.github.com> --- .github/workflows/ci.yml | 24 +- docker-compose.build.yml | 6 +- package-lock.json | 26 +- .../core/tests/compare-image-deps.test.js | 254 ++++++++++++ packages/web-dashboard/Dockerfile | 48 ++- .../web-dashboard/Dockerfile.dockerignore | 30 ++ packages/web-dashboard/README.md | 7 +- packages/web-dashboard/next.config.ts | 7 + scripts/compare-image-deps.mjs | 375 ++++++++++++++++++ 9 files changed, 749 insertions(+), 28 deletions(-) create mode 100644 packages/core/tests/compare-image-deps.test.js create mode 100644 packages/web-dashboard/Dockerfile.dockerignore create mode 100644 scripts/compare-image-deps.mjs 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..8ddfc98c --- /dev/null +++ b/packages/core/tests/compare-image-deps.test.js @@ -0,0 +1,254 @@ +// 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) +// - 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]); + +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("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; + + itOnPosix("lists through docker run for --image", () => { + 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); + const result = runScript(["--image", "test-image:1", "--lockfile", lockfile, "--root", image], { DOCKER: fakeDocker, FAKE_DOCKER_CALL_LOG: callLog }); + const call = fs.readFileSync(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"); + }); +}); 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..5bfe4b25 --- /dev/null +++ b/scripts/compare-image-deps.mjs @@ -0,0 +1,375 @@ +#!/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 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. +function listInstalled(root, workspace) { + const fs = require("node:fs"); + const path = require("node:path"); + const packages = []; + const entered = new Set(); + const manifestOf = (dir) => { + try { + return JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8")); + } catch { + return null; + } + }; + 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 { + return []; + } + }; + // A directory, possibly reached through a symbolic link, not visited before. + const enter = (dir) => { + try { + if (!fs.statSync(dir).isDirectory()) return false; + } catch { + return false; + } + const real = fs.realpathSync(dir); + 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 = manifestOf(dir); + if (!manifest || typeof manifest !== "object") return; + packages.push({ + path: path.relative(root, dir).split(path.sep).join("/"), + 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); + } + }; + walk(root); + packages.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)); + const app = manifestOf(path.join(root, workspace)); + const identity = (m) => (m && typeof m === "object" ? { name: typeof m.name === "string" ? m.name : null, version: typeof m.version === "string" ? m.version : null } : null); + process.stdout.write(JSON.stringify({ packages, 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) || 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();