From 7006d90c426e6d5fef8ac0813badff9a8f25b67c Mon Sep 17 00:00:00 2001 From: egdev6 Date: Sat, 21 Nov 2026 15:28:39 +0100 Subject: [PATCH 01/13] build(lint): add Biome and Lefthook pre-push with CI gate Biome lints and formats src/, scripts/ and vite.config.ts (vendored src/ds/egdev excluded). Lefthook runs biome ci and cargo fmt --check on pre-push; ci.yml and linux-pr-ci.yml run biome ci after npm ci. --- .github/workflows/ci.yml | 3 + .github/workflows/linux-pr-ci.yml | 3 + CONTRIBUTING.md | 20 ++ biome.json | 33 +++ lefthook.yml | 10 + odd/tasks/biome-lefthook.md | 24 ++ package-lock.json | 391 ++++++++++++++++++++++++++++++ package.json | 7 + 8 files changed, 491 insertions(+) create mode 100644 biome.json create mode 100644 lefthook.yml create mode 100644 odd/tasks/biome-lefthook.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 576a3917..7d96b3a5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -42,6 +42,9 @@ jobs: - name: Install locked frontend dependencies run: npm ci + - name: Biome lint and format + run: npx biome ci + - name: Frontend and script tests run: npm test diff --git a/.github/workflows/linux-pr-ci.yml b/.github/workflows/linux-pr-ci.yml index 291f4ff9..54d13890 100644 --- a/.github/workflows/linux-pr-ci.yml +++ b/.github/workflows/linux-pr-ci.yml @@ -69,6 +69,9 @@ jobs: - name: Install locked frontend dependencies run: npm ci + - name: Biome lint and format + run: npx biome ci + - name: Frontend and script tests run: npm test diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fdb0e5aa..33403c5e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -34,10 +34,20 @@ These are the scripts declared in `package.json`: | `npm run typecheck` | TypeScript checks | | `npm test` | Vitest tests plus the release scripts' Node tests | | `cd src-tauri; cargo test` | Rust tests | +| `npm run check` | Biome lint + format check (CI runs `npx biome ci`) | +| `npm run check:fix` | Apply Biome safe fixes and formatting | | `node scripts/i18n-inventory.mjs` | Regenerate `docs/i18n-inventory.md` (CI runs it with `--check`); `--sites` prints `path:line \| text` rows | | `npm run app:dev` | Run the desktop app with hot reload | | `npm run app:build` | Build a local (unsigned) installer | +### Lint and formatting (Biome + Lefthook) + +TypeScript, JavaScript and CSS under `src/`, `scripts/` and `vite.config.ts` are linted and formatted by [Biome](https://biomejs.dev) (`biome.json`). The vendored design-system bundle `src/ds/egdev/` is excluded because it is a copy that must not be edited by hand. CI runs `npx biome ci` in `ci.yml` and `linux-pr-ci.yml`; any lint error or unformatted file fails the check, warnings do not. + +`npm install` installs a [Lefthook](https://lefthook.dev) `pre-push` hook (`lefthook.yml`) that runs `npx biome ci` and the Rust format check before every push. If it fails, run `npm run check:fix` (and `cargo fmt` for Rust), commit, and push again. Skipping it with `--no-verify` only moves the failure to CI. + +The repository-wide Biome formatting landed as a formatting-only commit listed in `.git-blame-ignore-revs`; run `git config blame.ignoreRevsFile .git-blame-ignore-revs` once so `git blame` skips it. If you had a branch open before that commit, rebase it on `main` and run `npm run check:fix` to resolve formatting conflicts. + ### Rust formatting Rust formatting is checked by CI (`cargo fmt --manifest-path src-tauri/Cargo.toml --all -- --check` in `ci.yml` and `linux-pr-ci.yml`). Locally: `cd src-tauri && cargo fmt --all`, then commit the result as a formatting-only commit such as `chore(style): cargo fmt`, so functional changes stay reviewable. @@ -184,9 +194,19 @@ Estos son los scripts declarados en `package.json`: | `npm run typecheck` | Comprobar TypeScript | | `npm test` | Tests de Vitest y tests Node de los scripts de release | | `cd src-tauri; cargo test` | Tests de Rust | +| `npm run check` | Lint y comprobación de formato con Biome (CI ejecuta `npx biome ci`) | +| `npm run check:fix` | Aplicar los arreglos seguros y el formato de Biome | | `npm run app:dev` | Ejecutar la app de escritorio con hot reload | | `npm run app:build` | Compilar un instalador local (sin firma) | +### Lint y formato (Biome + Lefthook) + +El TypeScript, JavaScript y CSS de `src/`, `scripts/` y `vite.config.ts` se analizan y formatean con [Biome](https://biomejs.dev) (`biome.json`). Se excluye el bundle del design system `src/ds/egdev/`, porque es una copia que no se edita a mano. CI ejecuta `npx biome ci` en `ci.yml` y `linux-pr-ci.yml`: cualquier error de lint o archivo sin formatear hace fallar el check; los warnings no. + +`npm install` instala un hook `pre-push` de [Lefthook](https://lefthook.dev) (`lefthook.yml`) que ejecuta `npx biome ci` y la comprobación de formato de Rust antes de cada push. Si falla, ejecutá `npm run check:fix` (y `cargo fmt` para Rust), commiteá y volvé a hacer push. Saltarlo con `--no-verify` solo traslada el fallo a CI. + +El formato de Biome de todo el repositorio entró como commit solo-formato, listado en `.git-blame-ignore-revs`; ejecutá una vez `git config blame.ignoreRevsFile .git-blame-ignore-revs` para que `git blame` lo ignore. Si tenías una rama abierta antes de ese commit, rebaseala sobre `main` y ejecutá `npm run check:fix` para resolver los conflictos de formato. + ### Formato de Rust El formato de Rust se controla en CI (`cargo fmt --manifest-path src-tauri/Cargo.toml --all -- --check` en `ci.yml` y `linux-pr-ci.yml`). Localmente: `cd src-tauri && cargo fmt --all` y commiteá el resultado como commit solo-formato, por ejemplo `chore(style): cargo fmt`, para que los cambios funcionales sigan siendo revisables. diff --git a/biome.json b/biome.json new file mode 100644 index 00000000..9469bc0c --- /dev/null +++ b/biome.json @@ -0,0 +1,33 @@ +{ + "$schema": "./node_modules/@biomejs/biome/configuration_schema.json", + "vcs": { + "enabled": true, + "clientKind": "git", + "useIgnoreFile": true, + "defaultBranch": "main" + }, + "files": { + "includes": ["src/**", "scripts/**", "vite.config.ts", "!src/ds/egdev"] + }, + "formatter": { + "enabled": true, + "indentStyle": "space", + "indentWidth": 2, + "lineWidth": 160 + }, + "javascript": { + "formatter": { + "quoteStyle": "single", + "jsxQuoteStyle": "double" + } + }, + "assist": { + "enabled": false + }, + "linter": { + "enabled": true, + "rules": { + "recommended": true + } + } +} diff --git a/lefthook.yml b/lefthook.yml new file mode 100644 index 00000000..e327b094 --- /dev/null +++ b/lefthook.yml @@ -0,0 +1,10 @@ +# Git hooks managed by Lefthook (https://lefthook.dev). +# Installed automatically by `npm install` (the `prepare` script runs `lefthook install`). +# CI runs the same checks, so skipping the hook with `--no-verify` only delays the failure. +pre-push: + parallel: true + jobs: + - name: biome + run: npx biome ci + - name: cargo-fmt + run: cargo fmt --manifest-path src-tauri/Cargo.toml --all -- --check diff --git a/odd/tasks/biome-lefthook.md b/odd/tasks/biome-lefthook.md new file mode 100644 index 00000000..fa6876a7 --- /dev/null +++ b/odd/tasks/biome-lefthook.md @@ -0,0 +1,24 @@ +# Biome lint/format + Lefthook pre-push + CI gate +Branch: `chore/biome-lefthook`; base: `72f443d`. Delivery: work-unit commits on the branch; push, PR, merge and the Discord announcement after merge remain user decisions. +Risk: item 5 (dev dependencies, git hooks and CI gates); item 6 for lint fixes that touch runtime code (each fix covered by existing tests or justified). + +## Specs + +- S1: "tenemos metido biome y lefthook para hacer lint en pre-push?" → answer was no; proposal accepted with "si": "¿Querés que lo agregue (Biome con `lint`/`format`, Lefthook en pre-push y el mismo chequeo en CI)?" +- S2: Scope chosen by the user: "lint + format + arreglo de errores + aviso en dicord de que lo hemos añadido avisando de que tienen que sincronizar" +- S3: Baseline measured (Biome 2.6.8, defaults): 106 lint errors, 280 warnings, 32 infos over `src/` and `scripts/`. Formatter with single quotes and lineWidth 160 rewrites 178 files when the vendored `src/ds/egdev/` ("No editar a mano") is excluded. + +## Tasks + +- T1 | S1-S2 | parent inline | pending | `biome.json`, `lefthook.yml` (pre-push: `biome ci` + `cargo fmt --check`), npm scripts (`lint`, `format`, `check`, `prepare`), CI step in `ci.yml` and `linux-pr-ci.yml`, CONTRIBUTING EN/ES. Commit: - +- T2 | S2-S3 | parent inline | pending | Format-only commit with `biome format --write`, plus `.git-blame-ignore-revs`. Commit: - +- T3 | S2-S3 | parent inline | pending | Fix all lint errors so `biome ci` passes; warnings stay visible. Commit: - +- T4 | S1-S2 | parent inline | pending | Verify: `npm test`, `npm run build`, `npx biome ci`, `cargo fmt --check`, lefthook pre-push dry run. Commit: - +- T5 | S2 | parent | pending | Discord announcement draft (sync instructions: `npm install`, hooks, rebase over the format commit); publish after merge to `main`. Commit: n/a + +## Log + +L1 — User verbatim: "tenemos metido biome y lefthook para hacer lint en pre-push?" +L2 — User verbatim: "si" (accepting: add Biome lint/format, Lefthook pre-push and the same check in CI). +L3 — User verbatim scope answer: "lint + format + arreglo de errores + aviso en dicord de que lo hemos añadido avisando de que tienen que sincronizar" +L4 — Decision: exclude vendored `src/ds/egdev/` from Biome (header says it is a copied bundle, not to be edited by hand). lineWidth 160 chosen because it produced the smallest diff among 100/120/140/160 for the existing code. diff --git a/package-lock.json b/package-lock.json index 9421ca5d..3276e9c9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -20,10 +20,12 @@ "react-dom": "^19.1.0" }, "devDependencies": { + "@biomejs/biome": "2.6.8", "@tauri-apps/cli": "^2.8.0", "@types/react": "^19.1.0", "@types/react-dom": "^19.1.0", "@vitejs/plugin-react": "^5.0.0", + "lefthook": "2.2.2", "typescript": "^5.9.0", "vite": "^7.1.0", "vitest": "4.1.11" @@ -311,6 +313,217 @@ "node": ">=6.9.0" } }, + "node_modules/@biomejs/biome": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/biome/-/biome-2.6.8.tgz", + "integrity": "sha512-kqZUFvX6/aYQOmzfRN5ANcfNS9wLH4aHLWWP/dQKyhRZVoA6rdWszA7DGugFcxPbMiznUyVYyukVl+ExZN4PQA==", + "dev": true, + "license": "MIT OR Apache-2.0", + "bin": { + "biome": "bin/biome" + }, + "engines": { + "node": ">=14.21.3" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/biome" + }, + "optionalDependencies": { + "@biomejs/cli-android-arm64": "2.6.8", + "@biomejs/cli-android-x64": "2.6.8", + "@biomejs/cli-darwin-arm64": "2.6.8", + "@biomejs/cli-darwin-x64": "2.6.8", + "@biomejs/cli-linux-arm64": "2.6.8", + "@biomejs/cli-linux-arm64-musl": "2.6.8", + "@biomejs/cli-linux-x64": "2.6.8", + "@biomejs/cli-linux-x64-musl": "2.6.8", + "@biomejs/cli-win32-arm64": "2.6.8", + "@biomejs/cli-win32-x64": "2.6.8" + } + }, + "node_modules/@biomejs/cli-android-arm64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-android-arm64/-/cli-android-arm64-2.6.8.tgz", + "integrity": "sha512-X4JKPLK85kfUTwuuaORFplnBfGjKkp62PsFhhcL7F/Tpltc7pyUofjlkkMnlZZLWsifFl7LNB8ngVrwJg1uo1Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-android-x64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-android-x64/-/cli-android-x64-2.6.8.tgz", + "integrity": "sha512-C3Hk485vl+deEj53K08+SYYelPIPkdSZL3qHuD31Xi+qydVa4q2ze+aCYo1k3iJGWtvWtjHaGkDh7S2sX6wk8w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-darwin-arm64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-arm64/-/cli-darwin-arm64-2.6.8.tgz", + "integrity": "sha512-DHyj+JnRHcn4YdvpiqgTFZMYKSPELMCfFpNNlEuu1L8DKTGXhzW7raIwdsbo2Ie9nCljQLAQkVWQk/mwM0ueiA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-darwin-x64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-x64/-/cli-darwin-x64-2.6.8.tgz", + "integrity": "sha512-QWWUPjlA0RnkkgYnFLUHZu+RrDc0FdK0A+wEPA+dENQJwsuSHMH89lspnAw2QUWWc9VHyfluGx1Xmp6Y2GZi8Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-arm64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64/-/cli-linux-arm64-2.6.8.tgz", + "integrity": "sha512-0Bjim8lKwnrvXUHoI4k3Tb51BjoiLEwDnovCI8nSzkk6wj3dShiuAjrx6+X0Hjf4ejR1sRZgTQiSDHlpy9vB7w==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-arm64-musl": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.6.8.tgz", + "integrity": "sha512-WB9PhOitX+bRc0G3+GNJGlvbKoWn3JoB9z4E04JQizIC9aPCQyIvwvWG7QZHxw6k20Fi+dHLmZ2fSEmBa9HqiA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-x64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64/-/cli-linux-x64-2.6.8.tgz", + "integrity": "sha512-XIk3pLQT56I6Tti+u0DF8FtSNXjCMTPbxVTzfJ9cS2t1ImVKvrqV5b52GuEaJg6/wuiXvz0sjfb5saB4TPRjzA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-x64-musl": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64-musl/-/cli-linux-x64-musl-2.6.8.tgz", + "integrity": "sha512-64Yzo+J4fEk7Kf9SMnVdVxC+Y2A2e/L86QTP9JjGQ57lsddyELLpbBcNMxSJggre2T1AvISwwSrOApkBAHDqNA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-win32-arm64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-arm64/-/cli-win32-arm64-2.6.8.tgz", + "integrity": "sha512-ezjCEZzHIWE2pdh83a7zLVcAAcDaERcTcvfA7uWlxqz/1CuDxgtfO19pDg9B6YY4wKYIDvYBw2QCMnqIshSwmw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-win32-x64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-x64/-/cli-win32-x64-2.6.8.tgz", + "integrity": "sha512-cD6HvGczZUiAYsY8s2TxxXj2AHFzEdMomvVJfEjzOjBM45nGqIDfBpbtvwGQzDCN8X2yKKk9u1jnDZisT2nxIg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=14.21.3" + } + }, "node_modules/@esbuild/aix-ppc64": { "version": "0.28.2", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", @@ -1971,6 +2184,184 @@ "node": ">=6" } }, + "node_modules/lefthook": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/lefthook/-/lefthook-2.2.2.tgz", + "integrity": "sha512-37fYHAhL12r1twaEV0PA5TwoIT491eTGGYjhhXxlYNMq3DSkiGZBQ++Jfk5maXj0vq52NRauLtMikBKtbNJs3Q==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "lefthook": "bin/index.js" + }, + "optionalDependencies": { + "lefthook-android-arm64": "2.2.2", + "lefthook-darwin-arm64": "2.2.2", + "lefthook-darwin-x64": "2.2.2", + "lefthook-freebsd-arm64": "2.2.2", + "lefthook-freebsd-x64": "2.2.2", + "lefthook-linux-arm64": "2.2.2", + "lefthook-linux-x64": "2.2.2", + "lefthook-openbsd-arm64": "2.2.2", + "lefthook-openbsd-x64": "2.2.2", + "lefthook-windows-arm64": "2.2.2", + "lefthook-windows-x64": "2.2.2" + } + }, + "node_modules/lefthook-android-arm64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/lefthook-android-arm64/-/lefthook-android-arm64-2.2.2.tgz", + "integrity": "sha512-wb9rQQFLX7u1dJLxvMrq9VUfMYi5kxM7tJQ6Y4mWEOwaU+SmIm2wjoT/nromKq27Y8fh2Qd7FgCD3G1wfW8CnQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/lefthook-darwin-arm64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/lefthook-darwin-arm64/-/lefthook-darwin-arm64-2.2.2.tgz", + "integrity": "sha512-6V8D3bLnD/60Xhqn0o2EQD6H3Fe/U9LGkt4WF1O/3eBHbux+5ZJqoH0hfrC+Bi9Dy1Ve1AWxiAY7U2asYl8qVA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/lefthook-darwin-x64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/lefthook-darwin-x64/-/lefthook-darwin-x64-2.2.2.tgz", + "integrity": "sha512-fH/kArZ9ZZ65wCFtvBMgGcq25qwQpkQ5jp93ba+8wpjgxxzjczYGluwHvM/NQDJWLOFXuKXW0yFs76SramQkyQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/lefthook-freebsd-arm64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/lefthook-freebsd-arm64/-/lefthook-freebsd-arm64-2.2.2.tgz", + "integrity": "sha512-MCRsU01ju989QQffOfS3gCeFfyVDXs5B/FzR65fmrNvqcxb98fldvfzzoAbnK2q6SBJlRT3QT1tNEMCxddCwlA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/lefthook-freebsd-x64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/lefthook-freebsd-x64/-/lefthook-freebsd-x64-2.2.2.tgz", + "integrity": "sha512-LkKuJU0S2oLimeoHwPTy1TLWB6GcN0t5lLxiXNlsBKUkr6R47QRcvPMZMoXmu3IetQtd+WliXMLE8qTwi2fqBg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/lefthook-linux-arm64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/lefthook-linux-arm64/-/lefthook-linux-arm64-2.2.2.tgz", + "integrity": "sha512-d+HFtS2DEKaOnD7vRU0tUz8pNgHwsUYmQ22+1dyXpOrXGyzNXR0AqX5KsIRF36JGhVvO5X5Anw5QYgR3mxVSuA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/lefthook-linux-x64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/lefthook-linux-x64/-/lefthook-linux-x64-2.2.2.tgz", + "integrity": "sha512-N/OlQyAhcU6RAXjrwFxLsh70sn96rBoi+XkuLJ8CVBkk9Ci3VDXQayDZTNz5B1xML8RwoMcV8Wblniy1xFOmSA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/lefthook-openbsd-arm64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/lefthook-openbsd-arm64/-/lefthook-openbsd-arm64-2.2.2.tgz", + "integrity": "sha512-6G/gKXcpIwC+XcODg7ELZYP/hIrVIHQxhy2GoRdVyecmpGMFj+BZo3iqcUmeWusQMuL+UdNexbkrUaeJalIkNw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/lefthook-openbsd-x64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/lefthook-openbsd-x64/-/lefthook-openbsd-x64-2.2.2.tgz", + "integrity": "sha512-eMJGi3/tqKEqu7XCZlqwQWRtK5JlL/9diaqqgRlEdlRD7GxwzHZN21z6awbITum9emea3lALvXFe6V8odQLGOA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/lefthook-windows-arm64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/lefthook-windows-arm64/-/lefthook-windows-arm64-2.2.2.tgz", + "integrity": "sha512-4P1EaQb5xG1zhYD1RLJ6TEGdFkmHkB+Slqx6yRDPKuBDNxMiD0+kTAAdUY2E8xPuRR35xHpVPR+b3/HtzPrjQQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/lefthook-windows-x64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/lefthook-windows-x64/-/lefthook-windows-x64-2.2.2.tgz", + "integrity": "sha512-9Ck4zancQilBfXT3ZeRipm7Lcq4RQfxyMpy8SAVINw0t/BrbjsT25V46ZuziERcwdajnE4myfMzC33GoCBwr7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, "node_modules/lru-cache": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", diff --git a/package.json b/package.json index 8bb3e54e..9aa68ca6 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,11 @@ "dev": "vite", "build": "tsc --noEmit && vite build", "typecheck": "tsc --noEmit", + "lint": "biome lint", + "format": "biome format --write", + "check": "biome check", + "check:fix": "biome check --write", + "prepare": "lefthook install", "test": "vitest run --dir src && node --test scripts/bump.test.mjs scripts/i18n-inventory.test.mjs scripts/release-check.test.mjs scripts/setup-signing.test.mjs scripts/dev-retirement.test.mjs scripts/uninstall.test.mjs scripts/installer-locale.test.mjs scripts/security/check-repository.test.mjs scripts/security/semgrep-report.test.mjs scripts/security/export-snapshot.test.mjs scripts/security/snapshot-report.test.mjs scripts/security/semgrep-entry.test.mjs scripts/security/run-semgrep.test.mjs scripts/security/semgrep-parse-gate.test.mjs scripts/security/provision-tools.test.mjs scripts/security/zizmor-report.test.mjs scripts/security/zizmor-entry.test.mjs scripts/security/run-zizmor.test.mjs scripts/security/provider-logo-regexp.test.mjs scripts/security/code-safety.test.mjs scripts/verify-macos-bundle.test.mjs scripts/macos-ci.test.mjs scripts/macos-preview-policy.test.mjs scripts/macos-preview-preflight.test.mjs scripts/macos-preview-artifact.test.mjs scripts/macos-preview-workflow.test.mjs scripts/updates-section-regression.test.mjs scripts/verify-linux-bundles.test.mjs scripts/macos-release-preflight.test.mjs scripts/macos-release-workflow.test.mjs scripts/macos-notary-workflow.test.mjs scripts/macos-notary-checkpoint.test.mjs scripts/macos-notary-submit.test.mjs scripts/macos-notary-artifact.test.mjs scripts/macos-release-resume.test.mjs scripts/macos-release-resume-workflow.test.mjs scripts/macos-release-resume-publish.test.mjs scripts/linux-release-workflow.test.mjs scripts/linux-release-preflight.test.mjs scripts/linux-release-attach.test.mjs", "tauri": "tauri", "app:dev": "tauri dev", @@ -30,10 +35,12 @@ "react-dom": "^19.1.0" }, "devDependencies": { + "@biomejs/biome": "2.6.8", "@tauri-apps/cli": "^2.8.0", "@types/react": "^19.1.0", "@types/react-dom": "^19.1.0", "@vitejs/plugin-react": "^5.0.0", + "lefthook": "2.2.2", "typescript": "^5.9.0", "vite": "^7.1.0", "vitest": "4.1.11" From 81e387f3d79f99de5fa1611db1de2d6a2a365364 Mon Sep 17 00:00:00 2001 From: egdev6 Date: Sat, 21 Nov 2026 15:32:11 +0100 Subject: [PATCH 02/13] build(lint): keep CSS and vendored logos out of the Biome formatter CSS stays linted but not formatted: ui-theme and quota tests assert literal theme.css/styles.css text. Raw-imported provider SVGs are vendored marks validated by security tests. Two source-grep tests now accept line breaks so they do not depend on formatting. --- biome.json | 7 ++++++- odd/tasks/biome-lefthook.md | 8 ++++++-- src/lib/settings-visibility.test.ts | 2 +- src/lib/ui-theme.test.ts | 2 +- 4 files changed, 14 insertions(+), 5 deletions(-) diff --git a/biome.json b/biome.json index 9469bc0c..696d9c01 100644 --- a/biome.json +++ b/biome.json @@ -7,7 +7,7 @@ "defaultBranch": "main" }, "files": { - "includes": ["src/**", "scripts/**", "vite.config.ts", "!src/ds/egdev"] + "includes": ["src/**", "scripts/**", "vite.config.ts", "!src/ds/egdev", "!src/assets/logos"] }, "formatter": { "enabled": true, @@ -29,5 +29,10 @@ "rules": { "recommended": true } + }, + "css": { + "formatter": { + "enabled": false + } } } diff --git a/odd/tasks/biome-lefthook.md b/odd/tasks/biome-lefthook.md index fa6876a7..41246c7f 100644 --- a/odd/tasks/biome-lefthook.md +++ b/odd/tasks/biome-lefthook.md @@ -10,9 +10,11 @@ Risk: item 5 (dev dependencies, git hooks and CI gates); item 6 for lint fixes t ## Tasks -- T1 | S1-S2 | parent inline | pending | `biome.json`, `lefthook.yml` (pre-push: `biome ci` + `cargo fmt --check`), npm scripts (`lint`, `format`, `check`, `prepare`), CI step in `ci.yml` and `linux-pr-ci.yml`, CONTRIBUTING EN/ES. Commit: - +- T1 | S1-S2 | parent inline | done | `biome.json`, `lefthook.yml` (pre-push: `biome ci` + `cargo fmt --check`), npm scripts (`lint`, `format`, `check`, `prepare`), CI step in `ci.yml` and `linux-pr-ci.yml`, CONTRIBUTING EN/ES. Commit: `7006d90` - T2 | S2-S3 | parent inline | pending | Format-only commit with `biome format --write`, plus `.git-blame-ignore-revs`. Commit: - -- T3 | S2-S3 | parent inline | pending | Fix all lint errors so `biome ci` passes; warnings stay visible. Commit: - +- T3 | S2-S3 | parent inline | pending | Exclude raw-imported `src/assets/logos/*.svg` (vendored brand marks, validated by security tests) from Biome. Commit: - +- T3a | S2-S3 | worker | pending | Fix every Biome lint error in test files and scripts: `scripts/**`, `src/**/*.test.ts`, `src/**/*.test.tsx`. Commit: - +- T3b | S2-S3 | worker | pending | Fix every Biome lint error in app source: `src/*.tsx`, `src/components/**` (non-test). Commit: - - T4 | S1-S2 | parent inline | pending | Verify: `npm test`, `npm run build`, `npx biome ci`, `cargo fmt --check`, lefthook pre-push dry run. Commit: - - T5 | S2 | parent | pending | Discord announcement draft (sync instructions: `npm install`, hooks, rebase over the format commit); publish after merge to `main`. Commit: n/a @@ -21,4 +23,6 @@ Risk: item 5 (dev dependencies, git hooks and CI gates); item 6 for lint fixes t L1 — User verbatim: "tenemos metido biome y lefthook para hacer lint en pre-push?" L2 — User verbatim: "si" (accepting: add Biome lint/format, Lefthook pre-push and the same check in CI). L3 — User verbatim scope answer: "lint + format + arreglo de errores + aviso en dicord de que lo hemos añadido avisando de que tienen que sincronizar" +L5 — Lint fix rules for T3a/T3b: no behavior change. No `
` exists in `src/`, so `type="button"` is neutral. `useExhaustiveDependencies`: add or remove a dependency only when provably safe (stable setters/refs, or the effect is idempotent); otherwise keep the deps and add `// biome-ignore lint/correctness/useExhaustiveDependencies: `. Same for any rule where the fix would change runtime behavior: a justified `biome-ignore` beats a risky rewrite. Never disable a rule globally. `npm test` and `npm run typecheck` must stay green. + L4 — Decision: exclude vendored `src/ds/egdev/` from Biome (header says it is a copied bundle, not to be edited by hand). lineWidth 160 chosen because it produced the smallest diff among 100/120/140/160 for the existing code. diff --git a/src/lib/settings-visibility.test.ts b/src/lib/settings-visibility.test.ts index 7bea00b0..c523db6a 100644 --- a/src/lib/settings-visibility.test.ts +++ b/src/lib/settings-visibility.test.ts @@ -30,7 +30,7 @@ describe('obsolete hidden-circles block (#98)', () => { const toggles = [...source.matchAll(//g)].map((m) => m[0]); expect(toggles.length).toBeGreaterThan(0); for (const t of toggles) expect(t).toMatch(/onChange=\{(onVisibility|\(v\) => setVisibility\()/); - expect(source).toContain("checked={isAccountVisible(cfg, 'zai', cfg.zai.enabled)} onChange={(v) => setVisibility('zai', v)}"); + expect(source).toMatch(/checked=\{isAccountVisible\(cfg, 'zai', cfg\.zai\.enabled\)\}\s+onChange=\{\(v\) => setVisibility\('zai', v\)\}/); }); it('shows an enabled but hidden circle as unchecked, without disabling polling', () => { diff --git a/src/lib/ui-theme.test.ts b/src/lib/ui-theme.test.ts index ff1b3aca..f2a44f6d 100644 --- a/src/lib/ui-theme.test.ts +++ b/src/lib/ui-theme.test.ts @@ -162,7 +162,7 @@ describe('detail panel surface (#95)', () => { }); it('does not publish a detail popup until reveal reaches the open phase', () => { - expect(widget).toMatch(/const state: DetailState \| null = active[^?]*phase === 'open'/); + expect(widget).toMatch(/const state: DetailState \| null =\s+active[^?]*phase === 'open'/); }); it('applies popup position and size atomically so its old height never covers the strip', () => { expect(detail).toContain('await api.setDetailBounds(physical)'); From ef1b86ca507c763f83850f308d7e7c7e63a62f94 Mon Sep 17 00:00:00 2001 From: egdev6 Date: Sat, 21 Nov 2026 15:32:12 +0100 Subject: [PATCH 03/13] style: format TypeScript and scripts with Biome Formatting-only commit produced by `npx biome format --write`; no behavior change. Listed in .git-blame-ignore-revs. --- scripts/bump.mjs | 12 +- scripts/dev-retirement.test.mjs | 4 +- scripts/i18n-inventory.mjs | 74 +- scripts/i18n-inventory.test.mjs | 186 ++- scripts/installer-locale.test.mjs | 42 +- scripts/linux-release-attach.mjs | 43 +- scripts/linux-release-attach.test.mjs | 75 +- scripts/linux-release-preflight.mjs | 60 +- scripts/linux-release-preflight.test.mjs | 75 +- scripts/linux-release-workflow.test.mjs | 41 +- scripts/macos-ci.test.mjs | 12 +- scripts/macos-notary-artifact-fixtures.mjs | 96 +- scripts/macos-notary-artifact.mjs | 133 +- scripts/macos-notary-artifact.test.mjs | 127 +- scripts/macos-notary-checkpoint.mjs | 68 +- scripts/macos-notary-checkpoint.test.mjs | 117 +- scripts/macos-notary-submit.mjs | 73 +- scripts/macos-notary-submit.test.mjs | 74 +- scripts/macos-notary-workflow.test.mjs | 40 +- scripts/macos-preview-artifact.mjs | 45 +- scripts/macos-preview-artifact.test.mjs | 167 ++- scripts/macos-preview-policy.mjs | 94 +- scripts/macos-preview-policy.test.mjs | 86 +- scripts/macos-preview-preflight.mjs | 50 +- scripts/macos-preview-preflight.test.mjs | 260 +++- scripts/macos-preview-workflow.test.mjs | 101 +- scripts/macos-release-preflight.mjs | 45 +- scripts/macos-release-preflight.test.mjs | 94 +- scripts/macos-release-resume-publish.mjs | 73 +- scripts/macos-release-resume-publish.test.mjs | 26 +- .../macos-release-resume-workflow.test.mjs | 5 +- scripts/macos-release-resume.mjs | 97 +- scripts/macos-release-resume.test.mjs | 59 +- scripts/macos-release-workflow.test.mjs | 16 +- scripts/release-check.mjs | 8 +- scripts/release-check.test.mjs | 28 +- scripts/security/check-repository.mjs | 93 +- scripts/security/check-repository.test.mjs | 27 +- scripts/security/code-safety.mjs | 38 +- scripts/security/code-safety.test.mjs | 107 +- scripts/security/export-snapshot.mjs | 35 +- scripts/security/export-snapshot.test.mjs | 85 +- .../security/provider-logo-regexp.test.mjs | 16 +- scripts/security/provision-tools.mjs | 39 +- scripts/security/provision-tools.test.mjs | 23 +- scripts/security/run-semgrep.mjs | 148 ++- scripts/security/run-semgrep.test.mjs | 159 ++- scripts/security/run-zizmor.test.mjs | 64 +- scripts/security/semgrep-entry.test.mjs | 19 +- scripts/security/semgrep-parse-gate.test.mjs | 5 +- scripts/security/semgrep-report.mjs | 4 +- scripts/security/semgrep-report.test.mjs | 42 +- scripts/security/snapshot-report.mjs | 38 +- scripts/security/snapshot-report.test.mjs | 82 +- scripts/security/zizmor-entry.test.mjs | 5 +- scripts/security/zizmor-report.mjs | 20 +- scripts/security/zizmor-report.test.mjs | 100 +- scripts/setup-signing.mjs | 15 +- scripts/setup-signing.test.mjs | 103 +- scripts/uninstall.test.mjs | 16 +- scripts/updates-section-regression.test.mjs | 13 +- scripts/verify-linux-bundles.test.mjs | 2 +- scripts/verify-macos-bundle.mjs | 53 +- scripts/verify-macos-bundle.test.mjs | 130 +- src/DetailPanel.placement.test.tsx | 126 +- src/DetailPanel.test.tsx | 11 +- src/DetailPanel.tsx | 104 +- src/LocalePicker.test.tsx | 1 - src/LocalePicker.tsx | 21 +- src/Overlay.tsx | 6 +- src/Settings-accounts-i18n.test.tsx | 31 +- src/Settings-api-panels-i18n.test.tsx | 164 ++- src/Settings-email-i18n.test.tsx | 39 +- src/Settings-i18n.test.tsx | 90 +- src/Settings-panels-i18n.test.tsx | 75 +- src/Settings-providers-i18n.test.tsx | 182 ++- src/Settings.tsx | 1120 +++++++++++++---- src/Widget.tsx | 415 +++--- src/components/CodexInstall.test.tsx | 21 +- src/components/CodexInstall.tsx | 3 +- src/components/MeterBar.test.tsx | 13 +- src/components/MeterBar.tsx | 31 +- src/components/ProviderCard-i18n.test.tsx | 4 +- .../ProviderDetails-history-id.test.tsx | 28 +- src/components/ProviderDetails-i18n.test.tsx | 21 +- src/components/ProviderDetails.test.tsx | 165 ++- src/components/ProviderDetails.tsx | 52 +- src/components/ProviderGauge.test.tsx | 140 ++- src/components/ProviderGauge.tsx | 14 +- src/components/ProviderLogo.tsx | 13 +- src/components/StripFallback.tsx | 9 +- src/components/StripTools.test.tsx | 9 +- src/components/StripTools.tsx | 11 +- src/components/ValidityBadge.test.tsx | 70 +- src/components/ValidityBadge.tsx | 63 +- src/components/popup-period-colors.test.tsx | 51 +- src/components/quota-colors.test.tsx | 94 +- src/detail-placement.test.ts | 64 +- src/detail-placement.ts | 13 +- src/i18n/en.ts | 44 +- src/i18n/es.ts | 42 +- src/i18n/index.ts | 8 +- src/i18n/settings-nav.test.tsx | 17 +- src/i18n/use-locale.test.ts | 46 +- src/i18n/use-locale.ts | 5 +- src/lib/account-health.test.ts | 34 +- src/lib/accounts.ts | 3 +- src/lib/alerts.test.ts | 77 +- src/lib/alerts.ts | 15 +- src/lib/anchor-panel.test.ts | 11 +- src/lib/anchor-panel.ts | 6 +- src/lib/api.ts | 7 +- src/lib/app-identity.ts | 10 +- src/lib/auto-hide.test.ts | 549 +++++--- src/lib/auto-hide.ts | 10 +- src/lib/codex-install.test.ts | 4 +- src/lib/confetti-motion.test.ts | 27 +- src/lib/desktop-compat.test.ts | 8 +- src/lib/detail-panel.test.ts | 100 +- src/lib/detail-panel.ts | 5 +- src/lib/detail-presence.test.ts | 5 +- src/lib/dock.test.ts | 7 +- src/lib/email-dispatch.test.ts | 84 +- src/lib/email.test.ts | 105 +- src/lib/email.ts | 62 +- src/lib/format.test.ts | 65 +- src/lib/format.ts | 12 +- src/lib/hover-presence.test.ts | 33 +- src/lib/hover-presence.ts | 4 +- src/lib/keyring-message.ts | 3 +- src/lib/meter-colors.test.ts | 21 +- src/lib/meter-colors.ts | 2 +- src/lib/order.test.ts | 10 +- src/lib/order.ts | 3 +- src/lib/os-detect.test.ts | 2 +- src/lib/os-detect.ts | 2 +- src/lib/palette.ts | 11 +- src/lib/popup-preferences.test.ts | 26 +- src/lib/popup-preferences.ts | 16 +- src/lib/provider-logo-subkey.test.ts | 4 +- src/lib/reorder-hold.ts | 6 +- src/lib/reset-credits.test.ts | 62 +- src/lib/settings-dirty.test.ts | 12 +- src/lib/settings-dirty.ts | 3 +- src/lib/settings-live.test.ts | 62 +- src/lib/settings-live.ts | 5 +- src/lib/settings-save.test.ts | 25 +- src/lib/settings-save.ts | 5 +- src/lib/settings-visibility.test.ts | 11 +- src/lib/settings-visibility.ts | 35 +- src/lib/shortcut-notices.test.tsx | 16 +- .../stale-presentation-differential.test.tsx | 104 +- .../stale-presentation-regression.test.tsx | 16 +- src/lib/surface-clip.test.ts | 28 +- src/lib/surface-clip.ts | 18 +- src/lib/svg.ts | 13 +- src/lib/test-slots.ts | 24 +- src/lib/text-scale.test.ts | 11 +- src/lib/types.ts | 17 +- src/lib/ui-theme.test.ts | 22 +- src/lib/updater-controller.ts | 34 +- src/lib/updater-policy.test.ts | 22 +- src/lib/updater-policy.ts | 12 +- src/lib/use-widget-startup.test.ts | 36 +- src/lib/use-widget-startup.ts | 19 +- src/lib/useDockReveal.ts | 8 +- src/lib/useTextScale.ts | 9 +- src/lib/useUpdater.ts | 8 +- src/lib/widget-placement.test.ts | 31 +- src/lib/widget-placement.ts | 42 +- src/lib/widget-recovery.test.ts | 47 +- src/lib/widget-recovery.ts | 15 +- src/lib/widget-refresh.test.ts | 8 +- src/lib/widget-refresh.ts | 21 +- src/main.tsx | 14 +- 175 files changed, 6828 insertions(+), 2859 deletions(-) diff --git a/scripts/bump.mjs b/scripts/bump.mjs index f5b44d2b..798334c4 100644 --- a/scripts/bump.mjs +++ b/scripts/bump.mjs @@ -103,12 +103,7 @@ export function bumpVersion(version, { cwd = process.cwd() } = {}) { }; const texts = { pkg: read(FILES[0]), lock: read(FILES[1]), toml: read(FILES[2]), cargoLock: read(FILES[3]) }; - const current = [ - packageJsonVersion(texts.pkg), - ...packageLockVersions(texts.lock), - cargoTomlVersion(texts.toml), - cargoLockVersion(texts.cargoLock), - ]; + const current = [packageJsonVersion(texts.pkg), ...packageLockVersions(texts.lock), cargoTomlVersion(texts.toml), cargoLockVersion(texts.cargoLock)]; if (current.some((value) => !value)) throw new Error(`No pude leer la versión en todas las fuentes: ${current.join(', ')}`); if (new Set(current).size !== 1) throw new Error(`Versiones actuales incoherentes: ${current.join(', ')}`); if (compareVersions(version, current[0]) <= 0) throw new Error(`La versión ${version} no es mayor que la actual ${current[0]}`); @@ -119,10 +114,7 @@ export function bumpVersion(version, { cwd = process.cwd() } = {}) { lock.version = version; if (lock.packages?.['']) lock.packages[''].version = version; const toml = setCargoTomlVersion(texts.toml, version); - const cargoLock = texts.cargoLock.replace( - /(\[\[package\]\]\r?\nname = "quorb"\r?\nversion = ")[^"]+(")/, - `$1${version}$2`, - ); + const cargoLock = texts.cargoLock.replace(/(\[\[package\]\]\r?\nname = "quorb"\r?\nversion = ")[^"]+(")/, `$1${version}$2`); fs.writeFileSync(path.join(cwd, FILES[0]), JSON.stringify(pkg, null, 2) + '\n'); fs.writeFileSync(path.join(cwd, FILES[1]), JSON.stringify(lock, null, 2) + '\n'); diff --git a/scripts/dev-retirement.test.mjs b/scripts/dev-retirement.test.mjs index 7454a951..9465d7a0 100644 --- a/scripts/dev-retirement.test.mjs +++ b/scripts/dev-retirement.test.mjs @@ -125,9 +125,7 @@ test('stable Tauri config and its updater feed are untouched', () => { const base = readJson('src-tauri/tauri.conf.json'); assert.equal(base.identifier, 'es.egdev.quorb'); assert.equal(base.productName, 'Quorb'); - assert.deepEqual(base.plugins.updater.endpoints, [ - 'https://github.com/egdev6/quorb/releases/latest/download/latest.json', - ]); + assert.deepEqual(base.plugins.updater.endpoints, ['https://github.com/egdev6/quorb/releases/latest/download/latest.json']); assert.ok(base.plugins.updater.pubkey, 'stable updater public key must remain'); const release = readJson('src-tauri/tauri.release.conf.json'); diff --git a/scripts/i18n-inventory.mjs b/scripts/i18n-inventory.mjs index 0bb15198..31aa7354 100644 --- a/scripts/i18n-inventory.mjs +++ b/scripts/i18n-inventory.mjs @@ -54,16 +54,43 @@ export function isUiText(s) { // --------------------------------------------------------------------------- const SKIP_ATTRS = new Set([ - 'accept', 'autoComplete', 'class', 'className', 'd', 'dir', 'fill', 'height', 'href', 'htmlFor', 'id', 'inputMode', - 'key', 'lang', 'method', 'mode', 'name', 'pattern', 'rel', 'role', 'src', 'stroke', 'style', 'tabIndex', 'target', - 'type', 'viewBox', 'width', 'xmlns', + 'accept', + 'autoComplete', + 'class', + 'className', + 'd', + 'dir', + 'fill', + 'height', + 'href', + 'htmlFor', + 'id', + 'inputMode', + 'key', + 'lang', + 'method', + 'mode', + 'name', + 'pattern', + 'rel', + 'role', + 'src', + 'stroke', + 'style', + 'tabIndex', + 'target', + 'type', + 'viewBox', + 'width', + 'xmlns', ]); // Always visible to the user: kept whenever they hold a letter (except whole URLs). // Only ARIA attributes that carry readable text; state ones (aria-hidden, aria-live…) hold tokens. const VISIBLE_ATTR = /^(placeholder|title|alt|label|hint|aria-(label|description|placeholder|roledescription|valuetext))$/; // Wrappers a visible attribute value may hide its literals behind (`cond ? 'a' : 'b'`, `x ?? 'y'`). const isValueWrapper = (n) => ts.isJsxExpression(n) || ts.isConditionalExpression(n) || ts.isParenthesizedExpression(n) || ts.isBinaryExpression(n); -const SKIP_CALLS = /^(console\.\w+|invoke|listen|emit|emitTo|once|\w+\.(addEventListener|removeEventListener|querySelector|querySelectorAll|getElementById|setAttribute|getItem|setItem|removeItem|matchMedia|toggle|add|remove|contains)|clsx|cn|classNames|require)$/; +const SKIP_CALLS = + /^(console\.\w+|invoke|listen|emit|emitTo|once|\w+\.(addEventListener|removeEventListener|querySelector|querySelectorAll|getElementById|setAttribute|getItem|setItem|removeItem|matchMedia|toggle|add|remove|contains)|clsx|cn|classNames|require)$/; /** Visible-text candidates of one TS/TSX source, ordered by position. */ export function extractTs(source, fileName) { @@ -74,16 +101,16 @@ export function extractTs(source, fileName) { // URL, otherwise the `isUiText` shape heuristic. const add = (pos, raw, context) => { const text = raw.replace(/\s+/g, ' ').trim(); - const keep = context === 'jsx' ? /\p{L}/u.test(text) - : context === 'attr' ? /\p{L}/u.test(text) && !/^\S+:\/\/\S*$/.test(text) - : isUiText(text); + const keep = context === 'jsx' ? /\p{L}/u.test(text) : context === 'attr' ? /\p{L}/u.test(text) && !/^\S+:\/\/\S*$/.test(text) : isUiText(text); if (keep) found.push({ pos, line: sf.getLineAndCharacterOfPosition(pos).line + 1, text }); }; // A literal compared with `===`/`!==` or used as a `case` label is a code value, not text. const isComparedLiteral = (node) => { const p = node.parent; - return (ts.isBinaryExpression(p) && [ts.SyntaxKind.EqualsEqualsEqualsToken, ts.SyntaxKind.ExclamationEqualsEqualsToken].includes(p.operatorToken.kind)) - || (ts.isCaseClause(p) && p.expression === node); + return ( + (ts.isBinaryExpression(p) && [ts.SyntaxKind.EqualsEqualsEqualsToken, ts.SyntaxKind.ExclamationEqualsEqualsToken].includes(p.operatorToken.kind)) || + (ts.isCaseClause(p) && p.expression === node) + ); }; const visit = (node, context) => { if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node) || ts.isTypeNode(node)) return; @@ -185,7 +212,7 @@ export function extractRust(source) { j = close + 1; continue; } - out += { n: '\n', t: '\t', r: '', '0': '', '"': '"', "'": "'", '\\': '\\' }[e] ?? e; + out += { n: '\n', t: '\t', r: '', 0: '', '"': '"', "'": "'", '\\': '\\' }[e] ?? e; j += 2; continue; } @@ -207,9 +234,13 @@ export function extractRust(source) { let level = 0; let j = i; do { - if (src[j] === '/' && src[j + 1] === '*') { level++; j += 2; } - else if (src[j] === '*' && src[j + 1] === '/') { level--; j += 2; } - else j++; + if (src[j] === '/' && src[j + 1] === '*') { + level++; + j += 2; + } else if (src[j] === '*' && src[j + 1] === '/') { + level--; + j += 2; + } else j++; } while (level > 0 && j < n); advance(j); continue; @@ -229,7 +260,10 @@ export function extractRust(source) { if ((c === 'r' || (c === 'b' && next === 'r')) && !isIdent(src[i - 1])) { let j = c === 'b' ? i + 2 : i + 1; let hashes = 0; - while (src[j] === '#') { hashes++; j++; } + while (src[j] === '#') { + hashes++; + j++; + } if (src[j] === '"') { const close = '"' + '#'.repeat(hashes); const end = src.indexOf(close, j + 1); @@ -390,7 +424,9 @@ function main(argv) { } } if (sites && (check || out !== DEFAULT_OUT)) { - process.stderr.write(`--sites prints site rows on stdout and cannot be combined with --check or --out\nusage: node scripts/i18n-inventory.mjs [--ref ] [--out ] [--check] [--sites]\n`); + process.stderr.write( + `--sites prints site rows on stdout and cannot be combined with --check or --out\nusage: node scripts/i18n-inventory.mjs [--ref ] [--out ] [--check] [--sites]\n`, + ); return 2; } const { trees, files } = collect(process.cwd(), ref); @@ -410,9 +446,13 @@ function main(argv) { const withoutHashes = (s) => s.replace(/^Generated by .* from the source trees .*$/m, ''); if (current !== null && withoutHashes(current) === withoutHashes(doc)) { // Hashes-only drift: main moved the source trees without changing any text. - process.stderr.write(`${out} is out of date in its header tree hashes only (the listed texts still match); refresh them with: node scripts/i18n-inventory.mjs --out ${out}\n`); + process.stderr.write( + `${out} is out of date in its header tree hashes only (the listed texts still match); refresh them with: node scripts/i18n-inventory.mjs --out ${out}\n`, + ); } else { - process.stderr.write(`${out} is out of date; regenerate with: node scripts/i18n-inventory.mjs --out ${out}\nnote: CI validates the merge of this branch with main; if main changed texts under src/ or src-tauri/src/, merge main into the branch and regenerate\n`); + process.stderr.write( + `${out} is out of date; regenerate with: node scripts/i18n-inventory.mjs --out ${out}\nnote: CI validates the merge of this branch with main; if main changed texts under src/ or src-tauri/src/, merge main into the branch and regenerate\n`, + ); } return 1; } diff --git a/scripts/i18n-inventory.test.mjs b/scripts/i18n-inventory.test.mjs index 4b6bd9f5..229d84e6 100644 --- a/scripts/i18n-inventory.test.mjs +++ b/scripts/i18n-inventory.test.mjs @@ -11,12 +11,37 @@ const SCRIPT = path.join(path.dirname(fileURLToPath(import.meta.url)), 'i18n-inv const texts = (entries) => entries.map((e) => [e.line, e.text]); test('isUiText keeps human text and drops identifiers, urls and css', () => { - for (const s of ['Guardar', 'Guardar cambios', 'sesión', 'Cuenta ${…}', ' · saldo comunicado', 'Quitar', - 'Dónde escucha 9Router (por defecto http://localhost:20128).', 'p. ej. /usage/used_tokens']) { + for (const s of [ + 'Guardar', + 'Guardar cambios', + 'sesión', + 'Cuenta ${…}', + ' · saldo comunicado', + 'Quitar', + 'Dónde escucha 9Router (por defecto http://localhost:20128).', + 'p. ej. /usage/used_tokens', + ]) { assert.equal(isUiText(s), true, s); } - for (const s of ['', ' ', '{}', 'save_config', 'eg-gauge__key', 'top', 'camelCase', 'https://github.com/egdev6/quorb', - 'GET', 'USD', 'Content-Type', './lib/types', 'src/lib/format.ts', '#ff0036', '%APPDATA%', '12px', '--eg-accent']) { + for (const s of [ + '', + ' ', + '{}', + 'save_config', + 'eg-gauge__key', + 'top', + 'camelCase', + 'https://github.com/egdev6/quorb', + 'GET', + 'USD', + 'Content-Type', + './lib/types', + 'src/lib/format.ts', + '#ff0036', + '%APPDATA%', + '12px', + '--eg-accent', + ]) { assert.equal(isUiText(s), false, s); } }); @@ -93,7 +118,7 @@ function makeRepo() { git(dir, 'config', 'core.autocrlf', 'false'); fs.mkdirSync(path.join(dir, 'src'), { recursive: true }); fs.mkdirSync(path.join(dir, 'src-tauri', 'src'), { recursive: true }); - fs.writeFileSync(path.join(dir, 'src', 'App.tsx'), "export const A = () =>

Hola mundo

;\n"); + fs.writeFileSync(path.join(dir, 'src', 'App.tsx'), 'export const A = () =>

Hola mundo

;\n'); fs.writeFileSync(path.join(dir, 'src', 'App.test.tsx'), "it('Texto de test', () => {});\n"); fs.writeFileSync(path.join(dir, 'src-tauri', 'src', 'lib.rs'), 'const M: &str = "Salir de Quorb";\n'); git(dir, 'add', '.'); @@ -111,16 +136,19 @@ function makeMultiRepo() { git(dir, 'config', 'core.autocrlf', 'false'); fs.mkdirSync(path.join(dir, 'src'), { recursive: true }); fs.mkdirSync(path.join(dir, 'src-tauri', 'src'), { recursive: true }); - fs.writeFileSync(path.join(dir, 'src', 'App.tsx'), [ - 'export const A = () => (', // 1 - ' <>', // 2 - '

Zebra

', // 3 - '

Alfa

', // 4 - '

Zebra

', // 5 - ' ', // 6 - ');', // 7 - '', - ].join('\n')); + fs.writeFileSync( + path.join(dir, 'src', 'App.tsx'), + [ + 'export const A = () => (', // 1 + ' <>', // 2 + '

Zebra

', // 3 + '

Alfa

', // 4 + '

Zebra

', // 5 + ' ', // 6 + ');', // 7 + '', + ].join('\n'), + ); fs.writeFileSync(path.join(dir, 'src-tauri', 'src', 'lib.rs'), 'const M: &str = "Uno";\nconst N: &str = "Dos";\n'); git(dir, 'add', '.'); git(dir, 'commit', '-q', '-m', 'base'); @@ -206,14 +234,10 @@ test('sections deduplicate and sort texts; --sites prints path:line rows; --chec // --sites keeps every occurrence with its line, in path order then line order. const sites = run(dir, '--sites'); assert.equal(sites.status, 0, sites.stderr); - assert.equal(sites.stdout, [ - 'src-tauri/src/lib.rs:1 | Uno', - 'src-tauri/src/lib.rs:2 | Dos', - 'src/App.tsx:3 | Zebra', - 'src/App.tsx:4 | Alfa', - 'src/App.tsx:5 | Zebra', - '', - ].join('\n')); + assert.equal( + sites.stdout, + ['src-tauri/src/lib.rs:1 | Uno', 'src-tauri/src/lib.rs:2 | Dos', 'src/App.tsx:3 | Zebra', 'src/App.tsx:4 | Alfa', 'src/App.tsx:5 | Zebra', ''].join('\n'), + ); // --sites works against any ref. const refSites = run(dir, '--sites', '--ref', git(dir, 'rev-parse', 'HEAD')); assert.equal(refSites.status, 0, refSites.stderr); @@ -402,8 +426,31 @@ const yamlScalar = (value) => { const unwrapQuotes = (word) => word.replace(/^(['"])(.*)\1$/, '$2'); const CONTROL_WORDS = new Set([ - 'if', 'then', 'else', 'elif', 'fi', 'for', 'while', 'until', 'do', 'done', 'case', 'esac', 'select', - 'function', '{', '}', '!', 'exit', 'return', 'exec', 'eval', 'source', '.', 'trap', 'alias', + 'if', + 'then', + 'else', + 'elif', + 'fi', + 'for', + 'while', + 'until', + 'do', + 'done', + 'case', + 'esac', + 'select', + 'function', + '{', + '}', + '!', + 'exit', + 'return', + 'exec', + 'eval', + 'source', + '.', + 'trap', + 'alias', ]); /** @@ -466,10 +513,7 @@ const splitShellCommands = (cmd) => { const commandWords = (text) => text.trim().split(/\s+/).map(unwrapQuotes); -const leavesSubset = ([first, ...args]) => - CONTROL_WORDS.has(first) || - /^[({]|\)$/.test(first) || - (first === 'set' && args.some((a) => a.startsWith('+'))); +const leavesSubset = ([first, ...args]) => CONTROL_WORDS.has(first) || /^[({]|\)$/.test(first) || (first === 'set' && args.some((a) => a.startsWith('+'))); /** Separators that make a command a statement of its own: unconditional execution, failure not masked. */ const STATEMENT_SEPARATORS = new Set(['', ';', '\n']); @@ -504,9 +548,7 @@ const isShellStep = (shell) => shell === null || ['bash', 'sh'].includes(shell.s const runsCheckAfterInstall = (jobs) => Object.values(jobs).some((job) => { if (job.if || !failsTheJob(job.continueOnError)) return false; - const events = job.steps - .filter((s) => s.run !== null && !s.if && failsTheJob(s.continueOnError) && isShellStep(s.shell)) - .flatMap((s) => runEvents(s.run)); + const events = job.steps.filter((s) => s.run !== null && !s.if && failsTheJob(s.continueOnError) && isShellStep(s.shell)).flatMap((s) => runEvents(s.run)); const install = events.indexOf('install'); return install >= 0 && events.indexOf('check', install + 1) > install; }); @@ -595,10 +637,7 @@ test('echoing the check command is not executing it (#160)', () => { ].join('\n'); assert.equal(runsCheckAfterInstall(parseWorkflowRuns(echoOnly)), false, 'printing the check cannot accredit its execution'); // The substring contract accepted exactly this workflow: pin why it had to go. - assert.ok( - /\bnode scripts\/i18n-inventory\.mjs --check\b/.test(echoOnly), - 'documentation: the replaced substring regex matched the echo mention', - ); + assert.ok(/\bnode scripts\/i18n-inventory\.mjs --check\b/.test(echoOnly), 'documentation: the replaced substring regex matched the echo mention'); const compound = [ 'jobs:', @@ -608,34 +647,14 @@ test('echoing the check command is not executing it (#160)', () => { ' - run: echo "inventory gate" && node scripts/i18n-inventory.mjs --check', ' ', ].join('\n'); - assert.equal( - runsCheckAfterInstall(parseWorkflowRuns(compound)), - false, - 'a check after && runs only if echo succeeds: not a gate (#186 review)', - ); + assert.equal(runsCheckAfterInstall(parseWorkflowRuns(compound)), false, 'a check after && runs only if echo succeeds: not a gate (#186 review)'); }); test('separators inside quotes or comments do not fabricate a check segment (#160)', () => { - assert.equal( - runsCheck('echo "texto; node scripts/i18n-inventory.mjs --check ;fin"'), - false, - 'a ; inside a quoted echo argument is data, not a separator', - ); - assert.equal( - runsCheck("echo 'texto; node scripts/i18n-inventory.mjs --check'"), - false, - 'a ; inside a single-quoted argument is data, not a separator', - ); - assert.equal( - runsCheck('# texto; node scripts/i18n-inventory.mjs --check'), - false, - 'a ; inside a comment is not a separator', - ); - assert.equal( - runsCheck('npm test # then; node scripts/i18n-inventory.mjs --check'), - false, - 'a trailing comment cannot accredit the check', - ); + assert.equal(runsCheck('echo "texto; node scripts/i18n-inventory.mjs --check ;fin"'), false, 'a ; inside a quoted echo argument is data, not a separator'); + assert.equal(runsCheck("echo 'texto; node scripts/i18n-inventory.mjs --check'"), false, 'a ; inside a single-quoted argument is data, not a separator'); + assert.equal(runsCheck('# texto; node scripts/i18n-inventory.mjs --check'), false, 'a ; inside a comment is not a separator'); + assert.equal(runsCheck('npm test # then; node scripts/i18n-inventory.mjs --check'), false, 'a trailing comment cannot accredit the check'); assert.equal( runsCheck('echo "texto" && node scripts/i18n-inventory.mjs --check'), false, @@ -654,8 +673,7 @@ test('separators inside quotes or comments do not fabricate a check segment (#16 }); /** One job that installs and then runs the given step lines (6-space `- ` indent). */ -const workflowWith = (...stepLines) => - ['jobs:', ' checks:', ' steps:', ' - run: npm ci', ...stepLines, ' '].join('\n'); +const workflowWith = (...stepLines) => ['jobs:', ' checks:', ' steps:', ' - run: npm ci', ...stepLines, ' '].join('\n'); const accredits = (yaml) => runsCheckAfterInstall(parseWorkflowRuns(yaml)); const CHECK = 'node scripts/i18n-inventory.mjs --check'; @@ -715,14 +733,26 @@ test('a check whose failure cannot fail the step does not accredit it (#160)', ( assert.equal(accredits(workflowWith(` - run: ${CHECK} | tee out.txt`)), false, 'a pipe reports the exit code of tee'); assert.equal(accredits(workflowWith(` - run: ${CHECK} &`)), false, 'a background check is never awaited'); assert.equal(accredits(workflowWith(' - run: |', ' set +e', ` ${CHECK}`)), false, 'set +e lets the step pass after a failed check'); - assert.equal(accredits(workflowWith(` - run: ${CHECK} && echo ok`)), false, 'a check before && can be masked by later statements; only statement position accredits (#186 review)'); - assert.equal(accredits(workflowWith(` - run: ${CHECK} 2>&1`)), false, 'only the literal canonical command accredits; extra words are not the gate (#186 review)'); + assert.equal( + accredits(workflowWith(` - run: ${CHECK} && echo ok`)), + false, + 'a check before && can be masked by later statements; only statement position accredits (#186 review)', + ); + assert.equal( + accredits(workflowWith(` - run: ${CHECK} 2>&1`)), + false, + 'only the literal canonical command accredits; extra words are not the gate (#186 review)', + ); assert.equal(accredits(workflowWith(` - run: ${CHECK} > report.txt`)), false, 'an output redirection is not the canonical invocation (#186 review)'); }); test('compound runs still accredit the check in statement position (#186 review)', () => { assert.equal(accredits(workflowWith(` - run: npm test; ${CHECK}`)), true, 'a ;-separated check runs unconditionally and fails the step under bash -e'); - assert.equal(accredits(workflowWith(' - run: |', ` ${CHECK}`, ' echo done')), true, 'a failed plain check still fails the step before any later statement'); + assert.equal( + accredits(workflowWith(' - run: |', ` ${CHECK}`, ' echo done')), + true, + 'a failed plain check still fails the step before any later statement', + ); }); test('step and job settings that skip or tolerate the check do not accredit it (#160)', () => { @@ -737,9 +767,29 @@ test('step and job settings that skip or tolerate the check do not accredit it ( assert.equal(accredits(job('if: false')), false, 'a conditional job may be skipped'); assert.equal(accredits(job('continue-on-error: true')), false, 'a job allowed to fail is not a gate'); - const jobDefaults = ['jobs:', ' checks:', ' defaults:', ' run:', ' shell: pwsh', ' steps:', ' - run: npm ci', ` - run: ${CHECK}`, ' '].join('\n'); + const jobDefaults = [ + 'jobs:', + ' checks:', + ' defaults:', + ' run:', + ' shell: pwsh', + ' steps:', + ' - run: npm ci', + ` - run: ${CHECK}`, + ' ', + ].join('\n'); assert.equal(accredits(jobDefaults), false, 'a job default shell outside bash/sh is not the supported subset'); - const workflowDefaults = ['defaults:', ' run:', ' shell: python', 'jobs:', ' checks:', ' steps:', ' - run: npm ci', ` - run: ${CHECK}`, ' '].join('\n'); + const workflowDefaults = [ + 'defaults:', + ' run:', + ' shell: python', + 'jobs:', + ' checks:', + ' steps:', + ' - run: npm ci', + ` - run: ${CHECK}`, + ' ', + ].join('\n'); assert.equal(accredits(workflowDefaults), false, 'a workflow default shell outside bash/sh is not the supported subset'); const actionInput = workflowWith(' - uses: some/action@v1', ' with:', ` run: ${CHECK}`); diff --git a/scripts/installer-locale.test.mjs b/scripts/installer-locale.test.mjs index a3d8efa4..2a6c9850 100644 --- a/scripts/installer-locale.test.mjs +++ b/scripts/installer-locale.test.mjs @@ -14,18 +14,16 @@ function macro(name) { const pattern = new RegExp(`^!macro ${name}[ \\t]*\\n([\\s\\S]*?)^!macroend[ \\t]*$`, 'gm'); const matches = [...source.matchAll(pattern)]; assert.equal(matches.length, 1, `expected exactly one ${name} macro`); - return matches[0][1].split('\n').map((line) => line.trim()) + return matches[0][1] + .split('\n') + .map((line) => line.trim()) .filter((line) => line && !line.startsWith(';')); } function interactivePostinstall() { const lines = macro('NSIS_HOOK_POSTINSTALL'); // All writes are inside this conjunction; all three other modes take Else. - assert.deepEqual(lines.slice(0, 3), [ - '${IfNot} ${Silent}', - '${AndIf} $PassiveMode <> 1', - '${AndIf} $UpdateMode <> 1', - ]); + assert.deepEqual(lines.slice(0, 3), ['${IfNot} ${Silent}', '${AndIf} $PassiveMode <> 1', '${AndIf} $UpdateMode <> 1']); assert.deepEqual(lines.slice(-3), ['${Else}', `Delete ${handoff}`, '${EndIf}']); return lines.slice(3, -3); } @@ -56,10 +54,16 @@ test('the language dialog only shows in interactive, non-passive, non-update run // The remembered or default language is still loaded before the guard. const registry = lines.findIndex((line) => line.startsWith('ReadRegStr $mui.LangDLL.RegistryLanguage')); assert.ok(registry >= 0 && registry < guard); - assert.equal(lines.filter((line) => line === 'LangDLL::LangDialog "${MUI_LANGDLL_WINDOWTITLE}" "${MUI_LANGDLL_INFO}" A ${MUI_LANGDLL_LANGUAGES} ""' || line === 'LangDLL::LangDialog "${MUI_LANGDLL_WINDOWTITLE}" "${MUI_LANGDLL_INFO}" AC ${MUI_LANGDLL_LANGUAGES_CP} ""').length, 2); + assert.equal( + lines.filter( + (line) => + line === 'LangDLL::LangDialog "${MUI_LANGDLL_WINDOWTITLE}" "${MUI_LANGDLL_INFO}" A ${MUI_LANGDLL_LANGUAGES} ""' || + line === 'LangDLL::LangDialog "${MUI_LANGDLL_WINDOWTITLE}" "${MUI_LANGDLL_INFO}" AC ${MUI_LANGDLL_LANGUAGES_CP} ""', + ).length, + 2, + ); }); - test('locale configuration keeps per-user hooks and all existing bundle targets', () => { const conf = JSON.parse(read('src-tauri/tauri.conf.json')); assert.equal(conf.bundle.windows.nsis.installMode, 'currentUser'); @@ -69,13 +73,7 @@ test('locale configuration keeps per-user hooks and all existing bundle targets' test('postinstall writes only interactively and removes stale choices in all other modes', () => { const body = interactivePostinstall(); - assert.deepEqual(body.slice(0, 5), [ - `CreateDirectory ${directory}`, - `Delete ${handoff}`, - 'ClearErrors', - `FileOpen $0 ${handoff} w`, - '${IfNot} ${Errors}', - ]); + assert.deepEqual(body.slice(0, 5), [`CreateDirectory ${directory}`, `Delete ${handoff}`, 'ClearErrors', `FileOpen $0 ${handoff} w`, '${IfNot} ${Errors}']); assert.equal(body.filter((line) => /^FileOpen\b/.test(line)).length, 1); assert.equal(body.filter((line) => /^FileWrite\b/.test(line)).length, 3); assert.equal(body.filter((line) => /^FileClose\b/.test(line)).length, 1); @@ -98,13 +96,7 @@ test('postinstall writes Spanish for language 1034 and English otherwise, then t test('handoff write errors do not abort installation and remove a partial file', () => { const body = interactivePostinstall(); - assert.deepEqual(body.slice(-5), [ - 'FileClose $0', - '${If} ${Errors}', - `Delete ${handoff}`, - '${EndIf}', - '${EndIf}', - ]); + assert.deepEqual(body.slice(-5), ['FileClose $0', '${If} ${Errors}', `Delete ${handoff}`, '${EndIf}', '${EndIf}']); assert.doesNotMatch(body.join('\n'), /^(?:Abort|Quit|SetErrorLevel|MessageBox)\b/m); }); @@ -112,11 +104,7 @@ test('preuninstall removes the handoff outside update mode without replacing cle const pre = macro('NSIS_HOOK_PREUNINSTALL'); const guard = pre.indexOf('${If} $UpdateMode <> 1'); assert.notEqual(guard, -1); - assert.deepEqual(pre.slice(guard, guard + 3), [ - '${If} $UpdateMode <> 1', - `Delete ${handoff}`, - '${EndIf}', - ]); + assert.deepEqual(pre.slice(guard, guard + 3), ['${If} $UpdateMode <> 1', `Delete ${handoff}`, '${EndIf}']); assert.equal(pre.filter((line) => /^Delete\b/.test(line)).length, 1); assert.ok(pre.includes('${If} $DeleteAppDataCheckboxState = 1')); assert.ok(pre.some((line) => line.includes('--quorb-uninstall-cleanup --delete-data'))); diff --git a/scripts/linux-release-attach.mjs b/scripts/linux-release-attach.mjs index 90689381..97b53e20 100644 --- a/scripts/linux-release-attach.mjs +++ b/scripts/linux-release-attach.mjs @@ -8,8 +8,7 @@ import { linuxAssetNames, preflightRelease } from './linux-release-preflight.mjs const repository = 'egdev6/quorb'; const maxBundle = 512 * 1024 * 1024; const hash = (bytes) => createHash('sha256').update(bytes).digest('hex'); -const positiveId = (value) => typeof value === 'string' && /^[1-9][0-9]*$/.test(value) && - Number.isSafeInteger(Number(value)); +const positiveId = (value) => typeof value === 'string' && /^[1-9][0-9]*$/.test(value) && Number.isSafeInteger(Number(value)); const digest = (value) => typeof value === 'string' && /^[0-9a-f]{64}$/.test(value) && value === value.trim(); const publicationError = (message) => Object.assign(new Error(message), { safePublish: true }); @@ -17,16 +16,16 @@ const publicationError = (message) => Object.assign(new Error(message), { safePu // extra files, symlinks, changed bytes and invalid fingerprints before any POST. export function loadBundles({ env = process.env, io = fs } = {}) { validateReleaseInputs({ ref: env.GITHUB_REF, version: env.RELEASE_VERSION, sourceSha: env.RELEASE_SOURCE_SHA }); - if (typeof env.BUNDLE_DIR !== 'string' || !path.isAbsolute(env.BUNDLE_DIR) || - !digest(env.DEB_SHA256) || !digest(env.APPIMAGE_SHA256)) throw new Error('Invalid bundle context'); + if (typeof env.BUNDLE_DIR !== 'string' || !path.isAbsolute(env.BUNDLE_DIR) || !digest(env.DEB_SHA256) || !digest(env.APPIMAGE_SHA256)) + throw new Error('Invalid bundle context'); const [deb, debSum, appimage, appimageSum] = linuxAssetNames(env.RELEASE_VERSION); const entries = io.readdirSync(env.BUNDLE_DIR); if (entries.length !== 2 || !entries.includes(deb) || !entries.includes(appimage)) throw new Error('Unexpected bundle files'); const read = (name, expected) => { const file = path.join(env.BUNDLE_DIR, name); const stat = io.lstatSync(file); - if (!stat.isFile() || stat.isSymbolicLink() || !Number.isSafeInteger(stat.size) || - stat.size < 1 || stat.size > maxBundle) throw new Error('Invalid bundle file'); + if (!stat.isFile() || stat.isSymbolicLink() || !Number.isSafeInteger(stat.size) || stat.size < 1 || stat.size > maxBundle) + throw new Error('Invalid bundle file'); const bytes = io.readFileSync(file); if (!Buffer.isBuffer(bytes) || bytes.length !== stat.size || hash(bytes) !== expected) throw new Error('Bundle digest mismatch'); return bytes; @@ -34,8 +33,12 @@ export function loadBundles({ env = process.env, io = fs } = {}) { const debBytes = read(deb, env.DEB_SHA256); const appimageBytes = read(appimage, env.APPIMAGE_SHA256); const checksum = (name, bytes) => Buffer.from(`${hash(bytes)} ${name}\n`); - return new Map([[deb, debBytes], [debSum, checksum(deb, debBytes)], - [appimage, appimageBytes], [appimageSum, checksum(appimage, appimageBytes)]]); + return new Map([ + [deb, debBytes], + [debSum, checksum(deb, debBytes)], + [appimage, appimageBytes], + [appimageSum, checksum(appimage, appimageBytes)], + ]); } async function uploadId(response) { @@ -61,21 +64,21 @@ async function uploadId(response) { } } -export async function attachRelease({ env = process.env, io = fs, fetch = globalThis.fetch, - preflight = preflightRelease } = {}) { +export async function attachRelease({ env = process.env, io = fs, fetch = globalThis.fetch, preflight = preflightRelease } = {}) { if (!positiveId(env.RELEASE_ID)) throw new Error('Invalid release identity'); const files = loadBundles({ env, io }); // Recheck release identity, tag and all four absent names immediately before // POST. GitHub rejects duplicate names; never use an overwrite/clobber API. const release = await preflight({ env, fetch }); if (String(release.releaseId) !== env.RELEASE_ID) throw new Error('Release identity changed'); - const headers = { Authorization: `Bearer ${env.GH_TOKEN}`, Accept: 'application/vnd.github+json', - 'X-GitHub-Api-Version': '2022-11-28' }; + const headers = { Authorization: `Bearer ${env.GH_TOKEN}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' }; const uploaded = []; try { for (const [name, bytes] of files) { const response = await fetch(`https://uploads.github.com/repos/${repository}/releases/${env.RELEASE_ID}/assets?name=${encodeURIComponent(name)}`, { - method: 'POST', redirect: 'error', signal: AbortSignal.timeout(120_000), + method: 'POST', + redirect: 'error', + signal: AbortSignal.timeout(120_000), headers: { ...headers, 'Content-Type': name.endsWith('.sha256') ? 'text/plain' : 'application/octet-stream' }, body: bytes, }); @@ -90,10 +93,15 @@ export async function attachRelease({ env = process.env, io = fs, fetch = global for (const id of uploaded.reverse()) { try { const response = await fetch(`https://api.github.com/repos/${repository}/releases/assets/${id}`, { - method: 'DELETE', redirect: 'error', signal: AbortSignal.timeout(30_000), headers, + method: 'DELETE', + redirect: 'error', + signal: AbortSignal.timeout(30_000), + headers, }); if (response.status !== 204) throw new Error(); - } catch { failed.push(id); } + } catch { + failed.push(id); + } } if (failed.length) throw publicationError(`Upload failed; rollback failed for owned asset IDs ${failed.join(', ')}; inspect release assets`); throw publicationError('Upload failed or ambiguous; removed confirmed uploads only; inspect release assets before retrying'); @@ -102,8 +110,9 @@ export async function attachRelease({ env = process.env, io = fs, fetch = global } if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { - try { console.log(JSON.stringify(await attachRelease())); } - catch (error) { + try { + console.log(JSON.stringify(await attachRelease())); + } catch (error) { console.error(error.safePublish ? error.message : 'Attachment failed; inspect release assets before recovery'); process.exitCode = 1; } diff --git a/scripts/linux-release-attach.test.mjs b/scripts/linux-release-attach.test.mjs index fedaf0d1..5be2bc87 100644 --- a/scripts/linux-release-attach.test.mjs +++ b/scripts/linux-release-attach.test.mjs @@ -12,21 +12,35 @@ const hash = (bytes) => createHash('sha256').update(bytes).digest('hex'); const checksum = (name, bytes) => Buffer.from(`${hash(bytes)} ${name}\n`); function fixture({ failAt = 0, rollbackFailure = false, badResponse = false } = {}) { - const files = new Map([[deb, Buffer.from('deb bundle')], [appimage, Buffer.from('appimage bundle')]]); - const env = { GITHUB_REF: 'refs/heads/main', GITHUB_REPOSITORY: 'egdev6/quorb', - RELEASE_VERSION: version, RELEASE_SOURCE_SHA: 'a'.repeat(40), RELEASE_ID: '42', - GH_TOKEN: 'fixture-token', BUNDLE_DIR: '/fake-bundles', - DEB_SHA256: hash(files.get(deb)), APPIMAGE_SHA256: hash(files.get(appimage)) }; + const files = new Map([ + [deb, Buffer.from('deb bundle')], + [appimage, Buffer.from('appimage bundle')], + ]); + const env = { + GITHUB_REF: 'refs/heads/main', + GITHUB_REPOSITORY: 'egdev6/quorb', + RELEASE_VERSION: version, + RELEASE_SOURCE_SHA: 'a'.repeat(40), + RELEASE_ID: '42', + GH_TOKEN: 'fixture-token', + BUNDLE_DIR: '/fake-bundles', + DEB_SHA256: hash(files.get(deb)), + APPIMAGE_SHA256: hash(files.get(appimage)), + }; const calls = []; const stored = new Map([['windows.exe', { id: 10, bytes: Buffer.from('untouched') }]]); let attempt = 0; - const options = { env, + const options = { + env, io: { readdirSync: () => [...files.keys()], lstatSync: (file) => ({ isFile: () => true, isSymbolicLink: () => false, size: files.get(path.basename(file)).length }), readFileSync: (file) => files.get(path.basename(file)), }, - preflight: async () => { calls.push('preflight'); return { releaseId: 42 }; }, + preflight: async () => { + calls.push('preflight'); + return { releaseId: 42 }; + }, fetch: async (url, request) => { calls.push([url, request]); if (request.method === 'DELETE') { @@ -65,12 +79,19 @@ test('rejects wrong, missing, extra, nonregular or modified artifact files befor (f) => f.files.delete(deb), (f) => f.files.set('unexpected.txt', Buffer.from('x')), (f) => f.files.set(deb, Buffer.from('changed')), - (f) => { f.env.DEB_SHA256 = 'x'.repeat(64); }, - (f) => { f.options.io.lstatSync = () => ({ isFile: () => false, isSymbolicLink: () => true, size: 1 }); }, - (f) => { f.files.set(appimage, Buffer.alloc(0)); }, + (f) => { + f.env.DEB_SHA256 = 'x'.repeat(64); + }, + (f) => { + f.options.io.lstatSync = () => ({ isFile: () => false, isSymbolicLink: () => true, size: 1 }); + }, + (f) => { + f.files.set(appimage, Buffer.alloc(0)); + }, ]; for (const change of scenarios) { - const f = fixture(); change(f); + const f = fixture(); + change(f); await assert.rejects(f.run()); assert.deepEqual(f.calls, []); assert.deepEqual([...f.stored.keys()], ['windows.exe']); @@ -83,7 +104,10 @@ test('revalidates release identity and uploads exactly four assets without overw assert.equal(f.calls[0], 'preflight'); const requests = f.calls.slice(1); assert.equal(requests.length, 4); - assert.deepEqual(requests.map(([url]) => new URL(url).searchParams.get('name')), names); + assert.deepEqual( + requests.map(([url]) => new URL(url).searchParams.get('name')), + names, + ); for (const [url, request] of requests) { assert.ok(url.startsWith('https://uploads.github.com/repos/egdev6/quorb/releases/42/assets?name=')); assert.equal(request.method, 'POST'); @@ -97,11 +121,20 @@ test('revalidates release identity and uploads exactly four assets without overw test('changed identity, collision or invalid release ID abort before writes', async () => { for (const change of [ - (f) => { f.options.preflight = async () => ({ releaseId: 43 }); }, - (f) => { f.options.preflight = async () => { throw new Error('Release already contains an asset'); }; }, - (f) => { f.env.RELEASE_ID = '42/../10'; }, + (f) => { + f.options.preflight = async () => ({ releaseId: 43 }); + }, + (f) => { + f.options.preflight = async () => { + throw new Error('Release already contains an asset'); + }; + }, + (f) => { + f.env.RELEASE_ID = '42/../10'; + }, ]) { - const f = fixture(); change(f); + const f = fixture(); + change(f); await assert.rejects(f.run()); assert.ok(!f.calls.some((call) => Array.isArray(call))); assert.deepEqual([...f.stored.keys()], ['windows.exe']); @@ -117,7 +150,10 @@ test('each partial upload failure rolls back every confirmed asset from this run return true; }); const deletions = f.calls.filter((call) => Array.isArray(call) && call[1].method === 'DELETE'); - assert.deepEqual(deletions.map(([url]) => Number(url.split('/').at(-1))), Array.from({ length: failAt - 1 }, (_, i) => 100 + failAt - 1 - i)); + assert.deepEqual( + deletions.map(([url]) => Number(url.split('/').at(-1))), + Array.from({ length: failAt - 1 }, (_, i) => 100 + failAt - 1 - i), + ); assert.deepEqual([...f.stored.keys()], ['windows.exe']); } }); @@ -137,7 +173,10 @@ test('a name claimed after preflight is never overwritten or deleted on upload f assert.deepEqual(f.stored.get(appimage), { id: 900, bytes: Buffer.from('concurrent upload') }); assert.deepEqual([...f.stored.keys()], ['windows.exe', appimage]); const deletes = f.calls.filter((call) => Array.isArray(call) && call[1].method === 'DELETE'); - assert.deepEqual(deletes.map(([url]) => Number(url.split('/').at(-1))), [102, 101]); + assert.deepEqual( + deletes.map(([url]) => Number(url.split('/').at(-1))), + [102, 101], + ); }); test('ambiguous responses roll back confirmed IDs only; failed cleanup is reported and attempted for all', async () => { diff --git a/scripts/linux-release-preflight.mjs b/scripts/linux-release-preflight.mjs index a49473ee..42b308f4 100644 --- a/scripts/linux-release-preflight.mjs +++ b/scripts/linux-release-preflight.mjs @@ -19,7 +19,9 @@ export function linuxAssetNames(version) { async function readJson(response, signal) { if (!response?.ok || response.status !== 200 || typeof response.body?.getReader !== 'function') throw new Error(); const reader = response.body.getReader(); - const cancel = () => { void reader.cancel().catch(() => {}); }; + const cancel = () => { + void reader.cancel().catch(() => {}); + }; signal.addEventListener('abort', cancel, { once: true }); let complete = false; try { @@ -45,37 +47,47 @@ async function readJson(response, signal) { } // No import-time I/O; Git and HTTP can be replaced by offline test fakes. -export async function preflightRelease({ root = projectRoot, env = process.env, - execFileSync = execute, fetch = globalThis.fetch } = {}) { - const { GITHUB_REF: ref, RELEASE_VERSION: version, RELEASE_SOURCE_SHA: sourceSha, - GITHUB_REPOSITORY, GH_TOKEN: token } = env; +export async function preflightRelease({ root = projectRoot, env = process.env, execFileSync = execute, fetch = globalThis.fetch } = {}) { + const { GITHUB_REF: ref, RELEASE_VERSION: version, RELEASE_SOURCE_SHA: sourceSha, GITHUB_REPOSITORY, GH_TOKEN: token } = env; validateReleaseInputs({ ref, version, sourceSha }); if (GITHUB_REPOSITORY !== repository || typeof token !== 'string' || !token.trim() || /[\r\n]/.test(token)) { throw new Error('Invalid release environment'); } - const git = (args) => execFileSync('git', args, { - cwd: root, encoding: 'utf8', timeout: 10_000, maxBuffer: 4 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'], - }); + const git = (args) => + execFileSync('git', args, { + cwd: root, + encoding: 'utf8', + timeout: 10_000, + maxBuffer: 4 * 1024 * 1024, + stdio: ['ignore', 'pipe', 'pipe'], + }); let failure = 'Release source_sha must be an ancestor of origin/main'; try { git(['merge-base', '--is-ancestor', sourceSha, 'origin/main']); failure = 'Release manifest versions or Tauri configuration do not match source_sha'; const at = (file) => git(['show', `${sourceSha}:${file}`]); - const versions = [packageJsonVersion(at('package.json')), + const versions = [ + packageJsonVersion(at('package.json')), ...packageLockVersions(at('package-lock.json')), cargoTomlVersion(at('src-tauri/Cargo.toml')), - cargoLockVersion(at('src-tauri/Cargo.lock'))]; + cargoLockVersion(at('src-tauri/Cargo.lock')), + ]; const tauri = JSON.parse(at('src-tauri/tauri.conf.json')); - if (versions.some((value) => value !== version) || tauri?.productName !== 'Quorb' || - !['../package.json', version].includes(tauri?.version)) throw new Error(); + if (versions.some((value) => value !== version) || tauri?.productName !== 'Quorb' || !['../package.json', version].includes(tauri?.version)) + throw new Error(); // Bound all pages, annotated-tag hops and response bodies by one deadline. const signal = AbortSignal.timeout(30_000); - const request = async (route) => readJson(await fetch(`https://api.github.com/repos/${repository}${route}`, { - method: 'GET', redirect: 'error', signal, - headers: { Accept: 'application/vnd.github+json', Authorization: `Bearer ${token}`, - 'X-GitHub-Api-Version': '2022-11-28' }, - }), signal); + const request = async (route) => + readJson( + await fetch(`https://api.github.com/repos/${repository}${route}`, { + method: 'GET', + redirect: 'error', + signal, + headers: { Accept: 'application/vnd.github+json', Authorization: `Bearer ${token}`, 'X-GitHub-Api-Version': '2022-11-28' }, + }), + signal, + ); const list = async (route) => { const entries = []; for (let page = 1; page <= 20; page++) { @@ -92,8 +104,7 @@ export async function preflightRelease({ root = projectRoot, env = process.env, if (releases.some((release) => typeof release.tag_name !== 'string')) throw new Error(); const found = releases.filter((release) => release.tag_name === `v${version}`); if (found.length === 0) throw new Error(`Release v${version} must already exist`); - if (found.length !== 1 || !Number.isSafeInteger(found[0].id) || found[0].id <= 0 || - typeof found[0].draft !== 'boolean') throw new Error(); + if (found.length !== 1 || !Number.isSafeInteger(found[0].id) || found[0].id <= 0 || typeof found[0].draft !== 'boolean') throw new Error(); const release = found[0]; failure = 'Release tag must point at source_sha'; @@ -121,8 +132,7 @@ export async function preflightRelease({ root = projectRoot, env = process.env, if (failure === 'Unable to verify release metadata' && error.message === `Release v${version} must already exist`) { throw new Error(error.message); } - if (failure === 'Unable to verify release assets' && - linuxAssetNames(version).some((name) => error.message === `Release already contains ${name}`)) { + if (failure === 'Unable to verify release assets' && linuxAssetNames(version).some((name) => error.message === `Release already contains ${name}`)) { throw new Error(error.message); } throw new Error(failure); @@ -130,6 +140,10 @@ export async function preflightRelease({ root = projectRoot, env = process.env, } if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { - try { console.log(JSON.stringify(await preflightRelease())); } - catch (error) { console.error(error.message); process.exitCode = 1; } + try { + console.log(JSON.stringify(await preflightRelease())); + } catch (error) { + console.error(error.message); + process.exitCode = 1; + } } diff --git a/scripts/linux-release-preflight.test.mjs b/scripts/linux-release-preflight.test.mjs index 760255d4..45871473 100644 --- a/scripts/linux-release-preflight.test.mjs +++ b/scripts/linux-release-preflight.test.mjs @@ -6,13 +6,11 @@ const sha = 'a'.repeat(40); const other = 'b'.repeat(40); const secret = 'SYNTHETIC_TOKEN_MARKER'; const version = '0.9.0'; -const names = [`Quorb_${version}_amd64.deb`, `Quorb_${version}_amd64.deb.sha256`, - `Quorb_${version}_amd64.AppImage`, `Quorb_${version}_amd64.AppImage.sha256`]; +const names = [`Quorb_${version}_amd64.deb`, `Quorb_${version}_amd64.deb.sha256`, `Quorb_${version}_amd64.AppImage`, `Quorb_${version}_amd64.AppImage.sha256`]; function fixture() { const calls = []; - const env = { GITHUB_REF: 'refs/heads/main', GITHUB_REPOSITORY: 'egdev6/quorb', - RELEASE_VERSION: version, RELEASE_SOURCE_SHA: sha, GH_TOKEN: secret }; + const env = { GITHUB_REF: 'refs/heads/main', GITHUB_REPOSITORY: 'egdev6/quorb', RELEASE_VERSION: version, RELEASE_SOURCE_SHA: sha, GH_TOKEN: secret }; const files = { 'package.json': JSON.stringify({ version }), 'package-lock.json': JSON.stringify({ version, packages: { '': { version } } }), @@ -26,7 +24,9 @@ function fixture() { [`/git/ref/tags/v${version}`]: { object: { type: 'commit', sha } }, '/releases/42/assets?per_page=100&page=1': [], }; - const options = { env, root: '/fake-root', + const options = { + env, + root: '/fake-root', execFileSync(command, args, settings) { calls.push(['git', command, args, settings]); if (args[0] === 'merge-base') return ''; @@ -59,7 +59,10 @@ test('accepts exact ancestor, all release manifests, config and existing tag wit assert.deepEqual(await f.run(), { sourceSha: sha, version, releaseId: 42 }); const git = f.calls.filter(([kind]) => kind === 'git'); assert.deepEqual(git[0][2], ['merge-base', '--is-ancestor', sha, 'origin/main']); - assert.deepEqual(git.slice(1).map(([, , args]) => args[1]), Object.keys(f.files).map((file) => `${sha}:${file}`)); + assert.deepEqual( + git.slice(1).map(([, , args]) => args[1]), + Object.keys(f.files).map((file) => `${sha}:${file}`), + ); for (const [, , , settings] of git) assert.equal(settings.cwd, '/fake-root'); for (const [, url, settings] of f.calls.filter(([kind]) => kind === 'fetch')) { assert.ok(url.startsWith('https://api.github.com/repos/egdev6/quorb/')); @@ -72,20 +75,35 @@ test('accepts exact ancestor, all release manifests, config and existing tag wit test('rejects invalid ref, version, SHA, repository and token before any I/O', async () => { const cases = [ ['GITHUB_REF', 'refs/heads/feature', 'Release ref must be refs/heads/main'], - ...[undefined, '', 'v0.9.0', '00.9.0', '0.9.0-rc.1', '0.9.0+build', '0.9.0\n', '../0.9.0'].map((v) => ['RELEASE_VERSION', v, 'Release version must be stable SemVer']), - ...[undefined, '', 'A'.repeat(40), 'g'.repeat(40), `${sha}\n`, sha.slice(1)].map((v) => ['RELEASE_SOURCE_SHA', v, 'Release source_sha must be 40 lowercase hex characters']), + ...[undefined, '', 'v0.9.0', '00.9.0', '0.9.0-rc.1', '0.9.0+build', '0.9.0\n', '../0.9.0'].map((v) => [ + 'RELEASE_VERSION', + v, + 'Release version must be stable SemVer', + ]), + ...[undefined, '', 'A'.repeat(40), 'g'.repeat(40), `${sha}\n`, sha.slice(1)].map((v) => [ + 'RELEASE_SOURCE_SHA', + v, + 'Release source_sha must be 40 lowercase hex characters', + ]), ['GITHUB_REPOSITORY', 'other/quorb', 'Invalid release environment'], - ['GH_TOKEN', '', 'Invalid release environment'], ['GH_TOKEN', `${secret}\n`, 'Invalid release environment'], + ['GH_TOKEN', '', 'Invalid release environment'], + ['GH_TOKEN', `${secret}\n`, 'Invalid release environment'], ]; for (const [key, value, message] of cases) { - const f = fixture(); f.env[key] = value; - await rejects(f, message); assert.deepEqual(f.calls, []); + const f = fixture(); + f.env[key] = value; + await rejects(f, message); + assert.deepEqual(f.calls, []); } }); test('rejects non-ancestor and every mismatching or missing version source before HTTP', async () => { const f = fixture(); - await rejects(f, 'Release source_sha must be an ancestor of origin/main', { execFileSync: () => { throw new Error(secret); } }); + await rejects(f, 'Release source_sha must be an ancestor of origin/main', { + execFileSync: () => { + throw new Error(secret); + }, + }); for (const [file, text] of [ ['package.json', '{"version":"0.8.0"}'], ['package-lock.json', '{"version":"0.9.0","packages":{"":{"version":"0.8.0"}}}'], @@ -95,25 +113,31 @@ test('rejects non-ancestor and every mismatching or missing version source befor ['src-tauri/tauri.conf.json', '{"productName":"Quorb","version":"0.8.0"}'], ['package.json', '{'], ]) { - const g = fixture(); g.files[file] = text; + const g = fixture(); + g.files[file] = text; await rejects(g, 'Release manifest versions or Tauri configuration do not match source_sha'); assert.ok(!g.calls.some(([kind]) => kind === 'fetch')); } }); test('requires one existing release and its actual matching tag, including drafts', async () => { - const missing = fixture(); missing.routes['/releases?per_page=100&page=1'] = []; + const missing = fixture(); + missing.routes['/releases?per_page=100&page=1'] = []; await rejects(missing, `Release v${version} must already exist`); - const duplicate = fixture(); duplicate.routes['/releases?per_page=100&page=1'] = [duplicate.release, duplicate.release]; + const duplicate = fixture(); + duplicate.routes['/releases?per_page=100&page=1'] = [duplicate.release, duplicate.release]; await rejects(duplicate, 'Unable to verify release metadata'); for (const draft of [true, false]) { - const f = fixture(); f.release.draft = draft; + const f = fixture(); + f.release.draft = draft; f.routes[`/git/ref/tags/v${version}`] = new Response('', { status: 404 }); await rejects(f, 'Release tag must point at source_sha'); } - const mismatch = fixture(); mismatch.routes[`/git/ref/tags/v${version}`].object.sha = other; + const mismatch = fixture(); + mismatch.routes[`/git/ref/tags/v${version}`].object.sha = other; await rejects(mismatch, 'Release tag must point at source_sha'); - const draft = fixture(); draft.release.draft = true; + const draft = fixture(); + draft.release.draft = true; assert.equal((await draft.run()).releaseId, 42); }); @@ -123,7 +147,8 @@ test('resolves annotated tags and rejects cycles and malformed objects', async ( f.routes[`/git/tags/${other}`] = { object: { type: 'commit', sha } }; assert.equal((await f.run()).releaseId, 42); for (const object of [null, {}, { type: 'tree', sha }, { type: 'tag', sha: other }]) { - const g = fixture(); g.routes[`/git/ref/tags/v${version}`] = { object }; + const g = fixture(); + g.routes[`/git/ref/tags/v${version}`] = { object }; g.routes[`/git/tags/${other}`] = { object: { type: 'tag', sha: other } }; await rejects(g, 'Release tag must point at source_sha'); } @@ -145,10 +170,16 @@ test('checks all four asset names across pages and leaves unrelated release asse test('fails closed on malformed HTTP, pagination and secret-bearing errors', async () => { for (const value of [new Response('no', { status: 403 }), new Response('{'), new Response(' '.repeat(1024 * 1024 + 1)), {}]) { - const f = fixture(); f.routes['/releases?per_page=100&page=1'] = value; + const f = fixture(); + f.routes['/releases?per_page=100&page=1'] = value; await rejects(f, 'Unable to verify release metadata'); } - await rejects(fixture(), 'Unable to verify release metadata', { fetch: async () => { throw new Error(secret); } }); - const f = fixture(); f.routes['/releases/42/assets?per_page=100&page=1'] = [null]; + await rejects(fixture(), 'Unable to verify release metadata', { + fetch: async () => { + throw new Error(secret); + }, + }); + const f = fixture(); + f.routes['/releases/42/assets?per_page=100&page=1'] = [null]; await rejects(f, 'Unable to verify release assets'); }); diff --git a/scripts/linux-release-workflow.test.mjs b/scripts/linux-release-workflow.test.mjs index 26c3a148..70e776a5 100644 --- a/scripts/linux-release-workflow.test.mjs +++ b/scripts/linux-release-workflow.test.mjs @@ -10,8 +10,14 @@ test('manual dispatch accepts only the required version and source SHA', () => { const text = workflow(); const trigger = text.split('\non:\n')[1]?.split('\npermissions:\n')[0]; assert.ok(trigger); - assert.deepEqual([...trigger.matchAll(/^ ([\w-]+):/gm)].map((m) => m[1]), ['workflow_dispatch']); - assert.deepEqual([...trigger.matchAll(/^ ([\w-]+):/gm)].map((m) => m[1]), ['version', 'source_sha']); + assert.deepEqual( + [...trigger.matchAll(/^ ([\w-]+):/gm)].map((m) => m[1]), + ['workflow_dispatch'], + ); + assert.deepEqual( + [...trigger.matchAll(/^ ([\w-]+):/gm)].map((m) => m[1]), + ['version', 'source_sha'], + ); for (const name of ['version', 'source_sha']) { assert.match(trigger, new RegExp(` ${name}:\\n(?: [^\\n]*\\n)*? required: true\\n(?: [^\\n]*\\n)*? type: string`)); } @@ -55,7 +61,20 @@ test('validated exact source is built and clean-container verified before same-r assert.match(build, /ref: \$\{\{ needs\.preflight\.outputs\.source_sha \}\}\n\s+path: source/); assert.match(build, /working-directory: source\n\s+run: npm ci/); assert.match(build, /working-directory: source\n\s+run: npm run app:build/); - for (const dependency of ['pkg-config', 'libdbus-1-dev', 'libwebkit2gtk-4.1-dev', 'libxdo-dev', 'libssl-dev', 'libayatana-appindicator3-dev', 'librsvg2-dev', 'libsecret-1-dev', 'libfuse2', 'xvfb', 'dbus-x11']) assert.ok(build.includes(dependency), dependency); + for (const dependency of [ + 'pkg-config', + 'libdbus-1-dev', + 'libwebkit2gtk-4.1-dev', + 'libxdo-dev', + 'libssl-dev', + 'libayatana-appindicator3-dev', + 'librsvg2-dev', + 'libsecret-1-dev', + 'libfuse2', + 'xvfb', + 'dbus-x11', + ]) + assert.ok(build.includes(dependency), dependency); assert.match(build, /source\/src-tauri\/target\/release\/bundle\/deb\/Quorb_\$\{RELEASE_VERSION\}_amd64\.deb/); assert.match(build, /source\/src-tauri\/target\/release\/bundle\/appimage\/Quorb_\$\{RELEASE_VERSION\}_amd64\.AppImage/); assert.match(build, /docker build -t quorb-build-verify \.testcontainer/); @@ -81,7 +100,21 @@ test('Tauri naming configuration and npm test wiring agree with the release cont test('Linux release documentation explains the operator and user caveats', () => { const text = read('docs/release-linux.md'); - for (const expression of [/workflow_dispatch|Actions/i, /\bversion\b/, /\bsource_sha\b/, /\.deb/, /\.AppImage/, /\.sha256/, /main/, /manual/i, /latest\.json/, /libfuse2/i, /desktop/i, /recommend/i]) assert.match(text, expression); + for (const expression of [ + /workflow_dispatch|Actions/i, + /\bversion\b/, + /\bsource_sha\b/, + /\.deb/, + /\.AppImage/, + /\.sha256/, + /main/, + /manual/i, + /latest\.json/, + /libfuse2/i, + /desktop/i, + /recommend/i, + ]) + assert.match(text, expression); }); test('job-level env uses only contexts GitHub allows there', () => { diff --git a/scripts/macos-ci.test.mjs b/scripts/macos-ci.test.mjs index 2feab7da..538e11a2 100644 --- a/scripts/macos-ci.test.mjs +++ b/scripts/macos-ci.test.mjs @@ -10,7 +10,9 @@ function assertWorkflowContract(workflow, active, windows) { assert.equal(active, workflow); const parts = workflow.split(' steps:\n'); assert.equal(parts.length, 2); - assert.equal(parts[0], `name: macOS CI + assert.equal( + parts[0], + `name: macOS CI on: pull_request: @@ -30,8 +32,12 @@ jobs: name: Tests and bundle (macOS ARM64) runs-on: macos-15 timeout-minutes: 30 -`); - const steps = parts[1].split(/ - name: /).slice(1).map((step) => step.trimEnd()); +`, + ); + const steps = parts[1] + .split(/ - name: /) + .slice(1) + .map((step) => step.trimEnd()); const action = (name, ref, options) => `${name}\n uses: ${ref}\n with:\n${options}`; const refs = windows.match(/uses: (\S+)/g).map((line) => line.slice(6)); assert.deepEqual(refs, [ diff --git a/scripts/macos-notary-artifact-fixtures.mjs b/scripts/macos-notary-artifact-fixtures.mjs index 9e0e3fdc..52137f4a 100644 --- a/scripts/macos-notary-artifact-fixtures.mjs +++ b/scripts/macos-notary-artifact-fixtures.mjs @@ -3,14 +3,21 @@ import { execFileSync } from 'node:child_process'; import { hash } from './macos-notary-checkpoint.mjs'; export function zipFiles(files) { - return execFileSync('python3', ['-c', `import io,json,zipfile,sys,base64 + return execFileSync( + 'python3', + [ + '-c', + `import io,json,zipfile,sys,base64 b=io.BytesIO() with zipfile.ZipFile(b,'w',compression=zipfile.ZIP_STORED) as z: for name,value in json.loads(sys.stdin.read()).items(): z.writestr(name,base64.b64decode(value)) -sys.stdout.buffer.write(b.getvalue())`], { - input: JSON.stringify(Object.fromEntries(Object.entries(files).map(([name, data]) => [name, Buffer.from(data).toString('base64')]))), - stdio: ['pipe', 'pipe', 'pipe'], - }); +sys.stdout.buffer.write(b.getvalue())`, + ], + { + input: JSON.stringify(Object.fromEntries(Object.entries(files).map(([name, data]) => [name, Buffer.from(data).toString('base64')]))), + stdio: ['pipe', 'pipe', 'pipe'], + }, + ); } export function fileFixture(entries = []) { @@ -19,8 +26,16 @@ export function fileFixture(entries = []) { const files = new Map(entries.map(([name, bytes]) => [key(name), bytes])); const io = { readFileSync: (name) => files.get(key(name)), - mkdirSync: (name) => { name = key(name); if (files.has(name)) throw new Error('exists'); files.set(name, null); }, - writeFileSync: (name, bytes, opts) => { name = key(name); if (files.has(name) || opts.flag !== 'wx') throw new Error('overwrite'); files.set(name, bytes); }, + mkdirSync: (name) => { + name = key(name); + if (files.has(name)) throw new Error('exists'); + files.set(name, null); + }, + writeFileSync: (name, bytes, opts) => { + name = key(name); + if (files.has(name) || opts.flag !== 'wx') throw new Error('overwrite'); + files.set(name, bytes); + }, }; return { files, io }; } @@ -29,27 +44,72 @@ export function producerFixture() { const workflowSha = 'a'.repeat(40); const sourceSha = 'b'.repeat(40); const submissionId = '12345678-1234-1234-1234-123456789abc'; - const trusted = { repository: 'egdev6/quorb', workflowPath: '.github/workflows/macos-release.yml', workflowSha, sourceSha, version: '0.8.0', releaseId: '42', runId: '123', runAttempt: '2' }; + const trusted = { + repository: 'egdev6/quorb', + workflowPath: '.github/workflows/macos-release.yml', + workflowSha, + sourceSha, + version: '0.8.0', + releaseId: '42', + runId: '123', + runAttempt: '2', + }; const bytes = Buffer.from('synthetic signed DMG bytes'); const manifest = { schema: 1, ...trusted, dmgName: 'Quorb_0.8.0_aarch64.dmg', size: bytes.length, sha256: hash(bytes) }; - const run = { id: 123, run_attempt: 2, repository: { id: 10, full_name: 'egdev6/quorb' }, head_repository: { id: 10, full_name: 'egdev6/quorb' }, - head_branch: 'main', event: 'workflow_dispatch', path: trusted.workflowPath, workflow_id: 99, head_sha: workflowSha, status: 'completed', conclusion: 'cancelled', - run_started_at: '2026-01-01T00:00:00Z', updated_at: '2026-01-01T00:05:00Z' }; + const run = { + id: 123, + run_attempt: 2, + repository: { id: 10, full_name: 'egdev6/quorb' }, + head_repository: { id: 10, full_name: 'egdev6/quorb' }, + head_branch: 'main', + event: 'workflow_dispatch', + path: trusted.workflowPath, + workflow_id: 99, + head_sha: workflowSha, + status: 'completed', + conclusion: 'cancelled', + run_started_at: '2026-01-01T00:00:00Z', + updated_at: '2026-01-01T00:05:00Z', + }; const archives = new Map(); const artifact = (name, id, files) => { - const zip = zipFiles(files); archives.set(id, zip); - return { id, name, expired: false, digest: `sha256:${hash(zip)}`, size_in_bytes: zip.length, - created_at: '2026-01-01T00:01:00Z', expires_at: '2099-01-01T00:00:00Z', - workflow_run: { id: 123, repository_id: 10, head_repository_id: 10, head_branch: 'main', head_sha: workflowSha } }; + const zip = zipFiles(files); + archives.set(id, zip); + return { + id, + name, + expired: false, + digest: `sha256:${hash(zip)}`, + size_in_bytes: zip.length, + created_at: '2026-01-01T00:01:00Z', + expires_at: '2099-01-01T00:00:00Z', + workflow_run: { id: 123, repository_id: 10, head_repository_id: 10, head_branch: 'main', head_sha: workflowSha }, + }; }; const checkpoint = artifact('macos-notary-checkpoint-123-2', 456, { 'manifest.json': JSON.stringify(manifest), [manifest.dmgName]: bytes }); - const receipt = { schema: 1, ...trusted, checkpointArtifactId: '456', checkpointArtifactDigest: checkpoint.digest.slice(7), submissionId, dmgSha256: manifest.sha256 }; + const receipt = { + schema: 1, + ...trusted, + checkpointArtifactId: '456', + checkpointArtifactDigest: checkpoint.digest.slice(7), + submissionId, + dmgSha256: manifest.sha256, + }; const receiptArtifact = artifact('macos-notary-receipt-123-2', 457, { 'receipt.json': JSON.stringify(receipt) }); const artifacts = [checkpoint, receiptArtifact]; const { files, io } = fileFixture([[trusted.workflowPath, 'reviewed workflow bytes']]); const calls = []; - const env = { GITHUB_REF: 'refs/heads/main', GITHUB_REPOSITORY: trusted.repository, GITHUB_SHA: 'd'.repeat(40), - RELEASE_VERSION: trusted.version, RELEASE_SOURCE_SHA: sourceSha, RELEASE_ID: '42', SOURCE_RUN_ID: '123', SOURCE_RUN_ATTEMPT: '2', GH_TOKEN: 'synthetic' }; + const env = { + GITHUB_REF: 'refs/heads/main', + GITHUB_REPOSITORY: trusted.repository, + GITHUB_SHA: 'd'.repeat(40), + RELEASE_VERSION: trusted.version, + RELEASE_SOURCE_SHA: sourceSha, + RELEASE_ID: '42', + SOURCE_RUN_ID: '123', + SOURCE_RUN_ATTEMPT: '2', + GH_TOKEN: 'synthetic', + }; const exec = (command, args) => { calls.push([command, args]); if (command !== 'git') throw new Error('Unexpected command'); diff --git a/scripts/macos-notary-artifact.mjs b/scripts/macos-notary-artifact.mjs index afe746a3..9e70f8ef 100644 --- a/scripts/macos-notary-artifact.mjs +++ b/scripts/macos-notary-artifact.mjs @@ -3,16 +3,32 @@ import { hash, positiveId, hex, MAX_DMG, repository, workflowPath } from './maco const API = `https://api.github.com/repos/${repository}`; const MAX_ZIP = MAX_DMG + 1024 * 1024; -const timestamp = (value) => typeof value === 'string' && Number.isFinite(Date.parse(value)) ? Date.parse(value) : NaN; +const timestamp = (value) => (typeof value === 'string' && Number.isFinite(Date.parse(value)) ? Date.parse(value) : NaN); export function validateRun(run, workflow, { runId, runAttempt }) { - if (!positiveId(runId) || !positiveId(runAttempt) || run?.id !== Number(runId) || run.run_attempt !== Number(runAttempt) || - !Number.isSafeInteger(workflow?.id) || workflow.id <= 0 || workflow.path !== workflowPath || - run.workflow_id !== workflow.id || run.path !== workflowPath || run.event !== 'workflow_dispatch' || - run.head_branch !== 'main' || run.repository?.full_name !== repository || run.head_repository?.full_name !== repository || - !Number.isSafeInteger(run.repository?.id) || run.repository.id <= 0 || run.repository.id !== run.head_repository?.id || - !hex(run.head_sha, 40) || run.status !== 'completed' || !Number.isFinite(timestamp(run.run_started_at)) || - !Number.isFinite(timestamp(run.updated_at)) || timestamp(run.updated_at) < timestamp(run.run_started_at)) { + if ( + !positiveId(runId) || + !positiveId(runAttempt) || + run?.id !== Number(runId) || + run.run_attempt !== Number(runAttempt) || + !Number.isSafeInteger(workflow?.id) || + workflow.id <= 0 || + workflow.path !== workflowPath || + run.workflow_id !== workflow.id || + run.path !== workflowPath || + run.event !== 'workflow_dispatch' || + run.head_branch !== 'main' || + run.repository?.full_name !== repository || + run.head_repository?.full_name !== repository || + !Number.isSafeInteger(run.repository?.id) || + run.repository.id <= 0 || + run.repository.id !== run.head_repository?.id || + !hex(run.head_sha, 40) || + run.status !== 'completed' || + !Number.isFinite(timestamp(run.run_started_at)) || + !Number.isFinite(timestamp(run.updated_at)) || + timestamp(run.updated_at) < timestamp(run.run_started_at) + ) { throw new Error('Untrusted producer run/workflow/attempt'); } // Deliberately not checking conclusion=success: cancellation after checkpoint @@ -22,13 +38,27 @@ export function validateRun(run, workflow, { runId, runAttempt }) { export function validateArtifact(artifact, run, name, { now = Date.now(), end = timestamp(run.updated_at) } = {}) { const linked = artifact?.workflow_run; - if (!Number.isSafeInteger(artifact?.id) || artifact.id <= 0 || artifact.name !== name || artifact.expired !== false || - !/^sha256:[0-9a-f]{64}$/.test(artifact.digest ?? '') || !Number.isSafeInteger(artifact.size_in_bytes) || - artifact.size_in_bytes < 1 || artifact.size_in_bytes > MAX_ZIP || timestamp(artifact.expires_at) <= now || - !Number.isFinite(timestamp(artifact.expires_at)) || !Number.isFinite(timestamp(artifact.created_at)) || - timestamp(artifact.created_at) < timestamp(run.run_started_at) || timestamp(artifact.created_at) > end || - linked?.id !== run.id || linked.repository_id !== run.repository.id || linked.head_repository_id !== run.repository.id || - linked.head_sha !== run.head_sha || linked.head_branch !== 'main') throw new Error('Untrusted artifact metadata/attempt/expiry'); + if ( + !Number.isSafeInteger(artifact?.id) || + artifact.id <= 0 || + artifact.name !== name || + artifact.expired !== false || + !/^sha256:[0-9a-f]{64}$/.test(artifact.digest ?? '') || + !Number.isSafeInteger(artifact.size_in_bytes) || + artifact.size_in_bytes < 1 || + artifact.size_in_bytes > MAX_ZIP || + timestamp(artifact.expires_at) <= now || + !Number.isFinite(timestamp(artifact.expires_at)) || + !Number.isFinite(timestamp(artifact.created_at)) || + timestamp(artifact.created_at) < timestamp(run.run_started_at) || + timestamp(artifact.created_at) > end || + linked?.id !== run.id || + linked.repository_id !== run.repository.id || + linked.head_repository_id !== run.repository.id || + linked.head_sha !== run.head_sha || + linked.head_branch !== 'main' + ) + throw new Error('Untrusted artifact metadata/attempt/expiry'); return artifact; } @@ -60,7 +90,10 @@ async function boundedBytes(response, limit) { chunks.push(value); } return Buffer.concat(chunks, size); - } finally { await reader.cancel().catch(() => {}); reader.releaseLock(); } + } finally { + await reader.cancel().catch(() => {}); + reader.releaseLock(); + } } export function githubClient({ token, fetch = globalThis.fetch } = {}) { @@ -74,7 +107,9 @@ export function githubClient({ token, fetch = globalThis.fetch } = {}) { try { const response = await fetch(API + route, { headers, redirect: 'error', signal }); return JSON.parse((await boundedBytes(response, 1024 * 1024)).toString('utf8')); - } catch { throw new Error('Unable to read trusted GitHub Actions metadata'); } + } catch { + throw new Error('Unable to read trusted GitHub Actions metadata'); + } }, async artifacts(runId) { if (!positiveId(runId)) throw new Error('Invalid run ID'); @@ -91,21 +126,39 @@ export function githubClient({ token, fetch = globalThis.fetch } = {}) { } export async function downloadZip(artifact, { token, fetch = globalThis.fetch } = {}) { - if (!Number.isSafeInteger(artifact?.id) || artifact.id <= 0 || !/^sha256:[0-9a-f]{64}$/.test(artifact.digest ?? '') || - !Number.isSafeInteger(artifact.size_in_bytes) || artifact.size_in_bytes < 1 || artifact.size_in_bytes > MAX_ZIP || - typeof token !== 'string' || !token.trim() || /[\r\n]/.test(token)) throw new Error('Invalid artifact download context'); + if ( + !Number.isSafeInteger(artifact?.id) || + artifact.id <= 0 || + !/^sha256:[0-9a-f]{64}$/.test(artifact.digest ?? '') || + !Number.isSafeInteger(artifact.size_in_bytes) || + artifact.size_in_bytes < 1 || + artifact.size_in_bytes > MAX_ZIP || + typeof token !== 'string' || + !token.trim() || + /[\r\n]/.test(token) + ) + throw new Error('Invalid artifact download context'); try { const signal = AbortSignal.timeout(120_000); let response = await fetch(`${API}/actions/artifacts/${artifact.id}/zip`, { - method: 'GET', redirect: 'manual', signal, + method: 'GET', + redirect: 'manual', + signal, headers: { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' }, }); if (response.status === 302) { const location = new URL(response.headers.get('location')); // GitHub currently redirects artifact archives to Azure blob storage. // No alternate user endpoints and no credentials forwarded to blob hosts. - if (location.protocol !== 'https:' || location.username || location.password || location.port || location.hash || - !/^[a-z0-9]+\.blob\.core\.windows\.net$/.test(location.hostname)) throw new Error(); + if ( + location.protocol !== 'https:' || + location.username || + location.password || + location.port || + location.hash || + !/^[a-z0-9]+\.blob\.core\.windows\.net$/.test(location.hostname) + ) + throw new Error(); await response.body?.cancel(); response = await fetch(location.href, { method: 'GET', redirect: 'error', signal }); } @@ -155,15 +208,29 @@ with zipfile.ZipFile(io.BytesIO(raw)) as archive: export function extractZip(bytes, limits, run = execFileSync) { try { - if (!Buffer.isBuffer(bytes) || bytes.length > MAX_ZIP || !Object.keys(limits).length || - Object.entries(limits).some(([name, size]) => !/^[A-Za-z0-9_.-]+$/.test(name) || !Number.isSafeInteger(size) || size < 1 || size > MAX_DMG)) throw new Error(); - const result = JSON.parse(run('python3', ['-c', ZIP_PARSER, JSON.stringify(limits)], { - input: bytes, timeout: 120_000, maxBuffer: MAX_ZIP * 2, stdio: ['pipe', 'pipe', 'pipe'], - }).toString('utf8')); + if ( + !Buffer.isBuffer(bytes) || + bytes.length > MAX_ZIP || + !Object.keys(limits).length || + Object.entries(limits).some(([name, size]) => !/^[A-Za-z0-9_.-]+$/.test(name) || !Number.isSafeInteger(size) || size < 1 || size > MAX_DMG) + ) + throw new Error(); + const result = JSON.parse( + run('python3', ['-c', ZIP_PARSER, JSON.stringify(limits)], { + input: bytes, + timeout: 120_000, + maxBuffer: MAX_ZIP * 2, + stdio: ['pipe', 'pipe', 'pipe'], + }).toString('utf8'), + ); if (Object.keys(result).sort().join(',') !== Object.keys(limits).sort().join(',')) throw new Error(); - return new Map(Object.entries(result).map(([name, data]) => { - if (typeof data !== 'string' || Buffer.byteLength(data, 'base64') > limits[name]) throw new Error(); - return [name, Buffer.from(data, 'base64')]; - })); - } catch { throw new Error('Unsafe or invalid artifact ZIP'); } + return new Map( + Object.entries(result).map(([name, data]) => { + if (typeof data !== 'string' || Buffer.byteLength(data, 'base64') > limits[name]) throw new Error(); + return [name, Buffer.from(data, 'base64')]; + }), + ); + } catch { + throw new Error('Unsafe or invalid artifact ZIP'); + } } diff --git a/scripts/macos-notary-artifact.test.mjs b/scripts/macos-notary-artifact.test.mjs index b31a18ad..c8fffda7 100644 --- a/scripts/macos-notary-artifact.test.mjs +++ b/scripts/macos-notary-artifact.test.mjs @@ -5,26 +5,62 @@ import { createHash } from 'node:crypto'; import { validateRun, selectArtifacts, extractZip, downloadZip, githubClient } from './macos-notary-artifact.mjs'; const workflow = { id: 99, path: '.github/workflows/macos-release.yml' }; -const run = { id: 123, run_attempt: 2, repository: { id: 10, full_name: 'egdev6/quorb' }, head_repository: { id: 10, full_name: 'egdev6/quorb' }, - head_branch: 'main', event: 'workflow_dispatch', path: workflow.path, workflow_id: 99, head_sha: 'a'.repeat(40), status: 'completed', conclusion: 'cancelled', - run_started_at: '2026-01-01T00:00:00Z', updated_at: '2026-01-01T00:05:00Z' }; -const artifact = (name, id) => ({ id, name, expired: false, digest: `sha256:${'c'.repeat(64)}`, size_in_bytes: 200, - created_at: '2026-01-01T00:01:00Z', expires_at: '2099-01-01T00:00:00Z', - workflow_run: { id: 123, repository_id: 10, head_repository_id: 10, head_branch: 'main', head_sha: run.head_sha } }); +const run = { + id: 123, + run_attempt: 2, + repository: { id: 10, full_name: 'egdev6/quorb' }, + head_repository: { id: 10, full_name: 'egdev6/quorb' }, + head_branch: 'main', + event: 'workflow_dispatch', + path: workflow.path, + workflow_id: 99, + head_sha: 'a'.repeat(40), + status: 'completed', + conclusion: 'cancelled', + run_started_at: '2026-01-01T00:00:00Z', + updated_at: '2026-01-01T00:05:00Z', +}; +const artifact = (name, id) => ({ + id, + name, + expired: false, + digest: `sha256:${'c'.repeat(64)}`, + size_in_bytes: 200, + created_at: '2026-01-01T00:01:00Z', + expires_at: '2099-01-01T00:00:00Z', + workflow_run: { id: 123, repository_id: 10, head_repository_id: 10, head_branch: 'main', head_sha: run.head_sha }, +}); const checkpoint = artifact('macos-notary-checkpoint-123-2', 1); const receipt = artifact('macos-notary-receipt-123-2', 2); test('canceled same-repo producer is recoverable, but provenance and attempts are strict', () => { assert.doesNotThrow(() => validateRun(run, workflow, { runId: '123', runAttempt: '2' })); - for (const patch of [{ id: 124 }, { run_attempt: 1 }, { head_repository: { id: 11, full_name: 'fork/quorb' } }, { repository: { id: 11, full_name: 'other/quorb' } }, - { head_branch: 'feature' }, { event: 'push' }, { path: 'other.yml' }, { workflow_id: 100 }, { head_sha: '--help' }, { status: 'in_progress' }]) { + for (const patch of [ + { id: 124 }, + { run_attempt: 1 }, + { head_repository: { id: 11, full_name: 'fork/quorb' } }, + { repository: { id: 11, full_name: 'other/quorb' } }, + { head_branch: 'feature' }, + { event: 'push' }, + { path: 'other.yml' }, + { workflow_id: 100 }, + { head_sha: '--help' }, + { status: 'in_progress' }, + ]) { assert.throws(() => validateRun({ ...run, ...patch }, workflow, { runId: '123', runAttempt: '2' }), /producer/i); } assert.deepEqual(selectArtifacts([checkpoint, receipt], run), { checkpoint, receipt }); assert.deepEqual(selectArtifacts([checkpoint], run, true), { checkpoint, receipt: null }); assert.throws(() => selectArtifacts([checkpoint], run), /receipt/i); - for (const patch of [{ expired: true }, { expires_at: '2020-01-01' }, { created_at: '2025-12-31' }, { digest: null }, { name: 'macos-notary-checkpoint-123-1' }, - { workflow_run: { ...checkpoint.workflow_run, id: 999 } }, { workflow_run: { ...checkpoint.workflow_run, head_repository_id: 11 } }]) { + for (const patch of [ + { expired: true }, + { expires_at: '2020-01-01' }, + { created_at: '2025-12-31' }, + { digest: null }, + { name: 'macos-notary-checkpoint-123-1' }, + { workflow_run: { ...checkpoint.workflow_run, id: 999 } }, + { workflow_run: { ...checkpoint.workflow_run, head_repository_id: 11 } }, + ]) { assert.throws(() => selectArtifacts([{ ...checkpoint, ...patch }, receipt], run), /artifact|checkpoint/i); } assert.throws(() => selectArtifacts([checkpoint, checkpoint, receipt], run), /duplicate/i); @@ -32,17 +68,27 @@ test('canceled same-repo producer is recoverable, but provenance and attempts ar }); function zip(entries) { - return execFileSync('python3', ['-c', `import io,json,zipfile,sys,base64 + return execFileSync( + 'python3', + [ + '-c', + `import io,json,zipfile,sys,base64 b=io.BytesIO() with zipfile.ZipFile(b,'w') as z: for e in json.loads(sys.stdin.read()): i=zipfile.ZipInfo(e['name']); i.external_attr=e.get('mode',0)<<16 z.writestr(i,e.get('data','').encode()) -sys.stdout.buffer.write(b.getvalue())`], { input: JSON.stringify(entries) }); +sys.stdout.buffer.write(b.getvalue())`, + ], + { input: JSON.stringify(entries) }, + ); } test('real in-memory Python ZIP parser rejects extras, traversal, symlinks, duplicates and oversize before extraction', () => { - const good = zip([{ name: 'manifest.json', data: '{}' }, { name: 'Quorb.dmg', data: 'DMG' }]); + const good = zip([ + { name: 'manifest.json', data: '{}' }, + { name: 'Quorb.dmg', data: 'DMG' }, + ]); assert.equal(extractZip(good, { 'manifest.json': 65536, 'Quorb.dmg': 100 }).get('Quorb.dmg').toString(), 'DMG'); for (const entries of [ [{ name: '../Quorb.dmg' }, { name: 'manifest.json' }], @@ -50,14 +96,19 @@ test('real in-memory Python ZIP parser rejects extras, traversal, symlinks, dupl [{ name: 'Quorb.dmg' }, { name: 'manifest.json' }, { name: 'extra' }], [{ name: 'Quorb.dmg' }, { name: 'Quorb.dmg' }], [{ name: 'Quorb.dmg', data: 'too large' }, { name: 'manifest.json' }], - ]) assert.throws(() => extractZip(zip(entries), { 'manifest.json': 65536, 'Quorb.dmg': 3 }), /ZIP/); + ]) + assert.throws(() => extractZip(zip(entries), { 'manifest.json': 65536, 'Quorb.dmg': 3 }), /ZIP/); assert.throws(() => extractZip(Buffer.from('not zip'), { 'manifest.json': 100 }), /ZIP/); - const bomb = execFileSync('python3', ['-c', `import io,zipfile,sys + const bomb = execFileSync('python3', [ + '-c', + `import io,zipfile,sys b=io.BytesIO() with zipfile.ZipFile(b,'w',compression=zipfile.ZIP_DEFLATED) as z: z.writestr('Quorb.dmg',b'0'*1000000) -sys.stdout.buffer.write(b.getvalue())`]); +sys.stdout.buffer.write(b.getvalue())`, + ]); assert.throws(() => extractZip(bomb, { 'Quorb.dmg': 1000000 }), /ZIP/); - const crc = Buffer.from(good); crc[40] ^= 0xff; + const crc = Buffer.from(good); + crc[40] ^= 0xff; assert.throws(() => extractZip(crc, { 'manifest.json': 65536, 'Quorb.dmg': 100 }), /ZIP/); }); @@ -74,7 +125,8 @@ test('authenticated API raw ZIP digest is fatal before parsing; redirects never const calls = []; const fetch = async (url, options) => { calls.push([url, options]); - if (calls.length === 1) return new Response(null, { status: 302, headers: { location: 'https://productionresultssa0.blob.core.windows.net/actions/a?sig=synthetic' } }); + if (calls.length === 1) + return new Response(null, { status: 302, headers: { location: 'https://productionresultssa0.blob.core.windows.net/actions/a?sig=synthetic' } }); return new Response(bytes); }; assert.deepEqual(await downloadZip(meta, { token: 'synthetic', fetch }), bytes); @@ -83,27 +135,50 @@ test('authenticated API raw ZIP digest is fatal before parsing; redirects never assert.ok(calls[0][1].headers.Authorization); assert.equal(calls[1][1].headers?.Authorization, undefined); await assert.rejects(downloadZip({ ...meta, digest: `sha256:${'d'.repeat(64)}` }, { token: 'synthetic', fetch: async () => new Response(bytes) }), /digest/i); - await assert.rejects(downloadZip(meta, { token: 'synthetic', fetch: async () => new Response(null, { status: 302, headers: { location: 'https://attacker.example/zip' } }) }), /download/i); - for (const response of [new Response(bytes, { headers: { 'content-length': '999999999' } }), new Response(Buffer.concat([bytes, bytes])), new Response('SECRET', { status: 403 })]) { + await assert.rejects( + downloadZip(meta, { token: 'synthetic', fetch: async () => new Response(null, { status: 302, headers: { location: 'https://attacker.example/zip' } }) }), + /download/i, + ); + for (const response of [ + new Response(bytes, { headers: { 'content-length': '999999999' } }), + new Response(Buffer.concat([bytes, bytes])), + new Response('SECRET', { status: 403 }), + ]) { await assert.rejects(downloadZip(meta, { token: 'synthetic', fetch: async () => response }), /download/i); } }); test('metadata client paginates completely, bounds data, rejects arbitrary endpoints and sanitizes failures', async () => { const calls = []; - const api = githubClient({ token: 'synthetic', fetch: async (url) => { - calls.push(url); - return Response.json({ artifacts: url.endsWith('page=1') ? Array(100).fill(checkpoint) : [receipt] }); - } }); + const api = githubClient({ + token: 'synthetic', + fetch: async (url) => { + calls.push(url); + return Response.json({ artifacts: url.endsWith('page=1') ? Array(100).fill(checkpoint) : [receipt] }); + }, + }); assert.equal((await api.artifacts('123')).length, 101); assert.equal(calls.length, 2); for (const route of ['https://attacker.example', '/releases/42', '/actions/../other']) await assert.rejects(api.json(route), /route/); assert.equal(calls.length, 2); - for (const fetch of [async () => { throw new Error('SECRET'); }, async () => new Response('not JSON'), async () => new Response('x'.repeat(1024 * 1024 + 1)), async () => new Response(null, { status: 302 })]) { + for (const fetch of [ + async () => { + throw new Error('SECRET'); + }, + async () => new Response('not JSON'), + async () => new Response('x'.repeat(1024 * 1024 + 1)), + async () => new Response(null, { status: 302 }), + ]) { await assert.rejects(githubClient({ token: 'synthetic', fetch }).json('/actions/runs/123'), (error) => !error.message.includes('SECRET')); } let pages = 0; - const truncated = githubClient({ token: 'synthetic', fetch: async () => { pages++; return Response.json({ artifacts: Array(100).fill(checkpoint) }); } }); + const truncated = githubClient({ + token: 'synthetic', + fetch: async () => { + pages++; + return Response.json({ artifacts: Array(100).fill(checkpoint) }); + }, + }); await assert.rejects(truncated.artifacts('123'), /truncated/); assert.equal(pages, 20); }); diff --git a/scripts/macos-notary-checkpoint.mjs b/scripts/macos-notary-checkpoint.mjs index da1a4f88..5a18635b 100644 --- a/scripts/macos-notary-checkpoint.mjs +++ b/scripts/macos-notary-checkpoint.mjs @@ -14,28 +14,47 @@ export const positiveId = (value) => typeof value === 'string' && /^[1-9][0-9]*$ export const uuid = (value) => typeof value === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value); export const hex = (value, length) => typeof value === 'string' && new RegExp(`^[0-9a-f]{${length}}$`).test(value); const bindingKeys = ['repository', 'workflowPath', 'workflowSha', 'sourceSha', 'version', 'releaseId', 'runId', 'runAttempt']; -const exactKeys = (value, keys) => value && typeof value === 'object' && !Array.isArray(value) && - Object.keys(value).sort().join(',') === [...keys].sort().join(','); +const exactKeys = (value, keys) => + value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).sort().join(',') === [...keys].sort().join(','); export function validateTrusted(trusted) { validateReleaseInputs({ ref: 'refs/heads/main', version: trusted.version, sourceSha: trusted.sourceSha }); - if (trusted.repository !== repository || trusted.workflowPath !== workflowPath || !hex(trusted.workflowSha, 40) || - !['releaseId', 'runId', 'runAttempt'].every((key) => positiveId(trusted[key]))) throw new Error('Invalid checkpoint context'); + if ( + trusted.repository !== repository || + trusted.workflowPath !== workflowPath || + !hex(trusted.workflowSha, 40) || + !['releaseId', 'runId', 'runAttempt'].every((key) => positiveId(trusted[key])) + ) + throw new Error('Invalid checkpoint context'); return trusted; } export function trustedEnvironment(env = process.env) { if (env.GITHUB_REF !== 'refs/heads/main') throw new Error('Checkpoint requires main'); - return validateTrusted({ repository: env.GITHUB_REPOSITORY, workflowPath, workflowSha: env.GITHUB_SHA, - sourceSha: env.RELEASE_SOURCE_SHA, version: env.RELEASE_VERSION, releaseId: env.RELEASE_ID, - runId: env.GITHUB_RUN_ID, runAttempt: env.GITHUB_RUN_ATTEMPT }); + return validateTrusted({ + repository: env.GITHUB_REPOSITORY, + workflowPath, + workflowSha: env.GITHUB_SHA, + sourceSha: env.RELEASE_SOURCE_SHA, + version: env.RELEASE_VERSION, + releaseId: env.RELEASE_ID, + runId: env.GITHUB_RUN_ID, + runAttempt: env.GITHUB_RUN_ATTEMPT, + }); } export function validateManifest(value, trusted) { validateTrusted(trusted); - if (!exactKeys(value, ['schema', ...bindingKeys, 'dmgName', 'size', 'sha256']) || value.schema !== 1 || - bindingKeys.some((key) => value[key] !== trusted[key]) || value.dmgName !== `Quorb_${trusted.version}_aarch64.dmg` || - !Number.isSafeInteger(value.size) || value.size < 1 || value.size > MAX_DMG || !hex(value.sha256, 64)) { + if ( + !exactKeys(value, ['schema', ...bindingKeys, 'dmgName', 'size', 'sha256']) || + value.schema !== 1 || + bindingKeys.some((key) => value[key] !== trusted[key]) || + value.dmgName !== `Quorb_${trusted.version}_aarch64.dmg` || + !Number.isSafeInteger(value.size) || + value.size < 1 || + value.size > MAX_DMG || + !hex(value.sha256, 64) + ) { throw new Error('Invalid checkpoint manifest'); } return value; @@ -46,18 +65,26 @@ export function validateDmg(bytes, manifest) { } export function validateReceipt(value, trusted, artifact, manifest) { - if (!exactKeys(value, ['schema', ...bindingKeys, 'checkpointArtifactId', 'checkpointArtifactDigest', 'submissionId', 'dmgSha256']) || - value.schema !== 1 || bindingKeys.some((key) => value[key] !== trusted[key]) || !uuid(value.submissionId) || - value.checkpointArtifactId !== String(artifact.id) || value.checkpointArtifactDigest !== artifact.digest?.replace(/^sha256:/, '') || - !hex(value.checkpointArtifactDigest, 64) || value.dmgSha256 !== manifest.sha256) throw new Error('Invalid submission receipt'); + if ( + !exactKeys(value, ['schema', ...bindingKeys, 'checkpointArtifactId', 'checkpointArtifactDigest', 'submissionId', 'dmgSha256']) || + value.schema !== 1 || + bindingKeys.some((key) => value[key] !== trusted[key]) || + !uuid(value.submissionId) || + value.checkpointArtifactId !== String(artifact.id) || + value.checkpointArtifactDigest !== artifact.digest?.replace(/^sha256:/, '') || + !hex(value.checkpointArtifactDigest, 64) || + value.dmgSha256 !== manifest.sha256 + ) + throw new Error('Invalid submission receipt'); return value; } // Tauri bundler 2.10.1 sign.rs notarize_auth checks both flows. Absent, not empty: // API key/issuer presence alone can trigger its private_keys directory search. export function signingEnvironment(env) { - return Object.fromEntries(Object.entries(env).filter(([key]) => !key.startsWith('APPLE_API_') && - !['APPLE_ID', 'APPLE_PASSWORD', 'APPLE_TEAM_ID'].includes(key))); + return Object.fromEntries( + Object.entries(env).filter(([key]) => !key.startsWith('APPLE_API_') && !['APPLE_ID', 'APPLE_PASSWORD', 'APPLE_TEAM_ID'].includes(key)), + ); } export function buildSigned({ env = process.env, run = execFileSync } = {}) { @@ -66,7 +93,9 @@ export function buildSigned({ env = process.env, run = execFileSync } = {}) { } try { run('npm', ['run', 'app:build:mac'], { cwd: 'source', env: signingEnvironment(env), stdio: 'inherit' }); - } catch { throw new Error('Signed build failed'); } + } catch { + throw new Error('Signed build failed'); + } } export function createCheckpoint({ env = process.env, io = fs, verify = verifyMacosBundle, signature = verifyDeveloperSignature } = {}) { @@ -88,5 +117,8 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me if (process.argv[2] === 'build') buildSigned(); else if (process.argv[2] === 'stage') createCheckpoint(); else throw new Error('Expected build or stage'); - } catch (error) { console.error(error.message); process.exitCode = 1; } + } catch (error) { + console.error(error.message); + process.exitCode = 1; + } } diff --git a/scripts/macos-notary-checkpoint.test.mjs b/scripts/macos-notary-checkpoint.test.mjs index 43a251e0..9ba30fc4 100644 --- a/scripts/macos-notary-checkpoint.test.mjs +++ b/scripts/macos-notary-checkpoint.test.mjs @@ -7,21 +7,36 @@ import { validateManifest, validateDmg, validateReceipt, signingEnvironment, cre import { submitCheckpoint } from './macos-notary-submit.mjs'; export const trusted = { - repository: 'egdev6/quorb', workflowPath: '.github/workflows/macos-release.yml', - workflowSha: 'a'.repeat(40), sourceSha: 'b'.repeat(40), version: '0.8.0', - releaseId: '42', runId: '123', runAttempt: '2', + repository: 'egdev6/quorb', + workflowPath: '.github/workflows/macos-release.yml', + workflowSha: 'a'.repeat(40), + sourceSha: 'b'.repeat(40), + version: '0.8.0', + releaseId: '42', + runId: '123', + runAttempt: '2', }; export const bytes = Buffer.from('synthetic signed DMG'); export const manifest = { - schema: 1, ...trusted, dmgName: 'Quorb_0.8.0_aarch64.dmg', size: bytes.length, + schema: 1, + ...trusted, + dmgName: 'Quorb_0.8.0_aarch64.dmg', + size: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex'), }; export const receipt = { - schema: 1, ...trusted, checkpointArtifactId: '456', checkpointArtifactDigest: 'c'.repeat(64), - submissionId: '12345678-1234-1234-1234-123456789abc', dmgSha256: manifest.sha256, + schema: 1, + ...trusted, + checkpointArtifactId: '456', + checkpointArtifactDigest: 'c'.repeat(64), + submissionId: '12345678-1234-1234-1234-123456789abc', + dmgSha256: manifest.sha256, }; -for (const [style, paths] of [['POSIX', path.posix], ['Windows', path.win32]]) { +for (const [style, paths] of [ + ['POSIX', path.posix], + ['Windows', path.win32], +]) { test(`offline filesystem canonicalizes ${style} separators without weakening exclusive writes or exact file checks`, () => { for (const directory of ['notary-checkpoint', 'notary-retained', 'notary-publish']) { const { files, io } = fileFixture(); @@ -32,8 +47,10 @@ for (const [style, paths] of [['POSIX', path.posix], ['Windows', path.win32]]) { assert.deepEqual(files.get(`${directory}/${manifest.dmgName}`), bytes); assert.deepEqual(io.readFileSync(`${directory}/${manifest.dmgName}`), bytes); assert.deepEqual(io.readFileSync(dmg), bytes); - assert.deepEqual([...files.keys()].filter((name) => name.startsWith(`${directory}/`)).sort(), - [`${directory}/${manifest.dmgName}`, `${directory}/manifest.json`]); + assert.deepEqual([...files.keys()].filter((name) => name.startsWith(`${directory}/`)).sort(), [ + `${directory}/${manifest.dmgName}`, + `${directory}/manifest.json`, + ]); assert.ok(!files.has(`${directory}/unexpected.dmg`)); assert.throws(() => io.writeFileSync(`${directory}/${manifest.dmgName}`, bytes, { flag: 'wx' }), /overwrite/); assert.throws(() => io.writeFileSync(paths.join(directory, 'unexpected.dmg'), bytes, { flag: 'w' }), /overwrite/); @@ -56,43 +73,89 @@ test('manifest and receipt are strictly bound to externally trusted values, not assert.throws(() => validateManifest({ ...manifest, ...change }, trusted), /manifest/i); } assert.throws(() => validateDmg(Buffer.from('tampered'), manifest), /DMG/); - for (const change of [{ submissionId: '--help' }, { checkpointArtifactId: '457' }, { checkpointArtifactDigest: 'd'.repeat(64) }, { dmgSha256: 'f'.repeat(64) }, { extra: true }]) { + for (const change of [ + { submissionId: '--help' }, + { checkpointArtifactId: '457' }, + { checkpointArtifactDigest: 'd'.repeat(64) }, + { dmgSha256: 'f'.repeat(64) }, + { extra: true }, + ]) { assert.throws(() => validateReceipt({ ...receipt, ...change }, trusted, { id: 456, digest: `sha256:${'c'.repeat(64)}` }, manifest), /receipt/i); } }); test('build removes every Tauri notarization credential including alternate Apple ID flow', () => { - const env = signingEnvironment({ PATH: '/bin', APPLE_CERTIFICATE: 'cert', APPLE_CERTIFICATE_PASSWORD: 'pass', APPLE_SIGNING_IDENTITY: 'id', - APPLE_API_KEY: 'key', APPLE_API_KEY_PATH: 'path', APPLE_API_ISSUER: 'issuer', APPLE_API_KEY_P8: 'private', - APPLE_ID: 'id', APPLE_PASSWORD: 'password', APPLE_TEAM_ID: 'team' }); + const env = signingEnvironment({ + PATH: '/bin', + APPLE_CERTIFICATE: 'cert', + APPLE_CERTIFICATE_PASSWORD: 'pass', + APPLE_SIGNING_IDENTITY: 'id', + APPLE_API_KEY: 'key', + APPLE_API_KEY_PATH: 'path', + APPLE_API_ISSUER: 'issuer', + APPLE_API_KEY_P8: 'private', + APPLE_ID: 'id', + APPLE_PASSWORD: 'password', + APPLE_TEAM_ID: 'team', + }); assert.deepEqual(env, { PATH: '/bin', APPLE_CERTIFICATE: 'cert', APPLE_CERTIFICATE_PASSWORD: 'pass', APPLE_SIGNING_IDENTITY: 'id' }); let calls = 0; - buildSigned({ env: { ...env, APPLE_API_KEY: 'inherited', APPLE_ID: 'inherited' }, run: (command, args, options) => { - calls++; - assert.equal(command, 'npm'); assert.deepEqual(args, ['run', 'app:build:mac']); - assert.equal(options.cwd, 'source'); assert.deepEqual(options.env, env); - } }); + buildSigned({ + env: { ...env, APPLE_API_KEY: 'inherited', APPLE_ID: 'inherited' }, + run: (command, args, options) => { + calls++; + assert.equal(command, 'npm'); + assert.deepEqual(args, ['run', 'app:build:mac']); + assert.equal(options.cwd, 'source'); + assert.deepEqual(options.env, env); + }, + }); assert.equal(calls, 1); }); test('checkpoint contains only signed DMG and strict manifest; successful upload binding is required before key creation or submit', () => { - const env = { GITHUB_REF: 'refs/heads/main', GITHUB_REPOSITORY: trusted.repository, GITHUB_SHA: trusted.workflowSha, - GITHUB_RUN_ID: trusted.runId, GITHUB_RUN_ATTEMPT: trusted.runAttempt, RELEASE_SOURCE_SHA: trusted.sourceSha, RELEASE_VERSION: trusted.version, RELEASE_ID: trusted.releaseId }; + const env = { + GITHUB_REF: 'refs/heads/main', + GITHUB_REPOSITORY: trusted.repository, + GITHUB_SHA: trusted.workflowSha, + GITHUB_RUN_ID: trusted.runId, + GITHUB_RUN_ATTEMPT: trusted.runAttempt, + RELEASE_SOURCE_SHA: trusted.sourceSha, + RELEASE_VERSION: trusted.version, + RELEASE_ID: trusted.releaseId, + }; const { files, io } = fileFixture([['/synthetic/Quorb_0.8.0_aarch64.dmg', bytes]]); const signatures = []; - const result = createCheckpoint({ env, io, verify: () => ({ version: '0.8.0', app: '/synthetic/Quorb.app', dmg: '/synthetic/Quorb_0.8.0_aarch64.dmg' }), signature: (target) => signatures.push(target) }); + const result = createCheckpoint({ + env, + io, + verify: () => ({ version: '0.8.0', app: '/synthetic/Quorb.app', dmg: '/synthetic/Quorb_0.8.0_aarch64.dmg' }), + signature: (target) => signatures.push(target), + }); assert.deepEqual(result, manifest); assert.equal(signatures.length, 2); - assert.deepEqual([...files.keys()].filter((name) => name.startsWith('notary-checkpoint/')).sort(), ['notary-checkpoint/Quorb_0.8.0_aarch64.dmg', 'notary-checkpoint/manifest.json']); + assert.deepEqual([...files.keys()].filter((name) => name.startsWith('notary-checkpoint/')).sort(), [ + 'notary-checkpoint/Quorb_0.8.0_aarch64.dmg', + 'notary-checkpoint/manifest.json', + ]); let keyCalls = 0; - const key = (callback) => { keyCalls++; return callback([]); }; + const key = (callback) => { + keyCalls++; + return callback([]); + }; assert.throws(() => submitCheckpoint({ env, io, key }), /upload must succeed/); assert.equal(keyCalls, 0); const uploaded = { ...env, CHECKPOINT_ARTIFACT_ID: '456', CHECKPOINT_ARTIFACT_DIGEST: 'c'.repeat(64) }; - const saved = submitCheckpoint({ env: uploaded, io, key, run: (_command, args) => { - assert.ok(files.has('notary-checkpoint/manifest.json')); - assert.ok(!args.includes('--wait')); return JSON.stringify({ id: receipt.submissionId }); - } }); + const saved = submitCheckpoint({ + env: uploaded, + io, + key, + run: (_command, args) => { + assert.ok(files.has('notary-checkpoint/manifest.json')); + assert.ok(!args.includes('--wait')); + return JSON.stringify({ id: receipt.submissionId }); + }, + }); assert.deepEqual(saved, receipt); assert.equal(keyCalls, 1); assert.deepEqual(JSON.parse(files.get('notary-receipt/receipt.json')), receipt); diff --git a/scripts/macos-notary-submit.mjs b/scripts/macos-notary-submit.mjs index fafc278e..52ffde26 100644 --- a/scripts/macos-notary-submit.mjs +++ b/scripts/macos-notary-submit.mjs @@ -4,13 +4,21 @@ import { execFileSync } from 'node:child_process'; import { fileURLToPath } from 'node:url'; import { trustedEnvironment, validateManifest, validateDmg, positiveId, hex, uuid } from './macos-notary-checkpoint.mjs'; -const execute = (command, args) => execFileSync(command, args, { - encoding: 'utf8', timeout: 120_000, maxBuffer: 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'], -}); +const execute = (command, args) => + execFileSync(command, args, { + encoding: 'utf8', + timeout: 120_000, + maxBuffer: 1024 * 1024, + stdio: ['ignore', 'pipe', 'pipe'], + }); export function withNotaryKey(callback, { env = process.env, io = fs } = {}) { - if (!positiveId(env.GITHUB_RUN_ID) || !positiveId(env.GITHUB_RUN_ATTEMPT) || !path.isAbsolute(env.RUNNER_TEMP ?? '') || - !['APPLE_API_KEY_P8', 'APPLE_API_KEY', 'APPLE_API_ISSUER'].every((key) => typeof env[key] === 'string' && env[key].trim())) { + if ( + !positiveId(env.GITHUB_RUN_ID) || + !positiveId(env.GITHUB_RUN_ATTEMPT) || + !path.isAbsolute(env.RUNNER_TEMP ?? '') || + !['APPLE_API_KEY_P8', 'APPLE_API_KEY', 'APPLE_API_ISSUER'].every((key) => typeof env[key] === 'string' && env[key].trim()) + ) { throw new Error('Missing notarization credentials/context'); } const keyPath = path.join(env.RUNNER_TEMP, `quorb-notary-${env.GITHUB_RUN_ID}-${env.GITHUB_RUN_ATTEMPT}.p8`); @@ -25,8 +33,11 @@ export function withNotaryKey(callback, { env = process.env, io = fs } = {}) { throw new Error('Notarization operation failed'); } finally { if (written) { - try { io.unlinkSync(keyPath); } - catch { throw new Error('Notarization private key cleanup failed'); } + try { + io.unlinkSync(keyPath); + } catch { + throw new Error('Notarization private key cleanup failed'); + } } } } @@ -45,13 +56,16 @@ export function submitDmg(dmg, auth, run = execute) { } } -const safeText = (value) => typeof value === 'string' ? value.slice(0, 500).replace(/[^a-zA-Z0-9 ._/@()\-]/g, '?') : ''; +const safeText = (value) => (typeof value === 'string' ? value.slice(0, 500).replace(/[^a-zA-Z0-9 ._/@()\-]/g, '?') : ''); export function querySubmission(id, sha256, auth, run = execute) { if (!uuid(id) || !hex(sha256, 64)) throw safeError('Invalid submission UUID/hash'); id = id.toLowerCase(); let info; - try { info = JSON.parse(run('xcrun', ['notarytool', 'info', id, ...auth, '--output-format', 'json'])); } - catch { throw safeError('Unable to query submission info'); } + try { + info = JSON.parse(run('xcrun', ['notarytool', 'info', id, ...auth, '--output-format', 'json'])); + } catch { + throw safeError('Unable to query submission info'); + } if (!uuid(info.id) || info.id.toLowerCase() !== id) throw safeError('Submission identity mismatch'); if (info.status === 'In Progress') return { outcome: 'pending' }; if (!['Accepted', 'Invalid', 'Rejected'].includes(info.status)) throw safeError('Unknown submission status'); @@ -64,14 +78,21 @@ export function querySubmission(id, sha256, auth, run = execute) { throw safeError('Unable to retrieve rejection log'); } if (info.status !== 'Accepted') { - return { outcome: 'rejected', issues: Array.isArray(log.issues) ? log.issues.slice(0, 50).map((issue) => ({ - severity: safeText(issue?.severity), path: safeText(issue?.path), message: safeText(issue?.message), - })) : [] }; + return { + outcome: 'rejected', + issues: Array.isArray(log.issues) + ? log.issues.slice(0, 50).map((issue) => ({ + severity: safeText(issue?.severity), + path: safeText(issue?.path), + message: safeText(issue?.message), + })) + : [], + }; } // Synthetic tests exercise sha256; availability in a real Apple log remains an // explicit runtime prerequisite. Absence must never silently weaken this gate. - if (!uuid(log.jobId) || log.jobId.toLowerCase() !== id || typeof log.sha256 !== 'string' || - log.sha256.toLowerCase() !== sha256 || log.status !== 'Accepted') throw safeError('Apple log UUID/hash/status binding failed'); + if (!uuid(log.jobId) || log.jobId.toLowerCase() !== id || typeof log.sha256 !== 'string' || log.sha256.toLowerCase() !== sha256 || log.status !== 'Accepted') + throw safeError('Apple log UUID/hash/status binding failed'); return { outcome: 'accepted', submissionId: id }; } @@ -85,17 +106,27 @@ export function submitCheckpoint({ env = process.env, io = fs, run = execute, ke io.mkdirSync('notary-receipt'); const submissionId = key((auth) => submitDmg(dmg, auth, run), { env, io }); console.log(`Submission ID: ${submissionId}`); - const receipt = { schema: 1, ...trusted, checkpointArtifactId: env.CHECKPOINT_ARTIFACT_ID, - checkpointArtifactDigest: env.CHECKPOINT_ARTIFACT_DIGEST, submissionId, dmgSha256: manifest.sha256 }; + const receipt = { + schema: 1, + ...trusted, + checkpointArtifactId: env.CHECKPOINT_ARTIFACT_ID, + checkpointArtifactDigest: env.CHECKPOINT_ARTIFACT_DIGEST, + submissionId, + dmgSha256: manifest.sha256, + }; io.writeFileSync('notary-receipt/receipt.json', JSON.stringify(receipt, null, 2) + '\n', { flag: 'wx' }); - if (env.GITHUB_STEP_SUMMARY) io.appendFileSync(env.GITHUB_STEP_SUMMARY, - `## Submitted; not a completed release\nSubmission: \`${submissionId}\`\nSource run: ${trusted.runId}, attempt: ${trusted.runAttempt}\nCheckpoint artifact: ${env.CHECKPOINT_ARTIFACT_ID}\nResume manually after Apple processing. Do not resubmit.\n`); + if (env.GITHUB_STEP_SUMMARY) + io.appendFileSync( + env.GITHUB_STEP_SUMMARY, + `## Submitted; not a completed release\nSubmission: \`${submissionId}\`\nSource run: ${trusted.runId}, attempt: ${trusted.runAttempt}\nCheckpoint artifact: ${env.CHECKPOINT_ARTIFACT_ID}\nResume manually after Apple processing. Do not resubmit.\n`, + ); return receipt; } if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { - try { submitCheckpoint(); } - catch (error) { + try { + submitCheckpoint(); + } catch (error) { console.error(error.safeNotary ? error.message : 'Checkpoint submit failed; inspect receipt/diagnostics before any recovery; never auto-resubmit'); process.exitCode = 1; } diff --git a/scripts/macos-notary-submit.test.mjs b/scripts/macos-notary-submit.test.mjs index 77008fc5..5650d915 100644 --- a/scripts/macos-notary-submit.test.mjs +++ b/scripts/macos-notary-submit.test.mjs @@ -8,13 +8,24 @@ const auth = ['--key', '/private/key.p8', '--key-id', 'synthetic', '--issuer', ' test('submit calls once, never waits or retries; errors cannot leak command credentials', () => { const calls = []; - assert.equal(submitDmg('/checkpoint/Quorb.dmg', auth, (cmd, args) => { - calls.push([cmd, args]); return JSON.stringify({ id }); - }), id); + assert.equal( + submitDmg('/checkpoint/Quorb.dmg', auth, (cmd, args) => { + calls.push([cmd, args]); + return JSON.stringify({ id }); + }), + id, + ); assert.equal(calls.length, 1); assert.deepEqual(calls[0], ['xcrun', ['notarytool', 'submit', '/checkpoint/Quorb.dmg', ...auth, '--output-format', 'json']]); let count = 0; - assert.throws(() => submitDmg('/checkpoint/Quorb.dmg', auth, () => { count++; throw new Error('SECRET'); }), /ambiguous.*diagnostics/i); + assert.throws( + () => + submitDmg('/checkpoint/Quorb.dmg', auth, () => { + count++; + throw new Error('SECRET'); + }), + /ambiguous.*diagnostics/i, + ); assert.equal(count, 1); assert.throws(() => submitDmg('/checkpoint/Quorb.dmg', auth, () => '{}'), /ambiguous/i); }); @@ -28,25 +39,42 @@ test('pending never requests log; accepted requires exact UUID and synthetic pre return JSON.stringify({ jobId: id.toUpperCase(), status: 'Accepted', sha256 }); }); assert.equal(result.outcome, status === 'In Progress' ? 'pending' : 'accepted'); - assert.deepEqual(calls.map((args) => args[1]), status === 'In Progress' ? ['info'] : ['info', 'log']); + assert.deepEqual( + calls.map((args) => args[1]), + status === 'In Progress' ? ['info'] : ['info', 'log'], + ); if (calls[1]) assert.ok(!calls[1].includes('--output-format')); } - for (const log of [{}, { jobId: id, status: 'Accepted' }, { jobId: id, status: 'Accepted', sha256: 'b'.repeat(64) }, { jobId: '00000000-0000-0000-0000-000000000000', status: 'Accepted', sha256 }]) { + for (const log of [ + {}, + { jobId: id, status: 'Accepted' }, + { jobId: id, status: 'Accepted', sha256: 'b'.repeat(64) }, + { jobId: '00000000-0000-0000-0000-000000000000', status: 'Accepted', sha256 }, + ]) { assert.throws(() => querySubmission(id, sha256, auth, (cmd, args) => JSON.stringify(args[1] === 'info' ? { id, status: 'Accepted' } : log)), /binding/i); } - assert.equal(querySubmission(id, sha256, auth, (cmd, args) => { - if (args[1] === 'info') return JSON.stringify({ id, status: 'Accepted' }); - throw new Error('not ready SECRET'); - }).outcome, 'pending'); + assert.equal( + querySubmission(id, sha256, auth, (cmd, args) => { + if (args[1] === 'info') return JSON.stringify({ id, status: 'Accepted' }); + throw new Error('not ready SECRET'); + }).outcome, + 'pending', + ); }); test('invalid status/UUID and rejected issues fail safely; log does not accept output-format', () => { assert.throws(() => querySubmission('--help', sha256, auth, () => assert.fail()), /UUID/); assert.throws(() => querySubmission(id, sha256, auth, () => JSON.stringify({ id: 'wrong', status: 'Accepted' })), /identity/); assert.throws(() => querySubmission(id, sha256, auth, () => JSON.stringify({ id, status: 'unknown' })), /status/); - const result = querySubmission(id, sha256, auth, (cmd, args) => JSON.stringify(args[1] === 'info' ? { id, status: 'Invalid' } : { - issues: [{ severity: 'error', message: 'bad\n::error::untrusted', path: 'Quorb.app', secret: 'SECRET' }], - })); + const result = querySubmission(id, sha256, auth, (cmd, args) => + JSON.stringify( + args[1] === 'info' + ? { id, status: 'Invalid' } + : { + issues: [{ severity: 'error', message: 'bad\n::error::untrusted', path: 'Quorb.app', secret: 'SECRET' }], + }, + ), + ); assert.equal(result.outcome, 'rejected'); assert.doesNotMatch(JSON.stringify(result), /SECRET|::error::/); }); @@ -54,8 +82,24 @@ test('invalid status/UUID and rejected issues fail safely; log does not accept o test('private key is exclusive 0600 and removed even after failure; no raw error leaks', () => { const calls = []; const io = { writeFileSync: (...args) => calls.push(['write', ...args]), unlinkSync: (...args) => calls.push(['unlink', ...args]) }; - const env = { RUNNER_TEMP: '/controlled', GITHUB_RUN_ID: '42', GITHUB_RUN_ATTEMPT: '1', APPLE_API_KEY_P8: 'synthetic', APPLE_API_KEY: 'key', APPLE_API_ISSUER: 'issuer' }; - assert.throws(() => withNotaryKey(() => { throw new Error('SECRET'); }, { env, io }), /Notarization operation failed/); + const env = { + RUNNER_TEMP: '/controlled', + GITHUB_RUN_ID: '42', + GITHUB_RUN_ATTEMPT: '1', + APPLE_API_KEY_P8: 'synthetic', + APPLE_API_KEY: 'key', + APPLE_API_ISSUER: 'issuer', + }; + assert.throws( + () => + withNotaryKey( + () => { + throw new Error('SECRET'); + }, + { env, io }, + ), + /Notarization operation failed/, + ); assert.deepEqual(calls[0].slice(2), ['synthetic', { mode: 0o600, flag: 'wx' }]); assert.equal(calls[1][0], 'unlink'); assert.equal(calls[0][1], calls[1][1]); diff --git a/scripts/macos-notary-workflow.test.mjs b/scripts/macos-notary-workflow.test.mjs index f0301de7..9711edd0 100644 --- a/scripts/macos-notary-workflow.test.mjs +++ b/scripts/macos-notary-workflow.test.mjs @@ -18,7 +18,10 @@ const digest = (text) => createHash('sha256').update(normalize(text)).digest('he function script(text = read(active)) { const body = normalize(text).split(" python3 <<'PY'\n")[1]?.split('\n PY')[0]; assert.ok(body, 'Expected inline Python diagnostics'); - return body.split('\n').map((line) => line.slice(10)).join('\n'); + return body + .split('\n') + .map((line) => line.slice(10)) + .join('\n'); } function execute(submission = '', status = 'In Progress', fail = '') { @@ -48,11 +51,21 @@ subprocess.run = fake_run `; try { const result = spawnSync(process.platform === 'win32' ? 'python' : 'python3', ['-c', fake + script()], { - encoding: 'utf8', timeout: 10000, - env: { ...process.env, RUNNER_TEMP: dir, - GITHUB_RUN_ID: '42', GITHUB_RUN_ATTEMPT: '1', SUBMISSION_ID: submission, - APPLE_API_KEY_P8: 'synthetic-private-key', APPLE_API_KEY: 'synthetic-key-id', - APPLE_API_ISSUER: 'synthetic-issuer', CALLS: calls, STATUS: status, FAIL: fail }, + encoding: 'utf8', + timeout: 10000, + env: { + ...process.env, + RUNNER_TEMP: dir, + GITHUB_RUN_ID: '42', + GITHUB_RUN_ATTEMPT: '1', + SUBMISSION_ID: submission, + APPLE_API_KEY_P8: 'synthetic-private-key', + APPLE_API_KEY: 'synthetic-key-id', + APPLE_API_ISSUER: 'synthetic-issuer', + CALLS: calls, + STATUS: status, + FAIL: fail, + }, }); assert.ifError(result.error); return { ...result, calls: existsSync(calls) ? readFileSync(calls, 'utf8').trim().split('\n').map(JSON.parse) : [], keyExists: existsSync(key) }; @@ -97,7 +110,10 @@ test('reviewed digest rejects changes to every nonempty line', () => { test('history only lists IDs without resubmitting or retaining the key', () => { const result = execute(); assert.equal(result.status, 0, result.stderr); - assert.deepEqual(result.calls.map((call) => call[1]), ['history']); + assert.deepEqual( + result.calls.map((call) => call[1]), + ['history'], + ); assert.match(result.stdout, new RegExp(id)); assert.equal(result.keyExists, false); assert.doesNotMatch(result.stdout + result.stderr, /synthetic-private-key/); @@ -106,7 +122,10 @@ test('history only lists IDs without resubmitting or retaining the key', () => { test('pending ID queries info but does not request an unavailable log', () => { const result = execute(id); assert.equal(result.status, 0, result.stderr); - assert.deepEqual(result.calls.map((call) => call[1]), ['history', 'info']); + assert.deepEqual( + result.calls.map((call) => call[1]), + ['history', 'info'], + ); assert.match(result.stdout, /In Progress/); assert.equal(result.keyExists, false); }); @@ -115,7 +134,10 @@ for (const status of ['Accepted', 'Invalid', 'Rejected']) { test(`terminal ${status} fetches log for the exact requested ID`, () => { const result = execute(id, status); assert.equal(result.status, 0, result.stderr); - assert.deepEqual(result.calls.map((call) => call[1]), ['history', 'info', 'log']); + assert.deepEqual( + result.calls.map((call) => call[1]), + ['history', 'info', 'log'], + ); for (const call of result.calls.slice(1)) assert.equal(call[2], id); for (const call of result.calls) { if (call[1] === 'log') assert.ok(!call.includes('--output-format')); diff --git a/scripts/macos-preview-artifact.mjs b/scripts/macos-preview-artifact.mjs index e4058783..94dbd0e0 100644 --- a/scripts/macos-preview-artifact.mjs +++ b/scripts/macos-preview-artifact.mjs @@ -7,15 +7,14 @@ import { verifyMacosBundle } from './verify-macos-bundle.mjs'; const projectRoot = fileURLToPath(new URL('../', import.meta.url)); const failure = 'Preview artifact rejected'; -function artifact(mode, { root = projectRoot, env = process.env, io = fs, - execFileSync = execute, verifyBundle = verifyMacosBundle } = {}) { +function artifact(mode, { root = projectRoot, env = process.env, io = fs, execFileSync = execute, verifyBundle = verifyMacosBundle } = {}) { try { root = path.resolve(root); - const sourceSha = env.PREVIEW_SOURCE_SHA, version = env.PREVIEW_VERSION; + const sourceSha = env.PREVIEW_SOURCE_SHA, + version = env.PREVIEW_VERSION; const canonical = (dmgName, sha256, size) => buildPreviewManifest({ version, sourceSha, dmgName, sha256, size }); canonical('probe.dmg', '0'.repeat(64), 1); - if (env.GITHUB_REPOSITORY !== 'egdev6/quorb' || env.GITHUB_REF !== 'refs/heads/main' || - env.GITHUB_SHA !== sourceSha) throw new Error(); + if (env.GITHUB_REPOSITORY !== 'egdev6/quorb' || env.GITHUB_REF !== 'refs/heads/main' || env.GITHUB_SHA !== sourceSha) throw new Error(); function checked(target, kind) { const relative = path.relative(root, target); const segments = relative ? relative.split(path.sep) : []; @@ -32,7 +31,11 @@ function artifact(mode, { root = projectRoot, env = process.env, io = fs, const read = (target) => io.readFileSync(checked(target, 'file')); if (JSON.parse(read(path.join(root, 'package.json')))?.version !== version) throw new Error(); const head = execFileSync('git', ['rev-parse', 'HEAD'], { - cwd: root, encoding: 'utf8', timeout: 10_000, maxBuffer: 4096, stdio: ['ignore', 'pipe', 'pipe'], + cwd: root, + encoding: 'utf8', + timeout: 10_000, + maxBuffer: 4096, + stdio: ['ignore', 'pipe', 'pipe'], }).replace(/\r?\n$/, ''); if (head !== sourceSha) throw new Error(); const target = checked(path.join(root, 'src-tauri', 'target'), 'directory'); @@ -40,12 +43,15 @@ function artifact(mode, { root = projectRoot, env = process.env, io = fs, const download = path.join(target, 'macos-preview-download'); const readme = read(path.join(root, 'docs', 'macos-preview-README.md')); if (mode === 'stage') { - const run = (command, args) => execFileSync(command, args, { - cwd: root, encoding: 'utf8', timeout: 120_000, stdio: ['ignore', 'pipe', 'pipe'], - }); + const run = (command, args) => + execFileSync(command, args, { + cwd: root, + encoding: 'utf8', + timeout: 120_000, + stdio: ['ignore', 'pipe', 'pipe'], + }); const report = verifyBundle({ root, sourceSha, io, run }); - if (report.sourceSha !== sourceSha || report.version !== version || report.arch !== 'arm64' || - report.minimumSystemVersion !== '15.0') throw new Error(); + if (report.sourceSha !== sourceSha || report.version !== version || report.arch !== 'arm64' || report.minimumSystemVersion !== '15.0') throw new Error(); const bundle = path.join(target, 'release', 'bundle'); if (!path.isAbsolute(report.dmg)) throw new Error(); const relative = path.relative(bundle, report.dmg); @@ -57,7 +63,11 @@ function artifact(mode, { root = projectRoot, env = process.env, io = fs, verifyPreviewReadback(manifest, manifest, bytes); // Existing parents were checked; mkdir is exclusive, never recursive or a cleanup. io.mkdirSync(upload); - for (const [name, data] of [[manifest.dmg.name, bytes], ['manifest.json', JSON.stringify(manifest)], ['README.md', readme]]) { + for (const [name, data] of [ + [manifest.dmg.name, bytes], + ['manifest.json', JSON.stringify(manifest)], + ['README.md', readme], + ]) { io.writeFileSync(path.join(upload, name), data, { flag: 'wx' }); } } else { @@ -72,7 +82,8 @@ function artifact(mode, { root = projectRoot, env = process.env, io = fs, if (!read(path.join(directory, 'README.md')).equals(readme)) throw new Error(); return { manifest, bytes }; } - const expected = load(upload), actual = load(download); + const expected = load(upload), + actual = load(download); verifyPreviewReadback(expected.manifest, actual.manifest, actual.bytes); } return { sourceSha, version }; @@ -81,8 +92,12 @@ function artifact(mode, { root = projectRoot, env = process.env, io = fs, throw new Error(failure); } } -export function stagePreview(options) { return artifact('stage', options); } -export function readbackPreview(options) { return artifact('readback', options); } +export function stagePreview(options) { + return artifact('stage', options); +} +export function readbackPreview(options) { + return artifact('readback', options); +} if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { try { diff --git a/scripts/macos-preview-artifact.test.mjs b/scripts/macos-preview-artifact.test.mjs index 935ded88..606ea768 100644 --- a/scripts/macos-preview-artifact.test.mjs +++ b/scripts/macos-preview-artifact.test.mjs @@ -30,13 +30,13 @@ function fixture() { put(path.join(root, 'package.json'), 'file', Buffer.from('{"version":"0.6.0"}')); put(dmg, 'file', bytes); put(readme, 'file', Buffer.from('Injected README only; no real preview delivery.')); - const writes = [], calls = []; + const writes = [], + calls = []; const io = { lstatSync(name) { const entry = files.get(name); if (!entry) throw new Error(secret); - return Object.fromEntries(['file', 'directory', 'symbolicLink'].map((type) => - [`is${type[0].toUpperCase()}${type.slice(1)}`, () => entry.type === type])); + return Object.fromEntries(['file', 'directory', 'symbolicLink'].map((type) => [`is${type[0].toUpperCase()}${type.slice(1)}`, () => entry.type === type])); }, readFileSync(name, encoding) { if (!files.has(name)) throw new Error(secret); @@ -56,11 +56,28 @@ function fixture() { put(name, 'file', Buffer.from(data)); }, }; - const env = { GITHUB_REPOSITORY: 'egdev6/quorb', GITHUB_REF: 'refs/heads/main', GITHUB_SHA: sha, - PREVIEW_SOURCE_SHA: sha, PREVIEW_VERSION: '0.6.0', GITHUB_WORKSPACE: secret }; + const env = { + GITHUB_REPOSITORY: 'egdev6/quorb', + GITHUB_REF: 'refs/heads/main', + GITHUB_SHA: sha, + PREVIEW_SOURCE_SHA: sha, + PREVIEW_VERSION: '0.6.0', + GITHUB_WORKSPACE: secret, + }; const report = { sourceSha: sha, version: '0.6.0', arch: 'arm64', minimumSystemVersion: '15.0', dmg, dmgSha256: digest }; - const options = { root, env, io, execFileSync: (...args) => { calls.push(args); return `${sha}\r\n`; }, - verifyBundle: (args) => { calls.push(args); return report; } }; + const options = { + root, + env, + io, + execFileSync: (...args) => { + calls.push(args); + return `${sha}\r\n`; + }, + verifyBundle: (args) => { + calls.push(args); + return report; + }, + }; const stage = (patch = {}) => stagePreview({ ...options, ...patch }); const readback = (patch = {}) => readbackPreview({ ...options, ...patch }); function copied() { @@ -91,9 +108,19 @@ test('stages three exclusive files with canonical basename/source manifest; simu assert.deepEqual(f.io.readFileSync(path.join(upload, 'Quorb.dmg')), bytes); assert.deepEqual(f.readback(), { sourceSha: sha, version: '0.6.0' }); assert.deepEqual(f.writes, []); - assert.deepEqual(f.calls, [['git', ['rev-parse', 'HEAD'], { - cwd: root, encoding: 'utf8', timeout: 10_000, maxBuffer: 4096, stdio: ['ignore', 'pipe', 'pipe'], - }]]); + assert.deepEqual(f.calls, [ + [ + 'git', + ['rev-parse', 'HEAD'], + { + cwd: root, + encoding: 'utf8', + timeout: 10_000, + maxBuffer: 4096, + stdio: ['ignore', 'pipe', 'pipe'], + }, + ], + ]); }); test('rejects environment, package and HEAD mismatches before writes', () => { for (const key of Object.keys(fixture().env).filter((key) => key !== 'GITHUB_WORKSPACE')) { @@ -115,10 +142,17 @@ test('rejects environment, package and HEAD mismatches before writes', () => { } }); test('checks verifier metadata, safe subtree and final DMG hash before writing', () => { - for (const [key, value] of [['sourceSha', 'b'.repeat(40)], ['version', '0.6.1'], ['arch', 'x64'], - ['minimumSystemVersion', '14.0'], ['dmgSha256', 'b'.repeat(64)], ['dmg', path.join(`${root}-sibling`, 'Quorb.dmg')], - ['dmg', path.join(root, 'elsewhere.dmg')], ['dmg', path.join(path.dirname(dmg), 'a:b.dmg')], - ['dmg', path.join(path.dirname(dmg), 'a\\b.dmg')]]) { + for (const [key, value] of [ + ['sourceSha', 'b'.repeat(40)], + ['version', '0.6.1'], + ['arch', 'x64'], + ['minimumSystemVersion', '14.0'], + ['dmgSha256', 'b'.repeat(64)], + ['dmg', path.join(`${root}-sibling`, 'Quorb.dmg')], + ['dmg', path.join(root, 'elsewhere.dmg')], + ['dmg', path.join(path.dirname(dmg), 'a:b.dmg')], + ['dmg', path.join(path.dirname(dmg), 'a\\b.dmg')], + ]) { const f = fixture(); f.report[key] = value; rejected(f); @@ -146,14 +180,21 @@ test('rejects symlinks, missing entries and wrong kinds at every consumed level' }); test('readback rejects tampering, unsafe manifest names, extra entries and nonregular files on either side', () => { for (const directory of [upload, download]) { - for (const [key, value] of [['delivery', 'signed'], ['sourceSha', 'b'.repeat(40)], ['version', '0.6.1'], + for (const [key, value] of [ + ['delivery', 'signed'], + ['sourceSha', 'b'.repeat(40)], + ['version', '0.6.1'], ['dmg', { name: '../escape.dmg', sha256: digest, size: bytes.length }], ['dmg', { name: 'a:b.dmg', sha256: digest, size: bytes.length }], ['dmg', { name: 'a\\b.dmg', sha256: digest, size: bytes.length }], ['dmg', { name: 'Other.dmg', sha256: digest, size: bytes.length }], ['dmg', { name: 'Quorb.dmg', sha256: 'b'.repeat(64), size: bytes.length }], ['dmg', { name: 'Quorb.dmg', sha256: digest, size: bytes.length + 1 }], - ['notarized', true], ['retentionDays', 90], ['arch', 'x64'], ['updater', 'automatic']]) { + ['notarized', true], + ['retentionDays', 90], + ['arch', 'x64'], + ['updater', 'automatic'], + ]) { const f = fixture(); f.copied(); const name = path.join(directory, 'manifest.json'); @@ -166,8 +207,9 @@ test('readback rejects tampering, unsafe manifest names, extra entries and nonre const f = fixture(); f.copied(); const target = path.join(directory, name); - if (type === 'missing') { if (!f.files.delete(target)) continue; } - else f.put(target, type, Buffer.from(secret)); + if (type === 'missing') { + if (!f.files.delete(target)) continue; + } else f.put(target, type, Buffer.from(secret)); rejected(f, () => f.readback()); } } @@ -187,30 +229,61 @@ test('readback rejects tampering, unsafe manifest names, extra entries and nonre test('sanitizes filesystem, verifier and command errors without raw causes', () => { for (const key of ['execFileSync', 'verifyBundle']) { const f = fixture(); - rejected(f, () => f.stage({ [key]: () => { throw new Error(secret); } })); + rejected(f, () => + f.stage({ + [key]: () => { + throw new Error(secret); + }, + }), + ); } for (const key of ['lstatSync', 'readFileSync', 'mkdirSync', 'writeFileSync', 'readdirSync']) { const f = fixture(); - f.io[key] = () => { throw new Error(secret); }; + f.io[key] = () => { + throw new Error(secret); + }; if (key === 'readdirSync') f.copied(); - rejected(f, () => key === 'readdirSync' ? f.readback() : f.stage(), key !== 'writeFileSync'); + rejected(f, () => (key === 'readdirSync' ? f.readback() : f.stage()), key !== 'writeFileSync'); } }); test('module-relative default ignores workspace; verifier commands capture stderr with a finite timeout', () => { const f = fixture(); const seen = []; - rejected(f, () => f.stage({ root: undefined, io: { lstatSync: (name) => { seen.push(name); throw new Error(secret); } } })); + rejected(f, () => + f.stage({ + root: undefined, + io: { + lstatSync: (name) => { + seen.push(name); + throw new Error(secret); + }, + }, + }), + ); assert.deepEqual(seen, [path.resolve(fileURLToPath(new URL('../', import.meta.url)))]); - assert.deepEqual(f.stage({ verifyBundle: ({ run }) => { run('/usr/bin/plutil', ['fixed']); return f.report; } }), - { sourceSha: sha, version: '0.6.0' }); - assert.deepEqual(f.calls.at(-1), ['/usr/bin/plutil', ['fixed'], { - cwd: root, encoding: 'utf8', timeout: 120_000, stdio: ['ignore', 'pipe', 'pipe'], - }]); + assert.deepEqual( + f.stage({ + verifyBundle: ({ run }) => { + run('/usr/bin/plutil', ['fixed']); + return f.report; + }, + }), + { sourceSha: sha, version: '0.6.0' }, + ); + assert.deepEqual(f.calls.at(-1), [ + '/usr/bin/plutil', + ['fixed'], + { + cwd: root, + encoding: 'utf8', + timeout: 120_000, + stdio: ['ignore', 'pipe', 'pipe'], + }, + ]); }); test('import is inert; CLI guards native paths/modes and emits sanitized JSON without touching real artifacts', () => { const target = new URL('./macos-preview-artifact.mjs', import.meta.url).href; - const modules = ['macos-preview-artifact.mjs', 'macos-preview-policy.mjs', 'verify-macos-bundle.mjs'] - .map((name) => new URL(name, import.meta.url).href); + const modules = ['macos-preview-artifact.mjs', 'macos-preview-policy.mjs', 'verify-macos-bundle.mjs'].map((name) => new URL(name, import.meta.url).href); const f = fixture(); f.copied(); const entries = [...f.files].map(([name, entry]) => [path.relative(root, name), entry.type, entry.data?.toString('base64')]); @@ -227,17 +300,20 @@ test('import is inert; CLI guards native paths/modes and emits sanitized JSON wi fs.lstatSync = fs.readdirSync = fs.mkdirSync = fs.writeFileSync = cp.execFileSync = unexpected; process.env = {}; `; - const child = (code) => execFileSync(process.execPath, ['--input-type=module', '-e', setup + code], - { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }); + const child = (code) => execFileSync(process.execPath, ['--input-type=module', '-e', setup + code], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }); assert.equal(child(`syncBuiltinESMExports(); await import('${target}'); process.stdout.write('inert');`), 'inert'); for (const args of [[], ['unknown'], ['stage', '--root=elsewhere'], ['stage'], ['readback']]) { - assert.throws(() => child(`process.argv = [process.execPath, fileURLToPath('${target}'), ...${JSON.stringify(args)}]; - syncBuiltinESMExports(); await import('${target}');`), (error) => { - assert.equal(error.status, 1); - assert.equal(error.stdout, ''); - assert.equal(error.stderr.replace(/\r\n/g, '\n'), 'Preview artifact rejected\n'); - return true; - }); + assert.throws( + () => + child(`process.argv = [process.execPath, fileURLToPath('${target}'), ...${JSON.stringify(args)}]; + syncBuiltinESMExports(); await import('${target}');`), + (error) => { + assert.equal(error.status, 1); + assert.equal(error.stdout, ''); + assert.equal(error.stderr.replace(/\r\n/g, '\n'), 'Preview artifact rejected\n'); + return true; + }, + ); } const runtime = ` const root = fileURLToPath(new URL('../', '${target}')); @@ -262,11 +338,14 @@ test('import is inert; CLI guards native paths/modes and emits sanitized JSON wi `fs.lstatSync = () => { throw new Error('${secret}'); };`, `process.argv[2] = 'stage';`, ]) { - assert.throws(() => child(runtime + fault + invoke), (error) => { - assert.equal(error.status, 1); - assert.equal(error.stdout, ''); - assert.equal(error.stderr.replace(/\r\n/g, '\n'), 'Preview artifact rejected\n'); - return true; - }); + assert.throws( + () => child(runtime + fault + invoke), + (error) => { + assert.equal(error.status, 1); + assert.equal(error.stdout, ''); + assert.equal(error.stderr.replace(/\r\n/g, '\n'), 'Preview artifact rejected\n'); + return true; + }, + ); } }); diff --git a/scripts/macos-preview-policy.mjs b/scripts/macos-preview-policy.mjs index 478973d4..efc690c6 100644 --- a/scripts/macos-preview-policy.mjs +++ b/scripts/macos-preview-policy.mjs @@ -3,12 +3,7 @@ import { createHash } from 'node:crypto'; import { isDeepStrictEqual } from 'node:util'; -const requiredChecks = Object.freeze([ - 'Tests and build (Windows)', - 'Tests and bundle (macOS ARM64)', - 'Static code safety', - 'Secrets scan', -]); +const requiredChecks = Object.freeze(['Tests and build (Windows)', 'Tests and bundle (macOS ARM64)', 'Static code safety', 'Secrets scan']); const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value); // trim equality also excludes a final newline, which JavaScript's $ can accept. const matches = (value, pattern) => typeof value === 'string' && value === value.trim() && pattern.test(value); @@ -18,23 +13,48 @@ const validVersion = (value) => matches(value, /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]* export function validatePreviewSource(source) { if (!record(source)) throw new Error('Invalid preview source'); const { ref, expectedVersion, version, sourceSha, workflowSha, headSha, checks } = source; - if (ref !== 'refs/heads/main' || !validVersion(expectedVersion) || !validVersion(version) || - expectedVersion !== version || !validSha(sourceSha) || !validSha(workflowSha) || !validSha(headSha) || - sourceSha !== workflowSha || sourceSha !== headSha) { + if ( + ref !== 'refs/heads/main' || + !validVersion(expectedVersion) || + !validVersion(version) || + expectedVersion !== version || + !validSha(sourceSha) || + !validSha(workflowSha) || + !validSha(headSha) || + sourceSha !== workflowSha || + sourceSha !== headSha + ) { throw new Error('Invalid preview source'); } // Fail closed on incomplete/paginated responses, before counting names. - if (!record(checks) || !Number.isSafeInteger(checks.total_count) || checks.total_count < 0 || - !Array.isArray(checks.check_runs) || checks.total_count !== checks.check_runs.length || - checks.check_runs.some((check) => !record(check) || typeof check.name !== 'string' || - typeof check.status !== 'string' || !(check.conclusion === null || typeof check.conclusion === 'string') || - !validSha(check.head_sha) || !record(check.app) || typeof check.app.slug !== 'string')) { + if ( + !record(checks) || + !Number.isSafeInteger(checks.total_count) || + checks.total_count < 0 || + !Array.isArray(checks.check_runs) || + checks.total_count !== checks.check_runs.length || + checks.check_runs.some( + (check) => + !record(check) || + typeof check.name !== 'string' || + typeof check.status !== 'string' || + !(check.conclusion === null || typeof check.conclusion === 'string') || + !validSha(check.head_sha) || + !record(check.app) || + typeof check.app.slug !== 'string', + ) + ) { throw new Error('Invalid preview checks response'); } for (const name of requiredChecks) { const found = checks.check_runs.filter((check) => check.name === name); - if (found.length !== 1 || found[0].status !== 'completed' || found[0].conclusion !== 'success' || - found[0].app.slug !== 'github-actions' || found[0].head_sha !== sourceSha) { + if ( + found.length !== 1 || + found[0].status !== 'completed' || + found[0].conclusion !== 'success' || + found[0].app.slug !== 'github-actions' || + found[0].head_sha !== sourceSha + ) { throw new Error('Required preview checks not satisfied'); } } @@ -47,16 +67,29 @@ export function buildPreviewManifest(input) { throw new Error('Invalid preview manifest fields'); } const { version, sourceSha, dmgName, sha256, size } = input; - if (!validVersion(version) || !validSha(sourceSha) || - !matches(dmgName, /^[A-Za-z0-9][A-Za-z0-9._-]*\.dmg$/) || - !matches(sha256, /^[0-9a-f]{64}$/) || !Number.isSafeInteger(size) || size <= 0) { + if ( + !validVersion(version) || + !validSha(sourceSha) || + !matches(dmgName, /^[A-Za-z0-9][A-Za-z0-9._-]*\.dmg$/) || + !matches(sha256, /^[0-9a-f]{64}$/) || + !Number.isSafeInteger(size) || + size <= 0 + ) { throw new Error('Invalid preview manifest data'); } // Fixed policy: callers cannot inject signing, updater or retention claims. return { - schemaVersion: 1, delivery: 'unsigned-preview', developerId: false, notarized: false, - arch: 'arm64', minimumSystemVersion: '15.0', updater: 'manual', retentionDays: 14, - version, sourceSha, dmg: { name: dmgName, sha256, size }, + schemaVersion: 1, + delivery: 'unsigned-preview', + developerId: false, + notarized: false, + arch: 'arm64', + minimumSystemVersion: '15.0', + updater: 'manual', + retentionDays: 14, + version, + sourceSha, + dmg: { name: dmgName, sha256, size }, }; } @@ -65,15 +98,22 @@ export function verifyPreviewReadback(expected, actual, dmgBytes) { let canonical; try { canonical = buildPreviewManifest({ - version: expected.version, sourceSha: expected.sourceSha, - dmgName: expected.dmg.name, sha256: expected.dmg.sha256, size: expected.dmg.size, + version: expected.version, + sourceSha: expected.sourceSha, + dmgName: expected.dmg.name, + sha256: expected.dmg.sha256, + size: expected.dmg.size, }); } catch { throw new Error('Invalid preview readback manifest'); } - if (!isDeepStrictEqual(canonical, expected) || !isDeepStrictEqual(expected, actual) || - !(dmgBytes instanceof Uint8Array) || dmgBytes.byteLength !== expected.dmg.size || - createHash('sha256').update(dmgBytes).digest('hex') !== expected.dmg.sha256) { + if ( + !isDeepStrictEqual(canonical, expected) || + !isDeepStrictEqual(expected, actual) || + !(dmgBytes instanceof Uint8Array) || + dmgBytes.byteLength !== expected.dmg.size || + createHash('sha256').update(dmgBytes).digest('hex') !== expected.dmg.sha256 + ) { throw new Error('Invalid preview readback data'); } return true; diff --git a/scripts/macos-preview-policy.test.mjs b/scripts/macos-preview-policy.test.mjs index 6543ffa1..b3916221 100644 --- a/scripts/macos-preview-policy.test.mjs +++ b/scripts/macos-preview-policy.test.mjs @@ -7,16 +7,30 @@ const sha = 'a'.repeat(40); const names = ['Tests and build (Windows)', 'Tests and bundle (macOS ARM64)', 'Static code safety', 'Secrets scan']; const bytes = Buffer.from('fixture DMG bytes, not a mountable image'); const input = { - version: '0.6.0', sourceSha: sha, dmgName: 'Quorb_0.6.0_aarch64.dmg', - sha256: createHash('sha256').update(bytes).digest('hex'), size: bytes.length, + version: '0.6.0', + sourceSha: sha, + dmgName: 'Quorb_0.6.0_aarch64.dmg', + sha256: createHash('sha256').update(bytes).digest('hex'), + size: bytes.length, }; function source() { return { - ref: 'refs/heads/main', expectedVersion: '0.6.0', version: '0.6.0', - sourceSha: sha, workflowSha: sha, headSha: sha, - checks: { total_count: 4, check_runs: names.map((name) => ({ - name, status: 'completed', conclusion: 'success', head_sha: sha, app: { slug: 'github-actions' }, - })) }, + ref: 'refs/heads/main', + expectedVersion: '0.6.0', + version: '0.6.0', + sourceSha: sha, + workflowSha: sha, + headSha: sha, + checks: { + total_count: 4, + check_runs: names.map((name) => ({ + name, + status: 'completed', + conclusion: 'success', + head_sha: sha, + app: { slug: 'github-actions' }, + })), + }, }; } @@ -31,8 +45,11 @@ test('accepts only the exact main source and four uniquely successful Actions ch test('rejects non-main refs, invalid or mismatched stable versions and provenance', () => { const cases = [ - ['ref', 'main'], ['ref', 'refs/heads/feature'], ['ref', 'refs/heads/main\n'], - ['version', '0.6.1'], ['expectedVersion', '0.6.1'], + ['ref', 'main'], + ['ref', 'refs/heads/feature'], + ['ref', 'refs/heads/main\n'], + ['version', '0.6.1'], + ['expectedVersion', '0.6.1'], ]; for (const version of ['0.06.0', '01.6.0', '0.6.00', '0.6', '0.6.0-rc.1', '0.6.0+build', '../0.6.0', '0.6.0\n', null]) { cases.push(['version', version], ['expectedVersion', version]); @@ -49,11 +66,18 @@ test('rejects non-main refs, invalid or mismatched stable versions and provenanc }); test('rejects malformed, paginated or incomplete REST check responses before granting authority', () => { - for (const checks of [null, {}, [], { total_count: 0, check_runs: [] }, + for (const checks of [ + null, + {}, + [], + { total_count: 0, check_runs: [] }, { total_count: 5, check_runs: source().checks.check_runs }, { total_count: '4', check_runs: source().checks.check_runs }, - { total_count: -1, check_runs: [] }, { total_count: 1, check_runs: [null] }, - { total_count: 1, check_runs: [{}] }, { total_count: 4, check_runs: {} }]) { + { total_count: -1, check_runs: [] }, + { total_count: 1, check_runs: [null] }, + { total_count: 1, check_runs: [{}] }, + { total_count: 4, check_runs: {} }, + ]) { assert.throws(() => validatePreviewSource({ ...source(), checks }), /preview checks/); } const missing = source(); @@ -70,9 +94,17 @@ test('rejects malformed, paginated or incomplete REST check responses before gra test('each required name rejects duplicate, unsuccessful, pending, stale or non-Actions results', () => { for (let index = 0; index < names.length; index++) { - for (const patch of [{ conclusion: 'failure' }, { conclusion: 'skipped' }, { conclusion: null }, - { status: 'in_progress' }, { status: 'queued' }, { head_sha: 'b'.repeat(40) }, - { app: { slug: 'other' } }, { app: null }, { name: `${names[index]} ` }]) { + for (const patch of [ + { conclusion: 'failure' }, + { conclusion: 'skipped' }, + { conclusion: null }, + { status: 'in_progress' }, + { status: 'queued' }, + { head_sha: 'b'.repeat(40) }, + { app: { slug: 'other' } }, + { app: null }, + { name: `${names[index]} ` }, + ]) { const value = source(); Object.assign(value.checks.check_runs[index], patch); assert.throws(() => validatePreviewSource(value), /preview checks/); @@ -86,9 +118,16 @@ test('each required name rejects duplicate, unsuccessful, pending, stale or non- test('builds a deterministic unsigned preview manifest with a fixed policy', () => { const expected = { - schemaVersion: 1, delivery: 'unsigned-preview', developerId: false, notarized: false, - arch: 'arm64', minimumSystemVersion: '15.0', updater: 'manual', retentionDays: 14, - version: input.version, sourceSha: sha, + schemaVersion: 1, + delivery: 'unsigned-preview', + developerId: false, + notarized: false, + arch: 'arm64', + minimumSystemVersion: '15.0', + updater: 'manual', + retentionDays: 14, + version: input.version, + sourceSha: sha, dmg: { name: input.dmgName, sha256: input.sha256, size: bytes.length }, }; assert.deepEqual(buildPreviewManifest(input), expected); @@ -105,8 +144,15 @@ test('rejects unsafe names, invalid digest, size, version, SHA and policy inject for (const sha256 of ['', 'a'.repeat(63), 'G'.repeat(64), 'A'.repeat(64), `${input.sha256}\n`, null]) cases.push({ sha256 }); for (const size of [0, -1, 1.5, Number.MAX_SAFE_INTEGER + 1, '12', null]) cases.push({ size }); cases.push({ version: '0.06.0' }, { sourceSha: 'A'.repeat(40) }); - for (const [key, value] of [['delivery', 'signed'], ['developerId', true], ['notarized', true], - ['arch', 'x64'], ['minimumSystemVersion', '12.0'], ['updater', 'automatic'], ['retentionDays', 90]]) { + for (const [key, value] of [ + ['delivery', 'signed'], + ['developerId', true], + ['notarized', true], + ['arch', 'x64'], + ['minimumSystemVersion', '12.0'], + ['updater', 'automatic'], + ['retentionDays', 90], + ]) { cases.push({ [key]: value }); } for (const patch of cases) assert.throws(() => buildPreviewManifest({ ...input, ...patch }), /preview manifest/); diff --git a/scripts/macos-preview-preflight.mjs b/scripts/macos-preview-preflight.mjs index 7c38d308..3a9852b1 100644 --- a/scripts/macos-preview-preflight.mjs +++ b/scripts/macos-preview-preflight.mjs @@ -12,7 +12,9 @@ const versionFormat = /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/; async function readChecks(response, signal) { if (!response?.ok || response.status !== 200 || typeof response.body?.getReader !== 'function') throw new Error(); const reader = response.body.getReader(); - const cancel = () => { void reader.cancel().catch(() => {}); }; + const cancel = () => { + void reader.cancel().catch(() => {}); + }; signal.addEventListener('abort', cancel, { once: true }); let complete = false; try { @@ -38,15 +40,34 @@ async function readChecks(response, signal) { } // Dependencies are acquired only on invocation; imports never read provenance or contact GitHub. -export async function preflightPreview({ root = projectRoot, env = process.env, - readFileSync = readFile, execFileSync = execute, fetch = globalThis.fetch } = {}) { +export async function preflightPreview({ + root = projectRoot, + env = process.env, + readFileSync = readFile, + execFileSync = execute, + fetch = globalThis.fetch, +} = {}) { let failure = 'Invalid preview inputs'; try { - const { GITHUB_REPOSITORY: repository, GITHUB_REF: ref, GITHUB_SHA: workflowSha, - PREVIEW_SOURCE_SHA: sourceSha, PREVIEW_VERSION: expectedVersion, GH_TOKEN: token } = env; - if (repository !== 'egdev6/quorb' || ref !== 'refs/heads/main' || - !matches(workflowSha, shaFormat) || !matches(sourceSha, shaFormat) || sourceSha !== workflowSha || - !matches(expectedVersion, versionFormat) || typeof token !== 'string' || !token.trim() || /[\r\n]/.test(token)) { + const { + GITHUB_REPOSITORY: repository, + GITHUB_REF: ref, + GITHUB_SHA: workflowSha, + PREVIEW_SOURCE_SHA: sourceSha, + PREVIEW_VERSION: expectedVersion, + GH_TOKEN: token, + } = env; + if ( + repository !== 'egdev6/quorb' || + ref !== 'refs/heads/main' || + !matches(workflowSha, shaFormat) || + !matches(sourceSha, shaFormat) || + sourceSha !== workflowSha || + !matches(expectedVersion, versionFormat) || + typeof token !== 'string' || + !token.trim() || + /[\r\n]/.test(token) + ) { throw new Error(); } failure = 'Invalid preview package version'; @@ -54,16 +75,21 @@ export async function preflightPreview({ root = projectRoot, env = process.env, if (!matches(version, versionFormat) || version !== expectedVersion) throw new Error(); failure = 'Unable to verify preview HEAD'; const output = execFileSync('git', ['rev-parse', 'HEAD'], { - cwd: root, encoding: 'utf8', timeout: 10_000, maxBuffer: 4096, stdio: ['ignore', 'pipe', 'pipe'], + cwd: root, + encoding: 'utf8', + timeout: 10_000, + maxBuffer: 4096, + stdio: ['ignore', 'pipe', 'pipe'], }); const headSha = output.replace(/\r?\n$/, ''); if (!matches(headSha, shaFormat) || headSha !== workflowSha) throw new Error(); failure = 'Unable to read preview checks'; const signal = AbortSignal.timeout(10_000); const response = await fetch(`https://api.github.com/repos/egdev6/quorb/commits/${workflowSha}/check-runs?per_page=100`, { - method: 'GET', redirect: 'error', signal, - headers: { Accept: 'application/vnd.github+json', Authorization: `Bearer ${token}`, - 'X-GitHub-Api-Version': '2022-11-28' }, + method: 'GET', + redirect: 'error', + signal, + headers: { Accept: 'application/vnd.github+json', Authorization: `Bearer ${token}`, 'X-GitHub-Api-Version': '2022-11-28' }, }); const checks = await readChecks(response, signal); failure = 'Preview source checks rejected'; diff --git a/scripts/macos-preview-preflight.test.mjs b/scripts/macos-preview-preflight.test.mjs index 1c98a2a1..c0ae0cd2 100644 --- a/scripts/macos-preview-preflight.test.mjs +++ b/scripts/macos-preview-preflight.test.mjs @@ -9,16 +9,40 @@ const sha = 'a'.repeat(40); const secret = 'PRIVATE_FIXTURE_MARKER'; const root = path.resolve('fixture-root'); function fixture() { - const env = { GITHUB_REPOSITORY: 'egdev6/quorb', GITHUB_REF: 'refs/heads/main', - GITHUB_SHA: sha, PREVIEW_SOURCE_SHA: sha, PREVIEW_VERSION: '0.6.0', GH_TOKEN: secret }; - const checks = { total_count: 4, check_runs: [ - 'Tests and build (Windows)', 'Tests and bundle (macOS ARM64)', 'Static code safety', 'Secrets scan', - ].map((name) => ({ name, status: 'completed', conclusion: 'success', head_sha: sha, app: { slug: 'github-actions' } })) }; + const env = { + GITHUB_REPOSITORY: 'egdev6/quorb', + GITHUB_REF: 'refs/heads/main', + GITHUB_SHA: sha, + PREVIEW_SOURCE_SHA: sha, + PREVIEW_VERSION: '0.6.0', + GH_TOKEN: secret, + }; + const checks = { + total_count: 4, + check_runs: ['Tests and build (Windows)', 'Tests and bundle (macOS ARM64)', 'Static code safety', 'Secrets scan'].map((name) => ({ + name, + status: 'completed', + conclusion: 'success', + head_sha: sha, + app: { slug: 'github-actions' }, + })), + }; const calls = []; - const options = { root, env, - readFileSync: (...args) => { calls.push(['read', ...args]); return '{"version":"0.6.0"}'; }, - execFileSync: (...args) => { calls.push(['git', ...args]); return `${sha}\r\n`; }, - fetch: async (...args) => { calls.push(['fetch', ...args]); return new Response(JSON.stringify(checks)); }, + const options = { + root, + env, + readFileSync: (...args) => { + calls.push(['read', ...args]); + return '{"version":"0.6.0"}'; + }, + execFileSync: (...args) => { + calls.push(['git', ...args]); + return `${sha}\r\n`; + }, + fetch: async (...args) => { + calls.push(['fetch', ...args]); + return new Response(JSON.stringify(checks)); + }, }; return { env, checks, calls, options, run: (patch = {}) => preflightPreview({ ...options, ...patch }) }; } @@ -28,15 +52,18 @@ test('acquires fixed local provenance and one bounded authenticated request; ret f.env.GITHUB_API_URL = 'https://untrusted.invalid'; assert.deepEqual(await f.run(), { sourceSha: sha, version: '0.6.0' }); assert.deepEqual(f.calls[0], ['read', path.join(root, 'package.json'), 'utf8']); - assert.deepEqual(f.calls[1], ['git', 'git', ['rev-parse', 'HEAD'], - { cwd: root, encoding: 'utf8', timeout: 10_000, maxBuffer: 4096, stdio: ['ignore', 'pipe', 'pipe'] }]); + assert.deepEqual(f.calls[1], [ + 'git', + 'git', + ['rev-parse', 'HEAD'], + { cwd: root, encoding: 'utf8', timeout: 10_000, maxBuffer: 4096, stdio: ['ignore', 'pipe', 'pipe'] }, + ]); const [kind, url, options] = f.calls[2]; assert.equal(kind, 'fetch'); assert.equal(url, `https://api.github.com/repos/egdev6/quorb/commits/${sha}/check-runs?per_page=100`); assert.equal(options.method, 'GET'); assert.equal(options.redirect, 'error'); - assert.deepEqual(options.headers, { Accept: 'application/vnd.github+json', - Authorization: `Bearer ${secret}`, 'X-GitHub-Api-Version': '2022-11-28' }); + assert.deepEqual(options.headers, { Accept: 'application/vnd.github+json', Authorization: `Bearer ${secret}`, 'X-GitHub-Api-Version': '2022-11-28' }); assert.ok(options.signal instanceof AbortSignal); assert.equal(options.signal.aborted, false); assert.equal(f.calls.length, 3); @@ -51,8 +78,12 @@ async function rejected(f, patch, message) { } test('rejects invalid environment before any filesystem, Git or HTTP consumption', async () => { - const cases = [['GITHUB_REPOSITORY', 'other/quorb'], ['GITHUB_REF', 'refs/heads/topic'], - ['GITHUB_REF', 'refs/heads/main\n'], ['PREVIEW_SOURCE_SHA', 'b'.repeat(40)]]; + const cases = [ + ['GITHUB_REPOSITORY', 'other/quorb'], + ['GITHUB_REF', 'refs/heads/topic'], + ['GITHUB_REF', 'refs/heads/main\n'], + ['PREVIEW_SOURCE_SHA', 'b'.repeat(40)], + ]; for (const key of ['GITHUB_SHA', 'PREVIEW_SOURCE_SHA']) { for (const value of [undefined, '', 'A'.repeat(40), `${sha}\n`, `${sha}/..`, sha.slice(1)]) cases.push([key, value]); } @@ -76,8 +107,15 @@ test('rejects package failures and HEAD mismatch or extra output before HTTP, sa } for (const key of ['readFileSync', 'execFileSync']) { const f = fixture(); - await rejected(f, { [key]: () => { throw new Error(`${secret}/private/path`); } }, - key === 'readFileSync' ? 'Invalid preview package version' : 'Unable to verify preview HEAD'); + await rejected( + f, + { + [key]: () => { + throw new Error(`${secret}/private/path`); + }, + }, + key === 'readFileSync' ? 'Invalid preview package version' : 'Unable to verify preview HEAD', + ); assert.ok(!f.calls.some(([kind]) => kind === 'fetch')); } for (const value of ['b'.repeat(40), `${sha}\nextra`, `${sha}\n\n`, ` ${sha}\n`, `${sha}\r`, 'A'.repeat(40)]) { @@ -98,31 +136,71 @@ test('uses module-relative root rather than an environment-supplied root', async }); test('rejects HTTP/rate-limit/redirect failures, missing bodies and invalid JSON without retry', async () => { - for (const response of [new Response(secret, { status: 403 }), new Response(secret, { status: 429 }), - new Response(secret, { status: 302 }), new Response(secret, { status: 500 }), - new Response(null), new Response(`${secret}{`), new Response(''), {}]) { + for (const response of [ + new Response(secret, { status: 403 }), + new Response(secret, { status: 429 }), + new Response(secret, { status: 302 }), + new Response(secret, { status: 500 }), + new Response(null), + new Response(`${secret}{`), + new Response(''), + {}, + ]) { let calls = 0; - await rejected(fixture(), { fetch: async () => { calls++; return response; } }, 'Unable to read preview checks'); + await rejected( + fixture(), + { + fetch: async () => { + calls++; + return response; + }, + }, + 'Unable to read preview checks', + ); assert.equal(calls, 1); } for (const name of ['TypeError', 'TimeoutError', 'AbortError']) { - await rejected(fixture(), { fetch: async (_url, options) => { - assert.ok(options.signal instanceof AbortSignal); - throw new DOMException(secret, name); - } }, 'Unable to read preview checks'); + await rejected( + fixture(), + { + fetch: async (_url, options) => { + assert.ok(options.signal instanceof AbortSignal); + throw new DOMException(secret, name); + }, + }, + 'Unable to read preview checks', + ); } }); test('delegates complete REST check authority to the existing source policy', async () => { const mutations = [ - (c) => { c.total_count = 101; }, - (c) => { c.check_runs = null; }, - (c) => { c.check_runs.push(c.check_runs[0]); c.total_count++; }, - (c) => { c.check_runs.pop(); c.total_count--; }, - (c) => { c.check_runs[0].status = 'in_progress'; }, - (c) => { c.check_runs[0].conclusion = 'failure'; }, - (c) => { c.check_runs[0].app.slug = secret; }, - (c) => { c.check_runs[0].head_sha = 'b'.repeat(40); }, + (c) => { + c.total_count = 101; + }, + (c) => { + c.check_runs = null; + }, + (c) => { + c.check_runs.push(c.check_runs[0]); + c.total_count++; + }, + (c) => { + c.check_runs.pop(); + c.total_count--; + }, + (c) => { + c.check_runs[0].status = 'in_progress'; + }, + (c) => { + c.check_runs[0].conclusion = 'failure'; + }, + (c) => { + c.check_runs[0].app.slug = secret; + }, + (c) => { + c.check_runs[0].head_sha = 'b'.repeat(40); + }, ]; for (const mutate of mutations) { const f = fixture(); @@ -138,10 +216,18 @@ test('counts streamed UTF-8 bytes, cancels oversize bodies despite lying Content for (const headers of [{}, { 'Content-Length': '1' }]) { let cancelled = false; let pulls = 0; - const body = new ReadableStream({ - pull(controller) { pulls++; controller.enqueue(Buffer.from('é'.repeat(200_000))); }, - cancel() { cancelled = true; }, - }, { highWaterMark: 0 }); + const body = new ReadableStream( + { + pull(controller) { + pulls++; + controller.enqueue(Buffer.from('é'.repeat(200_000))); + }, + cancel() { + cancelled = true; + }, + }, + { highWaterMark: 0 }, + ); await rejected(fixture(), { fetch: async () => new Response(body, { headers }) }, 'Unable to read preview checks'); assert.equal(cancelled, true); assert.equal(pulls, 3); @@ -155,15 +241,26 @@ test('counts streamed UTF-8 bytes, cancels oversize bodies despite lying Content test('rejects read errors and simulated body timeouts without waiting on a real clock', async () => { for (const name of ['Error', 'TimeoutError', 'AbortError']) { - const body = new ReadableStream({ pull(controller) { controller.error(new DOMException(secret, name)); } }); + const body = new ReadableStream({ + pull(controller) { + controller.error(new DOMException(secret, name)); + }, + }); await rejected(fixture(), { fetch: async () => new Response(body) }, 'Unable to read preview checks'); assert.equal(body.locked, false); } let cancelled = false; - const body = new ReadableStream({ - pull(controller) { controller.enqueue('not byte data'); }, - cancel() { cancelled = true; }, - }, { highWaterMark: 0 }); + const body = new ReadableStream( + { + pull(controller) { + controller.enqueue('not byte data'); + }, + cancel() { + cancelled = true; + }, + }, + { highWaterMark: 0 }, + ); await rejected(fixture(), { fetch: async () => new Response(body) }, 'Unable to read preview checks'); assert.equal(cancelled, true); }); @@ -175,14 +272,27 @@ test('the request deadline also cancels body reading, using a controlled signal return controller.signal; }); let cancelled = false; - const body = new ReadableStream({ - pull() { controller.abort(new DOMException(secret, 'TimeoutError')); }, - cancel() { cancelled = true; }, - }, { highWaterMark: 0 }); - await rejected(fixture(), { fetch: async (_url, options) => { - assert.equal(options.signal, controller.signal); - return new Response(body); - } }, 'Unable to read preview checks'); + const body = new ReadableStream( + { + pull() { + controller.abort(new DOMException(secret, 'TimeoutError')); + }, + cancel() { + cancelled = true; + }, + }, + { highWaterMark: 0 }, + ); + await rejected( + fixture(), + { + fetch: async (_url, options) => { + assert.equal(options.signal, controller.signal); + return new Response(body); + }, + }, + 'Unable to read preview checks', + ); assert.equal(cancelled, true); }); @@ -204,13 +314,26 @@ test('import has no provenance I/O; guarded CLI emits only a sanitized error and syncBuiltinESMExports(); process.env = {}; `; - const imported = execFileSync(process.execPath, ['--input-type=module', '-e', `${setup} + const imported = execFileSync( + process.execPath, + [ + '--input-type=module', + '-e', + `${setup} await import(${JSON.stringify(target)}); process.stdout.write('import-only'); - `], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }); + `, + ], + { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }, + ); assert.equal(imported, 'import-only'); const f = fixture(); - const success = execFileSync(process.execPath, ['--input-type=module', '-e', `${setup} + const success = execFileSync( + process.execPath, + [ + '--input-type=module', + '-e', + `${setup} const loaderRead = fs.readFileSync; fs.readFileSync = (name, ...args) => String(name).endsWith('package.json') ? '{"version":"0.6.0"}' : loaderRead(name, ...args); @@ -220,16 +343,31 @@ test('import has no provenance I/O; guarded CLI emits only a sanitized error and process.env = ${JSON.stringify(f.env)}; process.argv[1] = fileURLToPath(${JSON.stringify(target)}); await import(${JSON.stringify(target)}); - `], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }); + `, + ], + { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }, + ); assert.equal(success.replace(/\r\n/g, '\n'), `${JSON.stringify({ sourceSha: sha, version: '0.6.0' })}\n`); assert.ok(!success.includes(secret)); - assert.throws(() => execFileSync(process.execPath, ['--input-type=module', '-e', `${setup} + assert.throws( + () => + execFileSync( + process.execPath, + [ + '--input-type=module', + '-e', + `${setup} process.argv[1] = fileURLToPath(${JSON.stringify(target)}); await import(${JSON.stringify(target)}); - `], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }), (error) => { - assert.equal(error.status, 1); - assert.equal(error.stdout, ''); - assert.equal(error.stderr.replace(/\r\n/g, '\n'), 'Invalid preview inputs\n'); - return true; - }); + `, + ], + { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }, + ), + (error) => { + assert.equal(error.status, 1); + assert.equal(error.stdout, ''); + assert.equal(error.stderr.replace(/\r\n/g, '\n'), 'Invalid preview inputs\n'); + return true; + }, + ); }); diff --git a/scripts/macos-preview-workflow.test.mjs b/scripts/macos-preview-workflow.test.mjs index 6efd5b77..bfec12c1 100644 --- a/scripts/macos-preview-workflow.test.mjs +++ b/scripts/macos-preview-workflow.test.mjs @@ -14,11 +14,26 @@ const pins = [ ]; const artifactName = 'quorb-macos-preview-${{ github.sha }}'; const guideClaims = [ - 'GitHub login', '14 days', 'not application expiry', 'ARM64', 'macOS 15', - 'manual updates', 'Developer ID', 'not notarized', 'manifest.sourceSha', - 'manifest.version', 'manifest.dmg.sha256', 'shasum -a 256', 'not proof of safety', - 'quarantine', 'malware', 'damaged', 'https://support.apple.com/en-us/102445', - 'not yet validated', 'Inicio de sesión', 'No elimines', + 'GitHub login', + '14 days', + 'not application expiry', + 'ARM64', + 'macOS 15', + 'manual updates', + 'Developer ID', + 'not notarized', + 'manifest.sourceSha', + 'manifest.version', + 'manifest.dmg.sha256', + 'shasum -a 256', + 'not proof of safety', + 'quarantine', + 'malware', + 'damaged', + 'https://support.apple.com/en-us/102445', + 'not yet validated', + 'Inicio de sesión', + 'No elimines', ]; function assertMaterialization(sourceBytes, activeBytes) { @@ -31,7 +46,9 @@ function assertContract(workflow, materialized, pkg, guide) { assert.equal(materialized, workflow); const parts = workflow.split(' steps:\n'); assert.equal(parts.length, 2); - assert.equal(parts[0], `name: macOS preview + assert.equal( + parts[0], + `name: macOS preview on: workflow_dispatch: @@ -62,8 +79,12 @@ jobs: env: PREVIEW_VERSION: \${{ inputs.version }} PREVIEW_SOURCE_SHA: \${{ inputs.source_sha }} -`); - assert.deepEqual(workflow.match(/uses: (\S+)/g).map((line) => line.slice(6)), pins); +`, + ); + assert.deepEqual( + workflow.match(/uses: (\S+)/g).map((line) => line.slice(6)), + pins, + ); const action = (name, pin, options) => `${name}\n uses: ${pin}\n with:\n${options}`; const stepParts = parts[1].split(/ - name: /); assert.equal(stepParts[0], ''); @@ -76,11 +97,18 @@ jobs: 'Install locked dependencies\n run: npm ci', 'Build app and DMG\n run: npm run app:build:mac', 'Stage verified preview\n run: node scripts/macos-preview-artifact.mjs stage', - action('Upload immutable preview', pins[3], ` name: ${artifactName}\n path: src-tauri/target/macos-preview-upload\n retention-days: 14\n if-no-files-found: error\n overwrite: false\n include-hidden-files: false`), + action( + 'Upload immutable preview', + pins[3], + ` name: ${artifactName}\n path: src-tauri/target/macos-preview-upload\n retention-days: 14\n if-no-files-found: error\n overwrite: false\n include-hidden-files: false`, + ), action('Download same-run preview by name', pins[4], ` name: ${artifactName}\n path: src-tauri/target/macos-preview-download`), 'Verify downloaded preview\n run: node scripts/macos-preview-artifact.mjs readback', ]); - assert.doesNotMatch(workflow, /secrets\.|pull_request_target|continue-on-error|always\(|id-token|keychain|notariz|latest\.json|minisign|tauri-action|gh release/); + assert.doesNotMatch( + workflow, + /secrets\.|pull_request_target|continue-on-error|always\(|id-token|keychain|notariz|latest\.json|minisign|tauri-action|gh release/, + ); assert.ok(pkg.scripts.test.includes('scripts/macos-preview-workflow.test.mjs')); assert.equal(pkg.scripts['app:build:mac'], 'tauri build --config src-tauri/tauri.macos.conf.json'); for (const claim of guideClaims) assert.ok(guide.includes(claim), `Missing guidance: ${claim}`); @@ -89,7 +117,9 @@ jobs: const fixtures = () => [read(source), read(source), JSON.parse(read('package.json')), read('docs/macos-preview-README.md')]; for (const [label, endings] of [ - ['LF', ['\n', '\n']], ['CRLF', ['\r\n', '\r\n']], ['mixed LF/CRLF', ['\n', '\r\n']], + ['LF', ['\n', '\n']], + ['CRLF', ['\r\n', '\r\n']], + ['mixed LF/CRLF', ['\n', '\r\n']], ]) { test(`pure preview contract accepts ${label} with in-memory materialization`, () => { const values = fixtures(); @@ -107,27 +137,42 @@ test('real preview integration requires active workflow with byte-identical revi test('rejects removed gates, unsafe scope, input interpolation, publishing and artifact drift', () => { const values = fixtures(); const mutations = [ - ['workflow_dispatch:', 'push:'], [' workflow_dispatch:', ' schedule:\n workflow_dispatch:'], + ['workflow_dispatch:', 'push:'], + [' workflow_dispatch:', ' schedule:\n workflow_dispatch:'], [' steps:\n', ' steps:\n - run: echo unreviewed\n'], - [' required: true', ' required: false'], [' type: string', ' type: boolean'], + [' required: true', ' required: false'], + [' type: string', ' type: boolean'], [' type: string', ' type: string\n default: 0.6.0'], - [" if: github.ref == 'refs/heads/main'\n", ''], ["refs/heads/main", 'refs/heads/topic'], + [" if: github.ref == 'refs/heads/main'\n", ''], + ['refs/heads/main', 'refs/heads/topic'], [' name: Build unsigned macOS preview', ' name: Tests and bundle (macOS ARM64)'], - ['contents: read', 'contents: write'], [' checks: read\n', ''], [' checks: read', ' id-token: write'], - ['cancel-in-progress: false', 'cancel-in-progress: true'], ['macos-preview-${{ github.ref }}', 'macos-ci-${{ github.ref }}'], - ['macos-15', 'ubuntu-latest'], ['timeout-minutes: 30', 'timeout-minutes: 90'], - ['node-version: 22', 'node-version: 24'], ['package-manager-cache: false', 'package-manager-cache: true'], - ['ref: ${{ github.sha }}', 'ref: ${{ inputs.source_sha }}'], ['persist-credentials: false', 'persist-credentials: true'], + ['contents: read', 'contents: write'], + [' checks: read\n', ''], + [' checks: read', ' id-token: write'], + ['cancel-in-progress: false', 'cancel-in-progress: true'], + ['macos-preview-${{ github.ref }}', 'macos-ci-${{ github.ref }}'], + ['macos-15', 'ubuntu-latest'], + ['timeout-minutes: 30', 'timeout-minutes: 90'], + ['node-version: 22', 'node-version: 24'], + ['package-manager-cache: false', 'package-manager-cache: true'], + ['ref: ${{ github.sha }}', 'ref: ${{ inputs.source_sha }}'], + ['persist-credentials: false', 'persist-credentials: true'], ['PREVIEW_SOURCE_SHA: ${{ inputs.source_sha }}', 'PREVIEW_SOURCE_SHA: ${{ github.sha }}'], ['PREVIEW_VERSION: ${{ inputs.version }}', 'PREVIEW_VERSION: 0.6.0'], - [' env:', ' env:\n GH_TOKEN: ${{ github.token }}'], [' GH_TOKEN: ${{ github.token }}\n', ''], - ['run: npm ci', 'run: npm ci --ignore-scripts'], ['run: npm ci', 'run: echo ${{ inputs.version }}'], - ['run: npm ci', 'if: always()\n run: npm ci'], ['run: npm ci', 'continue-on-error: true\n run: npm ci'], - ['run: npm run app:build:mac', 'run: npm run app:build:macos'], ['run: npm ci', 'run: npm test'], + [' env:', ' env:\n GH_TOKEN: ${{ github.token }}'], + [' GH_TOKEN: ${{ github.token }}\n', ''], + ['run: npm ci', 'run: npm ci --ignore-scripts'], + ['run: npm ci', 'run: echo ${{ inputs.version }}'], + ['run: npm ci', 'if: always()\n run: npm ci'], + ['run: npm ci', 'continue-on-error: true\n run: npm ci'], + ['run: npm run app:build:mac', 'run: npm run app:build:macos'], + ['run: npm ci', 'run: npm test'], ['run: node scripts/macos-preview-preflight.mjs', 'run: npm ci'], ['run: node scripts/macos-preview-artifact.mjs stage', 'run: gh release create preview'], - ['retention-days: 14', 'retention-days: 90'], ['overwrite: false', 'overwrite: true'], - ['include-hidden-files: false', 'include-hidden-files: true'], ['if-no-files-found: error', 'if-no-files-found: warn'], + ['retention-days: 14', 'retention-days: 90'], + ['overwrite: false', 'overwrite: true'], + ['include-hidden-files: false', 'include-hidden-files: true'], + ['if-no-files-found: error', 'if-no-files-found: warn'], ['path: src-tauri/target/macos-preview-upload', 'path: src-tauri/target'], ['path: src-tauri/target/macos-preview-download', 'path: elsewhere\n run-id: 123'], ['path: src-tauri/target/macos-preview-download', 'path: elsewhere\n github-token: ${{ github.token }}'], @@ -148,8 +193,10 @@ test('rejects removed gates, unsafe scope, input interpolation, publishing and a assertMaterialization(sourceBytes, Buffer.from(values[0])); assert.throws(() => assertMaterialization(sourceBytes, Buffer.from(`${values[0]}\n`))); assert.throws(() => assertMaterialization(sourceBytes, Buffer.from(values[0].replaceAll('\n', '\r\n')))); - const swapped = values[0].replace(/run: (npm ci|node scripts\/macos-preview-preflight\.mjs)/g, - (_, command) => `run: ${command === 'npm ci' ? 'node scripts/macos-preview-preflight.mjs' : 'npm ci'}`); + const swapped = values[0].replace( + /run: (npm ci|node scripts\/macos-preview-preflight\.mjs)/g, + (_, command) => `run: ${command === 'npm ci' ? 'node scripts/macos-preview-preflight.mjs' : 'npm ci'}`, + ); assert.notEqual(swapped, values[0]); assert.throws(() => assertContract(swapped, swapped, ...values.slice(2))); }); diff --git a/scripts/macos-release-preflight.mjs b/scripts/macos-release-preflight.mjs index 6951223f..4d9144d8 100644 --- a/scripts/macos-release-preflight.mjs +++ b/scripts/macos-release-preflight.mjs @@ -18,7 +18,9 @@ export function validateReleaseInputs({ ref, version, sourceSha }) { async function readJson(response, signal) { if (!response?.ok || response.status !== 200 || typeof response.body?.getReader !== 'function') throw new Error(); const reader = response.body.getReader(); - const cancel = () => { void reader.cancel().catch(() => {}); }; + const cancel = () => { + void reader.cancel().catch(() => {}); + }; signal.addEventListener('abort', cancel, { once: true }); let complete = false; try { @@ -44,17 +46,20 @@ async function readJson(response, signal) { } // No import-time I/O. All external observations are injectable for offline tests. -export async function preflightRelease({ root = projectRoot, env = process.env, - execFileSync = execute, fetch = globalThis.fetch } = {}) { - const { GITHUB_REF: ref, RELEASE_VERSION: version, RELEASE_SOURCE_SHA: sourceSha, - GITHUB_REPOSITORY: repository, GH_TOKEN: token } = env; +export async function preflightRelease({ root = projectRoot, env = process.env, execFileSync = execute, fetch = globalThis.fetch } = {}) { + const { GITHUB_REF: ref, RELEASE_VERSION: version, RELEASE_SOURCE_SHA: sourceSha, GITHUB_REPOSITORY: repository, GH_TOKEN: token } = env; validateReleaseInputs({ ref, version, sourceSha }); if (repository !== 'egdev6/quorb' || typeof token !== 'string' || !token.trim() || /[\r\n]/.test(token)) { throw new Error('Invalid release environment'); } - const git = (args) => execFileSync('git', args, { - cwd: root, encoding: 'utf8', timeout: 10_000, maxBuffer: 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'], - }); + const git = (args) => + execFileSync('git', args, { + cwd: root, + encoding: 'utf8', + timeout: 10_000, + maxBuffer: 1024 * 1024, + stdio: ['ignore', 'pipe', 'pipe'], + }); let failure = 'Release source_sha must be an ancestor of origin/main'; try { git(['merge-base', '--is-ancestor', sourceSha, 'origin/main']); @@ -65,9 +70,10 @@ export async function preflightRelease({ root = projectRoot, env = process.env, const signal = AbortSignal.timeout(30_000); const request = async (route, allowMissing = false) => { const response = await fetch(`https://api.github.com/repos/egdev6/quorb${route}`, { - method: 'GET', redirect: 'error', signal, - headers: { Accept: 'application/vnd.github+json', Authorization: `Bearer ${token}`, - 'X-GitHub-Api-Version': '2022-11-28' }, + method: 'GET', + redirect: 'error', + signal, + headers: { Accept: 'application/vnd.github+json', Authorization: `Bearer ${token}`, 'X-GitHub-Api-Version': '2022-11-28' }, }); if (allowMissing && response?.status === 404) { await response.body?.cancel(); @@ -93,8 +99,14 @@ export async function preflightRelease({ root = projectRoot, env = process.env, if (found.length === 0) throw new Error(`Release v${version} must already exist`); if (found.length !== 1) throw new Error(); const release = found[0]; - if (!Number.isSafeInteger(release.id) || release.id <= 0 || typeof release.draft !== 'boolean' || - release.prerelease !== false || typeof release.target_commitish !== 'string') throw new Error(); + if ( + !Number.isSafeInteger(release.id) || + release.id <= 0 || + typeof release.draft !== 'boolean' || + release.prerelease !== false || + typeof release.target_commitish !== 'string' + ) + throw new Error(); failure = 'Release tag must point at source_sha'; const tag = await request(`/git/ref/tags/v${version}`, true); @@ -130,9 +142,10 @@ export async function preflightRelease({ root = projectRoot, env = process.env, if (failure === 'Unable to verify release metadata' && error.message === `Release v${version} must already exist`) { throw new Error(error.message); } - if (failure === 'Unable to verify release assets' && - [ `Release already contains Quorb_${version}_aarch64.dmg`, - `Release already contains Quorb_${version}_aarch64.dmg.sha256` ].includes(error.message)) { + if ( + failure === 'Unable to verify release assets' && + [`Release already contains Quorb_${version}_aarch64.dmg`, `Release already contains Quorb_${version}_aarch64.dmg.sha256`].includes(error.message) + ) { throw new Error(error.message); } throw new Error(failure); diff --git a/scripts/macos-release-preflight.test.mjs b/scripts/macos-release-preflight.test.mjs index 94e1b9a3..fbd78a48 100644 --- a/scripts/macos-release-preflight.test.mjs +++ b/scripts/macos-release-preflight.test.mjs @@ -6,17 +6,17 @@ const sha = 'a'.repeat(40); const other = 'b'.repeat(40); const token = 'PRIVATE_FIXTURE_MARKER'; function fixture() { - const env = { GITHUB_REPOSITORY: 'egdev6/quorb', GITHUB_REF: 'refs/heads/main', - RELEASE_VERSION: '0.8.0', RELEASE_SOURCE_SHA: sha, GH_TOKEN: token }; - const release = { id: 118, tag_name: 'v0.8.0', draft: false, prerelease: false, - target_commitish: sha }; + const env = { GITHUB_REPOSITORY: 'egdev6/quorb', GITHUB_REF: 'refs/heads/main', RELEASE_VERSION: '0.8.0', RELEASE_SOURCE_SHA: sha, GH_TOKEN: token }; + const release = { id: 118, tag_name: 'v0.8.0', draft: false, prerelease: false, target_commitish: sha }; const calls = []; const responses = { '/releases?per_page=100&page=1': [release], '/git/ref/tags/v0.8.0': { object: { type: 'commit', sha } }, '/releases/118/assets?per_page=100&page=1': [], }; - const options = { root: '/fixture', env, + const options = { + root: '/fixture', + env, execFileSync(command, args, settings) { calls.push(['git', command, args, settings]); return args[0] === 'show' ? '{"version":"0.8.0"}' : ''; @@ -42,10 +42,13 @@ async function rejects(f, message, patch = {}) { test('accepts an ancestor, checks package at that SHA and resolves a lightweight tag', async () => { const f = fixture(); assert.deepEqual(await f.run(), { sourceSha: sha, version: '0.8.0', releaseId: 118 }); - assert.deepEqual(f.calls.filter(([kind]) => kind === 'git').map(([, command, args]) => [command, args]), [ - ['git', ['merge-base', '--is-ancestor', sha, 'origin/main']], - ['git', ['show', `${sha}:package.json`]], - ]); + assert.deepEqual( + f.calls.filter(([kind]) => kind === 'git').map(([, command, args]) => [command, args]), + [ + ['git', ['merge-base', '--is-ancestor', sha, 'origin/main']], + ['git', ['show', `${sha}:package.json`]], + ], + ); for (const [, , , settings] of f.calls.filter(([kind]) => kind === 'git')) { assert.equal(settings.cwd, '/fixture'); assert.equal(settings.timeout, 10_000); @@ -60,16 +63,17 @@ test('accepts an ancestor, checks package at that SHA and resolves a lightweight test('S4 rejects every non-main ref with the exact error before I/O', async () => { for (const ref of [undefined, 'main', 'refs/heads/topic', 'refs/pull/118/merge', 'refs/heads/main\n']) { - const f = fixture(); f.env.GITHUB_REF = ref; + const f = fixture(); + f.env.GITHUB_REF = ref; await rejects(f, 'Release ref must be refs/heads/main'); assert.deepEqual(f.calls, []); } }); test('S4 rejects non-stable or malformed versions with the exact error before I/O', async () => { - for (const version of [undefined, '', 'v0.8.0', '0.8', '00.8.0', '0.08.0', '0.8.00', - '0.8.0-rc.1', '0.8.0+build', '0.8.0\n', '../0.8.0', ' 0.8.0', 8]) { - const f = fixture(); f.env.RELEASE_VERSION = version; + for (const version of [undefined, '', 'v0.8.0', '0.8', '00.8.0', '0.08.0', '0.8.00', '0.8.0-rc.1', '0.8.0+build', '0.8.0\n', '../0.8.0', ' 0.8.0', 8]) { + const f = fixture(); + f.env.RELEASE_VERSION = version; await rejects(f, 'Release version must be stable SemVer'); assert.deepEqual(f.calls, []); } @@ -77,7 +81,8 @@ test('S4 rejects non-stable or malformed versions with the exact error before I/ test('S4 rejects malformed source_sha with the exact error before I/O', async () => { for (const value of [undefined, '', other.slice(1), 'A'.repeat(40), 'g'.repeat(40), `${sha}\n`, `${sha}/..`, 40]) { - const f = fixture(); f.env.RELEASE_SOURCE_SHA = value; + const f = fixture(); + f.env.RELEASE_SOURCE_SHA = value; await rejects(f, 'Release source_sha must be 40 lowercase hex characters'); assert.deepEqual(f.calls, []); } @@ -85,7 +90,9 @@ test('S4 rejects malformed source_sha with the exact error before I/O', async () test('S4 rejects non-ancestors and Git failures with the exact error, before API access', async () => { await rejects(fixture(), 'Release source_sha must be an ancestor of origin/main', { - execFileSync: () => { throw new Error(token); }, + execFileSync: () => { + throw new Error(token); + }, }); }); @@ -93,22 +100,27 @@ test('S4 rejects a different or unreadable package version at source_sha with th for (const data of ['{"version":"0.8.1"}', '{', 'null', '{}', '{"version":"0.8.0\\n"}']) { const f = fixture(); await rejects(f, 'Release package.json version must match version at source_sha', { - execFileSync: (_command, args) => args[0] === 'show' ? data : '', + execFileSync: (_command, args) => (args[0] === 'show' ? data : ''), }); assert.ok(!f.calls.some(([kind]) => kind === 'fetch')); } await rejects(fixture(), 'Release package.json version must match version at source_sha', { - execFileSync: (_command, args) => { if (args[0] === 'show') throw new Error(token); return ''; }, + execFileSync: (_command, args) => { + if (args[0] === 'show') throw new Error(token); + return ''; + }, }); }); test('S4 rejects a missing release with the exact error (drafts are discovered through the list API)', async () => { - const f = fixture(); f.responses['/releases?per_page=100&page=1'] = []; + const f = fixture(); + f.responses['/releases?per_page=100&page=1'] = []; await rejects(f, 'Release v0.8.0 must already exist'); }); test('S4 rejects tag/source mismatch with the exact error even if target_commitish matches', async () => { - const f = fixture(); f.responses['/git/ref/tags/v0.8.0'].object.sha = other; + const f = fixture(); + f.responses['/git/ref/tags/v0.8.0'].object.sha = other; await rejects(f, 'Release tag must point at source_sha'); }); @@ -120,7 +132,8 @@ test('S4 rejects the target macOS DMG asset with the exact error, including late }); test('accepts nested annotated tags and ignores stale target_commitish when a real tag exists', async () => { - const f = fixture(); f.release.target_commitish = 'main'; + const f = fixture(); + f.release.target_commitish = 'main'; f.responses['/git/ref/tags/v0.8.0'] = { object: { type: 'tag', sha: other } }; f.responses[`/git/tags/${other}`] = { object: { type: 'tag', sha: 'c'.repeat(40) } }; f.responses[`/git/tags/${'c'.repeat(40)}`] = { object: { type: 'commit', sha } }; @@ -129,7 +142,9 @@ test('accepts nested annotated tags and ignores stale target_commitish when a re test('accepts a Windows draft without a tag only with an exact SHA target_commitish', async () => { for (const target of [sha, other, 'main', `${sha}\n`]) { - const f = fixture(); f.release.draft = true; f.release.target_commitish = target; + const f = fixture(); + f.release.draft = true; + f.release.target_commitish = target; f.responses['/git/ref/tags/v0.8.0'] = new Response('', { status: 404 }); if (target === sha) assert.equal((await f.run()).releaseId, 118); else await rejects(f, 'Release tag must point at source_sha'); @@ -141,13 +156,16 @@ test('accepts a Windows draft without a tag only with an exact SHA target_commit test('fails closed on malformed, duplicate or prerelease release records and tag objects', async () => { for (const data of [null, {}, [null], [{ id: 118 }], [fixture().release, fixture().release]]) { - const f = fixture(); f.responses['/releases?per_page=100&page=1'] = data; + const f = fixture(); + f.responses['/releases?per_page=100&page=1'] = data; await rejects(f, 'Unable to verify release metadata'); } - const f = fixture(); f.release.prerelease = true; + const f = fixture(); + f.release.prerelease = true; await rejects(f, 'Unable to verify release metadata'); for (const object of [null, {}, { type: 'tree', sha }, { type: 'commit', sha: `${sha}\n` }, { type: 'tag', sha: other }]) { - const g = fixture(); g.responses['/git/ref/tags/v0.8.0'] = { object }; + const g = fixture(); + g.responses['/git/ref/tags/v0.8.0'] = { object }; g.responses[`/git/tags/${other}`] = { object: { type: 'tag', sha: other } }; await rejects(g, 'Release tag must point at source_sha'); } @@ -165,8 +183,14 @@ test('paginates release discovery and assets; rejects a checksum collision too', }); test('rejects untrusted repository and invalid tokens without consuming dependencies', async () => { - for (const [key, value] of [['GITHUB_REPOSITORY', 'other/quorb'], ['GH_TOKEN', undefined], ['GH_TOKEN', ''], ['GH_TOKEN', `${token}\n`]]) { - const f = fixture(); f.env[key] = value; + for (const [key, value] of [ + ['GITHUB_REPOSITORY', 'other/quorb'], + ['GH_TOKEN', undefined], + ['GH_TOKEN', ''], + ['GH_TOKEN', `${token}\n`], + ]) { + const f = fixture(); + f.env[key] = value; await rejects(f, 'Invalid release environment'); assert.deepEqual(f.calls, []); } @@ -179,11 +203,25 @@ test('sanitizes HTTP errors, redirects, invalid JSON, oversized and timed-out bo for (const data of ['{', token, ' '.repeat(1024 * 1024 + 1)]) { await rejects(fixture(), 'Unable to verify release metadata', { fetch: async () => new Response(data) }); } - await rejects(fixture(), 'Unable to verify release metadata', { fetch: async () => { throw new Error(token); } }); + await rejects(fixture(), 'Unable to verify release metadata', { + fetch: async () => { + throw new Error(token); + }, + }); const controller = new AbortController(); t.mock.method(AbortSignal, 'timeout', () => controller.signal); let cancelled = false; - const body = new ReadableStream({ pull() { controller.abort(); }, cancel() { cancelled = true; } }, { highWaterMark: 0 }); + const body = new ReadableStream( + { + pull() { + controller.abort(); + }, + cancel() { + cancelled = true; + }, + }, + { highWaterMark: 0 }, + ); await rejects(fixture(), 'Unable to verify release metadata', { fetch: async () => new Response(body) }); assert.equal(cancelled, true); }); diff --git a/scripts/macos-release-resume-publish.mjs b/scripts/macos-release-resume-publish.mjs index 98b52e14..da9ce6e7 100644 --- a/scripts/macos-release-resume-publish.mjs +++ b/scripts/macos-release-resume-publish.mjs @@ -7,16 +7,33 @@ import { githubClient, validateArtifact, downloadZip, extractZip } from './macos export async function loadFinalArtifact({ env = process.env, io = fs, fetch = globalThis.fetch } = {}) { validateReleaseInputs({ ref: env.GITHUB_REF, version: env.RELEASE_VERSION, sourceSha: env.RELEASE_SOURCE_SHA }); - if (env.GITHUB_REPOSITORY !== repository || !positiveId(env.GITHUB_REPOSITORY_ID) || !positiveId(env.GITHUB_RUN_ID) || - !positiveId(env.GITHUB_RUN_ATTEMPT) || !positiveId(env.FINAL_ARTIFACT_ID) || !hex(env.FINAL_ARTIFACT_DIGEST, 64) || - !hex(env.FINAL_SHA256, 64) || !hex(env.GITHUB_SHA, 40)) throw new Error('Invalid publication context'); + if ( + env.GITHUB_REPOSITORY !== repository || + !positiveId(env.GITHUB_REPOSITORY_ID) || + !positiveId(env.GITHUB_RUN_ID) || + !positiveId(env.GITHUB_RUN_ATTEMPT) || + !positiveId(env.FINAL_ARTIFACT_ID) || + !hex(env.FINAL_ARTIFACT_DIGEST, 64) || + !hex(env.FINAL_SHA256, 64) || + !hex(env.GITHUB_SHA, 40) + ) + throw new Error('Invalid publication context'); const api = githubClient({ token: env.GH_TOKEN, fetch }); const run = await api.json(`/actions/runs/${env.GITHUB_RUN_ID}/attempts/${env.GITHUB_RUN_ATTEMPT}`); - if (run.id !== Number(env.GITHUB_RUN_ID) || run.run_attempt !== Number(env.GITHUB_RUN_ATTEMPT) || run.head_sha !== env.GITHUB_SHA || - run.head_branch !== 'main' || run.event !== 'workflow_dispatch' || run.path !== '.github/workflows/macos-release-resume.yml' || - run.repository?.id !== Number(env.GITHUB_REPOSITORY_ID) || run.head_repository?.id !== Number(env.GITHUB_REPOSITORY_ID) || - run.repository?.full_name !== repository || run.head_repository?.full_name !== repository || - !Number.isFinite(Date.parse(run.run_started_at))) throw new Error('Untrusted final artifact run'); + if ( + run.id !== Number(env.GITHUB_RUN_ID) || + run.run_attempt !== Number(env.GITHUB_RUN_ATTEMPT) || + run.head_sha !== env.GITHUB_SHA || + run.head_branch !== 'main' || + run.event !== 'workflow_dispatch' || + run.path !== '.github/workflows/macos-release-resume.yml' || + run.repository?.id !== Number(env.GITHUB_REPOSITORY_ID) || + run.head_repository?.id !== Number(env.GITHUB_REPOSITORY_ID) || + run.repository?.full_name !== repository || + run.head_repository?.full_name !== repository || + !Number.isFinite(Date.parse(run.run_started_at)) + ) + throw new Error('Untrusted final artifact run'); const name = `macos-notary-final-${env.GITHUB_RUN_ID}-${env.GITHUB_RUN_ATTEMPT}`; const found = (await api.artifacts(env.GITHUB_RUN_ID)).filter((artifact) => artifact.name === name); if (found.length !== 1 || String(found[0].id) !== env.FINAL_ARTIFACT_ID || found[0].digest !== `sha256:${env.FINAL_ARTIFACT_DIGEST}`) { @@ -25,8 +42,8 @@ export async function loadFinalArtifact({ env = process.env, io = fs, fetch = gl const artifact = validateArtifact(found[0], run, name, { end: Date.now() }); const dmgName = `Quorb_${env.RELEASE_VERSION}_aarch64.dmg`; const files = extractZip(await downloadZip(artifact, { token: env.GH_TOKEN, fetch }), { [dmgName]: MAX_DMG, [`${dmgName}.sha256`]: 1024 }); - if (hash(files.get(dmgName)) !== env.FINAL_SHA256 || - files.get(`${dmgName}.sha256`).toString('utf8') !== `${env.FINAL_SHA256} ${dmgName}\n`) throw new Error('Final DMG/checksum mismatch'); + if (hash(files.get(dmgName)) !== env.FINAL_SHA256 || files.get(`${dmgName}.sha256`).toString('utf8') !== `${env.FINAL_SHA256} ${dmgName}\n`) + throw new Error('Final DMG/checksum mismatch'); io.mkdirSync('notary-publish'); for (const [name, bytes] of files) io.writeFileSync(path.join('notary-publish', name), bytes, { flag: 'wx' }); return { dmgName, files }; @@ -34,8 +51,7 @@ export async function loadFinalArtifact({ env = process.env, io = fs, fetch = gl const publicationError = (message) => Object.assign(new Error(message), { safePublish: true }); -export async function publishFinal({ env = process.env, fetch = globalThis.fetch, load = loadFinalArtifact, - preflight = preflightRelease } = {}) { +export async function publishFinal({ env = process.env, fetch = globalThis.fetch, load = loadFinalArtifact, preflight = preflightRelease } = {}) { if (!positiveId(env.RELEASE_ID)) throw new Error('Invalid release identity'); const { dmgName, files } = await load({ env, fetch }); // Revalidate the existing release ID, source/tag and both empty asset names @@ -45,8 +61,11 @@ export async function publishFinal({ env = process.env, fetch = globalThis.fetch const headers = { Authorization: `Bearer ${env.GH_TOKEN}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' }; const upload = async (name, type) => { const response = await fetch(`https://uploads.github.com/repos/${repository}/releases/${env.RELEASE_ID}/assets?name=${name}`, { - method: 'POST', redirect: 'error', signal: AbortSignal.timeout(120_000), - headers: { ...headers, 'Content-Type': type }, body: files.get(name), + method: 'POST', + redirect: 'error', + signal: AbortSignal.timeout(120_000), + headers: { ...headers, 'Content-Type': type }, + body: files.get(name), }); if (response.status !== 201) throw new Error(); const text = await response.text(); @@ -56,25 +75,35 @@ export async function publishFinal({ env = process.env, fetch = globalThis.fetch return data.id; }; let ownedId; - try { ownedId = await upload(dmgName, 'application/x-apple-diskimage'); } - catch { throw publicationError('DMG upload failed or ambiguous; deleting nothing, inspect release assets'); } - try { await upload(`${dmgName}.sha256`, 'text/plain'); } - catch { + try { + ownedId = await upload(dmgName, 'application/x-apple-diskimage'); + } catch { + throw publicationError('DMG upload failed or ambiguous; deleting nothing, inspect release assets'); + } + try { + await upload(`${dmgName}.sha256`, 'text/plain'); + } catch { // Only this invocation's positive asset ID can ever be rolled back. try { const response = await fetch(`https://api.github.com/repos/${repository}/releases/assets/${ownedId}`, { - method: 'DELETE', headers, redirect: 'error', signal: AbortSignal.timeout(30_000), + method: 'DELETE', + headers, + redirect: 'error', + signal: AbortSignal.timeout(30_000), }); if (response.status !== 204) throw new Error(); - } catch { throw publicationError(`Checksum upload failed; rollback failed for owned DMG asset ${ownedId}; manual cleanup required`); } + } catch { + throw publicationError(`Checksum upload failed; rollback failed for owned DMG asset ${ownedId}; manual cleanup required`); + } throw publicationError(`Checksum upload failed; removed only owned DMG asset ${ownedId}; inspect any ambiguous checksum`); } return { outcome: 'published', dmgName }; } if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { - try { console.log(JSON.stringify(await publishFinal())); } - catch (error) { + try { + console.log(JSON.stringify(await publishFinal())); + } catch (error) { console.error(error.safePublish ? error.message : 'Publication failed; inspect release assets before recovery'); process.exitCode = 1; } diff --git a/scripts/macos-release-resume-publish.test.mjs b/scripts/macos-release-resume-publish.test.mjs index 712c2e22..319350bb 100644 --- a/scripts/macos-release-resume-publish.test.mjs +++ b/scripts/macos-release-resume-publish.test.mjs @@ -7,11 +7,20 @@ import { hash } from './macos-notary-checkpoint.mjs'; const dmgName = 'Quorb_0.8.0_aarch64.dmg'; function fixture({ checksumFailure = false, dmgFailure = false, rollbackFailure = false, releaseId = 42 } = {}) { const calls = []; - const files = new Map([[dmgName, Buffer.from('final DMG')], [`${dmgName}.sha256`, Buffer.from('final checksum')]]); + const files = new Map([ + [dmgName, Buffer.from('final DMG')], + [`${dmgName}.sha256`, Buffer.from('final checksum')], + ]); const options = { env: { RELEASE_ID: '42', GH_TOKEN: 'synthetic' }, - load: async () => { calls.push('load'); return { dmgName, files }; }, - preflight: async () => { calls.push('preflight'); return { releaseId }; }, + load: async () => { + calls.push('load'); + return { dmgName, files }; + }, + preflight: async () => { + calls.push('preflight'); + return { releaseId }; + }, fetch: async (url, opts) => { calls.push([url, opts]); if (opts.method === 'DELETE') return new Response(null, { status: rollbackFailure ? 500 : 204 }); @@ -58,8 +67,15 @@ function finalFixture() { const f = producerFixture(); const finalSha256 = hash(f.bytes); const archive = zipFiles({ [dmgName]: f.bytes, [`${dmgName}.sha256`]: `${finalSha256} ${dmgName}\n` }); - Object.assign(f.env, { GITHUB_RUN_ID: '123', GITHUB_RUN_ATTEMPT: '2', GITHUB_REPOSITORY_ID: '10', GITHUB_SHA: f.run.head_sha, - FINAL_ARTIFACT_ID: '999', FINAL_ARTIFACT_DIGEST: hash(archive), FINAL_SHA256: finalSha256 }); + Object.assign(f.env, { + GITHUB_RUN_ID: '123', + GITHUB_RUN_ATTEMPT: '2', + GITHUB_REPOSITORY_ID: '10', + GITHUB_SHA: f.run.head_sha, + FINAL_ARTIFACT_ID: '999', + FINAL_ARTIFACT_DIGEST: hash(archive), + FINAL_SHA256: finalSha256, + }); f.run.path = '.github/workflows/macos-release-resume.yml'; const artifact = { ...f.checkpoint, id: 999, name: 'macos-notary-final-123-2', size_in_bytes: archive.length, digest: `sha256:${hash(archive)}` }; f.artifacts.splice(0, f.artifacts.length, artifact); diff --git a/scripts/macos-release-resume-workflow.test.mjs b/scripts/macos-release-resume-workflow.test.mjs index 7478fa5d..31cc62c5 100644 --- a/scripts/macos-release-resume-workflow.test.mjs +++ b/scripts/macos-release-resume-workflow.test.mjs @@ -32,7 +32,10 @@ test('resume contract supports matching CRLF and rejects every line mutation and const lines = text.split('\n'); for (const [index, line] of lines.entries()) { if (!line.trim()) continue; - for (const candidate of [lines.filter((_, i) => i !== index).join('\n'), lines.map((value, i) => i === index ? `${value} # mutation` : value).join('\n')]) { + for (const candidate of [ + lines.filter((_, i) => i !== index).join('\n'), + lines.map((value, i) => (i === index ? `${value} # mutation` : value)).join('\n'), + ]) { assert.throws(() => contract(Buffer.from(candidate), Buffer.from(candidate)), undefined, line); } } diff --git a/scripts/macos-release-resume.mjs b/scripts/macos-release-resume.mjs index 1a5053af..f9544976 100644 --- a/scripts/macos-release-resume.mjs +++ b/scripts/macos-release-resume.mjs @@ -3,23 +3,41 @@ import path from 'node:path'; import { execFileSync } from 'node:child_process'; import { fileURLToPath } from 'node:url'; import { preflightRelease, validateReleaseInputs } from './macos-release-preflight.mjs'; -import { repository, workflowPath, positiveId, uuid, MAX_DMG, validateTrusted, validateManifest, validateDmg, validateReceipt } from './macos-notary-checkpoint.mjs'; +import { + repository, + workflowPath, + positiveId, + uuid, + MAX_DMG, + validateTrusted, + validateManifest, + validateDmg, + validateReceipt, +} from './macos-notary-checkpoint.mjs'; import { githubClient, validateRun, selectArtifacts, downloadZip, extractZip } from './macos-notary-artifact.mjs'; import { withNotaryKey, querySubmission } from './macos-notary-submit.mjs'; import { stapleAndVerifyDmg } from './verify-macos-bundle.mjs'; function inputs(env) { validateReleaseInputs({ ref: env.GITHUB_REF, version: env.RELEASE_VERSION, sourceSha: env.RELEASE_SOURCE_SHA }); - if (env.GITHUB_REPOSITORY !== repository || !positiveId(env.SOURCE_RUN_ID) || !positiveId(env.SOURCE_RUN_ATTEMPT) || - !positiveId(env.RELEASE_ID) || (env.SUBMISSION_ID && !uuid(env.SUBMISSION_ID))) throw new Error('Invalid resume inputs'); + if ( + env.GITHUB_REPOSITORY !== repository || + !positiveId(env.SOURCE_RUN_ID) || + !positiveId(env.SOURCE_RUN_ATTEMPT) || + !positiveId(env.RELEASE_ID) || + (env.SUBMISSION_ID && !uuid(env.SUBMISSION_ID)) + ) + throw new Error('Invalid resume inputs'); } export async function loadCheckpoint({ env = process.env, io = fs, exec = execFileSync, fetch = globalThis.fetch } = {}) { inputs(env); const api = githubClient({ token: env.GH_TOKEN, fetch }); const workflow = await api.json('/actions/workflows/macos-release.yml'); - const run = validateRun(await api.json(`/actions/runs/${env.SOURCE_RUN_ID}/attempts/${env.SOURCE_RUN_ATTEMPT}`), workflow, - { runId: env.SOURCE_RUN_ID, runAttempt: env.SOURCE_RUN_ATTEMPT }); + const run = validateRun(await api.json(`/actions/runs/${env.SOURCE_RUN_ID}/attempts/${env.SOURCE_RUN_ATTEMPT}`), workflow, { + runId: env.SOURCE_RUN_ID, + runAttempt: env.SOURCE_RUN_ATTEMPT, + }); try { const git = (args) => exec('git', args, { encoding: 'utf8', timeout: 10_000, maxBuffer: 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] }); // An ancestor alone is insufficient: require the approved producer workflow @@ -27,29 +45,46 @@ export async function loadCheckpoint({ env = process.env, io = fs, exec = execFi git(['merge-base', '--is-ancestor', run.head_sha, env.GITHUB_SHA]); git(['merge-base', '--is-ancestor', run.head_sha, 'origin/main']); if (git(['show', `${run.head_sha}:${workflowPath}`]) !== io.readFileSync(workflowPath, 'utf8')) throw new Error(); - } catch { throw new Error('Producer workflow SHA/content is not approved'); } + } catch { + throw new Error('Producer workflow SHA/content is not approved'); + } const latest = await api.json(`/actions/runs/${env.SOURCE_RUN_ID}`); if (!Number.isSafeInteger(latest.run_attempt) || latest.run_attempt < run.run_attempt) throw new Error('Invalid producer attempt history'); let end = Date.parse(run.updated_at); if (latest.run_attempt > run.run_attempt) { const next = await api.json(`/actions/runs/${env.SOURCE_RUN_ID}/attempts/${run.run_attempt + 1}`); - if (next.id !== run.id || next.run_attempt !== run.run_attempt + 1 || !Number.isFinite(Date.parse(next.run_started_at))) throw new Error('Invalid producer attempt boundary'); + if (next.id !== run.id || next.run_attempt !== run.run_attempt + 1 || !Number.isFinite(Date.parse(next.run_started_at))) + throw new Error('Invalid producer attempt boundary'); end = Math.min(end, Date.parse(next.run_started_at) - 1); } const artifacts = selectArtifacts(await api.artifacts(env.SOURCE_RUN_ID), run, Boolean(env.SUBMISSION_ID), { end }); - const trusted = validateTrusted({ repository, workflowPath, workflowSha: run.head_sha, version: env.RELEASE_VERSION, - sourceSha: env.RELEASE_SOURCE_SHA, releaseId: env.RELEASE_ID, runId: env.SOURCE_RUN_ID, runAttempt: env.SOURCE_RUN_ATTEMPT }); + const trusted = validateTrusted({ + repository, + workflowPath, + workflowSha: run.head_sha, + version: env.RELEASE_VERSION, + sourceSha: env.RELEASE_SOURCE_SHA, + releaseId: env.RELEASE_ID, + runId: env.SOURCE_RUN_ID, + runAttempt: env.SOURCE_RUN_ATTEMPT, + }); const dmgName = `Quorb_${trusted.version}_aarch64.dmg`; const files = extractZip(await downloadZip(artifacts.checkpoint, { token: env.GH_TOKEN, fetch }), { 'manifest.json': 65536, [dmgName]: MAX_DMG }); let manifest; - try { manifest = validateManifest(JSON.parse(files.get('manifest.json').toString('utf8')), trusted); } - catch { throw new Error('Invalid checkpoint manifest'); } + try { + manifest = validateManifest(JSON.parse(files.get('manifest.json').toString('utf8')), trusted); + } catch { + throw new Error('Invalid checkpoint manifest'); + } validateDmg(files.get(dmgName), manifest); let receipt; if (artifacts.receipt) { const receiptFiles = extractZip(await downloadZip(artifacts.receipt, { token: env.GH_TOKEN, fetch }), { 'receipt.json': 65536 }); - try { receipt = validateReceipt(JSON.parse(receiptFiles.get('receipt.json').toString('utf8')), trusted, artifacts.checkpoint, manifest); } - catch { throw new Error('Invalid submission receipt'); } + try { + receipt = validateReceipt(JSON.parse(receiptFiles.get('receipt.json').toString('utf8')), trusted, artifacts.checkpoint, manifest); + } catch { + throw new Error('Invalid submission receipt'); + } } const submissionId = env.SUBMISSION_ID || receipt?.submissionId; if (!uuid(submissionId)) throw new Error('Missing submission UUID; use diagnostics, never resubmit'); @@ -62,8 +97,16 @@ export async function loadCheckpoint({ env = process.env, io = fs, exec = execFi export function preparedCheckpoint({ env = process.env, io = fs } = {}) { inputs(env); - const trusted = validateTrusted({ repository, workflowPath, workflowSha: env.PRODUCER_WORKFLOW_SHA, version: env.RELEASE_VERSION, - sourceSha: env.RELEASE_SOURCE_SHA, releaseId: env.RELEASE_ID, runId: env.SOURCE_RUN_ID, runAttempt: env.SOURCE_RUN_ATTEMPT }); + const trusted = validateTrusted({ + repository, + workflowPath, + workflowSha: env.PRODUCER_WORKFLOW_SHA, + version: env.RELEASE_VERSION, + sourceSha: env.RELEASE_SOURCE_SHA, + releaseId: env.RELEASE_ID, + runId: env.SOURCE_RUN_ID, + runAttempt: env.SOURCE_RUN_ATTEMPT, + }); const manifest = validateManifest(JSON.parse(io.readFileSync('notary-retained/manifest.json', 'utf8')), trusted); const dmg = path.resolve('notary-retained', manifest.dmgName); for (const target of ['notary-retained', 'notary-retained/manifest.json', dmg]) { @@ -79,17 +122,31 @@ function emit(result, env = process.env, io = fs) { if (typeof value !== 'string' || /[\r\n]/.test(value)) throw new Error('Unsafe resume output'); if (env.GITHUB_OUTPUT) io.appendFileSync(env.GITHUB_OUTPUT, `${key}=${value}\n`); } - if (env.GITHUB_STEP_SUMMARY) io.appendFileSync(env.GITHUB_STEP_SUMMARY, - result.outcome === 'accepted' ? '## Verified DMG ready for separately authorized publication\n' : '## Pending Apple processing — no publication, no resubmit\n'); + if (env.GITHUB_STEP_SUMMARY) + io.appendFileSync( + env.GITHUB_STEP_SUMMARY, + result.outcome === 'accepted' + ? '## Verified DMG ready for separately authorized publication\n' + : '## Pending Apple processing — no publication, no resubmit\n', + ); } -export async function resumeNotarization({ load = preparedCheckpoint, preflight = preflightRelease, query = querySubmission, - key = withNotaryKey, verify = stapleAndVerifyDmg, output = emit } = {}) { +export async function resumeNotarization({ + load = preparedCheckpoint, + preflight = preflightRelease, + query = querySubmission, + key = withNotaryKey, + verify = stapleAndVerifyDmg, + output = emit, +} = {}) { const checkpoint = await load(); const release = await preflight(); if (String(release.releaseId) !== checkpoint.manifest.releaseId) throw new Error('Release identity changed'); const result = key((auth) => query(checkpoint.submissionId, checkpoint.manifest.sha256, auth)); - if (result.outcome === 'pending') { output({ outcome: 'pending' }); return result; } + if (result.outcome === 'pending') { + output({ outcome: 'pending' }); + return result; + } if (result.outcome === 'rejected') { console.log(JSON.stringify({ outcome: 'rejected', issues: result.issues ?? [] })); throw new Error('Rejected notarization; inspect safe issues before correcting source'); diff --git a/scripts/macos-release-resume.test.mjs b/scripts/macos-release-resume.test.mjs index 6c1816e0..fd17c56c 100644 --- a/scripts/macos-release-resume.test.mjs +++ b/scripts/macos-release-resume.test.mjs @@ -5,16 +5,34 @@ import { producerFixture, zipFiles } from './macos-notary-artifact-fixtures.mjs' import { hash } from './macos-notary-checkpoint.mjs'; const id = '12345678-1234-1234-1234-123456789abc'; -const checkpoint = { manifest: { version: '0.8.0', sourceSha: 'b'.repeat(40), releaseId: '42', sha256: 'a'.repeat(64), dmgName: 'Quorb_0.8.0_aarch64.dmg' }, - dmg: '/controlled/Quorb_0.8.0_aarch64.dmg', submissionId: id }; +const checkpoint = { + manifest: { version: '0.8.0', sourceSha: 'b'.repeat(40), releaseId: '42', sha256: 'a'.repeat(64), dmgName: 'Quorb_0.8.0_aarch64.dmg' }, + dmg: '/controlled/Quorb_0.8.0_aarch64.dmg', + submissionId: id, +}; function fixture(outcome = 'accepted') { const calls = []; const dependencies = { - load: async () => { calls.push('load'); return checkpoint; }, - preflight: async () => { calls.push('preflight'); return { releaseId: 42 }; }, - query: () => { calls.push('query'); return { outcome }; }, - key: (callback) => { calls.push('key'); return callback([]); }, - verify: () => { calls.push('verify'); return { finalSha256: 'f'.repeat(64) }; }, + load: async () => { + calls.push('load'); + return checkpoint; + }, + preflight: async () => { + calls.push('preflight'); + return { releaseId: 42 }; + }, + query: () => { + calls.push('query'); + return { outcome }; + }, + key: (callback) => { + calls.push('key'); + return callback([]); + }, + verify: () => { + calls.push('verify'); + return { finalSha256: 'f'.repeat(64) }; + }, output: (result) => calls.push(result), }; return { calls, dependencies }; @@ -33,7 +51,9 @@ test('resume never builds, signs, submits or publishes; pending/rejected cannot test('content/run validation and release identity are checked before Apple credentials', async () => { const f = fixture(); - f.dependencies.load = async () => { throw new Error('bad digest'); }; + f.dependencies.load = async () => { + throw new Error('bad digest'); + }; await assert.rejects(resumeNotarization(f.dependencies), /bad digest/); assert.deepEqual(f.calls, []); const changed = fixture(); @@ -54,12 +74,16 @@ test('offline HTTP/Git/ZIP/files adapter restores exact canceled-attempt checkpo }); test('recovery UUID without receipt remains only a candidate until Apple hash binding', async () => { - const f = producerFixture(); f.artifacts.pop(); f.env.SUBMISSION_ID = '00000000-0000-0000-0000-000000000001'; + const f = producerFixture(); + f.artifacts.pop(); + f.env.SUBMISSION_ID = '00000000-0000-0000-0000-000000000001'; const result = await loadCheckpoint(f); assert.equal(result.submissionId, f.env.SUBMISSION_ID); - const normal = producerFixture(); normal.artifacts.pop(); + const normal = producerFixture(); + normal.artifacts.pop(); await assert.rejects(loadCheckpoint(normal), /receipt/i); - const malformed = producerFixture(); malformed.env.SUBMISSION_ID = '--help'; + const malformed = producerFixture(); + malformed.env.SUBMISSION_ID = '--help'; await assert.rejects(loadCheckpoint(malformed), /inputs/i); assert.deepEqual(malformed.calls, []); }); @@ -67,17 +91,24 @@ test('recovery UUID without receipt remains only a candidate until Apple hash bi test('adapter fails closed on unapproved ancestor/workflow bytes, manifest or receipt tampering and raw ZIP hash mismatch', async () => { for (const failure of ['ancestry', 'workflow', 'manifest', 'receipt', 'zip', 'dmg']) { const f = producerFixture(); - if (failure === 'ancestry') f.exec = () => { throw new Error('SECRET'); }; + if (failure === 'ancestry') + f.exec = () => { + throw new Error('SECRET'); + }; if (failure === 'workflow') f.exec = () => 'unapproved producer'; if (failure === 'zip') f.archives.set(456, Buffer.from('tampered archive')); if (['manifest', 'dmg'].includes(failure)) { const manifest = failure === 'manifest' ? { ...f.manifest, releaseId: '43' } : f.manifest; const bytes = zipFiles({ 'manifest.json': JSON.stringify(manifest), [manifest.dmgName]: failure === 'dmg' ? 'tampered DMG' : f.bytes }); - f.archives.set(456, bytes); f.checkpoint.digest = `sha256:${hash(bytes)}`; f.checkpoint.size_in_bytes = bytes.length; + f.archives.set(456, bytes); + f.checkpoint.digest = `sha256:${hash(bytes)}`; + f.checkpoint.size_in_bytes = bytes.length; } if (failure === 'receipt') { const bytes = zipFiles({ 'receipt.json': JSON.stringify({ ...f.receipt, checkpointArtifactId: '999' }) }); - f.archives.set(457, bytes); f.receiptArtifact.digest = `sha256:${hash(bytes)}`; f.receiptArtifact.size_in_bytes = bytes.length; + f.archives.set(457, bytes); + f.receiptArtifact.digest = `sha256:${hash(bytes)}`; + f.receiptArtifact.size_in_bytes = bytes.length; } await assert.rejects(loadCheckpoint(f), (error) => !error.message.includes('SECRET')); assert.ok(!f.files.has('notary-retained')); diff --git a/scripts/macos-release-workflow.test.mjs b/scripts/macos-release-workflow.test.mjs index dbd92d8a..33426a7a 100644 --- a/scripts/macos-release-workflow.test.mjs +++ b/scripts/macos-release-workflow.test.mjs @@ -9,7 +9,16 @@ const digest = (text) => createHash('sha256').update(normalize(text)).digest('he // Exact reviewed bytes, including every step, permission, pin and secret. This // replaces the old inline snapshot, not its strictness: no YAML subset matching. const reviewed = 'df1055991fe75d4c528361a7abec0c2f78952540393ad15f8c1e12e5689bcade'; -const requiredTests = ['macos-release-preflight', 'macos-release-workflow', 'macos-notary-checkpoint', 'macos-notary-submit', 'macos-notary-artifact', 'macos-release-resume', 'macos-release-resume-workflow', 'macos-release-resume-publish']; +const requiredTests = [ + 'macos-release-preflight', + 'macos-release-workflow', + 'macos-notary-checkpoint', + 'macos-notary-submit', + 'macos-notary-artifact', + 'macos-release-resume', + 'macos-release-resume-workflow', + 'macos-release-resume-publish', +]; function contract(draft, active, pkg) { assert.deepEqual(active, draft, 'Materialization must be byte-identical'); @@ -42,14 +51,15 @@ test('rejects deletion or mutation of every reviewed line, step order, pins and const lines = text.split('\n'); for (const [index, line] of lines.entries()) { if (!line.trim()) continue; - for (const change of [lines.filter((_, i) => i !== index).join('\n'), lines.map((value, i) => i === index ? `${value} # mutation` : value).join('\n')]) { + for (const change of [lines.filter((_, i) => i !== index).join('\n'), lines.map((value, i) => (i === index ? `${value} # mutation` : value)).join('\n')]) { assert.throws(() => contract(Buffer.from(change), Buffer.from(change), pkg()), undefined, line); } } const reversed = Buffer.from([...lines].reverse().join('\n')); assert.throws(() => contract(reversed, reversed, pkg())); for (const name of requiredTests) { - const changed = pkg(); changed.scripts.test = changed.scripts.test.replace(`scripts/${name}.test.mjs`, ''); + const changed = pkg(); + changed.scripts.test = changed.scripts.test.replace(`scripts/${name}.test.mjs`, ''); assert.throws(() => contract(draft(), draft(), changed)); } }); diff --git a/scripts/release-check.mjs b/scripts/release-check.mjs index c7b80c34..830977bf 100644 --- a/scripts/release-check.mjs +++ b/scripts/release-check.mjs @@ -8,13 +8,7 @@ // así que un borrador de release remoto sin tag local no se detecta aquí. import { execFileSync } from 'node:child_process'; import { pathToFileURL } from 'node:url'; -import { - isValidVersion, - packageJsonVersion, - packageLockVersions, - cargoTomlVersion, - cargoLockVersion, -} from './bump.mjs'; +import { isValidVersion, packageJsonVersion, packageLockVersions, cargoTomlVersion, cargoLockVersion } from './bump.mjs'; const SHA_RE = /^[0-9a-f]{40}$/; const PLACEHOLDER_RE = /pega[_\s-]*aqui[_\s-]*tu[_\s-]*clave[_\s-]*publica/i; diff --git a/scripts/release-check.test.mjs b/scripts/release-check.test.mjs index 73aa733f..34541ff0 100644 --- a/scripts/release-check.test.mjs +++ b/scripts/release-check.test.mjs @@ -25,8 +25,7 @@ function fakeGit(files, { ancestor = true, tag = false } = {}) { return { fileAt: (_sha, file) => files[file] ?? null, isAncestor: () => ancestor, tagExists: () => tag }; } -const run = (overrides = {}, opts = {}) => - checkRelease({ version: '0.1.1', sourceSha: SHA, git: fakeGit({ ...manifest('0.1.1'), ...overrides }, opts) }); +const run = (overrides = {}, opts = {}) => checkRelease({ version: '0.1.1', sourceSha: SHA, git: fakeGit({ ...manifest('0.1.1'), ...overrides }, opts) }); test('acepta una fuente coherente, anclada en origin/main y con notas', () => { assert.deepEqual(run(), []); @@ -35,7 +34,10 @@ test('acepta una fuente coherente, anclada en origin/main y con notas', () => { test('rechaza versiones inválidas o con inyección de shell', () => { for (const version of ['0.1', '0.1.1; touch pwned', '0.1.1$(id)', '0.1.1\nfoo', '../0.1.1']) { const errors = checkRelease({ version, sourceSha: SHA, git: fakeGit(manifest('0.1.1')) }); - assert.ok(errors.some((e) => /version inválida/i.test(e)), `esperaba error para ${JSON.stringify(version)}`); + assert.ok( + errors.some((e) => /version inválida/i.test(e)), + `esperaba error para ${JSON.stringify(version)}`, + ); } }); @@ -45,7 +47,10 @@ test('rechaza SHA incompleto, no hexadecimal o alterado', () => { assert.equal(isValidSha('Z'.repeat(40)), false); for (const sha of ['a'.repeat(39), 'Z'.repeat(40), `${SHA}; id`, `${SHA}\n`]) { const errors = checkRelease({ version: '0.1.1', sourceSha: sha, git: fakeGit(manifest('0.1.1')) }); - assert.ok(errors.some((e) => /source_sha/i.test(e)), `esperaba error para ${JSON.stringify(sha)}`); + assert.ok( + errors.some((e) => /source_sha/i.test(e)), + `esperaba error para ${JSON.stringify(sha)}`, + ); } }); @@ -57,7 +62,10 @@ test('rechaza una fuente que no es ancestro de origin/main', () => { test('rechaza manifiestos cuya versión no coincide con la solicitada', () => { for (const file of ['package.json', 'package-lock.json', 'src-tauri/Cargo.toml', 'src-tauri/Cargo.lock']) { const errors = run({ [file]: manifest('0.1.1')[file].replaceAll('0.1.1', '0.1.0') }); - assert.ok(errors.some((e) => e.includes(file)), `esperaba error para ${file}`); + assert.ok( + errors.some((e) => e.includes(file)), + `esperaba error para ${file}`, + ); } }); @@ -66,7 +74,10 @@ test('exige notas de la versión no vacías dentro del commit fuente', () => { assert.ok(errors.some((e) => /docs\/releases\/v0\.1\.1\.md/.test(e))); for (const notes of ['', ' \n ', '\r\n']) { const blank = run({ 'docs/releases/v0.1.1.md': notes }); - assert.ok(blank.some((e) => /docs\/releases\/v0\.1\.1\.md/.test(e)), `esperaba error para notas ${JSON.stringify(notes)}`); + assert.ok( + blank.some((e) => /docs\/releases\/v0\.1\.1\.md/.test(e)), + `esperaba error para notas ${JSON.stringify(notes)}`, + ); } }); @@ -84,7 +95,10 @@ test('exige una clave pública de updater minisign real, no placeholder ni basur ]; for (const pubkey of bad) { const errors = run({ 'src-tauri/tauri.conf.json': JSON.stringify({ plugins: { updater: { pubkey } } }) }); - assert.ok(errors.some((e) => /clave pública/.test(e)), `esperaba error para ${JSON.stringify(pubkey)}`); + assert.ok( + errors.some((e) => /clave pública/.test(e)), + `esperaba error para ${JSON.stringify(pubkey)}`, + ); } assert.equal(isValidUpdaterPubkey(REAL_PUBKEY), true); }); diff --git a/scripts/security/check-repository.mjs b/scripts/security/check-repository.mjs index 338bd505..ac11e709 100644 --- a/scripts/security/check-repository.mjs +++ b/scripts/security/check-repository.mjs @@ -21,21 +21,35 @@ const DECODER = new TextDecoder('utf-8', { fatal: true }); export class OperationalError extends Error {} const esc = (s) => s.replace(ESC, (c) => '\\u{' + c.codePointAt(0).toString(16).padStart(4, '0') + '}'); -const bad = (msg) => { throw new TypeError('policy: ' + msg); }; +const bad = (msg) => { + throw new TypeError('policy: ' + msg); +}; export function validatePolicy(policy) { if (policy === null || typeof policy !== 'object' || Array.isArray(policy)) bad('must be an object'); - const keys = Object.keys(policy).filter(k => k !== 'approvedBinaryImages').sort().join(','); + const keys = Object.keys(policy) + .filter((k) => k !== 'approvedBinaryImages') + .sort() + .join(','); if (keys !== 'allowedRootLifecycleHooks,allowedSymlinks,bidiExceptions,maxTextBytes,schemaVersion') bad('unexpected or missing keys'); if (policy.schemaVersion !== 1 || !Number.isInteger(policy.maxTextBytes) || policy.maxTextBytes < 0) bad('schemaVersion/maxTextBytes invalid'); - for (const key of ['allowedSymlinks', 'allowedRootLifecycleHooks', 'bidiExceptions']) if (!Array.isArray(policy[key]) || policy[key].some((v) => typeof v !== 'string')) bad(key + ' must be an array of strings'); + for (const key of ['allowedSymlinks', 'allowedRootLifecycleHooks', 'bidiExceptions']) + if (!Array.isArray(policy[key]) || policy[key].some((v) => typeof v !== 'string')) bad(key + ' must be an array of strings'); if (policy.bidiExceptions.length > 0) bad('bidiExceptions are not supported in this draft'); const images = policy.approvedBinaryImages ?? []; if (!Array.isArray(images)) bad('approvedBinaryImages must be an array'); const paths = new Set(); for (const image of images) { if (!image || typeof image !== 'object' || Object.keys(image).sort().join(',') !== 'path,sha256') bad('invalid image approval'); - if (typeof image.path !== 'string' || image.path.startsWith('/') || image.path.includes('\\') || image.path.includes(':') || image.path.split('/').some(p => !p || p === '.' || p === '..') || !IMAGE_EXT.has(extname(image.path).toLowerCase())) bad('invalid image path'); + if ( + typeof image.path !== 'string' || + image.path.startsWith('/') || + image.path.includes('\\') || + image.path.includes(':') || + image.path.split('/').some((p) => !p || p === '.' || p === '..') || + !IMAGE_EXT.has(extname(image.path).toLowerCase()) + ) + bad('invalid image path'); if (typeof image.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(image.sha256) || paths.has(image.path)) bad('invalid or duplicate image approval'); paths.add(image.path); } @@ -52,11 +66,16 @@ function scanText(text, path, add) { function checkHooks(text, path, policy, add) { let data; - try { data = JSON.parse(text); } catch { throw new OperationalError('package.json is not valid JSON'); } + try { + data = JSON.parse(text); + } catch { + throw new OperationalError('package.json is not valid JSON'); + } const scripts = data && typeof data === 'object' ? data.scripts : null; if (!scripts || typeof scripts !== 'object') return; for (const hook of ROOT_HOOKS) { - if (typeof scripts[hook] === 'string' && !(path === 'package.json' && policy.allowedRootLifecycleHooks.includes(hook))) add('block', 'lifecycle-hook', path, 0); + if (typeof scripts[hook] === 'string' && !(path === 'package.json' && policy.allowedRootLifecycleHooks.includes(hook))) + add('block', 'lifecycle-hook', path, 0); } } @@ -75,20 +94,46 @@ export function analyze(entries, policy) { if (bytes !== null && !Buffer.isBuffer(bytes)) throw new TypeError('entry.bytes must be a Buffer or null'); if (BIDI.test(path)) add('block', 'bidi-control-path', path, 0); else if (CF.test(path)) add('alert', 'cf-format-path', path, 0); - if (mode === SYMLINK_MODE) { if (!policy.allowedSymlinks.includes(path)) add('block', 'symlink-not-allowed', path, 0); continue; } - if (mode === '160000') { add('block', 'gitlink-not-allowed', path, 0); continue; } + if (mode === SYMLINK_MODE) { + if (!policy.allowedSymlinks.includes(path)) add('block', 'symlink-not-allowed', path, 0); + continue; + } + if (mode === '160000') { + add('block', 'gitlink-not-allowed', path, 0); + continue; + } if (!BLOB_MODES.includes(mode)) throw new TypeError('unsupported mode: ' + mode); - const approval = (policy.approvedBinaryImages ?? []).find(image => image.path === path); - if (approval && mode === '100644' && bytes !== null && bytes.length <= MAX_IMAGE_BYTES && createHash('sha256').update(bytes).digest('hex') === approval.sha256) { + const approval = (policy.approvedBinaryImages ?? []).find((image) => image.path === path); + if ( + approval && + mode === '100644' && + bytes !== null && + bytes.length <= MAX_IMAGE_BYTES && + createHash('sha256').update(bytes).digest('hex') === approval.sha256 + ) { approvedExclusions.push({ path: esc(path), sha256: approval.sha256 }); continue; } if (approval) add('block', 'image-approval-mismatch', path, 0); const isSource = SOURCE_EXT.has(extname(path).toLowerCase()); - if (bytes === null || bytes.length > policy.maxTextBytes) { if (isSource) add('block', 'source-too-large', path, 0); else coverageGaps.push({ path: esc(path), reason: 'large' }); continue; } - if (bytes.includes(0)) { if (isSource) throw new OperationalError('nul-byte-in-source'); coverageGaps.push({ path: esc(path), reason: 'binary' }); continue; } + if (bytes === null || bytes.length > policy.maxTextBytes) { + if (isSource) add('block', 'source-too-large', path, 0); + else coverageGaps.push({ path: esc(path), reason: 'large' }); + continue; + } + if (bytes.includes(0)) { + if (isSource) throw new OperationalError('nul-byte-in-source'); + coverageGaps.push({ path: esc(path), reason: 'binary' }); + continue; + } let text; - try { text = DECODER.decode(bytes); } catch { if (isSource) throw new OperationalError('invalid-utf8-in-source'); coverageGaps.push({ path: esc(path), reason: 'binary' }); continue; } + try { + text = DECODER.decode(bytes); + } catch { + if (isSource) throw new OperationalError('invalid-utf8-in-source'); + coverageGaps.push({ path: esc(path), reason: 'binary' }); + continue; + } scanText(text, path, add); if (path === 'package.json' || path.endsWith('/package.json')) checkHooks(text, path, policy, add); } @@ -112,10 +157,13 @@ function readSnapshot(repo, policy) { if (tab < 0) throw new OperationalError('unexpected git ls-tree output'); const [mode, type, oid, sizeRaw] = line.slice(0, tab).split(/\s+/); const path = line.slice(tab + 1); - if (type !== 'blob' || mode === SYMLINK_MODE) { entries.push({ path, mode, bytes: null }); continue; } + if (type !== 'blob' || mode === SYMLINK_MODE) { + entries.push({ path, mode, bytes: null }); + continue; + } const size = Number(sizeRaw); if (!Number.isInteger(size) || size < 0) throw new OperationalError('unexpected blob size'); - const approvedImage = (policy.approvedBinaryImages ?? []).some(image => image.path === path); + const approvedImage = (policy.approvedBinaryImages ?? []).some((image) => image.path === path); const limit = approvedImage ? MAX_IMAGE_BYTES : policy.maxTextBytes; entries.push({ path, mode, bytes: size > limit ? null : git(repo, ['cat-file', 'blob', oid]) }); } @@ -125,8 +173,11 @@ function readSnapshot(repo, policy) { export function main(argv) { const { repo, policyPath } = parseArgs(argv); let policy; - try { policy = validatePolicy(JSON.parse(readFileSync(policyPath, 'utf8'))); } - catch { throw new OperationalError('policy-load-failed'); } + try { + policy = validatePolicy(JSON.parse(readFileSync(policyPath, 'utf8'))); + } catch { + throw new OperationalError('policy-load-failed'); + } const report = analyze(readSnapshot(repo, policy), policy); process.stdout.write(JSON.stringify(report, null, 2) + '\n'); if (report.findings.some((f) => f.severity === 'block')) return 1; @@ -134,6 +185,10 @@ export function main(argv) { } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { - try { process.exitCode = main(process.argv.slice(2)); } - catch { process.stderr.write('operational-error\n'); process.exitCode = 2; } + try { + process.exitCode = main(process.argv.slice(2)); + } catch { + process.stderr.write('operational-error\n'); + process.exitCode = 2; + } } diff --git a/scripts/security/check-repository.test.mjs b/scripts/security/check-repository.test.mjs index 676ec0f2..81e9f83e 100644 --- a/scripts/security/check-repository.test.mjs +++ b/scripts/security/check-repository.test.mjs @@ -45,9 +45,10 @@ test('ICNS approval requires exact path, hash and regular non-executable mode', test('repository policy pins the preliminary macOS icon approval', () => { const policy = validatePolicy(JSON.parse(readFileSync(new URL('../../.github/security/policy.json', import.meta.url), 'utf8'))); - assert.deepEqual(policy.approvedBinaryImages.filter(image => image.path.endsWith('.icns')), [ - { path: 'src-tauri/icons/icon.icns', sha256: 'd987765bbdea610ebacb99161739d4e226a3841497e211fc98eb376b092ebbbc' }, - ]); + assert.deepEqual( + policy.approvedBinaryImages.filter((image) => image.path.endsWith('.icns')), + [{ path: 'src-tauri/icons/icon.icns', sha256: 'd987765bbdea610ebacb99161739d4e226a3841497e211fc98eb376b092ebbbc' }], + ); }); test('repository policy pins seven preliminary transparent-icon approvals without expanding the allowlist', () => { @@ -62,7 +63,10 @@ test('repository policy pins seven preliminary transparent-icon approvals withou { path: 'src/assets/quorb-logo.png', sha256: '646cf10a0c465fe7d11f2e6c6be544fdddfda93256d47f22aa04a009d1d01f1b' }, ]; assert.equal(policy.approvedBinaryImages.length, 19); - assert.deepEqual(policy.approvedBinaryImages.filter(image => expected.some(approval => approval.path === image.path)), expected); + assert.deepEqual( + policy.approvedBinaryImages.filter((image) => expected.some((approval) => approval.path === image.path)), + expected, + ); }); test('image approval never exempts links, executable modes or bidi paths', () => { @@ -80,7 +84,12 @@ test('image exemption handles bytes beyond text limit but never missing bytes', }); test('image approvals reject bad hashes, traversal, duplicates and source exemptions', () => { - for (const approvals of [[{ ...imageApproval, sha256: 'bad' }], [{ ...imageApproval, path: '../logo.png' }], [imageApproval, imageApproval], [{ ...imageApproval, path: 'src/main.ts' }]]) { + for (const approvals of [ + [{ ...imageApproval, sha256: 'bad' }], + [{ ...imageApproval, path: '../logo.png' }], + [imageApproval, imageApproval], + [{ ...imageApproval, path: 'src/main.ts' }], + ]) { assert.throws(() => validatePolicy(pol({ approvedBinaryImages: approvals })), TypeError); } }); @@ -106,7 +115,13 @@ test('zero-width joiner alerts but does not block', () => { test('nonblocking Cf on first line cannot mask later bidi', () => { const r = analyze([src('src/a.ts', 'a\u200db\nline\u202e\n')], pol()); assert.equal(r.ok, false); - assert.deepEqual(r.findings.map(f => [f.severity, f.line]), [['alert', 1], ['block', 2]]); + assert.deepEqual( + r.findings.map((f) => [f.severity, f.line]), + [ + ['alert', 1], + ['block', 2], + ], + ); }); test('bidi in tracked Markdown (non-source extension) is scanned and blocks', () => { diff --git a/scripts/security/code-safety.mjs b/scripts/security/code-safety.mjs index 85e3af97..051654fc 100644 --- a/scripts/security/code-safety.mjs +++ b/scripts/security/code-safety.mjs @@ -22,7 +22,9 @@ const COMMIT_SHA = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/; const UNSAFE = /[\p{Cc}\p{Cf}]/u; const MAX_REPORT_BYTES = 16 * 1024 * 1024; -const fail = () => { throw new Error(FAIL); }; +const fail = () => { + throw new Error(FAIL); +}; const defaultReadManifest = () => JSON.parse(readFileSync(MANIFEST_PATH, 'utf8')); function safePath(value) { @@ -36,9 +38,17 @@ async function runProvision(argv, deps) { const provisionTools = deps.provisionTools ?? defaultProvisionTools; const readManifest = deps.readManifest ?? defaultReadManifest; let manifest; - try { manifest = await readManifest(); } catch { return fail(); } + try { + manifest = await readManifest(); + } catch { + return fail(); + } let result; - try { result = await provisionTools({ manifest, destination }); } catch { return fail(); } + try { + result = await provisionTools({ manifest, destination }); + } catch { + return fail(); + } if (result === null || typeof result !== 'object') fail(); return { directory: result.directory, artifacts: result.artifacts }; } @@ -55,9 +65,17 @@ async function runScan(argv, deps) { const input = { repo, commit, wheelhouse, parent }; // A semgrep failure aborts the remaining scanner: no partial, no green result. let semgrep; - try { semgrep = await runSemgrep(input); } catch { return fail(); } + try { + semgrep = await runSemgrep(input); + } catch { + return fail(); + } let zizmor; - try { zizmor = await runZizmor(input); } catch { return fail(); } + try { + zizmor = await runZizmor(input); + } catch { + return fail(); + } return { semgrep, zizmor }; } @@ -72,7 +90,11 @@ export async function main(argv, deps = {}) { function serialize(report) { let json; - try { json = JSON.stringify(report); } catch { fail(); } + try { + json = JSON.stringify(report); + } catch { + fail(); + } if (Buffer.byteLength(json) > MAX_REPORT_BYTES) fail(); return `${json}\n`; } @@ -88,5 +110,7 @@ async function cli(argv) { } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { - cli(process.argv.slice(2)).then((code) => { process.exitCode = code; }); + cli(process.argv.slice(2)).then((code) => { + process.exitCode = code; + }); } diff --git a/scripts/security/code-safety.test.mjs b/scripts/security/code-safety.test.mjs index 2fb6dc02..4ceda79c 100644 --- a/scripts/security/code-safety.test.mjs +++ b/scripts/security/code-safety.test.mjs @@ -13,12 +13,24 @@ const MODULE = fileURLToPath(new URL('./code-safety.mjs', import.meta.url)); const FAIL = 'code-safety-failed'; const COMMIT = 'a'.repeat(40); const reject = (promise) => assert.rejects(promise, { message: FAIL }); -const bump = () => { throw new Error('dependency must not run'); }; +const bump = () => { + throw new Error('dependency must not run'); +}; const deps = () => ({ provisionTools: bump, runSemgrep: bump, runZizmor: bump, readManifest: bump }); test('rejects unsupported or malformed invocations without calling dependencies', async () => { - for (const argv of [undefined, null, 'provision', {}, [], ['bogus'], ['provision'], - ['provision', '/a', '/b'], ['scan', '/a', COMMIT, '/b'], ['scan', '/a', COMMIT, '/b', '/c', '/d']]) { + for (const argv of [ + undefined, + null, + 'provision', + {}, + [], + ['bogus'], + ['provision'], + ['provision', '/a', '/b'], + ['scan', '/a', COMMIT, '/b'], + ['scan', '/a', COMMIT, '/b', '/c', '/d'], + ]) { await reject(main(argv, deps())); } }); @@ -36,8 +48,7 @@ test('rejects relative, control/format-character paths and bad commit hashes', a ['scan', '/tmp/repo', COMMIT, `/tmp/bad${'\u200b'}`, '/tmp/parent'], ]; for (const argv of cases) await reject(main(argv, deps())); - for (const bad of ['a'.repeat(39), 'a'.repeat(41), 'A'.repeat(40), 'g'.repeat(40), - 'f'.repeat(63), `f${'g'.repeat(63)}`, 'f'.repeat(65), '']) { + for (const bad of ['a'.repeat(39), 'a'.repeat(41), 'A'.repeat(40), 'g'.repeat(40), 'f'.repeat(63), `f${'g'.repeat(63)}`, 'f'.repeat(65), '']) { await reject(main(['scan', '/tmp/repo', bad, '/tmp/wheels', '/tmp/parent'], deps())); } }); @@ -48,29 +59,51 @@ test('scan calls each runner once with identical input and aborts zizmor on semg const zizmor = { commit: COMMIT, findings: [] }; const input = { repo: '/repo', commit: COMMIT, wheelhouse: '/wheels', parent: '/parent' }; const out = await main(['scan', '/repo', COMMIT, '/wheels', '/parent'], { - runSemgrep: (value) => { seen.push(['semgrep', value]); return semgrep; }, - runZizmor: (value) => { seen.push(['zizmor', value]); return zizmor; }, + runSemgrep: (value) => { + seen.push(['semgrep', value]); + return semgrep; + }, + runZizmor: (value) => { + seen.push(['zizmor', value]); + return zizmor; + }, }); assert.deepEqual(out, { semgrep, zizmor }); - assert.deepEqual(seen, [['semgrep', input], ['zizmor', input]]); + assert.deepEqual(seen, [ + ['semgrep', input], + ['zizmor', input], + ]); let zizmorCalls = 0; - await reject(main(['scan', '/repo', COMMIT, '/wheels', '/parent'], { - runSemgrep: () => { throw new Error('scanner secret'); }, - runZizmor: () => { zizmorCalls += 1; return zizmor; }, - })); + await reject( + main(['scan', '/repo', COMMIT, '/wheels', '/parent'], { + runSemgrep: () => { + throw new Error('scanner secret'); + }, + runZizmor: () => { + zizmorCalls += 1; + return zizmor; + }, + }), + ); assert.equal(zizmorCalls, 0); - await reject(main(['scan', '/repo', COMMIT, '/wheels', '/parent'], { - runSemgrep: () => semgrep, - runZizmor: () => { throw new Error('scanner secret'); }, - })); + await reject( + main(['scan', '/repo', COMMIT, '/wheels', '/parent'], { + runSemgrep: () => semgrep, + runZizmor: () => { + throw new Error('scanner secret'); + }, + }), + ); }); test('provision loads the module-relative trusted manifest and forwards it verbatim', async () => { - const trusted = JSON.parse(readFileSync( - fileURLToPath(new URL('../../.github/security-drafts/tool-artifacts.json', import.meta.url)), 'utf8')); + const trusted = JSON.parse(readFileSync(fileURLToPath(new URL('../../.github/security-drafts/tool-artifacts.json', import.meta.url)), 'utf8')); let seen; const out = await main(['provision', '/new/wheels'], { - provisionTools: async (args) => { seen = args; return { directory: args.destination, artifacts: 7 }; }, + provisionTools: async (args) => { + seen = args; + return { directory: args.destination, artifacts: 7 }; + }, }); assert.deepEqual(seen, { manifest: trusted, destination: '/new/wheels' }); assert.deepEqual(out, { directory: '/new/wheels', artifacts: 7 }); @@ -79,22 +112,32 @@ test('provision loads the module-relative trusted manifest and forwards it verba let passed; await main(['provision', '/new/wheels'], { readManifest: () => injected, - provisionTools: async (args) => { passed = args.manifest; return { directory: args.destination, artifacts: 0 }; }, + provisionTools: async (args) => { + passed = args.manifest; + return { directory: args.destination, artifacts: 0 }; + }, }); assert.equal(passed, injected); - await reject(main(['provision', '/new/wheels'], { readManifest: () => { throw new Error('boom'); } })); - await reject(main(['provision', '/new/wheels'], - { readManifest: () => injected, provisionTools: async () => { throw new Error('boom'); } })); + await reject( + main(['provision', '/new/wheels'], { + readManifest: () => { + throw new Error('boom'); + }, + }), + ); + await reject( + main(['provision', '/new/wheels'], { + readManifest: () => injected, + provisionTools: async () => { + throw new Error('boom'); + }, + }), + ); }); test('CLI child fails closed with a generic label, exit 2, empty stdout and no leaked input', () => { const secret = 'LEAK-ME-1234'; - const runs = [ - ['bogus'], - ['provision', `relative/${secret}`], - ['scan', '/repo', 'not-a-hash', '/wheels', '/parent'], - ['scan', '/repo', COMMIT], - ]; + const runs = [['bogus'], ['provision', `relative/${secret}`], ['scan', '/repo', 'not-a-hash', '/wheels', '/parent'], ['scan', '/repo', COMMIT]]; for (const argv of runs) { const result = spawnSync(process.execPath, [MODULE, ...argv], { encoding: 'utf8' }); assert.equal(result.status, 2, argv.join(' ')); @@ -120,9 +163,9 @@ test('workflow adoption pins the reviewed integrated baseline and keeps target e }); test('importing the module performs no work and no CLI call', () => { - const result = spawnSync(process.execPath, - ['--input-type=module', '-e', `await import(${JSON.stringify(pathToFileURL(MODULE).href)});`], - { encoding: 'utf8' }); + const result = spawnSync(process.execPath, ['--input-type=module', '-e', `await import(${JSON.stringify(pathToFileURL(MODULE).href)});`], { + encoding: 'utf8', + }); assert.equal(result.status, 0); assert.equal(result.stdout, ''); assert.equal(result.stderr, ''); diff --git a/scripts/security/export-snapshot.mjs b/scripts/security/export-snapshot.mjs index 186f5252..2aef5b82 100644 --- a/scripts/security/export-snapshot.mjs +++ b/scripts/security/export-snapshot.mjs @@ -13,12 +13,14 @@ const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }); // Git for Windows rejects node's os.devNull (\\.\nul) as a config path, so use // the Git-aware null device on that platform while still suppressing globals. const GIT_NULL_CONFIG = process.platform === 'win32' ? 'NUL' : devNull; -const fail = () => { throw new Error('snapshot-export-failed'); }; -const hash = bytes => createHash('sha256').update(bytes).digest('hex'); +const fail = () => { + throw new Error('snapshot-export-failed'); +}; +const hash = (bytes) => createHash('sha256').update(bytes).digest('hex'); function safeOriginal(path) { if (!path || /[\p{Cc}\p{Cf}\\:]/u.test(path)) fail(); - if (path.split('/').some(p => !p || p === '.' || p === '..' || p.toLowerCase() === '.git')) fail(); + if (path.split('/').some((p) => !p || p === '.' || p === '..' || p.toLowerCase() === '.git')) fail(); } export function exportSnapshot({ repo, commit, parent, scope = 'js-ts' }) { @@ -27,10 +29,16 @@ export function exportSnapshot({ repo, commit, parent, scope = 'js-ts' }) { if (!['js-ts', 'workflows'].includes(scope)) fail(); if (typeof repo !== 'string' || typeof parent !== 'string' || typeof commit !== 'string' || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(commit)) fail(); // Do not inherit Git overrides, replacement objects, global config or lazy network fetches. - const env = { PATH: process.env.PATH, SystemRoot: process.env.SystemRoot, - GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: GIT_NULL_CONFIG, GIT_NO_REPLACE_OBJECTS: '1', GIT_NO_LAZY_FETCH: '1', GIT_TERMINAL_PROMPT: '0' }; - const git = args => execFileSync('git', args, { cwd: repo, env, - stdio: ['pipe', 'pipe', 'pipe'], maxBuffer: 16 * 1024 * 1024, timeout: 10000 }); + const env = { + PATH: process.env.PATH, + SystemRoot: process.env.SystemRoot, + GIT_CONFIG_NOSYSTEM: '1', + GIT_CONFIG_GLOBAL: GIT_NULL_CONFIG, + GIT_NO_REPLACE_OBJECTS: '1', + GIT_NO_LAZY_FETCH: '1', + GIT_TERMINAL_PROMPT: '0', + }; + const git = (args) => execFileSync('git', args, { cwd: repo, env, stdio: ['pipe', 'pipe', 'pipe'], maxBuffer: 16 * 1024 * 1024, timeout: 10000 }); if (git(['cat-file', '-t', commit]).toString().trim() !== 'commit') fail(); const records = decoder.decode(git(['ls-tree', '-rz', '-l', commit])).split('\0'); if (records.pop() !== '' || records.length > 10000) fail(); @@ -48,13 +56,18 @@ export function exportSnapshot({ repo, commit, parent, scope = 'js-ts' }) { seen.add(originalPath); const fields = record.slice(0, tab).trim().split(/\s+/); const [mode, type, oid, sizeText] = fields; - if (fields.length !== 4 || !['100644', '100755'].includes(mode) || type !== 'blob' || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(oid) || !/^\d+$/.test(sizeText)) fail(); + if ( + fields.length !== 4 || + !['100644', '100755'].includes(mode) || + type !== 'blob' || + !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(oid) || + !/^\d+$/.test(sizeText) + ) + fail(); const size = Number(sizeText); if (!Number.isSafeInteger(size)) fail(); const extension = extname(originalPath).toLowerCase(); - const included = scope === 'workflows' - ? /^\.github\/workflows\/[^/]+\.(?:yml|yaml)$/.test(originalPath) - : EXTENSIONS.has(extension); + const included = scope === 'workflows' ? /^\.github\/workflows\/[^/]+\.(?:yml|yaml)$/.test(originalPath) : EXTENSIONS.has(extension); if (!included) { excluded.push({ path: originalPath, reason: scope === 'workflows' ? 'outside-workflow-scope' : 'outside-js-ts-scope' }); continue; diff --git a/scripts/security/export-snapshot.test.mjs b/scripts/security/export-snapshot.test.mjs index 92283102..dfd51624 100644 --- a/scripts/security/export-snapshot.test.mjs +++ b/scripts/security/export-snapshot.test.mjs @@ -11,21 +11,44 @@ function fixture(t, files = { 'src/a.ts': 'export const n = 1;' }) { const base = mkdtempSync(join(tmpdir(), 'snapshot-test-')); t.after(() => rmSync(base, { recursive: true, force: true })); const repo = join(base, 'repo'); - mkdirSync(repo); mkdirSync(join(base, 'hooks')); mkdirSync(join(base, 'out')); - const git = (...args) => execFileSync('git', ['-c', `core.hooksPath=${join(base, 'hooks')}`, '-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', '-c', 'commit.gpgsign=false', ...args], { - cwd: repo, stdio: ['pipe', 'pipe', 'pipe'], - env: { PATH: process.env.PATH, SystemRoot: process.env.SystemRoot, HOME: base, GIT_CONFIG_NOSYSTEM: '1' }, - }).toString().trim(); + mkdirSync(repo); + mkdirSync(join(base, 'hooks')); + mkdirSync(join(base, 'out')); + const git = (...args) => + execFileSync( + 'git', + [ + '-c', + `core.hooksPath=${join(base, 'hooks')}`, + '-c', + 'user.name=Fixture', + '-c', + 'user.email=fixture@example.invalid', + '-c', + 'commit.gpgsign=false', + ...args, + ], + { + cwd: repo, + stdio: ['pipe', 'pipe', 'pipe'], + env: { PATH: process.env.PATH, SystemRoot: process.env.SystemRoot, HOME: base, GIT_CONFIG_NOSYSTEM: '1' }, + }, + ) + .toString() + .trim(); git('init', '-q'); for (const [path, bytes] of Object.entries(files)) { - const dest = join(repo, path); mkdirSync(join(dest, '..'), { recursive: true }); writeFileSync(dest, bytes); + const dest = join(repo, path); + mkdirSync(join(dest, '..'), { recursive: true }); + writeFileSync(dest, bytes); } - git('add', '.'); git('commit', '-qm', 'inert fixture'); + git('add', '.'); + git('commit', '-qm', 'inert fixture'); const commit = git('rev-parse', 'HEAD'); return { repo, commit, parent: join(base, 'out'), git }; } -test('exports committed bytes only with independent hashes and explicit exclusions', t => { +test('exports committed bytes only with independent hashes and explicit exclusions', (t) => { const f = fixture(t, { 'src/a.ts': 'export const n = 1;', '.hidden/b.js': 'void 0;', '.semgrepignore': '**', 'readme.md': 'out of scope' }); writeFileSync(join(f.repo, 'src/a.ts'), 'DIRTY SECRET'); const out = exportSnapshot(f); @@ -38,12 +61,12 @@ test('exports committed bytes only with independent hashes and explicit exclusio assert.ok(!bytes.includes('DIRTY SECRET')); assert.ok(target.path.startsWith(out.root + sep)); } - assert.ok(out.targets.some(x => x.originalPath === '.hidden/b.js')); + assert.ok(out.targets.some((x) => x.originalPath === '.hidden/b.js')); assert.ok(!existsSync(join(out.root, '.semgrepignore'))); }); -test('canonicalizes module TypeScript without changing bytes or original identity', t => { - const files = Object.fromEntries(['js', 'jsx', 'mjs', 'cjs', 'ts', 'tsx', 'mts', 'cts'].map(ext => [`a.${ext}`, 'const x = 1;\n'])); +test('canonicalizes module TypeScript without changing bytes or original identity', (t) => { + const files = Object.fromEntries(['js', 'jsx', 'mjs', 'cjs', 'ts', 'tsx', 'mts', 'cts'].map((ext) => [`a.${ext}`, 'const x = 1;\n'])); const out = exportSnapshot(fixture(t, files)); assert.equal(out.targets.length, 8); for (const target of out.targets) { @@ -55,29 +78,37 @@ test('canonicalizes module TypeScript without changing bytes or original identit } }); -test('workflow scope exports only direct YAML workflows as inert hashed blobs', t => { - const f = fixture(t, { '.github/workflows/a.yml': 'name: A\n', '.github/workflows/b.yaml': 'name: B\n', - '.github/workflows/nested/c.yml': 'name: ignored\n', 'src/a.ts': 'void 0;', 'action.yml': 'name: action\n' }); +test('workflow scope exports only direct YAML workflows as inert hashed blobs', (t) => { + const f = fixture(t, { + '.github/workflows/a.yml': 'name: A\n', + '.github/workflows/b.yaml': 'name: B\n', + '.github/workflows/nested/c.yml': 'name: ignored\n', + 'src/a.ts': 'void 0;', + 'action.yml': 'name: action\n', + }); const out = exportSnapshot({ ...f, scope: 'workflows' }); assert.equal(out.targets.length, 2); - assert.deepEqual(out.targets.map(t => t.originalPath), ['.github/workflows/a.yml', '.github/workflows/b.yaml']); + assert.deepEqual( + out.targets.map((t) => t.originalPath), + ['.github/workflows/a.yml', '.github/workflows/b.yaml'], + ); for (const target of out.targets) { assert.match(target.path, /\d{6}\.ya?ml$/); assert.equal(target.sha256, createHash('sha256').update(readFileSync(target.path)).digest('hex')); } assert.equal(out.excluded.length, 3); - assert.ok(out.excluded.every(e => e.reason === 'outside-workflow-scope')); + assert.ok(out.excluded.every((e) => e.reason === 'outside-workflow-scope')); assert.throws(() => exportSnapshot({ ...f, scope: 'anything' }), { message: 'snapshot-export-failed' }); }); -test('full commit ids required, not branch names or option strings', t => { +test('full commit ids required, not branch names or option strings', (t) => { const f = fixture(t); for (const commit of ['HEAD', '--help', f.commit.slice(0, 8), '0'.repeat(40)]) { assert.throws(() => exportSnapshot({ ...f, commit }), { message: 'snapshot-export-failed' }); } }); -test('symlinks and gitlinks are rejected, never dereferenced', t => { +test('symlinks and gitlinks are rejected, never dereferenced', (t) => { for (const mode of ['120000', '160000']) { const f = fixture(t); const oid = mode === '160000' ? f.commit : f.git('rev-parse', `${f.commit}:src/a.ts`); @@ -87,32 +118,36 @@ test('symlinks and gitlinks are rejected, never dereferenced', t => { } }); -test('binary and oversized source fail rather than silently disappearing', t => { +test('binary and oversized source fail rather than silently disappearing', (t) => { for (const bytes of [Buffer.from([0]), Buffer.from([255]), Buffer.alloc(1024 * 1024 + 1, 65)]) { const f = fixture(t, { 'bad.ts': bytes }); assert.throws(() => exportSnapshot(f), { message: 'snapshot-export-failed' }); } }); -test('empty scanner scope is an explicit failure', t => { +test('empty scanner scope is an explicit failure', (t) => { assert.throws(() => exportSnapshot(fixture(t, { 'readme.md': 'no source' })), { message: 'snapshot-export-failed' }); }); -test('partial exports are cleaned on failure', t => { +test('partial exports are cleaned on failure', (t) => { const f = fixture(t, { 'a.ts': 'void 0;', 'z.ts': Buffer.from([0]) }); assert.throws(() => exportSnapshot(f), { message: 'snapshot-export-failed' }); assert.deepEqual(readdirSync(f.parent), []); }); -test('ambient Git overrides cannot redirect the snapshot', t => { +test('ambient Git overrides cannot redirect the snapshot', (t) => { const f = fixture(t); const before = process.env.GIT_DIR; process.env.GIT_DIR = join(f.parent, 'missing'); - try { assert.equal(exportSnapshot(f).targets.length, 1); } - finally { if (before === undefined) delete process.env.GIT_DIR; else process.env.GIT_DIR = before; } + try { + assert.equal(exportSnapshot(f).targets.length, 1); + } finally { + if (before === undefined) delete process.env.GIT_DIR; + else process.env.GIT_DIR = before; + } }); -test('control-bearing paths fail without exposing their text', t => { +test('control-bearing paths fail without exposing their text', (t) => { const f = fixture(t, { 'SECRET\u202e.ts': 'void 0;' }); assert.throws(() => exportSnapshot(f), { message: 'snapshot-export-failed' }); }); diff --git a/scripts/security/provider-logo-regexp.test.mjs b/scripts/security/provider-logo-regexp.test.mjs index 5ea9ecb7..fb3d268e 100644 --- a/scripts/security/provider-logo-regexp.test.mjs +++ b/scripts/security/provider-logo-regexp.test.mjs @@ -11,8 +11,18 @@ test('escaped opener preserves HTML-comment removal semantics', () => { // These are test-owned literals; never import/evaluate the target component. const original = new RegExp(String.raw``, 'g'); const compatible = /\x3c!--[\s\S]*?-->/g; - const samples = ['', '', '', '', - '', '', '', - 'tail-->', 'xy', '']; + const samples = [ + '', + '', + '', + '', + '', + '', + '', + 'tail-->', + 'xy', + '', + ]; for (const input of samples) assert.equal(input.replace(compatible, ''), input.replace(original, '')); }); diff --git a/scripts/security/provision-tools.mjs b/scripts/security/provision-tools.mjs index fae21dc3..df8bce44 100644 --- a/scripts/security/provision-tools.mjs +++ b/scripts/security/provision-tools.mjs @@ -14,7 +14,9 @@ const WHEEL = /^[A-Za-z0-9_.+-]+\.whl$/; const LABEL = /^[A-Za-z0-9_.+-]{1,200}$/; const SHA256 = /^[a-f0-9]{64}$/; const IMMUTABLE = /^\/packages\/[0-9a-f]{2}\/[0-9a-f]{2}\/[0-9a-f]{60}\/[^/]+$/; -const fail = () => { throw new Error(FAIL); }; +const fail = () => { + throw new Error(FAIL); +}; function validateManifest(manifest) { if (manifest === null || typeof manifest !== 'object' || Array.isArray(manifest)) fail(); @@ -34,7 +36,11 @@ function validateManifest(manifest) { if (typeof url !== 'string' || !SHA256.test(sha256)) fail(); if (!Number.isInteger(size) || size <= 0 || size > MAX_ARTIFACT_BYTES) fail(); let parsed; - try { parsed = new URL(url); } catch { fail(); } + try { + parsed = new URL(url); + } catch { + fail(); + } if (parsed.protocol !== 'https:' || parsed.hostname !== 'files.pythonhosted.org') fail(); if (parsed.username !== '' || parsed.password !== '' || parsed.port !== '') fail(); if (parsed.search !== '' || parsed.hash !== '') fail(); @@ -53,7 +59,12 @@ function validateManifest(manifest) { function destinationParent(destination) { if (typeof destination !== 'string' || !isAbsolute(destination)) fail(); let exists = true; - try { lstatSync(destination); } catch (error) { if (error.code !== 'ENOENT') fail(); exists = false; } + try { + lstatSync(destination); + } catch (error) { + if (error.code !== 'ENOENT') fail(); + exists = false; + } if (exists) fail(); const parent = dirname(destination); const info = statSync(parent, { throwIfNoEntry: false }); @@ -66,7 +77,9 @@ async function install(artifact, stage, fetchImpl) { let response; try { response = await fetchImpl(url, { redirect: 'error', signal: AbortSignal.timeout(60000) }); - } catch { fail(); } + } catch { + fail(); + } if (!response || response.ok !== true || !response.body) fail(); const digest = createHash('sha256'); let received = 0; @@ -92,7 +105,7 @@ async function install(artifact, stage, fetchImpl) { } export async function provisionTools({ manifest, destination }, deps = { fetch: globalThis.fetch }) { - const fetchImpl = (deps && typeof deps.fetch === 'function') ? deps.fetch : globalThis.fetch; + const fetchImpl = deps && typeof deps.fetch === 'function' ? deps.fetch : globalThis.fetch; let stage; let created = false; try { @@ -104,9 +117,21 @@ export async function provisionTools({ manifest, destination }, deps = { fetch: for (const artifact of artifacts) renameSync(join(stage, artifact.filename), join(destination, artifact.filename)); return { directory: destination, artifacts: artifacts.length }; } catch { - if (created) { try { rmSync(destination, { recursive: true, force: true }); } catch { /* own dir only */ } } + if (created) { + try { + rmSync(destination, { recursive: true, force: true }); + } catch { + /* own dir only */ + } + } fail(); } finally { - if (stage) { try { rmSync(stage, { recursive: true, force: true }); } catch { /* private stage */ } } + if (stage) { + try { + rmSync(stage, { recursive: true, force: true }); + } catch { + /* private stage */ + } + } } } diff --git a/scripts/security/provision-tools.test.mjs b/scripts/security/provision-tools.test.mjs index 08eb8363..774805b4 100644 --- a/scripts/security/provision-tools.test.mjs +++ b/scripts/security/provision-tools.test.mjs @@ -41,7 +41,14 @@ function fakeFetch(responses) { if (r?.ok === false) return { ok: false, status: r.status ?? 500, body: null }; if (r?.body === false) return { ok: true, status: 200, body: null }; const list = Array.isArray(r?.chunks) ? r.chunks : [r?.chunks ?? Buffer.alloc(0)]; - return new Response(new ReadableStream({ start(c) { for (const chunk of list) c.enqueue(chunk); c.close(); } })); + return new Response( + new ReadableStream({ + start(c) { + for (const chunk of list) c.enqueue(chunk); + c.close(); + }, + }), + ); }; return { fetch, calls }; } @@ -73,8 +80,7 @@ test('accepts the actual PyPI 2/2/60 hexadecimal URL layout', async (t) => { const a = wheel(); const h = a.entry.sha256; a.entry.url = `https://files.pythonhosted.org/packages/${h.slice(0, 2)}/${h.slice(2, 4)}/${h.slice(4)}/${a.entry.filename}`; - const result = await provisionTools({ manifest: manifest(a.entry), destination: join(base, 'out') }, - { fetch: fakeFetch([{ chunks: [a.bytes] }]).fetch }); + const result = await provisionTools({ manifest: manifest(a.entry), destination: join(base, 'out') }, { fetch: fakeFetch([{ chunks: [a.bytes] }]).fetch }); assert.equal(result.artifacts, 1); }); @@ -82,15 +88,16 @@ test('never publishes bytes lost by a short filesystem write', async (t) => { const base = tempBase(t); const a = wheel(); const original = fs.writeSync; - fs.writeSync = (fd, bytes, offset = 0, length = bytes.length - offset) => - original(fd, bytes, offset, Math.min(length, 2)); + fs.writeSync = (fd, bytes, offset = 0, length = bytes.length - offset) => original(fd, bytes, offset, Math.min(length, 2)); syncBuiltinESMExports(); try { const destination = join(base, 'out'); - await provisionTools({ manifest: manifest(a.entry), destination }, - { fetch: fakeFetch([{ chunks: [a.bytes] }]).fetch }); + await provisionTools({ manifest: manifest(a.entry), destination }, { fetch: fakeFetch([{ chunks: [a.bytes] }]).fetch }); assert.deepEqual(readFileSync(join(destination, a.entry.filename)), a.bytes); - } finally { fs.writeSync = original; syncBuiltinESMExports(); } + } finally { + fs.writeSync = original; + syncBuiltinESMExports(); + } }); test('rejects malformed manifests before any fetch', async (t) => { diff --git a/scripts/security/run-semgrep.mjs b/scripts/security/run-semgrep.mjs index bea5ee67..4a8b1922 100644 --- a/scripts/security/run-semgrep.mjs +++ b/scripts/security/run-semgrep.mjs @@ -39,7 +39,9 @@ const MAX_REPORT_BYTES = 8 * 1024 * 1024; const MOUNT_BREAK = /[,\r\n]/; const COMMIT_SHA = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/; -const fail = (stage) => { throw new Error(`semgrep-run-failed:${stage}`); }; +const fail = (stage) => { + throw new Error(`semgrep-run-failed:${stage}`); +}; const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex'); function mountPath(value) { @@ -50,68 +52,113 @@ function mountPath(value) { function wheelhousePath(value) { mountPath(value); let info; - try { info = statSync(value); } catch { fail('wheelhouse'); } + try { + info = statSync(value); + } catch { + fail('wheelhouse'); + } if (!info.isDirectory()) fail('wheelhouse'); return value; } function readBytes(path, stage) { - try { return readFileSync(path); } catch { fail(stage); } + try { + return readFileSync(path); + } catch { + fail(stage); + } } function writeControl(dir, name, bytes) { - try { writeFileSync(join(dir, name), bytes, { flag: 'wx', mode: 0o400 }); } catch { fail('control'); } + try { + writeFileSync(join(dir, name), bytes, { flag: 'wx', mode: 0o400 }); + } catch { + fail('control'); + } } function removeDir(path) { - try { rmSync(path, { recursive: true, force: true }); return true; } catch { return false; } + try { + rmSync(path, { recursive: true, force: true }); + return true; + } catch { + return false; + } } function call(execute, args, timeout, maxBuffer) { - try { return execute('docker', ['--host', 'unix:///var/run/docker.sock', ...args], { shell: false, encoding: 'utf8', timeout, maxBuffer }) ?? {}; } - catch { return { error: true }; } + try { + return execute('docker', ['--host', 'unix:///var/run/docker.sock', ...args], { shell: false, encoding: 'utf8', timeout, maxBuffer }) ?? {}; + } catch { + return { error: true }; + } } const succeeded = (result) => result.error === undefined && result.status === 0; function snapshotFingerprint(inventory, verifyInventory) { - return inventory.targets.map((target) => { - let bytes; - try { bytes = readFileSync(target.path); } catch { fail('snapshot-hash'); } - const digest = sha256(bytes); - // The initial read must match the exporter's independent claim; later reads only - // need to prove the bytes did not change while the scanner was running. - if (verifyInventory && digest !== target.sha256) fail('snapshot-hash'); - return `${target.path}\0${digest}`; - }).join('\n'); + return inventory.targets + .map((target) => { + let bytes; + try { + bytes = readFileSync(target.path); + } catch { + fail('snapshot-hash'); + } + const digest = sha256(bytes); + // The initial read must match the exporter's independent claim; later reads only + // need to prove the bytes did not change while the scanner was running. + if (verifyInventory && digest !== target.sha256) fail('snapshot-hash'); + return `${target.path}\0${digest}`; + }) + .join('\n'); } function createArgs({ name, wheelhouse, snapshot, control, uid, gid }) { return [ - 'create', '--name', name, + 'create', + '--name', + name, '--pull=never', - '--platform', 'linux/amd64', + '--platform', + 'linux/amd64', '--network=none', '--read-only', '--cap-drop=ALL', - '--security-opt', 'no-new-privileges', - '--pids-limit', '256', - '--memory', '2g', - '--cpus', '2', - '--user', `${uid}:${gid}`, - '--tmpfs', '/tmp:rw,exec,nosuid,nodev,size=1073741824,mode=1777', - '--mount', `type=bind,src=${mountPath(wheelhouse)},dst=/wheels,readonly`, - '--mount', `type=bind,src=${mountPath(snapshot)},dst=/inputs,readonly`, - '--mount', `type=bind,src=${mountPath(control)},dst=/control,readonly`, - '--workdir', '/tmp', - '--env', 'HOME=/tmp', - '--env', 'SEMGREP_SEND_METRICS=off', - '--env', 'SEMGREP_ENABLE_VERSION_CHECK=0', - '--env', 'PIP_NO_INDEX=1', - '--env', 'PIP_DISABLE_PIP_VERSION_CHECK=1', + '--security-opt', + 'no-new-privileges', + '--pids-limit', + '256', + '--memory', + '2g', + '--cpus', + '2', + '--user', + `${uid}:${gid}`, + '--tmpfs', + '/tmp:rw,exec,nosuid,nodev,size=1073741824,mode=1777', + '--mount', + `type=bind,src=${mountPath(wheelhouse)},dst=/wheels,readonly`, + '--mount', + `type=bind,src=${mountPath(snapshot)},dst=/inputs,readonly`, + '--mount', + `type=bind,src=${mountPath(control)},dst=/control,readonly`, + '--workdir', + '/tmp', + '--env', + 'HOME=/tmp', + '--env', + 'SEMGREP_SEND_METRICS=off', + '--env', + 'SEMGREP_ENABLE_VERSION_CHECK=0', + '--env', + 'PIP_NO_INDEX=1', + '--env', + 'PIP_DISABLE_PIP_VERSION_CHECK=1', '--log-driver=none', IMAGE, - 'python', '/control/runner.py', + 'python', + '/control/runner.py', ]; } @@ -159,8 +206,16 @@ function runScanner(input, deps = {}, workflow = false) { if (rules.length === 0 || entry.length === 0 || gate.length === 0) fail('trusted-files'); if (sha256(lock) !== lockHash) fail('trusted-lock'); - try { inventory = exportSnapshot({ repo, commit, parent, scope: workflow ? 'workflows' : 'js-ts' }); } catch { fail('snapshot'); } - try { control = mkdtempSync(join(resolve(parent), 'semgrep-control-')); } catch { fail('control'); } + try { + inventory = exportSnapshot({ repo, commit, parent, scope: workflow ? 'workflows' : 'js-ts' }); + } catch { + fail('snapshot'); + } + try { + control = mkdtempSync(join(resolve(parent), 'semgrep-control-')); + } catch { + fail('control'); + } // Copy trusted rules/lock/entrypoint into a fresh control dir mounted read-only. // targets.json is generated from the independent inventory, mapping flat export @@ -172,8 +227,10 @@ function runScanner(input, deps = {}, workflow = false) { const targets = { targets: inventory.targets.map((t) => ({ path: `/inputs/${basename(t.path)}`, originalPath: t.originalPath, sha256: t.sha256 })) }; writeControl(control, 'targets.json', Buffer.from(JSON.stringify(targets))); - const controlFingerprint = () => ['rules.yml', 'requirements.lock', 'runner.py', 'targets.json', 'parse_gate.py'] - .map(file => sha256(readBytes(join(control, file), 'control-hash'))).join(':'); + const controlFingerprint = () => + ['rules.yml', 'requirements.lock', 'runner.py', 'targets.json', 'parse_gate.py'] + .map((file) => sha256(readBytes(join(control, file), 'control-hash'))) + .join(':'); const beforeControl = controlFingerprint(); const beforeSnapshot = snapshotFingerprint(inventory, true); @@ -182,12 +239,19 @@ function runScanner(input, deps = {}, workflow = false) { if (!succeeded(create)) fail('docker-create'); const start = call(execute, ['start', '--attach', name], SCAN_TIMEOUT_MS, MAX_REPORT_BYTES); if (!succeeded(start) || typeof start.stdout !== 'string') fail('scanner'); - if (controlFingerprint() !== beforeControl - || snapshotFingerprint(inventory, false) !== beforeSnapshot) fail('tamper'); + if (controlFingerprint() !== beforeControl || snapshotFingerprint(inventory, false) !== beforeSnapshot) fail('tamper'); let parsed; - try { parsed = JSON.parse(start.stdout); } catch { fail('report'); } - try { report = workflow ? normalizeZizmor(parsed, inventory) : normalizeSnapshotReport(parsed, inventory); } catch { fail('report'); } + try { + parsed = JSON.parse(start.stdout); + } catch { + fail('report'); + } + try { + report = workflow ? normalizeZizmor(parsed, inventory) : normalizeSnapshotReport(parsed, inventory); + } catch { + fail('report'); + } } catch (error) { failure = error; } finally { diff --git a/scripts/security/run-semgrep.test.mjs b/scripts/security/run-semgrep.test.mjs index 3b9b163a..56381e31 100644 --- a/scripts/security/run-semgrep.test.mjs +++ b/scripts/security/run-semgrep.test.mjs @@ -18,12 +18,17 @@ const report = (scanned = ['/inputs/000000.ts'], results = []) => ({ version: '1 function fixture(t) { const base = mkdtempSync(join(tmpdir(), 'run-semgrep-')); t.after(() => rmSync(base, { recursive: true, force: true })); - const root = join(base, 'snapshot'); mkdirSync(root); - const source = join(root, '000000.ts'); writeFileSync(source, 'void 0;'); - const wheelhouse = join(base, 'wheels'); mkdirSync(wheelhouse); - const parent = join(base, 'out'); mkdirSync(parent); + const root = join(base, 'snapshot'); + mkdirSync(root); + const source = join(root, '000000.ts'); + writeFileSync(source, 'void 0;'); + const wheelhouse = join(base, 'wheels'); + mkdirSync(wheelhouse); + const parent = join(base, 'out'); + mkdirSync(parent); const inventory = { - commit: COMMIT, root, + commit: COMMIT, + root, targets: [{ path: source, originalPath: 'src/a.ts', sha256: sha('void 0;') }], excluded: [{ path: 'README.md', reason: 'outside-js-ts-scope' }], }; @@ -35,10 +40,14 @@ const deps = (f, execute, extra = {}) => ({ platform: 'linux', uid: 1000, gid: 1 function capture(handler) { const calls = []; - return { calls, execute: (command, daemonArgs, options) => { - const args = daemonArgs[0] === '--host' ? daemonArgs.slice(2) : daemonArgs; - calls.push({ command, args, daemonArgs, options }); return handler(args); - } }; + return { + calls, + execute: (command, daemonArgs, options) => { + const args = daemonArgs[0] === '--host' ? daemonArgs.slice(2) : daemonArgs; + calls.push({ command, args, daemonArgs, options }); + return handler(args); + }, + }; } const startedReport = (stdout) => { @@ -57,11 +66,35 @@ const startedReport = (stdout) => { test('hardened create argv with read-only mounts and normalized advisory findings', (t) => { const f = fixture(t); - const stdout = JSON.stringify(report(['/inputs/000000.ts'], [{ check_id: 'inputs.decoded-text-execution', path: '/inputs/000000.ts', start: { line: 4 }, extra: { severity: 'WARNING' } }])); + const stdout = JSON.stringify( + report( + ['/inputs/000000.ts'], + [{ check_id: 'inputs.decoded-text-execution', path: '/inputs/000000.ts', start: { line: 4 }, extra: { severity: 'WARNING' } }], + ), + ); const { calls, execute } = startedReport(stdout); const out = runSemgrep(input(f), deps(f, execute)); const create = calls.find((c) => c.args[0] === 'create').args; - for (const control of ['--pull=never', '--platform', 'linux/amd64', '--network=none', '--read-only', '--cap-drop=ALL', '--security-opt', 'no-new-privileges', '--pids-limit', '256', '--memory', '2g', '--cpus', '2', '--log-driver=none', '--workdir', '/tmp', IMAGE]) { + for (const control of [ + '--pull=never', + '--platform', + 'linux/amd64', + '--network=none', + '--read-only', + '--cap-drop=ALL', + '--security-opt', + 'no-new-privileges', + '--pids-limit', + '256', + '--memory', + '2g', + '--cpus', + '2', + '--log-driver=none', + '--workdir', + '/tmp', + IMAGE, + ]) { assert.ok(create.includes(control), control); } assert.ok(create.includes('--user') && create.includes('1000:1000')); @@ -70,16 +103,26 @@ test('hardened create argv with read-only mounts and normalized advisory finding const mounts = create.filter((_value, i) => create[i - 1] === '--mount'); assert.equal(mounts.length, 3); assert.ok(mounts.every((m) => m.endsWith(',readonly'))); - for (const dst of ['/wheels', '/inputs', '/control']) assert.ok(mounts.some((m) => m.includes(`dst=${dst},readonly`)), dst); + for (const dst of ['/wheels', '/inputs', '/control']) + assert.ok( + mounts.some((m) => m.includes(`dst=${dst},readonly`)), + dst, + ); assert.ok(!create.includes('--rm')); - assert.deepEqual(calls.map((c) => c.args[0]), ['create', 'start', 'rm']); + assert.deepEqual( + calls.map((c) => c.args[0]), + ['create', 'start', 'rm'], + ); assert.deepEqual(out, { - commit: COMMIT, status: 'completed', scannedFiles: 1, excluded: f.inventory.excluded, + commit: COMMIT, + status: 'completed', + scannedFiles: 1, + excluded: f.inventory.excluded, findings: [{ rule: 'decoded-text-execution', path: 'src/a.ts', line: 4, severity: 'advisory' }], }); }); -test('pins all daemon calls to the local socket', t => { +test('pins all daemon calls to the local socket', (t) => { const f = fixture(t); const { calls, execute } = startedReport(JSON.stringify(report())); runSemgrep(input(f), deps(f, execute)); @@ -100,7 +143,8 @@ test('fails closed off Linux, for root uid and for unsafe mount paths before any test('rejects untrusted lock bytes and missing trusted files', (t) => { const f = fixture(t); const { calls, execute } = startedReport(JSON.stringify(report())); - const badLock = join(f.base, 'bad.lock'); writeFileSync(badLock, 'semgrep==1.180.0\n'); + const badLock = join(f.base, 'bad.lock'); + writeFileSync(badLock, 'semgrep==1.180.0\n'); assert.throws(() => runSemgrep(input(f), deps(f, execute, { lockPath: badLock })), /semgrep-run-failed:trusted-lock/); assert.throws(() => runSemgrep(input(f), deps(f, execute, { entrypointPath: join(f.base, 'missing.py') })), /semgrep-run-failed:trusted-files/); assert.equal(calls.length, 0); @@ -108,14 +152,25 @@ test('rejects untrusted lock bytes and missing trusted files', (t) => { test('docker create and scanner failures are operational with host cleanup', (t) => { const f1 = fixture(t); - const { calls: createCalls, execute: createFail } = capture((a) => (a[0] === 'rm' ? { status: 0, stdout: '', stderr: '' } : { status: 1, stdout: '', stderr: 'boom' })); + const { calls: createCalls, execute: createFail } = capture((a) => + a[0] === 'rm' ? { status: 0, stdout: '', stderr: '' } : { status: 1, stdout: '', stderr: 'boom' }, + ); assert.throws(() => runSemgrep(input(f1), deps(f1, createFail)), /semgrep-run-failed:docker-create/); - assert.deepEqual(createCalls.map(c => c.args[0]), ['create', 'rm']); + assert.deepEqual( + createCalls.map((c) => c.args[0]), + ['create', 'rm'], + ); assert.equal(createCalls[0].args[2], createCalls[1].args[2]); assert.deepEqual(readdirSync(f1.parent), []); assert.ok(!existsSync(f1.root)); const f2 = fixture(t); - const { execute: scanFail } = capture((a) => (a[0] === 'create' ? { status: 0, stdout: '', stderr: '' } : a[0] === 'start' ? { status: 2, stdout: '', stderr: 'boom' } : { status: 0, stdout: '', stderr: '' })); + const { execute: scanFail } = capture((a) => + a[0] === 'create' + ? { status: 0, stdout: '', stderr: '' } + : a[0] === 'start' + ? { status: 2, stdout: '', stderr: 'boom' } + : { status: 0, stdout: '', stderr: '' }, + ); assert.throws(() => runSemgrep(input(f2), deps(f2, scanFail)), /semgrep-run-failed:scanner/); }); @@ -133,24 +188,32 @@ test('removes container and host temp dirs on success and on start timeout', (t) const f = fixture(t); const { calls, execute } = capture((args) => { if (args[0] === 'create') return { status: 0, stdout: '', stderr: '' }; - if (args[0] === 'start') return timedOut ? { error: new Error('timeout'), status: null, stdout: '', stderr: '' } : { status: 0, stdout: JSON.stringify(report()), stderr: '' }; + if (args[0] === 'start') + return timedOut ? { error: new Error('timeout'), status: null, stdout: '', stderr: '' } : { status: 0, stdout: JSON.stringify(report()), stderr: '' }; return { status: 0, stdout: '', stderr: '' }; }); const invoke = () => runSemgrep(input(f), deps(f, execute)); - if (timedOut) assert.throws(invoke, /semgrep-run-failed:scanner/); else invoke(); - assert.deepEqual(calls.map((c) => c.args[0]), ['create', 'start', 'rm']); + if (timedOut) assert.throws(invoke, /semgrep-run-failed:scanner/); + else invoke(); + assert.deepEqual( + calls.map((c) => c.args[0]), + ['create', 'start', 'rm'], + ); assert.deepEqual(readdirSync(f.parent), []); assert.ok(!existsSync(f.root)); } }); -test('uncertain create still attempts named cleanup and never returns success', t => { +test('uncertain create still attempts named cleanup and never returns success', (t) => { const f = fixture(t); - const { calls, execute } = capture(args => args[0] === 'create' - ? { error: new Error('timeout'), status: null } - : { status: 1, stderr: 'No such container' }); + const { calls, execute } = capture((args) => + args[0] === 'create' ? { error: new Error('timeout'), status: null } : { status: 1, stderr: 'No such container' }, + ); assert.throws(() => runSemgrep(input(f), deps(f, execute)), /semgrep-run-failed:docker-create/); - assert.deepEqual(calls.map(c => c.args[0]), ['create', 'rm']); + assert.deepEqual( + calls.map((c) => c.args[0]), + ['create', 'rm'], + ); assert.equal(calls[0].args[2], calls[1].args[2]); assert.deepEqual(readdirSync(f.parent), []); assert.ok(!existsSync(f.root)); @@ -158,22 +221,33 @@ test('uncertain create still attempts named cleanup and never returns success', test('cleanup failure is operational, never green', (t) => { const f = fixture(t); - const { execute } = capture((args) => (args[0] === 'create' ? { status: 0, stdout: '', stderr: '' } - : args[0] === 'start' ? { status: 0, stdout: JSON.stringify(report()), stderr: '' } - : { status: 1, stdout: '', stderr: 'permission denied' })); + const { execute } = capture((args) => + args[0] === 'create' + ? { status: 0, stdout: '', stderr: '' } + : args[0] === 'start' + ? { status: 0, stdout: JSON.stringify(report()), stderr: '' } + : { status: 1, stdout: '', stderr: 'permission denied' }, + ); assert.throws(() => runSemgrep(input(f), deps(f, execute)), /semgrep-run-failed:cleanup/); }); test('never echoes raw scanner output or secrets in errors', (t) => { const f = fixture(t); const secret = 'SECRET-TOKEN-VALUE'; - const { execute } = capture((args) => (args[0] === 'create' ? { status: 0, stdout: '', stderr: '' } - : args[0] === 'start' ? { status: 1, stdout: `{"leak":"${secret}"`, stderr: `boom ${secret}` } - : { status: 0, stdout: '', stderr: '' })); - assert.throws(() => runSemgrep(input(f), deps(f, execute)), (error) => { - assert.ok(!error.message.includes(secret)); - return /semgrep-run-failed:scanner/.test(error.message); - }); + const { execute } = capture((args) => + args[0] === 'create' + ? { status: 0, stdout: '', stderr: '' } + : args[0] === 'start' + ? { status: 1, stdout: `{"leak":"${secret}"`, stderr: `boom ${secret}` } + : { status: 0, stdout: '', stderr: '' }, + ); + assert.throws( + () => runSemgrep(input(f), deps(f, execute)), + (error) => { + assert.ok(!error.message.includes(secret)); + return /semgrep-run-failed:scanner/.test(error.message); + }, + ); }); test('detects snapshot and control mutation around the scanner', (t) => { @@ -181,10 +255,17 @@ test('detects snapshot and control mutation around the scanner', (t) => { const f = fixture(t); let control; const { execute } = capture((args) => { - if (args[0] === 'create') { control = args.find((a) => a.includes('dst=/control')).split('src=')[1].split(',dst=')[0]; return { status: 0, stdout: '', stderr: '' }; } + if (args[0] === 'create') { + control = args + .find((a) => a.includes('dst=/control')) + .split('src=')[1] + .split(',dst=')[0]; + return { status: 0, stdout: '', stderr: '' }; + } if (args[0] === 'start') { const file = which === 'snapshot' ? f.source : join(control, which); - chmodSync(file, 0o600); writeFileSync(file, 'tampered'); + chmodSync(file, 0o600); + writeFileSync(file, 'tampered'); return { status: 0, stdout: JSON.stringify(report()), stderr: '' }; } return { status: 0, stdout: '', stderr: '' }; diff --git a/scripts/security/run-zizmor.test.mjs b/scripts/security/run-zizmor.test.mjs index 934275e2..86624998 100644 --- a/scripts/security/run-zizmor.test.mjs +++ b/scripts/security/run-zizmor.test.mjs @@ -6,35 +6,55 @@ import { join } from 'node:path'; import { tmpdir } from 'node:os'; import * as runners from './run-semgrep.mjs'; -test('zizmor profile binds YAML inventory and trusted entry/lock to offline runner', t => { +test('zizmor profile binds YAML inventory and trusted entry/lock to offline runner', (t) => { assert.equal(typeof runners.runZizmor, 'function'); const base = mkdtempSync(join(tmpdir(), 'zizmor-profile-')); t.after(() => rmSync(base, { recursive: true, force: true })); - const root = join(base, 'snapshot'), parent = join(base, 'out'), wheelhouse = join(base, 'wheels'); + const root = join(base, 'snapshot'), + parent = join(base, 'out'), + wheelhouse = join(base, 'wheels'); for (const path of [root, parent, wheelhouse]) mkdirSync(path); const bytes = 'name: Inert\n'; writeFileSync(join(root, '000000.yml'), bytes); const commit = 'a'.repeat(40); - const inventory = { commit, root, targets: [{ path: join(root, '000000.yml'), originalPath: '.github/workflows/ci.yml', - sha256: createHash('sha256').update(bytes).digest('hex') }], excluded: [] }; + const inventory = { + commit, + root, + targets: [{ path: join(root, '000000.yml'), originalPath: '.github/workflows/ci.yml', sha256: createHash('sha256').update(bytes).digest('hex') }], + excluded: [], + }; const calls = []; - const out = runners.runZizmor({ repo: '/repo', commit, parent, wheelhouse }, { - platform: 'linux', uid: 1000, gid: 1000, - exportSnapshot: options => { assert.equal(options.scope, 'workflows'); return inventory; }, - execute: (command, args) => { - assert.equal(command, 'docker'); assert.deepEqual(args.slice(0, 2), ['--host', 'unix:///var/run/docker.sock']); - calls.push(args[2]); - if (args[2] === 'create') { - for (const flag of ['--pull=never', '--network=none', '--read-only', '--cap-drop=ALL', 'no-new-privileges']) assert.ok(args.includes(flag)); - const mount = args.find(a => a.includes('dst=/control')); - const control = mount.split('src=')[1].split(',dst=')[0]; - assert.ok(readFileSync(join(control, 'requirements.lock'), 'utf8').includes('zizmor==1.30.1')); - assert.ok(readFileSync(join(control, 'runner.py'), 'utf8').includes('zizmor')); - } - return { status: 0, stderr: '', stdout: args[2] === 'start' - ? JSON.stringify({ version: '1.30.1', reports: [{ path: '/inputs/000000.yml', findings: [] }] }) : '' }; + const out = runners.runZizmor( + { repo: '/repo', commit, parent, wheelhouse }, + { + platform: 'linux', + uid: 1000, + gid: 1000, + exportSnapshot: (options) => { + assert.equal(options.scope, 'workflows'); + return inventory; + }, + execute: (command, args) => { + assert.equal(command, 'docker'); + assert.deepEqual(args.slice(0, 2), ['--host', 'unix:///var/run/docker.sock']); + calls.push(args[2]); + if (args[2] === 'create') { + for (const flag of ['--pull=never', '--network=none', '--read-only', '--cap-drop=ALL', 'no-new-privileges']) assert.ok(args.includes(flag)); + const mount = args.find((a) => a.includes('dst=/control')); + const control = mount.split('src=')[1].split(',dst=')[0]; + assert.ok(readFileSync(join(control, 'requirements.lock'), 'utf8').includes('zizmor==1.30.1')); + assert.ok(readFileSync(join(control, 'runner.py'), 'utf8').includes('zizmor')); + } + return { + status: 0, + stderr: '', + stdout: args[2] === 'start' ? JSON.stringify({ version: '1.30.1', reports: [{ path: '/inputs/000000.yml', findings: [] }] }) : '', + }; + }, }, - }); - assert.equal(out.scannedFiles, 1); assert.deepEqual(out.findings, []); - assert.deepEqual(calls, ['create', 'start', 'rm']); assert.deepEqual(readdirSync(parent), []); + ); + assert.equal(out.scannedFiles, 1); + assert.deepEqual(out.findings, []); + assert.deepEqual(calls, ['create', 'start', 'rm']); + assert.deepEqual(readdirSync(parent), []); }); diff --git a/scripts/security/semgrep-entry.test.mjs b/scripts/security/semgrep-entry.test.mjs index 1a663acb..fbddd3d3 100644 --- a/scripts/security/semgrep-entry.test.mjs +++ b/scripts/security/semgrep-entry.test.mjs @@ -16,7 +16,24 @@ test('checks inventory parse before scan and hashes again before emitting JSON', test('entrypoint keeps findings advisory and installs the locked runtime offline', () => { const source = readFileSync(new URL('./semgrep-entry.py', import.meta.url), 'utf8'); - for (const flag of ['--oss-only', '--metrics', '--disable-version-check', '--disable-nosem', '--strict', '--no-git-ignore', '--json', '--config', '/control/rules.yml', '--isolated', '--no-index', '--find-links=/wheels', '--only-binary=:all:', '--require-hashes', '--no-deps', '/control/requirements.lock']) { + for (const flag of [ + '--oss-only', + '--metrics', + '--disable-version-check', + '--disable-nosem', + '--strict', + '--no-git-ignore', + '--json', + '--config', + '/control/rules.yml', + '--isolated', + '--no-index', + '--find-links=/wheels', + '--only-binary=:all:', + '--require-hashes', + '--no-deps', + '/control/requirements.lock', + ]) { assert.ok(source.includes(flag), flag); } assert.ok(!source.includes('--scan-unknown-extensions'), 'do not bypass language detection'); diff --git a/scripts/security/semgrep-parse-gate.test.mjs b/scripts/security/semgrep-parse-gate.test.mjs index 940ceb45..2e868da9 100644 --- a/scripts/security/semgrep-parse-gate.test.mjs +++ b/scripts/security/semgrep-parse-gate.test.mjs @@ -8,7 +8,10 @@ test('Python parse gate behavior suite (Python 3 required)', () => { const python = process.platform === 'win32' ? 'python' : 'python3'; const script = fileURLToPath(new URL('./semgrep-parse-gate.test.py', import.meta.url)); const result = spawnSync(python, ['-B', script], { - encoding: 'utf8', timeout: 20000, maxBuffer: 1024 * 1024, shell: false, + encoding: 'utf8', + timeout: 20000, + maxBuffer: 1024 * 1024, + shell: false, }); assert.ifError(result.error); assert.equal(result.status, 0, result.stdout + result.stderr); diff --git a/scripts/security/semgrep-report.mjs b/scripts/security/semgrep-report.mjs index 958472ed..138c561e 100644 --- a/scripts/security/semgrep-report.mjs +++ b/scripts/security/semgrep-report.mjs @@ -10,7 +10,9 @@ const UNSAFE = /[\p{Cc}\p{Cf}]/u; const ESC = /[\p{Cc}\p{Cf}]/gu; const esc = (s) => s.replace(ESC, (c) => '\\u{' + c.codePointAt(0).toString(16).padStart(4, '0') + '}'); -const reject = () => { throw new Error('invalid-semgrep-report'); }; +const reject = () => { + throw new Error('invalid-semgrep-report'); +}; const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v); function safePath(value, root) { diff --git a/scripts/security/semgrep-report.test.mjs b/scripts/security/semgrep-report.test.mjs index 58f19f83..b831ed25 100644 --- a/scripts/security/semgrep-report.test.mjs +++ b/scripts/security/semgrep-report.test.mjs @@ -27,11 +27,13 @@ test('valid zero-finding report completes with scanned count', () => { }); test('known rules map to advisory findings with canonical rule ids', () => { - const out = call(report([ - result({ start: { line: 3 } }), - result({ check_id: 'inputs.dynamic-function-construction', path: '/snapshot/b.ts', start: { line: 5 } }), - result({ check_id: 'inputs.shell-command-execution', start: { line: 7 }, extra: {} }), - ])); + const out = call( + report([ + result({ start: { line: 3 } }), + result({ check_id: 'inputs.dynamic-function-construction', path: '/snapshot/b.ts', start: { line: 5 } }), + result({ check_id: 'inputs.shell-command-execution', start: { line: 7 }, extra: {} }), + ]), + ); assert.equal(out.status, 'completed'); assert.equal(out.scannedFiles, 2); assert.deepEqual(out.findings, [ @@ -49,10 +51,12 @@ test('raw scanner messages, snippets, metadata and extra fields never reach outp }); test('all findings are preserved without truncation', () => { - const results = Array.from({ length: 50 }, (_, i) => result({ - path: i % 2 ? '/snapshot/b.ts' : '/snapshot/a.js', - start: { line: i + 1 }, - })); + const results = Array.from({ length: 50 }, (_, i) => + result({ + path: i % 2 ? '/snapshot/b.ts' : '/snapshot/a.js', + start: { line: i + 1 }, + }), + ); assert.equal(call(report(results)).findings.length, 50); }); @@ -73,7 +77,10 @@ test('empty or duplicate expected target sets are rejected', () => { test('scanned set must match expected exactly: no missing, unexpected or duplicate', () => { assert.throws(() => normalizeSemgrep(report(), ['/snapshot/a.js', '/snapshot/missing.js'], { root: ROOT }), /invalid-semgrep-report/); - assert.throws(() => normalizeSemgrep(report([], ['/snapshot/a.js', '/snapshot/b.ts', '/snapshot/extra.js']), TARGETS, { root: ROOT }), /invalid-semgrep-report/); + assert.throws( + () => normalizeSemgrep(report([], ['/snapshot/a.js', '/snapshot/b.ts', '/snapshot/extra.js']), TARGETS, { root: ROOT }), + /invalid-semgrep-report/, + ); assert.throws(() => normalizeSemgrep(report([], ['/snapshot/a.js', '/snapshot/a.js']), ['/snapshot/a.js'], { root: ROOT }), /invalid-semgrep-report/); }); @@ -108,6 +115,19 @@ test('unknown rule terminals and non-WARNING severities are rejected', () => { }); test('malformed top-level and result shapes are rejected', () => { - const cases = [null, [], {}, { ...report(), results: 'nope' }, { ...report(), errors: 'x' }, { ...report(), paths: {} }, { ...report(), paths: { scanned: 'x' } }, report([null]), report([[]]), report([{ check_id: 7 }]), report([result({ start: {} })]), report([result({ extra: 'x' })])]; + const cases = [ + null, + [], + {}, + { ...report(), results: 'nope' }, + { ...report(), errors: 'x' }, + { ...report(), paths: {} }, + { ...report(), paths: { scanned: 'x' } }, + report([null]), + report([[]]), + report([{ check_id: 7 }]), + report([result({ start: {} })]), + report([result({ extra: 'x' })]), + ]; for (const bad of cases) assert.throws(() => call(bad), /invalid-semgrep-report/); }); diff --git a/scripts/security/snapshot-report.mjs b/scripts/security/snapshot-report.mjs index 8d311e59..263309a7 100644 --- a/scripts/security/snapshot-report.mjs +++ b/scripts/security/snapshot-report.mjs @@ -3,23 +3,37 @@ import { isAbsolute, relative, join } from 'node:path'; import { normalizeSemgrep } from './semgrep-report.mjs'; -const fail = () => { throw new Error('invalid-snapshot-report'); }; +const fail = () => { + throw new Error('invalid-snapshot-report'); +}; function originalPath(value) { - if (typeof value !== 'string' || /[\p{Cc}\p{Cf}\\:]/u.test(value) || - value.split('/').some(p => !p || p === '.' || p === '..' || p.toLowerCase() === '.git')) fail(); + if ( + typeof value !== 'string' || + /[\p{Cc}\p{Cf}\\:]/u.test(value) || + value.split('/').some((p) => !p || p === '.' || p === '..' || p.toLowerCase() === '.git') + ) + fail(); return value; } export function normalizeSnapshotReport(report, inventory) { try { - if (!inventory || typeof inventory.root !== 'string' || !isAbsolute(inventory.root) || - typeof inventory.commit !== 'string' || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(inventory.commit) || - !Array.isArray(inventory.targets) || inventory.targets.length === 0 || !Array.isArray(inventory.excluded)) fail(); + if ( + !inventory || + typeof inventory.root !== 'string' || + !isAbsolute(inventory.root) || + typeof inventory.commit !== 'string' || + !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(inventory.commit) || + !Array.isArray(inventory.targets) || + inventory.targets.length === 0 || + !Array.isArray(inventory.excluded) + ) + fail(); const mappings = new Map(); const originals = new Set(); for (const target of inventory.targets) { - if (!target || typeof target.path !== 'string' || !isAbsolute(target.path) || - typeof target.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(target.sha256)) fail(); + if (!target || typeof target.path !== 'string' || !isAbsolute(target.path) || typeof target.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(target.sha256)) + fail(); const name = relative(inventory.root, target.path); if (!/^\d{6}\.(?:js|jsx|mjs|cjs|ts|tsx|mts|cts)$/.test(name) || join(inventory.root, name) !== target.path) fail(); const original = originalPath(target.originalPath); @@ -28,7 +42,7 @@ export function normalizeSnapshotReport(report, inventory) { mappings.set(mountedPath, original); originals.add(original); } - const excluded = inventory.excluded.map(entry => { + const excluded = inventory.excluded.map((entry) => { if (!entry || entry.reason !== 'outside-js-ts-scope') fail(); const path = originalPath(entry.path); if (originals.has(path)) fail(); @@ -37,7 +51,9 @@ export function normalizeSnapshotReport(report, inventory) { }); // Never derive expectedPaths from report.paths.scanned: it is evidence to check. const normalized = normalizeSemgrep(report, [...mappings.keys()], { root: '/inputs' }); - const findings = normalized.findings.map(finding => ({ ...finding, path: mappings.get(finding.path) })); + const findings = normalized.findings.map((finding) => ({ ...finding, path: mappings.get(finding.path) })); return { commit: inventory.commit, status: normalized.status, scannedFiles: normalized.scannedFiles, excluded, findings }; - } catch { fail(); } + } catch { + fail(); + } } diff --git a/scripts/security/snapshot-report.test.mjs b/scripts/security/snapshot-report.test.mjs index dcef4f33..2046b3f0 100644 --- a/scripts/security/snapshot-report.test.mjs +++ b/scripts/security/snapshot-report.test.mjs @@ -9,7 +9,8 @@ import { tmpdir } from 'node:os'; const root = resolve('inert-snapshot'); const inventory = () => ({ - commit: 'a'.repeat(40), root, + commit: 'a'.repeat(40), + root, targets: [ { path: join(root, '000000.ts'), originalPath: 'src/a.ts', sha256: 'b'.repeat(64) }, { path: join(root, '000001.js'), originalPath: '.hidden/b.js', sha256: 'c'.repeat(64) }, @@ -17,10 +18,18 @@ const inventory = () => ({ excluded: [{ path: 'assets/logo.png', reason: 'outside-js-ts-scope' }], }); const report = () => ({ - version: '1.180.0', errors: [], skipped_rules: [], + version: '1.180.0', + errors: [], + skipped_rules: [], paths: { scanned: ['/inputs/000000.ts', '/inputs/000001.js'] }, - results: [{ check_id: 'inputs.decoded-text-execution', path: '/inputs/000001.js', - start: { line: 2 }, extra: { severity: 'WARNING', lines: 'SECRET SOURCE', message: 'SECRET MESSAGE' } }], + results: [ + { + check_id: 'inputs.decoded-text-execution', + path: '/inputs/000001.js', + start: { line: 2 }, + extra: { severity: 'WARNING', lines: 'SECRET SOURCE', message: 'SECRET MESSAGE' }, + }, + ], }); test('binds findings to original paths and preserves explicit excluded scope', () => { @@ -29,7 +38,9 @@ test('binds findings to original paths and preserves explicit excluded scope', ( const before = JSON.stringify({ manifest, raw }); const out = normalizeSnapshotReport(raw, manifest); assert.deepEqual(out, { - commit: manifest.commit, status: 'completed', scannedFiles: 2, + commit: manifest.commit, + status: 'completed', + scannedFiles: 2, excluded: manifest.excluded, findings: [{ rule: 'decoded-text-execution', path: '.hidden/b.js', line: 2, severity: 'advisory' }], }); @@ -40,7 +51,8 @@ test('binds findings to original paths and preserves explicit excluded scope', ( test('scanner cannot redefine expected coverage by removing or adding files', () => { for (const scanned of [[], ['/inputs/000001.js'], ['/inputs/000000.ts', '/inputs/000001.js', '/inputs/extra.js']]) { - const raw = report(); raw.paths.scanned = scanned; + const raw = report(); + raw.paths.scanned = scanned; assert.throws(() => normalizeSnapshotReport(raw, inventory()), { message: 'invalid-snapshot-report' }); } }); @@ -48,36 +60,60 @@ test('scanner cannot redefine expected coverage by removing or adding files', () test('rejects unsafe, ambiguous or malformed manifest mappings', () => { const cases = [null, {}, { ...inventory(), root: '.' }, { ...inventory(), commit: 'HEAD' }]; for (const patch of [ - { path: join(root, '..', '000000.ts') }, { path: join(root, 'nested', '000000.ts') }, - { originalPath: '../escape.ts' }, { originalPath: 'BAD\u202e.ts' }, { sha256: 'bad' }, + { path: join(root, '..', '000000.ts') }, + { path: join(root, 'nested', '000000.ts') }, + { originalPath: '../escape.ts' }, + { originalPath: 'BAD\u202e.ts' }, + { sha256: 'bad' }, ]) { - const m = inventory(); Object.assign(m.targets[0], patch); cases.push(m); + const m = inventory(); + Object.assign(m.targets[0], patch); + cases.push(m); } - const duplicate = inventory(); duplicate.targets[1] = { ...duplicate.targets[0] }; cases.push(duplicate); - const overlap = inventory(); overlap.excluded[0].path = 'src/a.ts'; cases.push(overlap); - const hidden = inventory(); hidden.excluded[0].reason = 'SECRET'; cases.push(hidden); + const duplicate = inventory(); + duplicate.targets[1] = { ...duplicate.targets[0] }; + cases.push(duplicate); + const overlap = inventory(); + overlap.excluded[0].path = 'src/a.ts'; + cases.push(overlap); + const hidden = inventory(); + hidden.excluded[0].reason = 'SECRET'; + cases.push(hidden); for (const m of cases) assert.throws(() => normalizeSnapshotReport(report(), m), { message: 'invalid-snapshot-report' }); }); -test('consumes a real Git export with an inert synthetic scanner report', t => { +test('consumes a real Git export with an inert synthetic scanner report', (t) => { const base = mkdtempSync(join(tmpdir(), 'snapshot-binding-test-')); t.after(() => rmSync(base, { recursive: true, force: true })); - const repo = join(base, 'repo'); mkdirSync(repo); - const hooks = join(base, 'hooks'); mkdirSync(hooks); - const git = (...args) => execFileSync('git', ['-c', `core.hooksPath=${hooks}`, '-c', 'user.name=Fixture', - '-c', 'user.email=fixture@example.invalid', '-c', 'commit.gpgsign=false', ...args], { - cwd: repo, stdio: ['pipe', 'pipe', 'pipe'], - env: { PATH: process.env.PATH, SystemRoot: process.env.SystemRoot, HOME: base, GIT_CONFIG_NOSYSTEM: '1' }, - }).toString().trim(); + const repo = join(base, 'repo'); + mkdirSync(repo); + const hooks = join(base, 'hooks'); + mkdirSync(hooks); + const git = (...args) => + execFileSync( + 'git', + ['-c', `core.hooksPath=${hooks}`, '-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', '-c', 'commit.gpgsign=false', ...args], + { + cwd: repo, + stdio: ['pipe', 'pipe', 'pipe'], + env: { PATH: process.env.PATH, SystemRoot: process.env.SystemRoot, HOME: base, GIT_CONFIG_NOSYSTEM: '1' }, + }, + ) + .toString() + .trim(); git('init', '-q'); writeFileSync(join(repo, 'a.ts'), 'void 0;'); writeFileSync(join(repo, 'README.md'), 'Excluded, not analyzed.'); - git('add', '.'); git('commit', '-qm', 'inert fixture'); + git('add', '.'); + git('commit', '-qm', 'inert fixture'); const manifest = exportSnapshot({ repo, commit: git('rev-parse', 'HEAD'), parent: base }); const raw = { version: '1.180.0', errors: [], skipped_rules: [], paths: { scanned: ['/inputs/000000.ts'] }, results: [] }; assert.deepEqual(normalizeSnapshotReport(raw, manifest), { - commit: manifest.commit, status: 'completed', scannedFiles: 1, - excluded: [{ path: 'README.md', reason: 'outside-js-ts-scope' }], findings: [], + commit: manifest.commit, + status: 'completed', + scannedFiles: 1, + excluded: [{ path: 'README.md', reason: 'outside-js-ts-scope' }], + findings: [], }); }); diff --git a/scripts/security/zizmor-entry.test.mjs b/scripts/security/zizmor-entry.test.mjs index 98136f07..c4c5fced 100644 --- a/scripts/security/zizmor-entry.test.mjs +++ b/scripts/security/zizmor-entry.test.mjs @@ -12,7 +12,10 @@ test('zizmor entrypoint Python behavior suite (Python 3 required)', () => { const python = process.platform === 'win32' ? 'python' : 'python3'; const script = fileURLToPath(new URL('./zizmor-entry.test.py', import.meta.url)); const result = spawnSync(python, ['-B', script], { - encoding: 'utf8', timeout: 20000, maxBuffer: 1024 * 1024, shell: false, + encoding: 'utf8', + timeout: 20000, + maxBuffer: 1024 * 1024, + shell: false, }); assert.ifError(result.error); assert.equal(result.status, 0, result.stdout + result.stderr); diff --git a/scripts/security/zizmor-report.mjs b/scripts/security/zizmor-report.mjs index f1ad232a..a95c3a22 100644 --- a/scripts/security/zizmor-report.mjs +++ b/scripts/security/zizmor-report.mjs @@ -17,7 +17,9 @@ const UNSAFE = /[\p{Cc}\p{Cf}\\:]/u; // any control/format bytes anywhere, including a hostile inventory root. const CONTROL_BYTES = /[\p{Cc}\p{Cf}]/u; -const fail = () => { throw new Error('invalid-zizmor-report'); }; +const fail = () => { + throw new Error('invalid-zizmor-report'); +}; const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v); const compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0); @@ -32,8 +34,7 @@ function segments(value) { function workflowOriginal(value) { segments(value); const parts = value.split('/'); - if (parts.length !== 3 || parts[0] !== '.github' || parts[1] !== 'workflows' || - !/\.(?:yml|yaml)$/.test(parts[2])) fail(); + if (parts.length !== 3 || parts[0] !== '.github' || parts[1] !== 'workflows' || !/\.(?:yml|yaml)$/.test(parts[2])) fail(); return value; } @@ -91,8 +92,7 @@ function reportEntries(report, byMounted) { function locationOf(loc, mounted) { if (!isObject(loc) || !isObject(loc.symbolic) || !isObject(loc.concrete)) fail(); const key = loc.symbolic.key; - if (!isObject(key) || Object.keys(key).length !== 1 || !isObject(key.Local) || - key.Local.verbatim_path !== mounted) fail(); + if (!isObject(key) || Object.keys(key).length !== 1 || !isObject(key.Local) || key.Local.verbatim_path !== mounted) fail(); const kind = loc.symbolic.kind; if (typeof kind !== 'string' || kind.length === 0) fail(); const concrete = loc.concrete.location; @@ -105,8 +105,7 @@ function locationOf(loc, mounted) { function findingOf(finding, mounted, original) { if (!isObject(finding) || typeof finding.ident !== 'string' || !RULE.test(finding.ident)) fail(); if ('ignored' in finding && typeof finding.ignored !== 'boolean') fail(); - if (!Array.isArray(finding.locations) || finding.locations.length === 0 || - finding.locations.length > MAX_FINDINGS) fail(); + if (!Array.isArray(finding.locations) || finding.locations.length === 0 || finding.locations.length > MAX_FINDINGS) fail(); let line; for (const loc of finding.locations) { const parsed = locationOf(loc, mounted); @@ -126,8 +125,7 @@ export function normalizeZizmor(report, inventory) { for (const finding of entry.findings) findings.push(findingOf(finding, entry.path, original)); } findings.sort((a, b) => compare(a.path, b.path) || a.line - b.line || compare(a.rule, b.rule)); - const unique = findings.filter((f, i) => i === 0 || f.path !== findings[i - 1].path || - f.line !== findings[i - 1].line || f.rule !== findings[i - 1].rule); + const unique = findings.filter((f, i) => i === 0 || f.path !== findings[i - 1].path || f.line !== findings[i - 1].line || f.rule !== findings[i - 1].rule); return { commit: trusted.commit, status: 'ok', @@ -135,5 +133,7 @@ export function normalizeZizmor(report, inventory) { excluded: trusted.excluded, findings: unique, }; - } catch { fail(); } + } catch { + fail(); + } } diff --git a/scripts/security/zizmor-report.test.mjs b/scripts/security/zizmor-report.test.mjs index 44e39ecc..52e08fa5 100644 --- a/scripts/security/zizmor-report.test.mjs +++ b/scripts/security/zizmor-report.test.mjs @@ -37,8 +37,7 @@ function loc(mounted, kind, row) { }; } -function finding({ mounted = '/inputs/000000.yml', ident = 'template-injection', row = 7, - kind = 'Primary', ignored = true, locations } = {}) { +function finding({ mounted = '/inputs/000000.yml', ident = 'template-injection', row = 7, kind = 'Primary', ignored = true, locations } = {}) { return { ident, desc: `desc ${SECRET}`, @@ -58,8 +57,7 @@ const report = () => ({ ], }); -const throws = (raw, inv = inventory()) => - assert.throws(() => normalizeZizmor(raw, inv), { message: 'invalid-zizmor-report' }); +const throws = (raw, inv = inventory()) => assert.throws(() => normalizeZizmor(raw, inv), { message: 'invalid-zizmor-report' }); test('binds the real json-v1 schema to originals and never leaks finding text', () => { const inv = inventory(); @@ -91,11 +89,7 @@ test('ignored:true is advisory evidence and does not suppress the finding', () = test('accepts empty findings and deduplicates/sorts deterministically', () => { const raw = report(); - raw.reports[0].findings = [ - finding({ row: 3, ident: 'artipacked' }), - finding({ row: 7 }), - finding({ row: 3, ident: 'artipacked' }), - ]; + raw.reports[0].findings = [finding({ row: 3, ident: 'artipacked' }), finding({ row: 7 }), finding({ row: 3, ident: 'artipacked' })]; const out = normalizeZizmor(raw, inventory()); assert.equal(out.scannedFiles, 2); assert.deepEqual(out.findings, [ @@ -105,19 +99,31 @@ test('accepts empty findings and deduplicates/sorts deterministically', () => { }); test('requires the exact independently expected report set', () => { - const missing = report(); missing.reports.pop(); + const missing = report(); + missing.reports.pop(); const empty = { version: '1.30.1', reports: [] }; - const extra = report(); extra.reports.push({ path: '/inputs/000002.yml', findings: [] }); - const dup = report(); dup.reports.push({ path: '/inputs/000000.yml', findings: [] }); - const alias = report(); alias.reports[0].path = '/inputs/000000.YML'; - const remoteAlias = report(); remoteAlias.reports[0].path = '/other/000000.yml'; + const extra = report(); + extra.reports.push({ path: '/inputs/000002.yml', findings: [] }); + const dup = report(); + dup.reports.push({ path: '/inputs/000000.yml', findings: [] }); + const alias = report(); + alias.reports[0].path = '/inputs/000000.YML'; + const remoteAlias = report(); + remoteAlias.reports[0].path = '/other/000000.yml'; for (const raw of [missing, empty, extra, dup, alias, remoteAlias]) throws(raw); }); test('rejects malformed report envelopes instead of returning empty findings', () => { - for (const raw of [null, {}, { version: '1.30.1' }, { version: '1.30.1', reports: null }, - { version: '1.30.1', reports: [null] }, { version: '1.30.1', reports: [{ path: 1, findings: [] }] }, - { version: '1.30.1', reports: [{ path: '/inputs/000000.yml', findings: null }] }]) throws(raw); + for (const raw of [ + null, + {}, + { version: '1.30.1' }, + { version: '1.30.1', reports: null }, + { version: '1.30.1', reports: [null] }, + { version: '1.30.1', reports: [{ path: 1, findings: [] }] }, + { version: '1.30.1', reports: [{ path: '/inputs/000000.yml', findings: null }] }, + ]) + throws(raw); }); test('rejects a wrong tool version', () => { @@ -129,15 +135,27 @@ test('every location must reference the current report target as Local', () => { const otherFile = report(); otherFile.reports[0].findings = [finding({ mounted: '/inputs/000001.yaml' })]; const remote = report(); - remote.reports[0].findings = [finding({ locations: [{ - symbolic: { key: { Remote: { verbatim_path: '/inputs/000000.yml' } }, kind: 'Primary' }, - concrete: loc('/inputs/000000.yml', 'Primary', 7).concrete, - }] })]; + remote.reports[0].findings = [ + finding({ + locations: [ + { + symbolic: { key: { Remote: { verbatim_path: '/inputs/000000.yml' } }, kind: 'Primary' }, + concrete: loc('/inputs/000000.yml', 'Primary', 7).concrete, + }, + ], + }), + ]; const mixed = report(); - mixed.reports[0].findings = [finding({ locations: [{ - symbolic: { key: { Local: { verbatim_path: '/inputs/000000.yml' }, Remote: { verbatim_path: '/inputs/000000.yml' } }, kind: 'Primary' }, - concrete: loc('/inputs/000000.yml', 'Primary', 7).concrete, - }] })]; + mixed.reports[0].findings = [ + finding({ + locations: [ + { + symbolic: { key: { Local: { verbatim_path: '/inputs/000000.yml' }, Remote: { verbatim_path: '/inputs/000000.yml' } }, kind: 'Primary' }, + concrete: loc('/inputs/000000.yml', 'Primary', 7).concrete, + }, + ], + }), + ]; for (const raw of [otherFile, remote, mixed]) throws(raw); }); @@ -157,10 +175,12 @@ test('requires a valid integer row and at least one Primary location', () => { test('rejects malformed location shapes', () => { const shapes = [ - null, {}, { symbolic: null, concrete: {} }, { symbolic: {}, concrete: {} }, + null, + {}, + { symbolic: null, concrete: {} }, + { symbolic: {}, concrete: {} }, { symbolic: { key: { Local: { verbatim_path: '/inputs/000000.yml' } }, kind: 'Primary' }, concrete: {} }, - { symbolic: { key: { Local: { verbatim_path: '/inputs/000000.yml' } }, kind: 'Primary' }, - concrete: { location: {} } }, + { symbolic: { key: { Local: { verbatim_path: '/inputs/000000.yml' } }, kind: 'Primary' }, concrete: { location: {} } }, ]; for (const shape of shapes) { const raw = report(); @@ -178,13 +198,23 @@ test('rejects unsafe idents', () => { }); test('rejects malformed or unsafe inventory mappings', () => { - const cases = [null, {}, { ...inventory(), root: '.' }, { ...inventory(), commit: 'HEAD' }, - { ...inventory(), commit: 'a'.repeat(41) }, { ...inventory(), targets: [] }]; + const cases = [ + null, + {}, + { ...inventory(), root: '.' }, + { ...inventory(), commit: 'HEAD' }, + { ...inventory(), commit: 'a'.repeat(41) }, + { ...inventory(), targets: [] }, + ]; for (const patch of [ - { path: join(root, 'nested', '000000.yml') }, { path: join(root, '000000.txt') }, - { path: 'relative/000000.yml' }, { originalPath: 'src/ci.yml' }, - { originalPath: '.github/workflows/sub/ci.yml' }, { originalPath: '.github/workflows/ci.txt' }, - { originalPath: '.github/workflows/../ci.yml' }, { originalPath: '.github/other/ci.yml' }, + { path: join(root, 'nested', '000000.yml') }, + { path: join(root, '000000.txt') }, + { path: 'relative/000000.yml' }, + { originalPath: 'src/ci.yml' }, + { originalPath: '.github/workflows/sub/ci.yml' }, + { originalPath: '.github/workflows/ci.txt' }, + { originalPath: '.github/workflows/../ci.yml' }, + { originalPath: '.github/other/ci.yml' }, { sha256: 'bad' }, ]) { const inv = inventory(); @@ -212,7 +242,7 @@ test('rejects malformed or unsafe inventory mappings', () => { test('rejects control and format characters in the host root of remapped targets', () => { for (const evil of ['\u0000', '\u202e']) { const inv = inventory(); - const mounts = inv.targets.map(target => target.path.split(sep).at(-1)); + const mounts = inv.targets.map((target) => target.path.split(sep).at(-1)); inv.root = `${root}${evil}`; inv.targets = inv.targets.map((target, index) => ({ ...target, path: join(inv.root, mounts[index]) })); const before = JSON.stringify(inv); diff --git a/scripts/setup-signing.mjs b/scripts/setup-signing.mjs index 634cb38d..90aa79b8 100644 --- a/scripts/setup-signing.mjs +++ b/scripts/setup-signing.mjs @@ -258,8 +258,15 @@ function defaultGitToplevel() { */ export async function runSetup(deps) { const { - argv, cwd, home, fsImpl = fs, run, confirm, promptHidden, - log = console.log, setUmask = (value) => process.umask(value), + argv, + cwd, + home, + fsImpl = fs, + run, + confirm, + promptHidden, + log = console.log, + setUmask = (value) => process.umask(value), tty = { stdin: process.stdin, stdout: process.stdout }, env = process.env, gitToplevel = defaultGitToplevel(), @@ -370,7 +377,9 @@ export async function runSetup(deps) { for (const { name, value } of uploads) { const result = run('gh', secretSetCommand(repo, name), { input: value }); if (result.status !== 0) { - throw new Error(`Falló la subida de ${name} a ${repo}. Subidos: ${uploaded.length ? uploaded.join(', ') : 'ninguno'}. No se reintenta ni se revierte; revísalo a mano.`); + throw new Error( + `Falló la subida de ${name} a ${repo}. Subidos: ${uploaded.length ? uploaded.join(', ') : 'ninguno'}. No se reintenta ni se revierte; revísalo a mano.`, + ); } uploaded.push(name); } diff --git a/scripts/setup-signing.test.mjs b/scripts/setup-signing.test.mjs index c9cd46a5..b3dd3a63 100644 --- a/scripts/setup-signing.test.mjs +++ b/scripts/setup-signing.test.mjs @@ -125,7 +125,10 @@ test('restrictPrivateKey endurece permisos laxos sin relajar permisos estrictos' restrictPrivateKey({ keyPath, fsImpl: { - statSync: (file) => { assert.equal(file, keyPath); return { mode }; }, + statSync: (file) => { + assert.equal(file, keyPath); + return { mode }; + }, chmodSync: (file, permissions) => calls.push([file, permissions]), }, }); @@ -181,16 +184,29 @@ test('assertOwnerTty exige TTY en stdin y stdout y rechaza CI', async () => { test('inspectKeyPair distingue none/complete/partial/symlink sin seguir enlaces', async () => { const { inspectKeyPair } = await load(); - for (const [pair, expected] of [['none', 'none'], ['complete', 'complete'], ['partial', 'partial'], ['symlink', 'unsafe']]) { + for (const [pair, expected] of [ + ['none', 'none'], + ['complete', 'complete'], + ['partial', 'partial'], + ['symlink', 'unsafe'], + ]) { assert.equal(inspectKeyPair({ fsImpl: fs, ...keys(mkHome({ pair })) }), expected, `estado de ${pair}`); } }); test('lstatOrNull falla cerrado: EACCES lanza y solo ENOENT devuelve none', async () => { const { inspectKeyPair } = await load(); - const denied = () => { const error = new Error('permiso denegado'); error.code = 'EACCES'; throw error; }; + const denied = () => { + const error = new Error('permiso denegado'); + error.code = 'EACCES'; + throw error; + }; assert.throws(() => inspectKeyPair({ fsImpl: { lstatSync: denied }, keyPath: '/x', pubPath: '/y' }), /permiso/); - const missing = () => { const error = new Error('no existe'); error.code = 'ENOENT'; throw error; }; + const missing = () => { + const error = new Error('no existe'); + error.code = 'ENOENT'; + throw error; + }; assert.equal(inspectKeyPair({ fsImpl: { lstatSync: missing }, keyPath: '/x', pubPath: '/y' }), 'none'); }); @@ -234,7 +250,16 @@ test('parseGitHubRemote reconoce https/ssh de GitHub y rechaza el resto', async assert.equal(parseGitHubRemote('git@github.com:egdev6/quorb.git'), REPO); assert.equal(parseGitHubRemote('ssh://git@github.com/egdev6/quorb.git'), REPO); assert.equal(parseGitHubRemote('ssh://git@github.com:22/egdev6/quorb.git'), REPO); - const bad = ['https://gitlab.com/egdev6/quorb.git', 'git@bitbucket.org:egdev6/quorb.git', 'https://x-token-abc@github.com/egdev6/quorb.git', 'github.com/egdev6/quorb', 'weird', '', null, 42]; + const bad = [ + 'https://gitlab.com/egdev6/quorb.git', + 'git@bitbucket.org:egdev6/quorb.git', + 'https://x-token-abc@github.com/egdev6/quorb.git', + 'github.com/egdev6/quorb', + 'weird', + '', + null, + 42, + ]; for (const value of bad) assert.equal(parseGitHubRemote(value), null, `debe rechazar ${JSON.stringify(value)}`); }); @@ -274,8 +299,14 @@ test('runSetup exige raíz git igual al cwd antes de generar o tocar gh', async const { run, calls } = fakeRunner(); await assert.rejects(runSetup(baseDeps({ run, cwd, gitToplevel: null })), /raíz git/i); await assert.rejects(runSetup(baseDeps({ run, cwd, gitToplevel: '/otro/sitio' })), /raíz git/i); - assert.equal(calls.some((c) => c.cmd === process.execPath), false); - assert.equal(calls.some((c) => c.cmd === 'gh'), false); + assert.equal( + calls.some((c) => c.cmd === process.execPath), + false, + ); + assert.equal( + calls.some((c) => c.cmd === 'gh'), + false, + ); }); test('runSetup ata --repo al remoto origin y rechaza desajustes sin subir nada', async () => { @@ -284,8 +315,16 @@ test('runSetup ata --repo al remoto origin y rechaza desajustes sin subir nada', for (const origin of origins) { const { run, calls } = fakeRunner({ origin }); await assert.rejects(runSetup(baseDeps({ run })), /origin|reconocida|coincide/i, `origin ${origin}`); - assert.equal(calls.some((c) => c.cmd === 'gh'), false, `sin gh para ${origin}`); - assert.equal(calls.some((c) => c.cmd === process.execPath), false, `sin generar para ${origin}`); + assert.equal( + calls.some((c) => c.cmd === 'gh'), + false, + `sin gh para ${origin}`, + ); + assert.equal( + calls.some((c) => c.cmd === process.execPath), + false, + `sin generar para ${origin}`, + ); } }); @@ -316,7 +355,10 @@ test('runSetup rechaza pares parciales, symlinks y .tauri enlazado sin escribir' const before = fs.readFileSync(path.join(cwd, 'src-tauri', 'tauri.conf.json'), 'utf8'); const { run, calls } = fakeRunner(); await assert.rejects(runSetup(baseDeps({ run, home, cwd })), rx); - assert.equal(calls.some((c) => c.cmd === process.execPath), false); + assert.equal( + calls.some((c) => c.cmd === process.execPath), + false, + ); assert.equal(fs.readFileSync(path.join(cwd, 'src-tauri', 'tauri.conf.json'), 'utf8'), before); } }); @@ -372,17 +414,26 @@ test('runSetup sube base64 canónico aunque el fichero nativo sea crudo', async test('runSetup no reutiliza un par existente sin confirmación explícita', async () => { const { runSetup } = await load(); let n = 0; - const confirm = async () => { n += 1; return n === 1; }; + const confirm = async () => { + n += 1; + return n === 1; + }; const { run, calls } = fakeRunner(); await assert.rejects(runSetup(baseDeps({ run, home: mkHome({ pair: 'complete' }), confirm })), /reutiliz|cancelad/i); - assert.equal(calls.some((c) => c.args[1] === 'set'), false); + assert.equal( + calls.some((c) => c.args[1] === 'set'), + false, + ); }); test('runSetup exige contraseña no vacía y no sube nada si está en blanco', async () => { const { runSetup } = await load(); const { run, calls } = fakeRunner(); await assert.rejects(runSetup(baseDeps({ run, home: mkHome({ pair: 'complete' }), promptHidden: async () => '' })), /contraseña/i); - assert.equal(calls.some((c) => c.args[1] === 'set'), false); + assert.equal( + calls.some((c) => c.args[1] === 'set'), + false, + ); }); test('runSetup aborta si listar secretos falla y no escribe config ni sube', async () => { @@ -392,7 +443,10 @@ test('runSetup aborta si listar secretos falla y no escribe config ni sube', asy const before = fs.readFileSync(path.join(cwd, 'src-tauri', 'tauri.conf.json'), 'utf8'); const { run, calls } = fakeRunner({ secretListStatus: 1 }); await assert.rejects(runSetup(baseDeps({ run, home, cwd })), /listar|secretos/i); - assert.equal(calls.some((c) => c.cmd === 'gh' && c.args[1] === 'set'), false); + assert.equal( + calls.some((c) => c.cmd === 'gh' && c.args[1] === 'set'), + false, + ); assert.equal(fs.readFileSync(path.join(cwd, 'src-tauri', 'tauri.conf.json'), 'utf8'), before); }); @@ -404,7 +458,10 @@ test('runSetup aborta si la lista de secretos es inválida y no escribe config', for (const secretList of ['not json', '{"a":1}', '[{"nope":"x"}]']) { const { run, calls } = fakeRunner({ secretList }); await assert.rejects(runSetup(baseDeps({ run, home, cwd })), /abort|formato|válidas|interpretar/i); - assert.equal(calls.some((c) => c.cmd === 'gh' && c.args[1] === 'set'), false); + assert.equal( + calls.some((c) => c.cmd === 'gh' && c.args[1] === 'set'), + false, + ); assert.equal(fs.readFileSync(path.join(cwd, 'src-tauri', 'tauri.conf.json'), 'utf8'), before); } }); @@ -419,16 +476,26 @@ test('runSetup no reporta éxito si solo sube uno de los dos secretos', async () return true; }); const sets = calls.filter((c) => c.cmd === 'gh' && c.args[1] === 'set'); - assert.deepEqual(sets.map((s) => s.args[2]), [SECRET_KEY, SECRET_PASSWORD], 'un intento por secreto, sin reintentos'); + assert.deepEqual( + sets.map((s) => s.args[2]), + [SECRET_KEY, SECRET_PASSWORD], + 'un intento por secreto, sin reintentos', + ); }); test('runSetup exige confirmación para reemplazar secretos existentes', async () => { const { runSetup } = await load(); let n = 0; - const confirm = async () => { n += 1; return n <= 2; }; // plan + reutilizar sí; reemplazar no + const confirm = async () => { + n += 1; + return n <= 2; + }; // plan + reutilizar sí; reemplazar no const { run, calls } = fakeRunner({ secretList: JSON.stringify([{ name: 'TAURI_SIGNING_PRIVATE_KEY' }]) }); await assert.rejects(runSetup(baseDeps({ run, home: mkHome({ pair: 'complete' }), confirm })), /reemplaz|rotan/i); - assert.equal(calls.some((c) => c.args[1] === 'set'), false); + assert.equal( + calls.some((c) => c.args[1] === 'set'), + false, + ); }); test('runSetup sanea el entorno del generador, descarta stdout y no filtra valores', async () => { diff --git a/scripts/uninstall.test.mjs b/scripts/uninstall.test.mjs index 8e88f0dd..b8411ff8 100644 --- a/scripts/uninstall.test.mjs +++ b/scripts/uninstall.test.mjs @@ -62,12 +62,7 @@ function assertStableIdentityAllowlist(source) { assert.equal(allowlist, '("es.egdev.quorb", ".quorb")'); } -const allowlistFixtureLines = [ - 'if !matches!(', - ' (profile.identifier, profile.home_dir),', - ' ("es.egdev.quorb", ".quorb")', - ')', -]; +const allowlistFixtureLines = ['if !matches!(', ' (profile.identifier, profile.home_dir),', ' ("es.egdev.quorb", ".quorb")', ')']; for (const [label, endings] of [ ['LF', ['\n', '\n', '\n']], ['CRLF', ['\r\n', '\r\n', '\r\n']], @@ -80,10 +75,11 @@ for (const [label, endings] of [ test(`stable identity allowlist rejects a foreign identity or extra profile with ${label}`, () => { assert.throws(() => assertStableIdentityAllowlist(fixture.replace('es.egdev.quorb', 'org.example.foreign')), assert.AssertionError); assert.throws(() => assertStableIdentityAllowlist(fixture.replace('".quorb"', '".foreign"')), assert.AssertionError); - assert.throws(() => assertStableIdentityAllowlist(fixture.replace( - '("es.egdev.quorb", ".quorb")', - '("es.egdev.quorb", ".quorb") | ("org.example.foreign", ".foreign")', - )), assert.AssertionError); + assert.throws( + () => + assertStableIdentityAllowlist(fixture.replace('("es.egdev.quorb", ".quorb")', '("es.egdev.quorb", ".quorb") | ("org.example.foreign", ".foreign")')), + assert.AssertionError, + ); }); } diff --git a/scripts/updates-section-regression.test.mjs b/scripts/updates-section-regression.test.mjs index 6eaf1327..9d57186d 100644 --- a/scripts/updates-section-regression.test.mjs +++ b/scripts/updates-section-regression.test.mjs @@ -32,7 +32,7 @@ test('UpdatesSection conserva el early-return mode !== native (regresión merge) // 1. La función existe con la firma exacta (locale opcional desde T2c). if ( !/function\s+UpdatesSection\s*\(\s*\{\s*auto\s*,\s*onAuto(?:\s*,\s*locale\s*=\s*'es')?\s*\}\s*:\s*\{\s*auto\s*:\s*boolean\s*;\s*onAuto\s*:\s*\(v:\s*boolean\)\s*=>\s*void\s*(?:;\s*locale\?:\s*Locale)?\s*\}\s*\)/.test( - src + src, ) ) { throw new Error('Firma de UpdatesSection no encontrada — el componente fue refactorizado; revisar manualmente'); @@ -43,17 +43,16 @@ test('UpdatesSection conserva el early-return mode !== native (regresión merge) const earlyReturnRe = /if\s*\(\s*mode\s*!==\s*'native'\s*\)\s*return\s*\(/; if (!earlyReturnRe.test(src)) { throw new Error( - 'Early-return `if (mode !== \'native\') return (` no encontrado en UpdatesSection. ' + - 'Restaurar el bloque (macOS modo manual debe mostrar el aviso de actualización manual).' + "Early-return `if (mode !== 'native') return (` no encontrado en UpdatesSection. " + + 'Restaurar el bloque (macOS modo manual debe mostrar el aviso de actualización manual).', ); } // 3. El texto específico del modo manual sigue literal (ahora como valor `es` // del catálogo) y el cableado usa esa clave. - if (!esCatalog.includes('manualMode: \'Actualización manual en macOS. No se buscan ni se instalan actualizaciones desde la app.\'')) { + if (!esCatalog.includes("manualMode: 'Actualización manual en macOS. No se buscan ni se instalan actualizaciones desde la app.'")) { throw new Error( - 'Texto del modo manual modificado. Mantener el valor es literal de settings.updates.manualMode ' + - 'para que el owner apruebe sin preguntas.' + 'Texto del modo manual modificado. Mantener el valor es literal de settings.updates.manualMode ' + 'para que el owner apruebe sin preguntas.', ); } if (!src.includes("t(locale, 'settings.updates.manualMode')")) { @@ -62,7 +61,7 @@ test('UpdatesSection conserva el early-return mode !== native (regresión merge) // 4. La rama nativa (modo `'native'`) sigue presente, devolviendo la UI completa // con el título "Versión instalada" (no "Versión actual"), por clave de catálogo. - if (!esCatalog.includes('installedTitle: \'Versión instalada\'')) { + if (!esCatalog.includes("installedTitle: 'Versión instalada'")) { throw new Error('El valor es de settings.updates.installedTitle debe seguir siendo «Versión instalada».'); } if (!//.test(src)) { diff --git a/scripts/verify-linux-bundles.test.mjs b/scripts/verify-linux-bundles.test.mjs index c45b9eb9..d70bbaa5 100644 --- a/scripts/verify-linux-bundles.test.mjs +++ b/scripts/verify-linux-bundles.test.mjs @@ -60,4 +60,4 @@ test('el gate falla si falta el .deb y solo llega el .AppImage', suiteOpts, () = const r = run(verify, [APPIMAGE]); assert.equal(r.code, 1); assert.match(r.stderr, /No hay ningún \.deb/); -}); \ No newline at end of file +}); diff --git a/scripts/verify-macos-bundle.mjs b/scripts/verify-macos-bundle.mjs index cfd18db9..6082fd10 100644 --- a/scripts/verify-macos-bundle.mjs +++ b/scripts/verify-macos-bundle.mjs @@ -62,11 +62,16 @@ export function verifyMacosBundle({ root = projectRoot, sourceSha = process.env. if (typeof executable !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(executable)) throw new Error('Unsafe executable name'); const binary = io.readFileSync(checked(path.join(apps[0], 'Contents/MacOS', executable), 'file')); // A thin, little-endian 64-bit ARM executable, not x86_64 or a universal container. - if (binary.length < 32 || binary.readUInt32LE(0) !== 0xfeedfacf || - binary.readUInt32LE(4) !== 0x0100000c || binary.readUInt32LE(12) !== 2) throw new Error('Expected native arm64 Mach-O executable'); + if (binary.length < 32 || binary.readUInt32LE(0) !== 0xfeedfacf || binary.readUInt32LE(4) !== 0x0100000c || binary.readUInt32LE(12) !== 2) + throw new Error('Expected native arm64 Mach-O executable'); run('/usr/bin/hdiutil', ['verify', dmgs[0]]); return { - sourceSha, version: pkg.version, arch: 'arm64', minimumSystemVersion, app: apps[0], dmg: dmgs[0], + sourceSha, + version: pkg.version, + arch: 'arm64', + minimumSystemVersion, + app: apps[0], + dmg: dmgs[0], dmgSha256: createHash('sha256').update(io.readFileSync(dmgs[0])).digest('hex'), }; } @@ -80,15 +85,25 @@ const securityCommand = (command, args) => { export function verifyDeveloperSignature(target, { run = securityCommand } = {}) { run('/usr/bin/codesign', ['--verify', '--deep', '--strict', target]); const signature = run('/usr/bin/codesign', ['-dv', '--verbose=4', target]); - if (!/^Authority=Developer ID Application: .+ \(SRD8T33RU5\)$/m.test(signature) || - !/^TeamIdentifier=SRD8T33RU5$/m.test(signature)) throw new Error('Unexpected Developer ID authority or team'); + if (!/^Authority=Developer ID Application: .+ \(SRD8T33RU5\)$/m.test(signature) || !/^TeamIdentifier=SRD8T33RU5$/m.test(signature)) + throw new Error('Unexpected Developer ID authority or team'); } export function validateMountEntities(plist, mount) { const entities = plist?.['system-entities']; - if (!Array.isArray(entities) || !entities.length || entities.length > 32 || - entities.some((entity) => !entity || typeof entity !== 'object' || Array.isArray(entity) || - typeof entity['dev-entry'] !== 'string' || !/^\/dev\/disk[0-9]+(?:s[0-9]+)*$/.test(entity['dev-entry']))) { + if ( + !Array.isArray(entities) || + !entities.length || + entities.length > 32 || + entities.some( + (entity) => + !entity || + typeof entity !== 'object' || + Array.isArray(entity) || + typeof entity['dev-entry'] !== 'string' || + !/^\/dev\/disk[0-9]+(?:s[0-9]+)*$/.test(entity['dev-entry']), + ) + ) { throw new Error('Invalid mounted DMG entities'); } const volumes = entities.filter((entity) => Object.hasOwn(entity, 'mount-point')); @@ -152,10 +167,24 @@ export function verifyMountedApp({ mount, version, io = fs, run = securityComman // No build, re-sign, app staple, repackaging or execution. Only the retained outer // DMG is mutated. Gatekeeper/network failures fail closed, including during cleanup. -export function stapleAndVerifyDmg({ dmg, version, inputSha256, temp = process.env.RUNNER_TEMP, io = fs, run = securityCommand, - parsePlist = (text) => JSON.parse(execFileSync('python3', ['-c', 'import plistlib,json,sys; print(json.dumps(plistlib.loads(sys.stdin.buffer.read())))'], { - input: text, encoding: 'utf8', timeout: 10_000, maxBuffer: 1024 * 1024, stdio: ['pipe', 'pipe', 'pipe'], - })) }) { +export function stapleAndVerifyDmg({ + dmg, + version, + inputSha256, + temp = process.env.RUNNER_TEMP, + io = fs, + run = securityCommand, + parsePlist = (text) => + JSON.parse( + execFileSync('python3', ['-c', 'import plistlib,json,sys; print(json.dumps(plistlib.loads(sys.stdin.buffer.read())))'], { + input: text, + encoding: 'utf8', + timeout: 10_000, + maxBuffer: 1024 * 1024, + stdio: ['pipe', 'pipe', 'pipe'], + }), + ), +}) { if (!path.isAbsolute(temp ?? '') || io.lstatSync(dmg).isSymbolicLink() || !io.lstatSync(dmg).isFile()) throw new Error('Unsafe retained DMG'); const before = createHash('sha256').update(io.readFileSync(dmg)).digest('hex'); if (before !== inputSha256) throw new Error('Retained DMG changed before staple'); diff --git a/scripts/verify-macos-bundle.test.mjs b/scripts/verify-macos-bundle.test.mjs index a9681a72..5e09a857 100644 --- a/scripts/verify-macos-bundle.test.mjs +++ b/scripts/verify-macos-bundle.test.mjs @@ -14,9 +14,19 @@ function fixture() { const files = new Map(); const dir = (name) => files.set(name, { type: 'directory' }); const file = (name, data) => files.set(name, { type: 'file', data }); - for (const name of [root, path.join(root, 'src-tauri'), path.join(root, 'src-tauri', 'target'), - path.join(root, 'src-tauri', 'target', 'release'), bundle, path.join(bundle, 'macos'), path.join(bundle, 'dmg'), - app, path.join(app, 'Contents'), path.join(app, 'Contents', 'MacOS')]) dir(name); + for (const name of [ + root, + path.join(root, 'src-tauri'), + path.join(root, 'src-tauri', 'target'), + path.join(root, 'src-tauri', 'target', 'release'), + bundle, + path.join(bundle, 'macos'), + path.join(bundle, 'dmg'), + app, + path.join(app, 'Contents'), + path.join(app, 'Contents', 'MacOS'), + ]) + dir(name); const header = Buffer.alloc(32); header.writeUInt32LE(0xfeedfacf); header.writeUInt32LE(0x0100000c, 4); @@ -32,10 +42,12 @@ function fixture() { lstatSync(name) { const entry = files.get(name); if (!entry) throw new Error(`Missing: ${name}`); - return Object.fromEntries(['file', 'directory', 'symbolicLink'].map((type) => - [`is${type[0].toUpperCase()}${type.slice(1)}`, () => entry.type === type])); + return Object.fromEntries(['file', 'directory', 'symbolicLink'].map((type) => [`is${type[0].toUpperCase()}${type.slice(1)}`, () => entry.type === type])); }, - readdirSync: (name) => [...files.keys()].filter((key) => key.startsWith(`${name}${path.sep}`) && !key.slice(name.length + 1).includes(path.sep)).map((key) => key.slice(name.length + 1)), + readdirSync: (name) => + [...files.keys()] + .filter((key) => key.startsWith(`${name}${path.sep}`) && !key.slice(name.length + 1).includes(path.sep)) + .map((key) => key.slice(name.length + 1)), readFileSync: (name) => files.get(name).data, }; const run = (command, args) => { @@ -67,8 +79,7 @@ test('rejects missing, older or incorrect minimum macOS metadata and config', () f.plist.LSMinimumSystemVersion = value; assert.throws(() => f.verify(), /minimum macOS/); const config = fixture(); - config.files.get(path.join(root, 'src-tauri', 'tauri.macos.conf.json')).data = - JSON.stringify({ bundle: { macOS: { minimumSystemVersion: value } } }); + config.files.get(path.join(root, 'src-tauri', 'tauri.macos.conf.json')).data = JSON.stringify({ bundle: { macOS: { minimumSystemVersion: value } } }); assert.throws(() => config.verify(), /minimum macOS/); } }); @@ -88,8 +99,14 @@ test('macOS config declares the minimum build target using the Tauri 2 field nam }); test('rejects mismatched metadata and unsafe executable names', () => { - for (const [key, value] of [['CFBundleShortVersionString', '9.0.0'], ['CFBundleIdentifier', 'other'], - ['CFBundleExecutable', '../quorb'], ['CFBundleExecutable', '/bin/sh'], ['CFBundleExecutable', '..'], ['CFBundleExecutable', 'a;id']]) { + for (const [key, value] of [ + ['CFBundleShortVersionString', '9.0.0'], + ['CFBundleIdentifier', 'other'], + ['CFBundleExecutable', '../quorb'], + ['CFBundleExecutable', '/bin/sh'], + ['CFBundleExecutable', '..'], + ['CFBundleExecutable', 'a;id'], + ]) { const f = fixture(); f.plist[key] = value; assert.throws(() => f.verify(), /version|identifier|executable/); @@ -117,7 +134,11 @@ test('rejects missing executable, symlinks at every path level and non-native Ma f.files.set(target, { type: 'symbolicLink' }); assert.throws(() => f.verify(), /symlink/); } - for (const [offset, value] of [[0, 0xcafebabe], [4, 0x01000007], [12, 6]]) { + for (const [offset, value] of [ + [0, 0xcafebabe], + [4, 0x01000007], + [12, 6], + ]) { const f = fixture(); f.files.get(executable).data.writeUInt32LE(value, offset); assert.throws(() => f.verify(), /Mach-O/); @@ -127,10 +148,16 @@ test('rejects missing executable, symlinks at every path level and non-native Ma test('fails closed on invalid plist, command failures, truncated binary and missing source SHA', () => { const f = fixture(); assert.throws(() => f.verify({ run: () => '{' }), /JSON/); - assert.throws(() => f.verify({ run: (command) => { - if (command.endsWith('plutil')) return JSON.stringify(f.plist); - throw new Error('hdiutil exit 1'); - } }), /hdiutil exit 1/); + assert.throws( + () => + f.verify({ + run: (command) => { + if (command.endsWith('plutil')) return JSON.stringify(f.plist); + throw new Error('hdiutil exit 1'); + }, + }), + /hdiutil exit 1/, + ); f.files.get(path.join(app, 'Contents', 'MacOS', 'quorb')).data = Buffer.alloc(4); assert.throws(() => f.verify(), /Mach-O/); assert.throws(() => f.verify({ sourceSha: '' }), /SHA/); @@ -140,7 +167,15 @@ test('rejects malformed source provenance and propagates plist tool failure', () for (const sha of ['', 'a'.repeat(39), 'g'.repeat(40), `${sourceSha}\n`, `${sourceSha};id`]) { assert.throws(() => fixture().verify({ sourceSha: sha }), /SHA/); } - assert.throws(() => fixture().verify({ run: () => { throw new Error('plutil exit 1'); } }), /plutil exit 1/); + assert.throws( + () => + fixture().verify({ + run: () => { + throw new Error('plutil exit 1'); + }, + }), + /plutil exit 1/, + ); }); const signature = 'Authority=Developer ID Application: Synthetic (SRD8T33RU5)\nTeamIdentifier=SRD8T33RU5\n'; @@ -160,8 +195,14 @@ test('verifies only the exact app inside the DMG, with authority, metadata, nati const f = mountedFixture(); assert.equal(f.mounted(), app); assert.ok(f.calls.some(([command, args]) => command.endsWith('/spctl') && args.at(-1) === app)); - for (const [field, value] of [['CFBundleShortVersionString', '0.7.0'], ['CFBundleIdentifier', 'wrong'], ['LSMinimumSystemVersion', '14.0'], ['CFBundleExecutable', '../escape']]) { - const bad = mountedFixture(); bad.plist[field] = value; + for (const [field, value] of [ + ['CFBundleShortVersionString', '0.7.0'], + ['CFBundleIdentifier', 'wrong'], + ['LSMinimumSystemVersion', '14.0'], + ['CFBundleExecutable', '../escape'], + ]) { + const bad = mountedFixture(); + bad.plist[field] = value; assert.throws(() => bad.mounted(), /mismatch|executable/); } const binary = mountedFixture(); @@ -169,27 +210,39 @@ test('verifies only the exact app inside the DMG, with authority, metadata, nati assert.throws(() => binary.mounted(), /arm64/); for (const value of [signature.replaceAll('SRD8T33RU5', 'WRONGTEAM1'), 'TeamIdentifier=SRD8T33RU5\n']) { const bad = mountedFixture(); - assert.throws(() => bad.mounted({ run: (command, args) => command.endsWith('/codesign') ? value : bad.run(command, args) }), /authority or team/); + assert.throws(() => bad.mounted({ run: (command, args) => (command.endsWith('/codesign') ? value : bad.run(command, args)) }), /authority or team/); } const network = mountedFixture(); - assert.throws(() => network.mounted({ run: (command, args) => { - if (command.endsWith('/spctl')) throw new Error('Gatekeeper offline'); - return network.run(command, args); - } }), /Gatekeeper offline/); + assert.throws( + () => + network.mounted({ + run: (command, args) => { + if (command.endsWith('/spctl')) throw new Error('Gatekeeper offline'); + return network.run(command, args); + }, + }), + /Gatekeeper offline/, + ); }); test('mounted app paths reject symlinks, extra or renamed apps and unsafe volume entities', () => { for (const target of [mount, app, path.join(app, 'Contents'), path.join(app, 'Contents/Info.plist'), path.join(app, 'Contents/MacOS/quorb')]) { - const f = mountedFixture(); f.files.set(target, { type: 'symbolicLink' }); + const f = mountedFixture(); + f.files.set(target, { type: 'symbolicLink' }); assert.throws(() => f.mounted(), /symlink/); } - const extra = mountedFixture(); extra.files.set(path.join(mount, 'Other.app'), { type: 'directory' }); + const extra = mountedFixture(); + extra.files.set(path.join(mount, 'Other.app'), { type: 'directory' }); assert.throws(() => extra.mounted(), /only contained/); const good = { 'system-entities': [{ 'dev-entry': '/dev/disk4' }, { 'dev-entry': '/dev/disk4s1', 'mount-point': mount }] }; assert.doesNotThrow(() => validateMountEntities(good, mount)); - for (const bad of [{}, { 'system-entities': [] }, { 'system-entities': [{ 'dev-entry': '/dev/disk4', 'mount-point': '/Volumes/Other' }] }, + for (const bad of [ + {}, + { 'system-entities': [] }, + { 'system-entities': [{ 'dev-entry': '/dev/disk4', 'mount-point': '/Volumes/Other' }] }, { 'system-entities': [...good['system-entities'], { 'dev-entry': '/dev/disk5', 'mount-point': mount }] }, - { 'system-entities': [{ 'dev-entry': '/dev/disk4; injected', 'mount-point': mount }] }]) { + { 'system-entities': [{ 'dev-entry': '/dev/disk4; injected', 'mount-point': mount }] }, + ]) { assert.throws(() => validateMountEntities(bad, mount), /entities|volume/); } }); @@ -203,12 +256,21 @@ test('staples only retained outer DMG, mounts readonly, always detaches, hashes const run = (command, args) => { if (args[0] === 'stapler' && args[1] === 'staple') f.files.get(dmg).data = Buffer.from('stapled disk image'); if (args[0] === fail || (fail === 'metadata' && command.endsWith('/plutil'))) { - f.calls.push([command, args]); throw new Error('synthetic failure'); + f.calls.push([command, args]); + throw new Error('synthetic failure'); } return f.run(command, args); }; - const verify = () => stapleAndVerifyDmg({ dmg, version: '0.6.0', inputSha256, temp: '/controlled', io: f.io, run, - parsePlist: () => fail === 'entities' ? {} : { 'system-entities': [{ 'dev-entry': '/dev/disk4', 'mount-point': mount }] } }); + const verify = () => + stapleAndVerifyDmg({ + dmg, + version: '0.6.0', + inputSha256, + temp: '/controlled', + io: f.io, + run, + parsePlist: () => (fail === 'entities' ? {} : { 'system-entities': [{ 'dev-entry': '/dev/disk4', 'mount-point': mount }] }), + }); if (fail) assert.throws(verify); else { const result = verify(); @@ -232,10 +294,14 @@ test('real Python plist parser accepts XML entities and malformed plist still tr f.io.rmdirSync = () => {}; const xml = `system-entitiesdev-entry/dev/disk4mount-point${mount}`; const run = (command, args) => { - if (args[0] === 'attach') { f.calls.push([command, args]); return malformed ? 'not plist' : xml; } + if (args[0] === 'attach') { + f.calls.push([command, args]); + return malformed ? 'not plist' : xml; + } return f.run(command, args); }; - const verify = () => stapleAndVerifyDmg({ dmg, version: '0.6.0', inputSha256: createHash('sha256').update('disk image').digest('hex'), temp: '/controlled', io: f.io, run }); + const verify = () => + stapleAndVerifyDmg({ dmg, version: '0.6.0', inputSha256: createHash('sha256').update('disk image').digest('hex'), temp: '/controlled', io: f.io, run }); if (malformed) assert.throws(verify); else assert.equal(verify().version, '0.6.0'); assert.ok(f.calls.some(([, args]) => args?.[0] === 'detach' && args[1] === mount)); diff --git a/src/DetailPanel.placement.test.tsx b/src/DetailPanel.placement.test.tsx index d296a912..dc71d59f 100644 --- a/src/DetailPanel.placement.test.tsx +++ b/src/DetailPanel.placement.test.tsx @@ -24,25 +24,31 @@ const harness = vi.hoisted(() => ({ })); vi.mock('react', async (importOriginal) => { - const react = await importOriginal() as typeof import('react'); + const react = (await importOriginal()) as typeof import('react'); return { ...react, useState: ((initial?: unknown) => { const index = harness.stateIndex++; - const value = index in harness.states ? harness.states[index] - : typeof initial === 'function' ? (initial as () => unknown)() : initial; - return [value, vi.fn((next: unknown) => { - harness.stateWrite(index, next); - const previous = index in harness.states ? harness.states[index] : value; - harness.states[index] = typeof next === 'function' ? (next as (p: unknown) => unknown)(previous) : next; - })] as unknown as ReturnType; + const value = index in harness.states ? harness.states[index] : typeof initial === 'function' ? (initial as () => unknown)() : initial; + return [ + value, + vi.fn((next: unknown) => { + harness.stateWrite(index, next); + const previous = index in harness.states ? harness.states[index] : value; + harness.states[index] = typeof next === 'function' ? (next as (p: unknown) => unknown)(previous) : next; + }), + ] as unknown as ReturnType; }) as unknown as typeof react.useState, useRef: ((initial: unknown) => { const index = harness.refIndex++; - return harness.refs[index] ??= { current: initial }; + return (harness.refs[index] ??= { current: initial }); }) as unknown as typeof react.useRef, - useEffect: ((run: () => void | (() => void)) => { harness.effects.push({ run }); }) as unknown as typeof react.useEffect, - useLayoutEffect: ((run: () => void | (() => void)) => { harness.layoutEffects.push({ run }); }) as unknown as typeof react.useLayoutEffect, + useEffect: ((run: () => void | (() => void)) => { + harness.effects.push({ run }); + }) as unknown as typeof react.useEffect, + useLayoutEffect: ((run: () => void | (() => void)) => { + harness.layoutEffects.push({ run }); + }) as unknown as typeof react.useLayoutEffect, }; }); @@ -55,11 +61,13 @@ const native = vi.hoisted(() => ({ emitTo: vi.fn(async (..._args: unknown[]) => {}), })); -vi.mock('./lib/api', () => ({ api: { - setDetailBounds: native.setDetailBounds, - setSurfaceClip: native.setSurfaceClip, - showDetail: native.showDetail, -} })); +vi.mock('./lib/api', () => ({ + api: { + setDetailBounds: native.setDetailBounds, + setSurfaceClip: native.setSurfaceClip, + showDetail: native.showDetail, + }, +})); vi.mock('@tauri-apps/api/window', () => ({ getCurrentWindow: () => ({ hide: native.hide }) })); vi.mock('@tauri-apps/api/event', () => ({ listen: vi.fn(async () => () => {}), emitTo: native.emitTo })); vi.mock('@tauri-apps/plugin-opener', () => ({ openUrl: vi.fn(async () => {}) })); @@ -70,17 +78,25 @@ const granted: PhysicalBounds = { x: 815, y: 88, w: 330, h: 400 }; /** La llamada nativa no se pudo confirmar: la geometría no se aplicó. */ const readFailed = (): DetailPlacementReport => ({ - status: 'unverified', bounds: null, reason: 'read_failed', read_back: false, + status: 'unverified', + bounds: null, + reason: 'read_failed', + read_back: false, }); /** La ventana todavía no era legible: informe blando, la geometría sí se pidió. */ const notViewable = (): DetailPlacementReport => ({ - status: 'unverified', bounds: null, reason: 'not_viewable', read_back: false, + status: 'unverified', + bounds: null, + reason: 'not_viewable', + read_back: false, }); /** Colocación confirmada: el compositor informó la geometría efectiva. */ const applied = (): DetailPlacementReport => ({ - status: 'applied', bounds: granted, read_back: true, + status: 'applied', + bounds: granted, + read_back: true, }); const detailState: DetailState = { @@ -133,20 +149,19 @@ const flush = async () => { * componente también emite `ready` e `interaction`, así que se filtra por * destino, evento y tipo. */ -const failureNotices = () => native.emitTo.mock.calls - .filter(([target, event, payload]) => target === 'widget' - && event === DETAIL_EVENTS.interaction - && (payload as { kind?: string } | undefined)?.kind === 'placement-failed') - .map(([, , payload]) => payload as unknown as { revision: number; provider: string; kind: string }); +const failureNotices = () => + native.emitTo.mock.calls + .filter( + ([target, event, payload]) => + target === 'widget' && event === DETAIL_EVENTS.interaction && (payload as { kind?: string } | undefined)?.kind === 'placement-failed', + ) + .map(([, , payload]) => payload as unknown as { revision: number; provider: string; kind: string }); /** * Monta el panel con estado y ejecuta su efecto de placement real con la * secuencia de informes nativa indicada. */ -const runPlacement = async ( - reports: DetailPlacementReport[], - place?: () => Promise, -) => { +const runPlacement = async (reports: DetailPlacementReport[], place?: () => Promise) => { harness.states = []; harness.stateIndex = 0; harness.refs = []; @@ -172,7 +187,10 @@ describe('the detail placement effect (#250/S17)', () => { beforeEach(() => { // El lazo de reintento usa `window.setTimeout`: sin esperas reales. vi.stubGlobal('window', { - setTimeout: (fn: () => void) => { fn(); return 0; }, + setTimeout: (fn: () => void) => { + fn(); + return 0; + }, clearTimeout: () => {}, addEventListener: () => {}, removeEventListener: () => {}, @@ -180,15 +198,22 @@ describe('the detail placement effect (#250/S17)', () => { }); panelHeight = 400; resize = null; - vi.stubGlobal('ResizeObserver', class { - constructor(callback: (entries: unknown[]) => void) { resize = callback; } - observe() {} - unobserve() {} - disconnect() {} - }); + vi.stubGlobal( + 'ResizeObserver', + class { + constructor(callback: (entries: unknown[]) => void) { + resize = callback; + } + observe() {} + unobserve() {} + disconnect() {} + }, + ); vi.stubGlobal('getComputedStyle', () => ({ - borderTopLeftRadius: '14px', borderTopRightRadius: '14px', - borderBottomRightRadius: '0px', borderBottomLeftRadius: '0px', + borderTopLeftRadius: '14px', + borderTopRightRadius: '14px', + borderBottomRightRadius: '0px', + borderBottomLeftRadius: '0px', })); // El aviso a la tira es una promesa (el componente le encadena `.catch`). native.emitTo.mockImplementation(async () => {}); @@ -214,9 +239,7 @@ describe('the detail placement effect (#250/S17)', () => { // El cierre seguro avisa a la tira aunque el panel nunca se mostrara // (#250/S22): la tira debe saber que el detalle no pudo colocarse. expect(native.hide).toHaveBeenCalledTimes(1); - expect(failureNotices()).toEqual([ - { revision: 1, provider: 'a', kind: 'placement-failed' }, - ]); + expect(failureNotices()).toEqual([{ revision: 1, provider: 'a', kind: 'placement-failed' }]); if (typeof cleanup === 'function') cleanup(); }); @@ -266,9 +289,7 @@ describe('the detail placement effect (#250/S17)', () => { expect(native.showDetail).toHaveBeenCalledTimes(1); expect(native.setSurfaceClip).toHaveBeenCalledTimes(1); // El cierre seguro avisa a la tira (#250/S22): el panel ya no está. - expect(failureNotices()).toEqual([ - { revision: 1, provider: 'a', kind: 'placement-failed' }, - ]); + expect(failureNotices()).toEqual([{ revision: 1, provider: 'a', kind: 'placement-failed' }]); if (typeof cleanup === 'function') cleanup(); }); @@ -319,16 +340,16 @@ describe('the detail placement effect (#250/S17)', () => { expect(positioned()).toBe(false); expect(positionedMark()).toBe(false); // Y la tira se entera con un único aviso. - expect(failureNotices()).toEqual([ - { revision: 1, provider: 'a', kind: 'placement-failed' }, - ]); + expect(failureNotices()).toEqual([{ revision: 1, provider: 'a', kind: 'placement-failed' }]); if (typeof cleanup === 'function') cleanup(); }); it('neither hides nor notifies the strip when a newer layout superseded the failing job (#250/S22)', async () => { // La primera colocación se queda esperando... let release!: (report: DetailPlacementReport) => void; - const pending = new Promise((resolve) => { release = resolve; }); + const pending = new Promise((resolve) => { + release = resolve; + }); native.setDetailBounds.mockImplementationOnce(() => pending); const cleanup = await runPlacement([applied()]); // ...y mientras tanto llega un reajuste: el job viejo queda superado. @@ -354,9 +375,7 @@ describe('the detail placement effect (#250/S17)', () => { const cleanup = await runPlacement([readFailed()]); expect(native.hide).toHaveBeenCalledTimes(1); // El aviso llega igual, una sola vez. - expect(failureNotices()).toEqual([ - { revision: 1, provider: 'a', kind: 'placement-failed' }, - ]); + expect(failureNotices()).toEqual([{ revision: 1, provider: 'a', kind: 'placement-failed' }]); warn.mockRestore(); if (typeof cleanup === 'function') cleanup(); }); @@ -366,7 +385,12 @@ describe('the detail placement effect (#250/S17)', () => { // oculta la ventana un reajuste nuevo lo supera. let calls = 0; let releaseHide!: () => void; - native.hide.mockImplementationOnce(() => new Promise((resolve) => { releaseHide = resolve; })); + native.hide.mockImplementationOnce( + () => + new Promise((resolve) => { + releaseHide = resolve; + }), + ); const cleanup = await runPlacement([], async () => (calls++ < 6 ? readFailed() : applied())); expect(native.hide).toHaveBeenCalledTimes(1); panelHeight = 500; diff --git a/src/DetailPanel.test.tsx b/src/DetailPanel.test.tsx index de2ec038..41c7b031 100644 --- a/src/DetailPanel.test.tsx +++ b/src/DetailPanel.test.tsx @@ -40,9 +40,11 @@ describe('DetailPanel (SSR)', () => { const wireUp = () => { const cache = { bounds: null as PhysicalBounds | null, readBack: false }; const positioned = { current: false }; - const cacheConfirmed = (bounds: PhysicalBounds) => { cache.bounds = bounds; cache.readBack = true; }; - const apply = (report: DetailPlacementReport): boolean => - confirmDetailPlacement(report, cacheConfirmed); + const cacheConfirmed = (bounds: PhysicalBounds) => { + cache.bounds = bounds; + cache.readBack = true; + }; + const apply = (report: DetailPlacementReport): boolean => confirmDetailPlacement(report, cacheConfirmed); const resetForClose = () => { // Reset del listener de estado cuando el widget cierra el panel (o al // cerrarse de nuevo): `lastAppliedRef` vacío + `positioned` false. @@ -50,8 +52,7 @@ const wireUp = () => { cache.bounds = null; cache.readBack = false; }; - const wouldDedupe = (requested: PhysicalBounds): boolean => - positioned.current && samePlacement(cache.bounds, requested, cache.readBack); + const wouldDedupe = (requested: PhysicalBounds): boolean => positioned.current && samePlacement(cache.bounds, requested, cache.readBack); const report = (over: Partial = {}): DetailPlacementReport => ({ status: 'applied', bounds: null, diff --git a/src/DetailPanel.tsx b/src/DetailPanel.tsx index 582d1ac0..aa19cf61 100644 --- a/src/DetailPanel.tsx +++ b/src/DetailPanel.tsx @@ -10,7 +10,20 @@ import { useLocale } from './i18n/use-locale'; import { useTextScale } from './lib/useTextScale'; import { reportSummary } from './lib/format'; import { clipSurfaceSafely, measureSurfaceClip } from './lib/surface-clip'; -import { createLatestQueue, basePanelZoom, detailBounds, fitPanel, panelScaleFromTransform, physicalPanelBounds, sameFit, DETAIL_EVENTS, type DetailInteraction, type DetailState, type PanelFit, type PhysicalBounds } from './lib/detail-panel'; +import { + createLatestQueue, + basePanelZoom, + detailBounds, + fitPanel, + panelScaleFromTransform, + physicalPanelBounds, + sameFit, + DETAIL_EVENTS, + type DetailInteraction, + type DetailState, + type PanelFit, + type PhysicalBounds, +} from './lib/detail-panel'; import { samePlacement } from './lib/widget-placement'; import { confirmDetailPlacement, detailPlacementFailed, retryDetailPlacement } from './detail-placement'; @@ -55,7 +68,9 @@ export function DetailPanel() { const state = dataRef.current; if (!state) return; emitTo('widget', DETAIL_EVENTS.interaction, { - revision: state.revision, provider: state.report.id, kind, + revision: state.revision, + provider: state.report.id, + kind, } satisfies DetailInteraction).catch(console.warn); }; @@ -69,16 +84,29 @@ export function DetailPanel() { const wasClosed = dataRef.current === null; dataRef.current = payload; // Invalidate an in-flight show immediately, before React commits new content. - enqueue(async () => { if (!payload) await getCurrentWindow().hide(); }).catch(console.warn); + enqueue(async () => { + if (!payload) await getCurrentWindow().hide(); + }).catch(console.warn); // #215: the read-back cache resets with `positioned` so the first // placement after a reopen is never deduped against the old geometry. - if (!payload || wasClosed) { setPositioned(false); positionedRef.current = false; lastAppliedRef.current = null; lastAppliedReadBackRef.current = false; } + if (!payload || wasClosed) { + setPositioned(false); + positionedRef.current = false; + lastAppliedRef.current = null; + lastAppliedReadBackRef.current = false; + } setData(payload); }); - if (disposed) { stateListener(); return; } + if (disposed) { + stateListener(); + return; + } unlisteners.push(stateListener); const requestListener = await listen(DETAIL_EVENTS.requestReady, ready); - if (disposed) { requestListener(); return; } + if (disposed) { + requestListener(); + return; + } unlisteners.push(requestListener); await ready(); }; @@ -87,7 +115,9 @@ export function DetailPanel() { disposed = true; unlisteners.forEach((unlisten) => unlisten()); dataRef.current = null; - enqueue(async () => { await getCurrentWindow().hide(); }).catch(console.warn); + enqueue(async () => { + await getCurrentWindow().hide(); + }).catch(console.warn); }; }, [enqueue]); @@ -138,7 +168,10 @@ export function DetailPanel() { // covers the widget below it. Physical bounds already include DPI rounding. // Only the confirmed (read-back) geometry reaches the cache; the requested // one never does (S3/D2). - const cache = (confirmed: PhysicalBounds) => { lastAppliedRef.current = confirmed; lastAppliedReadBackRef.current = true; }; + const cache = (confirmed: PhysicalBounds) => { + lastAppliedRef.current = confirmed; + lastAppliedReadBackRef.current = true; + }; /** * Cierre seguro uniforme (#250/S22): el panel deja de estar colocado, * se oculta y la tira se entera con un aviso. Lo usan las dos ramas @@ -213,7 +246,10 @@ export function DetailPanel() { layout(); const observer = new ResizeObserver((entries) => layout(entries[0])); observer.observe(panelRef.current); - return () => { disposed = true; observer.disconnect(); }; + return () => { + disposed = true; + observer.disconnect(); + }; }, [data, enqueue, textScale]); useEffect(() => { @@ -232,7 +268,15 @@ export function DetailPanel() {
interact('enter')} onMouseLeave={() => interact('leave')} > @@ -243,18 +287,48 @@ export function DetailPanel() { aria-label={t(locale, 'details.panel.title', { name: data.report.name })} // No transitions/animations: a transitioned `transform` would make the measured // rect lag behind the fitted scale and corrupt the next measurement. - style={{ left: 0, top: 0, width: data.width / base, transform: `scale(${scale})`, transformOrigin: 'top left', transition: 'none', animation: 'none', overflow: 'hidden', '--orb': data.orbSize, visibility: positioned ? 'visible' : 'hidden' } as CSSProperties} + style={ + { + left: 0, + top: 0, + width: data.width / base, + transform: `scale(${scale})`, + transformOrigin: 'top left', + transition: 'none', + animation: 'none', + overflow: 'hidden', + '--orb': data.orbSize, + visibility: positioned ? 'visible' : 'hidden', + } as CSSProperties + } >
-

{t(locale, 'details.panel.insightsHeading')}

+

+ {t(locale, 'details.panel.insightsHeading')} +

- {usageUrl && } - + {usageUrl && ( + + )} +
-
{t(locale, 'details.panel.updated', { when: updated })}{t(locale, 'details.panel.everyMinutes', { mins: data.refreshMinutes })}
+
+ {t(locale, 'details.panel.updated', { when: updated })} + {t(locale, 'details.panel.everyMinutes', { mins: data.refreshMinutes })} +
{data.error &&

{data.error}

}
diff --git a/src/LocalePicker.test.tsx b/src/LocalePicker.test.tsx index 98552ba2..af3a0d63 100644 --- a/src/LocalePicker.test.tsx +++ b/src/LocalePicker.test.tsx @@ -78,5 +78,4 @@ describe('LocalePicker', () => { const html = renderToStaticMarkup(); expect(html).toContain('margin:0 auto'); }); - }); diff --git a/src/LocalePicker.tsx b/src/LocalePicker.tsx index 87de4242..67462e7c 100644 --- a/src/LocalePicker.tsx +++ b/src/LocalePicker.tsx @@ -82,7 +82,20 @@ export function LocalePicker() { }; return ( -
+

Quorb

{PICKER_OPTIONS.map((option) => ( @@ -91,7 +104,11 @@ export function LocalePicker() { ))}
- {error &&

{error}

} + {error && ( +

+ {error} +

+ )}
); } diff --git a/src/Overlay.tsx b/src/Overlay.tsx index b3e420e9..0de251eb 100644 --- a/src/Overlay.tsx +++ b/src/Overlay.tsx @@ -168,11 +168,7 @@ function CustomFx({ path, size, sound, onDone }: { path: string; size: Payload[' return (
- {isImage ? ( - - ) : ( -
); } diff --git a/src/Settings-accounts-i18n.test.tsx b/src/Settings-accounts-i18n.test.tsx index cdc13edc..4387345c 100644 --- a/src/Settings-accounts-i18n.test.tsx +++ b/src/Settings-accounts-i18n.test.tsx @@ -36,7 +36,16 @@ const codexInstall = {} as CodexInstallController; const connect = ( locale: Locale, provider: 'claude' | 'codex' | 'gemini', - over: { cliMissing?: boolean; persisted?: boolean; extra?: boolean; dirty?: boolean; connected?: boolean; loginError?: string | null; sessionEnv?: 'host' | 'wsl'; wslDistro?: string } = {}, + over: { + cliMissing?: boolean; + persisted?: boolean; + extra?: boolean; + dirty?: boolean; + connected?: boolean; + loginError?: string | null; + sessionEnv?: 'host' | 'wsl'; + wslDistro?: string; + } = {}, ) => renderToStaticMarkup( { 'es', ); expectAll(editor('es', account('zai')), ['API key', 'Créala en z.ai › API Keys.'], 'es'); - expectAll( - editor('es', account('opencode_go')), - ['API key de OpenCode Go', 'Créala en OpenCode › Console.'], - 'es', - ); + expectAll(editor('es', account('opencode_go')), ['API key de OpenCode Go', 'Créala en OpenCode › Console.'], 'es'); expectAll( editor('es', account('anthropic_api')), [ @@ -397,7 +402,11 @@ describe('AccountEditor (SSR, i18n)', () => { 'en', ); const zai = editor('en', account('zai')); - expectAll(openrouter, ['API key', 'It can be from another account or from the same one with a different limit. openrouter.ai › Keys'], 'en'); + expectAll( + openrouter, + ['API key', 'It can be from another account or from the same one with a different limit. openrouter.ai › Keys'], + 'en', + ); expectAll(zai, ['API key', 'Create it at z.ai › API Keys.'], 'en'); const opencode = editor('en', account('opencode_go')); expectAll(opencode, ['OpenCode Go API key', 'Create it at OpenCode › Console.'], 'en'); @@ -531,13 +540,9 @@ describe('Missing CLI per environment (SSR, i18n)', () => { }); it('CliMissingWsl keeps the distro optional and translates to en', () => { - const withDistro = renderToStaticMarkup( - , - ); + const withDistro = renderToStaticMarkup(); expectAll(withDistro, ['is missing inside the WSL distro', 'Ubuntu-24.04', 'npm install -g @openai/codex'], 'en'); - const withoutDistro = renderToStaticMarkup( - , - ); + const withoutDistro = renderToStaticMarkup(); expectAll(withoutDistro, ['dentro de la distro WSL', 'npm install -g @google/gemini-cli'], 'es'); expectNone(withoutDistro, ['install.ps1'], 'es'); }); diff --git a/src/Settings-api-panels-i18n.test.tsx b/src/Settings-api-panels-i18n.test.tsx index 61fbc1d2..ee0f3b82 100644 --- a/src/Settings-api-panels-i18n.test.tsx +++ b/src/Settings-api-panels-i18n.test.tsx @@ -10,16 +10,7 @@ import { CodexInstall } from './components/CodexInstall'; import type { CodexInstallController, CodexInstallState, CodexSetupStatus } from './lib/codex-install'; import { secretKey } from './lib/accounts'; import type { Account, AppConfig, Locale } from './lib/types'; -import { - AccountEditor, - AdminApiPanel, - CliConnectView, - NanConnect, - NanPanel, - NineRouterConnect, - NineRouterPanel, - OpenRouterPanel, -} from './Settings'; +import { AccountEditor, AdminApiPanel, CliConnectView, NanConnect, NanPanel, NineRouterConnect, NineRouterPanel, OpenRouterPanel } from './Settings'; const noop = () => {}; @@ -34,7 +25,16 @@ const expectNone = (html: string, texts: string[], label: string) => { const base = { hiddenProviders: [], openrouter: { enabled: true }, - nan: { enabled: true, plan: 'community', baseUrl: 'https://api.nan.builders', billingDay: 1, usageUrl: null, usedPointer: null, limitPointer: null, usageLabel: null }, + nan: { + enabled: true, + plan: 'community', + baseUrl: 'https://api.nan.builders', + billingDay: 1, + usageUrl: null, + usedPointer: null, + limitPointer: null, + usageLabel: null, + }, nineRouter: { enabled: true, period: '7d', showSubProviders: false, minSpendUsd: 0, monthlyBudgetUsd: null, baseUrl: 'http://localhost:20128' }, anthropicApi: { enabled: true, monthlyBudgetUsd: null }, openaiApi: { enabled: true, monthlyBudgetUsd: null }, @@ -99,7 +99,8 @@ const controllerFor = (state: CodexInstallState): CodexInstallController => ({ refresh: async () => state, requestInstall: async () => ({ ok: true, outcome: 'installed' }), }); -const codex = (locale: Locale, state: CodexInstallState) => renderToStaticMarkup(); +const codex = (locale: Locale, state: CodexInstallState) => + renderToStaticMarkup(); describe('API provider panels (SSR, i18n)', () => { it('renders the Spanish literals of OpenRouter copied verbatim from the current code', () => { @@ -123,7 +124,14 @@ describe('API provider panels (SSR, i18n)', () => { const html = openrouter('en'); expectAll( html, - ['Pay-as-you-go · Official API', 'Show in the widget', 'This month's and today's spend, key limit (if any) and account balance.', 'aria-label="How to connect the account"', 'Create it at', 'openrouter.ai › Keys'], + [ + 'Pay-as-you-go · Official API', + 'Show in the widget', + 'This month's and today's spend, key limit (if any) and account balance.', + 'aria-label="How to connect the account"', + 'Create it at', + 'openrouter.ai › Keys', + ], 'en openrouter', ); expectNone(html, ['Pago por uso', 'Mostrar en el widget', 'Cómo conectar la cuenta', 'Créala en', 'Gasto del mes'], 'en openrouter'); @@ -191,7 +199,11 @@ describe('API provider panels (SSR, i18n)', () => { ], 'en nan', ); - expectNone(html, ['Suscripción · cuenta o API key', 'Conecta tu cuenta o pega una API key', 'Día de inicio de facturación', 'Etiqueta', 'Probar la API de NaN', 'p. ej.'], 'en nan'); + expectNone( + html, + ['Suscripción · cuenta o API key', 'Conecta tu cuenta o pega una API key', 'Día de inicio de facturación', 'Etiqueta', 'Probar la API de NaN', 'p. ej.'], + 'en nan', + ); }); it('renders the Spanish literals of the connected NaN account copied verbatim', () => { @@ -284,7 +296,18 @@ describe('API provider panels (SSR, i18n)', () => { it('renders the Spanish literals of the Anthropic API and OpenAI API panels copied verbatim', () => { expectAll( adminApi('es', 'anthropic_api'), - ['Pago por uso · Admin key', 'Anthropic API', 'Mostrar gasto del mes', 'Admin key', 'Admin API key (sk-ant-admin…)', 'Las APIs de coste no admiten OAuth: hace falta una', '(solo lectura de la organización).', 'Admin key (solo lectura de la organización).', 'Presupuesto mensual (opcional)', 'USD al mes'], + [ + 'Pago por uso · Admin key', + 'Anthropic API', + 'Mostrar gasto del mes', + 'Admin key', + 'Admin API key (sk-ant-admin…)', + 'Las APIs de coste no admiten OAuth: hace falta una', + '(solo lectura de la organización).', + 'Admin key (solo lectura de la organización).', + 'Presupuesto mensual (opcional)', + 'USD al mes', + ], 'es anthropic', ); expectAll(adminApi('es', 'openai_api'), ['OpenAI API', 'class="eg-field__label">Admin key<', 'Créala en', 'Organization › Admin keys'], 'es openai'); @@ -292,7 +315,19 @@ describe('API provider panels (SSR, i18n)', () => { it('renders the Anthropic API and OpenAI API panels in English and drops the Spanish literals', () => { const anthropic = adminApi('en', 'anthropic_api'); - expectAll(anthropic, ['Pay-as-you-go · Admin key', 'Show month spend', 'Cost APIs do not support OAuth: you need an', '(organization read-only).', 'Admin key (organization read-only).', 'Monthly budget (optional)', 'USD per month'], 'en anthropic'); + expectAll( + anthropic, + [ + 'Pay-as-you-go · Admin key', + 'Show month spend', + 'Cost APIs do not support OAuth: you need an', + '(organization read-only).', + 'Admin key (organization read-only).', + 'Monthly budget (optional)', + 'USD per month', + ], + 'en anthropic', + ); expectNone(anthropic, ['Pago por uso', 'Mostrar gasto del mes', 'Presupuesto mensual', 'hace falta una'], 'en anthropic'); const openai = adminApi('en', 'openai_api'); expectAll(openai, ['Pay-as-you-go · Admin key', 'Create it at', 'Organization › Admin keys'], 'en openai'); @@ -367,7 +402,11 @@ describe('Locale propagation to nested components (SSR, i18n)', () => { it('AccountEditor passes the locale to NanConnect in Spanish', () => { const html = accountEditor('es'); - expectAll(html, ['Conectar tu cuenta (recomendado)', 'placeholder="tu@correo.com"', 'Enviar enlace', 'Igual que «nan auth login --email»'], 'es editor→nan'); + expectAll( + html, + ['Conectar tu cuenta (recomendado)', 'placeholder="tu@correo.com"', 'Enviar enlace', 'Igual que «nan auth login --email»'], + 'es editor→nan', + ); }); it('AccountEditor passes the locale to NanConnect in English with no Spanish left', () => { @@ -388,23 +427,72 @@ describe('Locale propagation to nested components (SSR, i18n)', () => { describe('CodexInstall notice (SSR, i18n)', () => { it('renders every Spanish view copied verbatim from the current code', () => { expectAll(codex('es', codexState({})), ['Comprobando Codex CLI…', 'Quorb solo consulta el estado del equipo.'], 'es loading'); - expectAll(codex('es', codexState({ status: codexStatus({}) })), ['Falta Codex CLI en este equipo.', 'Quorb puede instalarlo desde aquí: Windows pedirá confirmación antes de instalar nada.', 'Instalar Codex', 'Qué instala exactamente'], 'es ready'); + expectAll( + codex('es', codexState({ status: codexStatus({}) })), + [ + 'Falta Codex CLI en este equipo.', + 'Quorb puede instalarlo desde aquí: Windows pedirá confirmación antes de instalar nada.', + 'Instalar Codex', + 'Qué instala exactamente', + ], + 'es ready', + ); expectAll(codex('es', codexState({ installing: true })), ['Instalando Codex CLI…', 'Instalando…'], 'es installing'); - expectAll(codex('es', codexState({ outcome: 'installed' })), ['Codex CLI instalado.', 'La instalación no crea la sesión: usa «Iniciar sesión» cuando quieras.'], 'es installed fresh'); - expectAll(codex('es', codexState({ status: codexStatus({ installed: true }) })), ['Codex está instalado; revisa tu comando de login.', 'Quorb ya detecta el CLI en este equipo.'], 'es installed stale'); - expectAll(codex('es', codexState({ outcome: 'cancelled' })), ['Instalación cancelada.', 'No se cambió nada. Puedes intentarlo de nuevo.', 'Reintentar'], 'es cancelled'); - expectAll(codex('es', codexState({ status: codexStatus({ busy: true }) })), ['El instalador está trabajando en otra ventana.', 'Espera a que termine; Quorb lo detecta solo.'], 'es busy'); - expectAll(codex('es', codexState({ status: codexStatus({ supported: false }) })), ['Este sistema no permite la instalación asistida.', 'Está pensada para Windows; puedes instalarlo a mano y Quorb lo detectará.', 'Volver a comprobar', 'Copiar orden'], 'es unsupported'); - expectAll(codex('es', codexState({ status: codexStatus({ nodeAvailable: false }) })), ['No se detecta Node.js y npm.', 'Quorb solo comprueba que existan; la versión (Node.js 22 o superior) la valida el instalador al confirmar. Instálalos y vuelve a comprobar.'], 'es no-node'); + expectAll( + codex('es', codexState({ outcome: 'installed' })), + ['Codex CLI instalado.', 'La instalación no crea la sesión: usa «Iniciar sesión» cuando quieras.'], + 'es installed fresh', + ); + expectAll( + codex('es', codexState({ status: codexStatus({ installed: true }) })), + ['Codex está instalado; revisa tu comando de login.', 'Quorb ya detecta el CLI en este equipo.'], + 'es installed stale', + ); + expectAll( + codex('es', codexState({ outcome: 'cancelled' })), + ['Instalación cancelada.', 'No se cambió nada. Puedes intentarlo de nuevo.', 'Reintentar'], + 'es cancelled', + ); + expectAll( + codex('es', codexState({ status: codexStatus({ busy: true }) })), + ['El instalador está trabajando en otra ventana.', 'Espera a que termine; Quorb lo detecta solo.'], + 'es busy', + ); + expectAll( + codex('es', codexState({ status: codexStatus({ supported: false }) })), + [ + 'Este sistema no permite la instalación asistida.', + 'Está pensada para Windows; puedes instalarlo a mano y Quorb lo detectará.', + 'Volver a comprobar', + 'Copiar orden', + ], + 'es unsupported', + ); + expectAll( + codex('es', codexState({ status: codexStatus({ nodeAvailable: false }) })), + [ + 'No se detecta Node.js y npm.', + 'Quorb solo comprueba que existan; la versión (Node.js 22 o superior) la valida el instalador al confirmar. Instálalos y vuelve a comprobar.', + ], + 'es no-node', + ); expectAll( codex('es', codexState({ error: 'boom', errorFrom: 'read' })), ['No se pudo consultar el instalador.', 'boom', 'Vuelve a comprobar el estado.'], 'es error read', ); - expectAll(codex('es', codexState({ error: 'boom', errorFrom: 'install' })), ['No se pudo instalar Codex CLI.', 'Puedes reintentarlo.'], 'es error install'); + expectAll( + codex('es', codexState({ error: 'boom', errorFrom: 'install' })), + ['No se pudo instalar Codex CLI.', 'Puedes reintentarlo.'], + 'es error install', + ); expectAll( codex('es', codexState({ status: codexStatus({}) })), - ['Paquete fijado: @openai/codex@0.162.1 desde el registro oficial de npm. No se instala «la última».', 'Carpeta de destino: %USERPROFILE%\\…\\tools\\codex-0.162.1, dentro de la carpeta de Quorb. No se toca el npm global ni las variables de entorno.', 'Se ignoran los scripts de ciclo de vida del paquete y se valida la versión real antes de darlo por bueno.'], + [ + 'Paquete fijado: @openai/codex@0.162.1 desde el registro oficial de npm. No se instala «la última».', + 'Carpeta de destino: %USERPROFILE%\\…\\tools\\codex-0.162.1, dentro de la carpeta de Quorb. No se toca el npm global ni las variables de entorno.', + 'Se ignoran los scripts de ciclo de vida del paquete y se valida la versión real antes de darlo por bueno.', + ], 'es details', ); }); @@ -426,10 +514,26 @@ describe('CodexInstall notice (SSR, i18n)', () => { const busy = codex('en', codexState({ status: codexStatus({ busy: true }) })); expectAll(busy, ['The installer is working in another window.', 'Wait for it to finish; Quorb detects it on its own.'], 'en busy'); expectNone(busy, ['El instalador está trabajando', 'Espera a que termine'], 'en busy'); - expectAll(codex('en', codexState({ outcome: 'cancelled' })), ['Installation cancelled.', 'Nothing was changed. You can try again.', 'Retry'], 'en cancelled'); - expectAll(codex('en', codexState({ status: codexStatus({ supported: false }) })), ['This system does not support assisted installation.', 'Check again', 'Copy command'], 'en unsupported'); + expectAll( + codex('en', codexState({ outcome: 'cancelled' })), + ['Installation cancelled.', 'Nothing was changed. You can try again.', 'Retry'], + 'en cancelled', + ); + expectAll( + codex('en', codexState({ status: codexStatus({ supported: false }) })), + ['This system does not support assisted installation.', 'Check again', 'Copy command'], + 'en unsupported', + ); expectAll(codex('en', codexState({ status: codexStatus({ nodeAvailable: false }) })), ['Node.js and npm are not detected.'], 'en no-node'); - expectAll(codex('en', codexState({ error: 'boom', errorFrom: 'read' })), ['The installer could not be queried.', 'boom', 'Check the state again.'], 'en error read'); - expectAll(codex('en', codexState({ error: 'boom', errorFrom: 'install' })), ['Codex CLI could not be installed.', 'You can retry.'], 'en error install'); + expectAll( + codex('en', codexState({ error: 'boom', errorFrom: 'read' })), + ['The installer could not be queried.', 'boom', 'Check the state again.'], + 'en error read', + ); + expectAll( + codex('en', codexState({ error: 'boom', errorFrom: 'install' })), + ['Codex CLI could not be installed.', 'You can retry.'], + 'en error install', + ); }); }); diff --git a/src/Settings-email-i18n.test.tsx b/src/Settings-email-i18n.test.tsx index 83d09fd1..01260312 100644 --- a/src/Settings-email-i18n.test.tsx +++ b/src/Settings-email-i18n.test.tsx @@ -46,11 +46,9 @@ const TONES: Record {}; -const statusText = (locale: 'es' | 'en', status: EmailStatus): string => - (locale === 'es' ? es : en).settings.alerts.email.status[status]; +const statusText = (locale: 'es' | 'en', status: EmailStatus): string => (locale === 'es' ? es : en).settings.alerts.email.status[status]; -const line = (locale: 'es' | 'en', status: EmailStatus) => - renderToStaticMarkup(); +const line = (locale: 'es' | 'en', status: EmailStatus) => renderToStaticMarkup(); describe('EmailStatusLine (SSR, i18n)', () => { it('renders the visible status feedback for every EmailStatus in Spanish and English', () => { @@ -114,9 +112,11 @@ describe('AlertsSection email feedback (SSR, S22)', () => { ); expect(html).toContain('onboarding@resend.dev'); expect(html).not.toContain('value="onboarding@resend.dev"'); - expect(html).toContain(locale === 'es' - ? 'Sin dominio propio, usa onboarding@resend.dev para pruebas hacia el correo de tu cuenta de Resend. Para otros destinatarios, usa un remitente de tu dominio verificado.' - : 'Without your own domain, use onboarding@resend.dev for tests to your Resend account email. For other recipients, use a sender from your verified domain.'); + expect(html).toContain( + locale === 'es' + ? 'Sin dominio propio, usa onboarding@resend.dev para pruebas hacia el correo de tu cuenta de Resend. Para otros destinatarios, usa un remitente de tu dominio verificado.' + : 'Without your own domain, use onboarding@resend.dev for tests to your Resend account email. For other recipients, use a sender from your verified domain.', + ); expect(html).toContain('type="email" autoComplete="off" value=""'); } }); @@ -125,12 +125,11 @@ describe('AlertsSection email feedback (SSR, S22)', () => { for (const userAgent of ['Mozilla/5.0 (X11; Linux x86_64)', 'Mozilla/5.0 (Macintosh; Intel Mac OS X)', 'Mozilla/5.0 (Windows NT 10.0)']) { vi.stubGlobal('navigator', { userAgent }); for (const locale of ['es', 'en'] as const) { - const html = renderToStaticMarkup( - {}} onError={noop} />, - ); - const warning = locale === 'es' - ? 'En algunos sistemas Linux, tendrás que volver a introducir la clave después de reiniciar.' - : 'On some Linux systems, you will need to enter the key again after restarting.'; + const html = renderToStaticMarkup( {}} onError={noop} />); + const warning = + locale === 'es' + ? 'En algunos sistemas Linux, tendrás que volver a introducir la clave después de reiniciar.' + : 'On some Linux systems, you will need to enter the key again after restarting.'; if (userAgent.includes('Linux')) expect(html).toContain(warning); else expect(html).not.toContain(warning); expect(html).not.toMatch(/keyutils|backend|#106/); @@ -141,12 +140,12 @@ describe('AlertsSection email feedback (SSR, S22)', () => { it('keeps the test save/send effects and consent/key requirements in concise help', () => { for (const locale of ['es', 'en'] as const) { - const html = renderToStaticMarkup( - {}} onError={noop} />, + const html = renderToStaticMarkup( {}} onError={noop} />); + expect(html).toContain( + locale === 'es' + ? 'Guarda los cambios y envía una prueba sin datos de consumo. Requiere consentimiento y clave guardada. No activa los avisos automáticos.' + : 'Saves changes and sends a test without usage data. Requires consent and a saved key. Does not enable automatic alerts.', ); - expect(html).toContain(locale === 'es' - ? 'Guarda los cambios y envía una prueba sin datos de consumo. Requiere consentimiento y clave guardada. No activa los avisos automáticos.' - : 'Saves changes and sends a test without usage data. Requires consent and a saved key. Does not enable automatic alerts.'); expect(html).toContain(locale === 'es' ? 'Sin reintentos' : 'No retries'); expect(html).toContain(locale === 'es' ? 'Resend procesa' : 'Resend processes'); } @@ -154,9 +153,7 @@ describe('AlertsSection email feedback (SSR, S22)', () => { it('shows the idle status feedback inside Alertas before any test send', () => { for (const locale of ['es', 'en'] as const) { - const html = renderToStaticMarkup( - {}} onError={noop} />, - ); + const html = renderToStaticMarkup( {}} onError={noop} />); expect(html, `estado inicial visible en ${locale}`).toContain(statusText(locale, 'idle')); expect(html, `rol de estado en ${locale}`).toContain('role="status"'); } diff --git a/src/Settings-i18n.test.tsx b/src/Settings-i18n.test.tsx index 61a9415f..6d4380c3 100644 --- a/src/Settings-i18n.test.tsx +++ b/src/Settings-i18n.test.tsx @@ -12,8 +12,7 @@ import { AlertsSection, LookSection, ProjectSection, SecretInput, ShortcutsSecti const { updaterMock } = vi.hoisted(() => ({ updaterMock: vi.fn() })); vi.mock('./lib/useUpdater', () => ({ useUpdater: (auto: boolean) => updaterMock(auto) })); -const updater = (mode: string, state: Record) => - updaterMock.mockReturnValue({ mode, state, check: () => {}, install: () => {} }); +const updater = (mode: string, state: Record) => updaterMock.mockReturnValue({ mode, state, check: () => {}, install: () => {} }); const lookCfg = { opacity: 0.9, @@ -45,9 +44,7 @@ const shortcutsCfg: ShortcutsConfig = { enabled: true, toggle: 'Ctrl+Alt+H', ope const noop = () => {}; const look = (locale: 'es' | 'en', liveError: string | null = 'fallo de prueba') => - renderToStaticMarkup( - , - ); + renderToStaticMarkup(); const alerts = (locale: 'es' | 'en') => renderToStaticMarkup( {}} onError={noop} />); @@ -124,7 +121,19 @@ describe('LookSection (SSR, i18n)', () => { ]) { expect(html, `falta «${text}» en en`).toContain(text); } - for (const text of ['Anillos', 'Tira', 'Tamaño del anillo', 'Color de acento', 'Círculos pequeños', 'Borde', 'Izquierda', 'Ocultar sola', 'Siempre encima', 'Personalización no aplicada', 'Reintentar']) { + for (const text of [ + 'Anillos', + 'Tira', + 'Tamaño del anillo', + 'Color de acento', + 'Círculos pequeños', + 'Borde', + 'Izquierda', + 'Ocultar sola', + 'Siempre encima', + 'Personalización no aplicada', + 'Reintentar', + ]) { expect(html, `sobra «${text}» en en`).not.toContain(text); } }); @@ -197,7 +206,24 @@ describe('AlertsSection (SSR, i18n)', () => { ]) { expect(html, `falta «${text}» en en`).toContain(text); } - for (const text of ['Cuándo avisar', 'Activar avisos', 'Notificación del sistema', 'Al superar el límite', 'Avisar al llegar a', 'Al reiniciarse', 'Efecto propio', 'Pequeño', 'Mediano', 'Pantalla completa', 'Con sonido', 'Probar', 'Archivo', 'Ningún archivo', 'Elegir…', 'Quitar']) { + for (const text of [ + 'Cuándo avisar', + 'Activar avisos', + 'Notificación del sistema', + 'Al superar el límite', + 'Avisar al llegar a', + 'Al reiniciarse', + 'Efecto propio', + 'Pequeño', + 'Mediano', + 'Pantalla completa', + 'Con sonido', + 'Probar', + 'Archivo', + 'Ningún archivo', + 'Elegir…', + 'Quitar', + ]) { expect(html, `sobra «${text}» en en`).not.toContain(text); } }); @@ -250,7 +276,19 @@ describe('ShortcutsSection (SSR, i18n)', () => { ]) { expect(html, `falta «${text}» en en`).toContain(text); } - for (const text of ['Atajos globales', 'Activar atajos', 'Atajos de teclado', 'Acción', 'Mostrar u ocultar la tira', 'Abrir el más cargado', 'Actualizar ahora', 'Sin atajo', 'Cambiar', 'Quitar', 'Pulsa un atajo o «Cambiar» y teclea la combinación. Se aplican al guardar.']) { + for (const text of [ + 'Atajos globales', + 'Activar atajos', + 'Atajos de teclado', + 'Acción', + 'Mostrar u ocultar la tira', + 'Abrir el más cargado', + 'Actualizar ahora', + 'Sin atajo', + 'Cambiar', + 'Quitar', + 'Pulsa un atajo o «Cambiar» y teclea la combinación. Se aplican al guardar.', + ]) { expect(html, `sobra «${text}» en en`).not.toContain(text); } }); @@ -322,7 +360,16 @@ describe('UpdatesSection (SSR, i18n)', () => { const installing = renderToStaticMarkup(); expect(installing).toContain('Installing…'); - for (const text of ['Versión instalada', 'estás en la última versión', 'Buscar ahora', 'Buscar actualizaciones solo', 'Hay una versión nueva', 'Instalar y reiniciar', 'Instalando', 'Llegan firmadas desde']) { + for (const text of [ + 'Versión instalada', + 'estás en la última versión', + 'Buscar ahora', + 'Buscar actualizaciones solo', + 'Hay una versión nueva', + 'Instalar y reiniciar', + 'Instalando', + 'Llegan firmadas desde', + ]) { expect(none + available + installing, `sobra «${text}» en en`).not.toContain(text); } }); @@ -352,9 +399,28 @@ describe('ProjectSection (SSR, i18n)', () => { describe('Email alerts in existing Settings alerts (SSR)', () => { it('shows consent/privacy before opt-in and explicit test in both languages', () => { - const es = alerts('es'); const en = alerts('en'); - for (const text of ['Email con Resend', 'Resend procesa remitente y destinatario', 'Quorb abierto', 'Sin reintentos', 'dominio verificado', 'onboarding@resend.dev', 'Enviar prueba']) expect(es).toContain(text); - for (const text of ['Email with Resend', 'Resend processes sender and recipient', 'Quorb open', 'No retries', 'verified domain', 'onboarding@resend.dev', 'Send test']) expect(en).toContain(text); + const es = alerts('es'); + const en = alerts('en'); + for (const text of [ + 'Email con Resend', + 'Resend procesa remitente y destinatario', + 'Quorb abierto', + 'Sin reintentos', + 'dominio verificado', + 'onboarding@resend.dev', + 'Enviar prueba', + ]) + expect(es).toContain(text); + for (const text of [ + 'Email with Resend', + 'Resend processes sender and recipient', + 'Quorb open', + 'No retries', + 'verified domain', + 'onboarding@resend.dev', + 'Send test', + ]) + expect(en).toContain(text); expect(es).toContain('type="password"'); expect(es).toContain('disabled=""'); expect(es).not.toContain('Integraciones'); diff --git a/src/Settings-panels-i18n.test.tsx b/src/Settings-panels-i18n.test.tsx index cd91b9a3..c8530693 100644 --- a/src/Settings-panels-i18n.test.tsx +++ b/src/Settings-panels-i18n.test.tsx @@ -7,15 +7,7 @@ import { renderToStaticMarkup } from 'react-dom/server'; import { describe, expect, it } from 'vitest'; import type { CodexInstallController } from './lib/codex-install'; import type { AppConfig, Locale } from './lib/types'; -import { - AntigravityPanel, - CopilotPanel, - CursorPanel, - MiniMaxPanel, - OpenCodeGoPanel, - SubscriptionPanel, - ZaiPanel, -} from './Settings'; +import { AntigravityPanel, CopilotPanel, CursorPanel, MiniMaxPanel, OpenCodeGoPanel, SubscriptionPanel, ZaiPanel } from './Settings'; const noop = () => {}; @@ -213,14 +205,7 @@ describe('Subscription provider panels (SSR, i18n)', () => { // los de Windows hasta #92») ya no aplica en esta rama: es falsa aquí. const wslCfg = { ...cfg, sessionEnv: 'wsl' } as AppConfig; const html = renderToStaticMarkup( - , + , ); expect(html).not.toContain('usan el CLI de Windows'); }); @@ -267,7 +252,19 @@ describe('Subscription provider panels (SSR, i18n)', () => { ); expectNone( html, - ['Suscripción', 'Mostrar en el widget', 'Uso del plan', 'Cómo conectar', 'Inicia sesión', 'Token manual', 'Avanzado', 'Base de datos', 'Vacío', 'no oficial', 'Comprobando'], + [ + 'Suscripción', + 'Mostrar en el widget', + 'Uso del plan', + 'Cómo conectar', + 'Inicia sesión', + 'Token manual', + 'Avanzado', + 'Base de datos', + 'Vacío', + 'no oficial', + 'Comprobando', + ], 'en cursor', ); }); @@ -307,7 +304,17 @@ describe('Subscription provider panels (SSR, i18n)', () => { ); expectNone( html, - ['Suscripción', 'Mostrar en el widget', 'Cuota de cada', 'Cómo conectar', 'Abre Antigravity', 'Quorb consulta', 'no oficial', 'solo verificado', 'Comprobando'], + [ + 'Suscripción', + 'Mostrar en el widget', + 'Cuota de cada', + 'Cómo conectar', + 'Abre Antigravity', + 'Quorb consulta', + 'no oficial', + 'solo verificado', + 'Comprobando', + ], 'en antigravity', ); }); @@ -361,7 +368,19 @@ describe('Subscription provider panels (SSR, i18n)', () => { expect(copilot('en', 'custom')).toContain('Premium requests included per month'); expectNone( [html, copilot('en', 'custom')].join('\n'), - ['Suscripción', 'Mostrar en el widget', 'Peticiones premium', 'Se reinician', 'Cómo conectar', 'Usuario', 'Otra cantidad', 'Token de', 'Créalo', 'permiso', 'Comprobando'], + [ + 'Suscripción', + 'Mostrar en el widget', + 'Peticiones premium', + 'Se reinician', + 'Cómo conectar', + 'Usuario', + 'Otra cantidad', + 'Token de', + 'Créalo', + 'permiso', + 'Comprobando', + ], 'en copilot', ); }); @@ -415,7 +434,21 @@ describe('Subscription provider panels (SSR, i18n)', () => { ); expectNone( html, - ['Suscripción', 'Mostrar en el widget', 'Cuota del plan', 'dos credenciales', 'Cómo conectar', 'del plan', 'Del panel', 'región', 'pago por uso', 'Sin ella', 'Avanzado', 'Las claves', 'Comprobando'], + [ + 'Suscripción', + 'Mostrar en el widget', + 'Cuota del plan', + 'dos credenciales', + 'Cómo conectar', + 'del plan', + 'Del panel', + 'región', + 'pago por uso', + 'Sin ella', + 'Avanzado', + 'Las claves', + 'Comprobando', + ], 'en minimax', ); }); diff --git a/src/Settings-providers-i18n.test.tsx b/src/Settings-providers-i18n.test.tsx index 69bbbe4c..f7619bd5 100644 --- a/src/Settings-providers-i18n.test.tsx +++ b/src/Settings-providers-i18n.test.tsx @@ -65,7 +65,18 @@ const cfg = enabledOnly('claude', 'copilot'); const card = (locale: Locale, tab: 'claude' | 'copilot' = 'claude', drawerOpen = true, platform: 'windows' | 'macos' | 'linux' = 'windows') => renderToStaticMarkup( - , + , ); const descriptions: [es: string, en: string][] = [ @@ -89,14 +100,22 @@ const descriptions: [es: string, en: string][] = [ describe('Providers list: tab descriptions and badges (SSR, i18n)', () => { it('renders the Spanish literals copied verbatim from the current code', () => { const html = card('es'); - expectAll(html, descriptions.map(([es]) => es), 'es'); + expectAll( + html, + descriptions.map(([es]) => es), + 'es', + ); expectAll(html, ['ChatGPT y Codex', 'Claude', 'GitHub Copilot', 'NaN Builders', '9Router', 'z.ai'], 'es'); expectAll(html, ['Activo', 'Falta conectar', 'Desactivado', 'Conectar', 'Configurar', ' · 2 cuentas'], 'es'); }); it('renders the English texts when the locale is en, with no Spanish left', () => { const html = card('en'); - expectAll(html, descriptions.map(([, en]) => en), 'en'); + expectAll( + html, + descriptions.map(([, en]) => en), + 'en', + ); // «ChatGPT y Codex» es el único nombre con una conjunción española; el resto son marcas. expectAll(html, ['ChatGPT and Codex', 'Claude', 'GitHub Copilot', 'NaN Builders', '9Router', 'z.ai'], 'en'); expectAll(html, ['Active', 'Needs connecting', 'Disabled', 'Connect', 'Set up', ' · 2 accounts'], 'en'); @@ -128,12 +147,34 @@ describe('ProvidersCard: session-environment selector is Windows-only (PR #248)' it('warns that WSL without a distro reads the host session (PR #248)', () => { const wslCfg = { ...cfg, sessionEnv: 'wsl', wslDistro: ' ' } as AppConfig; const empty = renderToStaticMarkup( - , + , ); expect(empty).toContain('Sin distro, WSL no está completo'); // Con distro escrita, la ayuda normal (sin el aviso). const named = renderToStaticMarkup( - , + , ); expect(named).toContain('Distro donde viven los CLIs'); expect(named).not.toContain('Sin distro, WSL no está completo'); @@ -201,17 +242,12 @@ describe('PAGES labels, titles and nav chrome (SSR, i18n)', () => { 'en', ); expectAll(nav('en'), ['aria-label="Collapse the menu"', 'title="Collapse the menu"'], 'en'); - expectNone( - html, - ['Proveedores', 'Suscripciones y APIs', 'Secciones de ajustes', 'Activos pero sin configurar', 'Expandir el menú', 'Contraer'], - 'en', - ); + expectNone(html, ['Proveedores', 'Suscripciones y APIs', 'Secciones de ajustes', 'Activos pero sin configurar', 'Expandir el menú', 'Contraer'], 'en'); }); }); describe('Providers shell: headings, drawer and accounts (SSR, i18n)', () => { - const drawerHead = (locale: Locale) => - renderToStaticMarkup(); + const drawerHead = (locale: Locale) => renderToStaticMarkup(); const accounts: Account[] = [{ id: 'claude:b', provider: 'claude', label: 'Cuenta 2', enabled: true } as Account]; const bar = (locale: Locale, tab: 'claude' | 'nine_router') => renderToStaticMarkup(); @@ -232,24 +268,28 @@ describe('Providers shell: headings, drawer and accounts (SSR, i18n)', () => { ); expectAll(drawerHead('es'), ['Configuración', 'Cerrar la configuración', 'Falta conectar', 'GitHub Copilot'], 'es'); expectAll(bar('es', 'claude'), ['aria-label="Cuentas"', 'Principal', '+ Añadir cuenta', 'Cuenta 2'], 'es'); - expectAll( - bar('es', 'nine_router'), - ['Los subproveedores de 9Router se descubren solos desde su historial de uso; no se añaden a mano.'], - 'es', - ); + expectAll(bar('es', 'nine_router'), ['Los subproveedores de 9Router se descubren solos desde su historial de uso; no se añaden a mano.'], 'es'); expect(bar('es', 'nine_router')).not.toContain('Añadir cuenta'); }); it('renders the English texts when the locale is en, with no Spanish left', () => { const html = card('en') + drawerHead('en') + bar('en', 'claude') + bar('en', 'nine_router'); - expectAll(card('en'), ['aria-label="Providers"', '

Providers

', 'Check every', 'min', 'Subscriptions', 'APIs and credits', 'To change the order of the rings, drag them on the strip.'], 'en'); - expectAll(drawerHead('en'), ['Configuration', 'Close the configuration', 'Needs connecting', 'GitHub Copilot'], 'en'); - expectAll(bar('en', 'claude'), ['aria-label="Accounts"', 'Main', '+ Add account'], 'en'); expectAll( - bar('en', 'nine_router'), - ['The 9Router sub-providers are discovered automatically from its usage history; they are not added by hand.'], + card('en'), + [ + 'aria-label="Providers"', + '

Providers

', + 'Check every', + 'min', + 'Subscriptions', + 'APIs and credits', + 'To change the order of the rings, drag them on the strip.', + ], 'en', ); + expectAll(drawerHead('en'), ['Configuration', 'Close the configuration', 'Needs connecting', 'GitHub Copilot'], 'en'); + expectAll(bar('en', 'claude'), ['aria-label="Accounts"', 'Main', '+ Add account'], 'en'); + expectAll(bar('en', 'nine_router'), ['The 9Router sub-providers are discovered automatically from its usage history; they are not added by hand.'], 'en'); expectNone( html, [ @@ -303,7 +343,11 @@ describe('Save bar, unsaved changes and global notices (SSR, i18n)', () => { const readable = renderToStaticMarkup(); expect(readable).toContain('fallo'); expect(readable).not.toContain('Reintentar'); - expectAll(renderToStaticMarkup(), ['Sesión de escritorio: Wayland', ' · gnome', 'con límites:', 'sin límites conocidos:', 'texto del backend', 'nota del backend'], 'es'); + expectAll( + renderToStaticMarkup(), + ['Sesión de escritorio: Wayland', ' · gnome', 'con límites:', 'sin límites conocidos:', 'texto del backend', 'nota del backend'], + 'es', + ); }); it('renders the English texts when the locale is en, with no Spanish left', () => { @@ -321,35 +365,75 @@ describe('Save bar, unsaved changes and global notices (SSR, i18n)', () => { expect(foot('en', 'window')).not.toContain('Done'); expectAll( html, - ['Start at login', 'Could not read “Start at login”: ', 'Retry', 'Desktop session: Wayland', ' · gnome', 'with limits:', 'no known limits:', 'texto del backend'], + [ + 'Start at login', + 'Could not read “Start at login”: ', + 'Retry', + 'Desktop session: Wayland', + ' · gnome', + 'with limits:', + 'no known limits:', + 'texto del backend', + ], 'en', ); expectNone( html.replace('texto del backend', '').replace(/nota del backend/g, ''), - ['Listo', 'Cerrar', 'Guardar cambios', 'Guardando', 'Arrancar al iniciar sesión', 'No se pudo leer', 'Reintentar', 'Sesión de escritorio', 'con límites', 'sin límites conocidos'], + [ + 'Listo', + 'Cerrar', + 'Guardar cambios', + 'Guardando', + 'Arrancar al iniciar sesión', + 'No se pudo leer', + 'Reintentar', + 'Sesión de escritorio', + 'con límites', + 'sin límites conocidos', + ], 'en', ); }); }); describe('HealthStep, healthSummary and CliMissing (SSR, i18n)', () => { - const report = (over: Partial): UsageReport => ({ - id: 'claude', - name: 'Claude', - kind: 'subscription', - status: 'ok', - plan: null, - meters: [], - spend: null, - message: null, - action: null, - fetchedAt: '2026-01-01T00:00:00Z', - ...over, - } as UsageReport); - const meter = (percent: number | null) => ({ id: 'five_hour', label: 'Sesión 5 h', percent, used: null, limit: null, unit: null, resetsAt: null, windowSeconds: null }); + const report = (over: Partial): UsageReport => + ({ + id: 'claude', + name: 'Claude', + kind: 'subscription', + status: 'ok', + plan: null, + meters: [], + spend: null, + message: null, + action: null, + fetchedAt: '2026-01-01T00:00:00Z', + ...over, + }) as UsageReport; + const meter = (percent: number | null) => ({ + id: 'five_hour', + label: 'Sesión 5 h', + percent, + used: null, + limit: null, + unit: null, + resetsAt: null, + windowSeconds: null, + }); const view = (locale: Locale, h: Health, over: { hidden?: boolean; dirty?: boolean; onLogin?: () => void } = {}) => renderToStaticMarkup( -