diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5f99a9c1..8311a1da 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,17 +17,45 @@ env: GIT_CONFIG_COUNT: "1" GIT_CONFIG_KEY_0: init.defaultBranch GIT_CONFIG_VALUE_0: develop + EXPECTED_NPM_VERSION: "10.9.8" jobs: + lock-reproduction: + name: gate / ci / npm-lock-reproduction + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 + with: + node-version: "22.22.3" + cache: npm + - name: Verify exact npm lockfile generator + run: test "$(npm --version)" = "$EXPECTED_NPM_VERSION" + - name: Reproduce package lock without lifecycle execution + run: npm install --package-lock-only --ignore-scripts --no-audit --no-fund + - name: Preserve the exact generated lock as review evidence + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: npm-lock-reproduction-${{ github.event.pull_request.head.sha || github.sha }} + path: package-lock.json + if-no-files-found: error + retention-days: 3 + - name: Reject lockfile drift + run: git diff --exit-code -- package-lock.json + verify: name: ci / build-and-test + needs: lock-reproduction runs-on: ubuntu-latest steps: - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 with: - node-version: 22.22.3 + node-version: "22.22.3" cache: npm + - name: Verify exact npm lockfile generator + run: test "$(npm --version)" = "$EXPECTED_NPM_VERSION" - uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2 with: version: "0.8.6" @@ -51,13 +79,16 @@ jobs: rust-check: name: gate / ci / rust-check + needs: lock-reproduction runs-on: macos-15 steps: - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 with: - node-version: 22.22.3 + node-version: "22.22.3" cache: npm + - name: Verify exact npm lockfile generator + run: test "$(npm --version)" = "$EXPECTED_NPM_VERSION" - name: Install stable Rust toolchain run: rustup toolchain install stable --profile minimal - name: Install node dependencies diff --git a/CHANGELOG.md b/CHANGELOG.md index eea69689..c746043f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,14 @@ - Display the analyzed song tempo (BPM) as a badge in the rehearsal workspace. - 각 합주 역할(Role)별 개인 연습 진행도를 0~100% 범위로 기록 및 시각화할 수 있는 연습 진척도(`practiceProgress`) 트래커 기능 추가. UI 컨트롤(슬라이더 및 +/- 버튼)과 한/영 다국어 지원 포함. +### Changed + +- Pinned npm `10.9.8` as the lockfile generator and made primary CI reject a different npm version or any package-lock-only replay diff. + +### Fixed + +- Upgraded the local score PDF parser to `pdfjs-dist` 6.2.108, pinned Undici 7.29.0 across the workspace, and constrained PDF loading to copied in-memory bytes with a same-origin bundled worker and npm-generated lock provenance. + ## [0.1.3] - 2026-04-29 ### Fixed diff --git a/apps/desktop/package.json b/apps/desktop/package.json index e7685d6f..e09719b2 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -20,7 +20,7 @@ "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "lucide-react": "^1.24.0", - "pdfjs-dist": "6.1.200", + "pdfjs-dist": "6.2.108", "react": "^19.2.4", "react-dom": "^19.2.7", "sonner": "^2.0.7", diff --git a/apps/desktop/src/features/score/pdfjs.test.ts b/apps/desktop/src/features/score/pdfjs.test.ts new file mode 100644 index 00000000..b225830e --- /dev/null +++ b/apps/desktop/src/features/score/pdfjs.test.ts @@ -0,0 +1,42 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { getDocument, GlobalWorkerOptions } from "pdfjs-dist"; +import { configureScorePdfWorker, loadScorePdf } from "./pdfjs"; + +vi.mock("pdfjs-dist", () => ({ + getDocument: vi.fn(() => ({ promise: Promise.resolve(), destroy: vi.fn() })), + GlobalWorkerOptions: { workerSrc: "" } +})); + +vi.mock("pdfjs-dist/build/pdf.worker.min.mjs?url", () => ({ + default: "/assets/pdf.worker.min.mjs" +})); + +describe("score PDF.js boundary", () => { + beforeEach(() => { + vi.mocked(getDocument).mockClear(); + GlobalWorkerOptions.workerSrc = ""; + }); + + it("uses the locally bundled worker asset", () => { + configureScorePdfWorker(); + + expect(GlobalWorkerOptions.workerSrc).toBe("/assets/pdf.worker.min.mjs"); + + configureScorePdfWorker(); + expect(GlobalWorkerOptions.workerSrc).toBe("/assets/pdf.worker.min.mjs"); + }); + + it("copies validated bytes through the supported data-only API", () => { + const source = new Uint8Array([0x25, 0x50, 0x44, 0x46]); + + loadScorePdf(source); + + expect(getDocument).toHaveBeenCalledTimes(1); + const parameters = vi.mocked(getDocument).mock.calls[0]?.[0]; + expect(parameters).toBeTypeOf("object"); + expect(Object.keys(parameters as object)).toEqual(["data"]); + const copiedBytes = (parameters as { data: Uint8Array }).data; + expect(copiedBytes).toEqual(source); + expect(copiedBytes).not.toBe(source); + }); +}); diff --git a/apps/desktop/src/features/score/pdfjs.ts b/apps/desktop/src/features/score/pdfjs.ts index b62526c8..e0ce7692 100644 --- a/apps/desktop/src/features/score/pdfjs.ts +++ b/apps/desktop/src/features/score/pdfjs.ts @@ -22,6 +22,11 @@ export function configureScorePdfWorker(): void { * this helper never fetches arbitrary URLs. The bytes are copied before they * are handed to pdf.js because pdf.js transfers the underlying buffer to its * worker, which would otherwise detach the caller's copy and break retries. + * + * PDF.js 6.2.108 no longer exposes the legacy `isEvalSupported` initialization + * option. Security therefore relies on the patched parser release plus this + * narrow data-only, same-origin-worker boundary rather than an ignored and + * falsely reassuring unknown option. */ export function loadScorePdf(data: Uint8Array): PDFDocumentLoadingTask { configureScorePdfWorker(); diff --git a/docs/doctoring/high-security-pdf-http-baseline.md b/docs/doctoring/high-security-pdf-http-baseline.md new file mode 100644 index 00000000..d83a63eb --- /dev/null +++ b/docs/doctoring/high-security-pdf-http-baseline.md @@ -0,0 +1,81 @@ +# High-security PDF and HTTP dependency baseline + +## Decision + +BandScope treats the PDF parser and its transitive HTTP client as one security-release boundary: + +- `pdfjs-dist` is pinned exactly to `6.2.108`; +- `undici` is pinned exactly to `7.29.0` through the root npm override; and +- the complete npm workspace lock is generated only by the repository-pinned npm `10.9.8` workflow and imported unchanged from the workflow artifact. + +PDF.js `6.2.108` no longer exposes the legacy `isEvalSupported` member in its public `DocumentInitParameters` contract, and `getDocument` no longer reads that member. BandScope therefore does not cast or pass an unknown option that would be ignored while creating false assurance. The primary remediation is the patched parser release, reinforced by a narrow data-only call, copied caller-owned bytes, and a same-origin bundled worker. + +```mermaid +flowchart LR + A[Validated local PDF bytes] --> B[Copied Uint8Array] + B --> D[Data-only DocumentInitParameters] + D --> C[pdfjs-dist 6.2.108] + C --> W[Same-origin bundled worker] + W --> R[Canvas render] + J[jsdom development path] --> U[undici 7.29.0 override] + N[npm 10.9.8] --> L[Exact package-lock artifact] + L --> C + L --> U +``` + +## Threat boundary + +The score viewer accepts only bytes already copied into the app-owned workspace through the native PDF intake boundary. It does not accept a URL, credentials, custom request headers, or a remote worker. This prevents a PDF from selecting an attacker-controlled fetch origin or script asset. + +PDF bytes remain untrusted after the native magic-byte, size, and path checks. Parser vulnerabilities, malformed object graphs, embedded actions, and resource-exhaustion paths can still occur inside a syntactically valid PDF. The patched parser, exact dependency lock, copied data-only input, same-origin worker, and existing native intake limits therefore remain mandatory for locally selected files. + +Undici is currently a development dependency reached through jsdom, but development and CI parsers process attacker-controlled fixtures, generated HTML, and network-like request bodies. A dev-only label does not make header injection, shared-cache disclosure, retry desynchronization, or cookie-attribute injection acceptable in the trusted build boundary. + +## Lockfile provenance + +The security manifests are changed before the lock. The exact branch workflow then: + +1. verifies Node `22.22.3` and npm `10.9.8`; +2. runs `npm install --package-lock-only --ignore-scripts --no-audit --no-fund`; +3. uploads the generated `package-lock.json` under a head-SHA-bound artifact name; and +4. fails while the generated lock differs from the branch. + +The maintainer imports that generated artifact byte-for-byte and reruns the workflow. The second run must produce a clean diff. No tarball URL, SRI, dependency range, `peer` classification, or workspace record is edited by hand. + +The lock contract requires the exact public-registry tarball and SHA-512 SRI for both patched packages and requires every existing `node_modules/@esbuild/*` location to retain npm 10.9.8's `peer: true` classification. This distinguishes the intended security graph from unrelated Dependabot generator churn. + +## Verification + +The merge gate includes: + +- exact manifest and lock artifact tests; +- a direct PDF.js wrapper test proving copied bytes, the locally bundled worker, and an exact data-only initialization object; +- TypeScript compilation against the installed PDF.js `DocumentInitParameters` rather than an unsafe cast; +- valid and malformed local score-PDF component tests; +- desktop lint, strict typecheck, complete measured tests, and production build; +- Tauri/Rust checks and native PDF intake regressions; +- `npm audit --workspaces --audit-level=high` with no high finding; +- repository SAST, CodeQL, security scan, secret scan, SBOM, and dependency evidence; +- current-head central coverage and automated review; +- zero unresolved actionable threads and a qualifying independent non-author approval; and +- normal branch protection without administrative bypass. + +## Failure, rollback, and incident evidence + +On a failed lock replay or parser regression, preserve the exact head SHA, Node/npm versions, generated-lock artifact ID and digest, original and generated lock blob SHA, test output, audit report, and workflow run ID. Do not merge a partially updated graph. + +Rollback restores the previous desktop manifest, root override, complete lock, PDF loader, tests, and CHANGELOG entry together. Because the previous graph contains known high findings, rollback is an emergency availability action only and requires an explicit security exception, compensating controls, owner, expiration, and immediate replacement plan. + +## References + +GitHub. (2026). *PDF.js vulnerable to arbitrary JavaScript execution upon opening a malicious PDF* (GHSA-hq66-cqwq-w95j) [Security advisory]. https://github.com/advisories/GHSA-hq66-cqwq-w95j + +Mozilla. (2026). *Document initialization parameters in PDF.js 6.2.108* [Source code]. GitHub. https://github.com/mozilla/pdf.js/blob/v6.2.108/src/display/api.js + +Mozilla. (2026). *PDF.js 6.2.108* [Software release]. https://github.com/mozilla/pdf.js/releases/tag/v6.2.108 + +Node.js contributors. (2026). *Undici 7.29.0* [Software release]. https://github.com/nodejs/undici/releases/tag/v7.29.0 + +npm, Inc. (2026). *npm ci*. npm Docs. https://docs.npmjs.com/cli/v11/commands/npm-ci/ + +npm, Inc. (2026). *package-lock.json*. npm Docs. https://docs.npmjs.com/cli/v11/configuring-npm/package-lock-json/ diff --git a/docs/doctoring/npm-lockfile-generator-provenance.md b/docs/doctoring/npm-lockfile-generator-provenance.md new file mode 100644 index 00000000..1d50f2a5 --- /dev/null +++ b/docs/doctoring/npm-lockfile-generator-provenance.md @@ -0,0 +1,77 @@ +# npm lockfile generator provenance + +## Decision + +BandScope generates and verifies its root npm workspace lock with exactly npm `10.9.8`. The root manifest records that decision through: + +- `packageManager: npm@10.9.8` as package-manager selection metadata; and +- `devEngines.packageManager` with `onFail: error` as npm's source-tree command gate. + +The npm version is intentionally not repeated under `engines`. npm serializes `engines` into the root lock package, so adding an npm-only source-tool constraint there creates lock metadata churn unrelated to dependency resolution. `devEngines`, the explicit CI assertion, and the replay gate enforce the generator while the published `engines.node` range remains the runtime compatibility contract. + +The primary GitHub Actions workflow uses Node `22.22.3`, verifies the bundled npm version before any installation, runs `npm ci`, then runs a package-lock-only regeneration with scripts, audit, and funding output disabled. Any `package-lock.json` diff fails the exact head. + +The Node runtime support decision remains separate. This change does not raise the public `>=22.13 <23` Node range; a coordinated Node-floor migration is tracked independently. + +## Why the generator is part of the lock identity + +npm documents `package-lock.json` as the location-keyed description of the exact dependency tree. Lockfile version 3 is intended for npm 9 and newer. npm also notes that different package-manager versions may use different installation algorithms and metadata representations. A committed lockfile therefore is not fully reproducible unless the generator version and install-shaping flags are versioned with it. + +`npm ci` is the immutable consumption path: it requires a lockfile, rejects manifest/lock dependency disagreement, removes an existing `node_modules`, and does not write the manifest or lock. It does not prove that a future dependency update will regenerate byte-identical metadata. The additional package-lock-only replay closes that gap. + +```mermaid +flowchart LR + M[package.json ranges and workspaces] --> G[npm 10.9.8] + C[project npm configuration] --> G + G --> L[package-lock.json v3] + L --> I[npm ci clean install] + I --> R[npm 10.9.8 package-lock-only replay] + R --> D{lock diff?} + D -->|no| A[reproducible exact-head evidence] + D -->|yes| F[fail closed] +``` + +## Security and operational boundary + +- Dependency PRs may change only manifest ranges and the lock records produced by npm `10.9.8`. +- Reviewers must reject unrelated lock metadata that cannot be reproduced by the pinned generator. +- No lock record may be added or removed by hand to satisfy a validator. +- Install-shaping flags that change the tree, such as `legacy-peer-deps` or `install-links`, must be committed in project configuration and used identically by `npm ci` and regeneration. +- Dependency lifecycle scripts remain disabled for the reproduction pass. The normal clean install retains the repository's reviewed execution behavior. +- The exact npm version check occurs before `npm ci`; a different bundled or globally installed npm cannot generate acceptance evidence. +- The lockfile remains the sole npm workspace lock. Nested workspace locks are prohibited. + +`packageManager` alone is not the enforcement boundary for npm because Corepack's npm shim is not enabled by default in Node distributions. Enforcement is provided by npm `devEngines`, the explicit CI version assertion, and the lock replay. + +## Verification + +`services/analysis-engine/tests/test_npm_toolchain_contract.py` verifies the manifest metadata, separation of runtime and generator constraints, exact CI Node/npm identity, replay command and flags, clean lock diff, and lockfile version 3. Repository CI then executes the replay using the hosted toolchain. + +A dependency update is mergeable only after: + +1. npm `10.9.8` produces the checked-in lock from the updated manifest; +2. a second package-lock-only replay is byte-clean; +3. `npm ci`, lint, strict typecheck, measured tests, production build, Rust/Tauri checks, and security/supply-chain gates succeed on the same head; and +4. current-head review, unresolved-thread, independent-approval, and branch-protection requirements succeed without bypass. + +## Incident response and rollback + +When replay changes the lock unexpectedly: + +1. preserve the exact head SHA, npm and Node versions, command flags, original lock blob SHA, regenerated lock, and CI run ID; +2. determine whether the manifest changed, npm changed, project configuration changed, or the protected lock was generated by a different toolchain; +3. never accept a partial or hand-edited lock; +4. regenerate from a clean checkout using the reviewed npm version and run the replay twice; +5. if rollback is necessary, restore the prior manifest and complete lock together, then rerun the entire exact-head gate. + +## References + +npm, Inc. (2026). *npm ci*. npm Docs. https://docs.npmjs.com/cli/v11/commands/npm-ci/ + +npm, Inc. (2026). *npm install*. npm Docs. https://docs.npmjs.com/cli/v10/commands/npm-install/ + +npm, Inc. (2026). *package-lock.json*. npm Docs. https://docs.npmjs.com/cli/v11/configuring-npm/package-lock-json/ + +npm, Inc. (2026). *package.json*. npm Docs. https://docs.npmjs.com/cli/configuring-npm/package-json/ + +Node.js contributors. (2026). *Corepack* [Software documentation]. GitHub. https://github.com/nodejs/corepack diff --git a/package-lock.json b/package-lock.json index cf1c991c..792ca517 100644 --- a/package-lock.json +++ b/package-lock.json @@ -15,7 +15,8 @@ "@eslint/js": "^10.0.1", "eslint-plugin-jsdoc": "^63.0.13", "react": "^19.2.4", - "react-dom": "^19.2.7" + "react-dom": "^19.2.7", + "undici": "7.29.0" }, "engines": { "node": ">=22.13 <23" @@ -32,7 +33,7 @@ "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "lucide-react": "^1.24.0", - "pdfjs-dist": "6.1.200", + "pdfjs-dist": "6.2.108", "react": "^19.2.4", "react-dom": "^19.2.7", "sonner": "^2.0.7", @@ -212,6 +213,18 @@ "url": "https://opencollective.com/vitest" } }, + "apps/desktop/node_modules/pdfjs-dist": { + "version": "6.2.108", + "resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-6.2.108.tgz", + "integrity": "sha512-YxFb+SQcodN2rnX9Tn3dHYlqfb7NjlzzfONPpJd+AKoKtUjEdevTfbC07d5TcczzOK6261auRkP/M8OBHs9vFQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=22.13.0 || >=24" + }, + "optionalDependencies": { + "@napi-rs/canvas": "^1.0.0" + } + }, "apps/desktop/node_modules/vitest": { "version": "4.1.10", "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.10.tgz", @@ -6367,18 +6380,6 @@ "node": ">= 14.16" } }, - "node_modules/pdfjs-dist": { - "version": "6.1.200", - "resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-6.1.200.tgz", - "integrity": "sha512-o8MolyzirkkLrcdsae/HEOiIcXWI7DS5zGpvqW8xTC2YUsW30rltFw2bDGvw/fskUdEMrQm2br68jzDS5BH2vw==", - "license": "Apache-2.0", - "engines": { - "node": ">=22.13.0 || >=24" - }, - "optionalDependencies": { - "@napi-rs/canvas": "^1.0.0" - } - }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -7179,9 +7180,9 @@ } }, "node_modules/undici": { - "version": "7.28.0", - "resolved": "https://registry.npmjs.org/undici/-/undici-7.28.0.tgz", - "integrity": "sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.0.tgz", + "integrity": "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==", "dev": true, "license": "MIT", "engines": { diff --git a/package.json b/package.json index a71236ed..2c3a4e94 100644 --- a/package.json +++ b/package.json @@ -3,9 +3,17 @@ "private": true, "version": "0.1.3", "type": "module", + "packageManager": "npm@10.9.8", "engines": { "node": ">=22.13 <23" }, + "devEngines": { + "packageManager": { + "name": "npm", + "version": "10.9.8", + "onFail": "error" + } + }, "workspaces": [ "apps/*", "packages/*" @@ -33,10 +41,12 @@ "@eslint/js": "^10.0.1", "eslint-plugin-jsdoc": "^63.0.13", "react": "^19.2.4", - "react-dom": "^19.2.7" + "react-dom": "^19.2.7", + "undici": "7.29.0" }, "overrides": { "brace-expansion": "5.0.9", - "postcss": "8.5.25" + "postcss": "8.5.25", + "undici": "$undici" } } diff --git a/services/analysis-engine/tests/test_high_security_dependency_baseline.py b/services/analysis-engine/tests/test_high_security_dependency_baseline.py new file mode 100644 index 00000000..7be5df94 --- /dev/null +++ b/services/analysis-engine/tests/test_high_security_dependency_baseline.py @@ -0,0 +1,78 @@ +"""Contracts for the coordinated PDF.js and Undici security baseline.""" + +from __future__ import annotations + +import json +from pathlib import Path + +_REPOSITORY_ROOT = Path(__file__).resolve().parents[3] +_PDFJS_VERSION = "6.2.108" +_UNDICI_VERSION = "7.29.0" +_PDFJS_INTEGRITY = ( + "sha512-YxFb+SQcodN2rnX9Tn3dHYlqfb7NjlzzfONPpJd+AKoKtUjEdevTfbC07d5Tcczz" + "OK6261auRkP/M8OBHs9vFQ==" +) +_UNDICI_INTEGRITY = ( + "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9" + "rWmsreUyf5lwyao+7GNNVw==" +) + + +def _read_json(relative_path: str) -> dict[str, object]: + """Return one repository JSON document as a mapping.""" + document = json.loads((_REPOSITORY_ROOT / relative_path).read_text(encoding="utf-8")) + assert isinstance(document, dict) + return document + + +def test_manifests_pin_the_security_floors_without_semver_drift() -> None: + """Keep the vulnerable transitive client and PDF parser on exact versions.""" + root_manifest = _read_json("package.json") + desktop_manifest = _read_json("apps/desktop/package.json") + + assert root_manifest["devDependencies"]["undici"] == _UNDICI_VERSION # type: ignore[index] + assert root_manifest["overrides"]["undici"] == "$undici" # type: ignore[index] + assert desktop_manifest["dependencies"]["pdfjs-dist"] == _PDFJS_VERSION # type: ignore[index] + + +def test_lock_records_match_exact_registry_artifacts_and_preserve_peer_metadata() -> None: + """Require the pinned generator's exact graph without unrelated esbuild churn.""" + lock_document = _read_json("package-lock.json") + packages = lock_document["packages"] + assert isinstance(packages, dict) + + root_package = packages[""] + assert isinstance(root_package, dict) + assert root_package["devDependencies"]["undici"] == _UNDICI_VERSION # type: ignore[index] + + desktop = packages["apps/desktop"] + assert isinstance(desktop, dict) + assert desktop["dependencies"]["pdfjs-dist"] == _PDFJS_VERSION # type: ignore[index] + + pdfjs = packages["apps/desktop/node_modules/pdfjs-dist"] + assert isinstance(pdfjs, dict) + assert pdfjs["version"] == _PDFJS_VERSION + assert pdfjs["resolved"] == ( + "https://registry.npmjs.org/pdfjs-dist/-/" + f"pdfjs-dist-{_PDFJS_VERSION}.tgz" + ) + assert pdfjs["integrity"] == _PDFJS_INTEGRITY + assert pdfjs["license"] == "Apache-2.0" + assert pdfjs["engines"] == {"node": ">=22.13.0 || >=24"} + + undici = packages["node_modules/undici"] + assert isinstance(undici, dict) + assert undici["version"] == _UNDICI_VERSION + assert undici["resolved"] == "https://registry.npmjs.org/undici/-/undici-7.29.0.tgz" + assert undici["integrity"] == _UNDICI_INTEGRITY + + esbuild_locations = { + path: metadata + for path, metadata in packages.items() + if isinstance(path, str) and path.startswith("node_modules/@esbuild/") + } + assert esbuild_locations + assert all( + isinstance(metadata, dict) and metadata.get("peer") is True + for metadata in esbuild_locations.values() + ) diff --git a/services/analysis-engine/tests/test_npm_toolchain_contract.py b/services/analysis-engine/tests/test_npm_toolchain_contract.py new file mode 100644 index 00000000..5e9a65db --- /dev/null +++ b/services/analysis-engine/tests/test_npm_toolchain_contract.py @@ -0,0 +1,62 @@ +"""Contracts for deterministic npm lockfile generation and CI provenance.""" + +from __future__ import annotations + +import json +from pathlib import Path + +_REPOSITORY_ROOT = Path(__file__).resolve().parents[3] +_EXPECTED_NPM_VERSION = "10.9.8" +_EXPECTED_NODE_VERSION = "22.22.3" + + +def _root_manifest() -> dict[str, object]: + """Return the checked-in root package manifest as a JSON object.""" + manifest = json.loads((_REPOSITORY_ROOT / "package.json").read_text(encoding="utf-8")) + assert isinstance(manifest, dict) + return manifest + + +def test_root_manifest_pins_the_lockfile_generator_and_fails_on_drift() -> None: + """Require npm and source-tree commands to reject a different generator.""" + manifest = _root_manifest() + + assert manifest["packageManager"] == f"npm@{_EXPECTED_NPM_VERSION}" + assert manifest["engines"] == {"node": ">=22.13 <23"} + assert manifest["devEngines"] == { + "packageManager": { + "name": "npm", + "version": _EXPECTED_NPM_VERSION, + "onFail": "error", + } + } + + +def test_primary_ci_proves_exact_npm_before_install_and_lock_reproduction() -> None: + """Keep the clean installer and lock reproduction on one explicit toolchain.""" + workflow = (_REPOSITORY_ROOT / ".github" / "workflows" / "ci.yml").read_text(encoding="utf-8") + + assert f'node-version: "{_EXPECTED_NODE_VERSION}"' in workflow + assert f'EXPECTED_NPM_VERSION: "{_EXPECTED_NPM_VERSION}"' in workflow + assert 'test "$(npm --version)" = "$EXPECTED_NPM_VERSION"' in workflow + assert "lock-reproduction:" in workflow + assert "needs: lock-reproduction" in workflow + assert "npm install --package-lock-only" in workflow + assert "--ignore-scripts" in workflow + assert "--no-audit" in workflow + assert "--no-fund" in workflow + assert "actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a" in workflow + assert ( + "npm-lock-reproduction-${{ github.event.pull_request.head.sha || github.sha }}" + in workflow + ) + assert "if-no-files-found: error" in workflow + assert "git diff --exit-code -- package-lock.json" in workflow + + +def test_root_lock_uses_the_supported_location_keyed_format() -> None: + """Require the npm-v9-and-newer lock format used by the pinned generator.""" + lock_document = json.loads((_REPOSITORY_ROOT / "package-lock.json").read_text(encoding="utf-8")) + + assert lock_document["lockfileVersion"] == 3 + assert isinstance(lock_document["packages"], dict)