From 6236abc766eb27efdfa1116597376675d32e642f Mon Sep 17 00:00:00 2001 From: "dcd-release-please[bot]" <296541543+dcd-release-please[bot]@users.noreply.github.com> Date: Tue, 1 Dec 2026 11:59:53 +0000 Subject: [PATCH 01/12] chore: merge production into dev after 5.16.0 (#368) * chore: pin the 5.12.0 promotion Release-As: 5.12.0 * chore(production): release 5.12.0 * chore: release 5.13.0 * ci: Replace release-please with a custom version that handles our dev -> prod flow (#305) * ci: cut a stable release with one workflow run and one PR A stable release used to take a hand-built promotion branch (dev, a merge of production, and an empty Release-As pin commit), a promotion PR, then release-please's own Release PR, then the back-merge PR. A new "Promote to stable" workflow (promote.yml) now builds the release branch: dev, with production merged in, plus one commit that sets the version in package.json and server.json and adds the CHANGELOG.md section. It opens that as the only PR into production. Merging it is the release: the Release workflow tags the untagged version, creates the GitHub Release from the changelog section, and publishes npm, the binaries and the back-merge as before. scripts/stable-release.mjs derives the version from the Conventional Commit PR titles since the last release, as release-please did, but never derives a major: a breaking marker stops the run until the version is given explicitly. Its changelog lists each PR once, using the full title when GitHub cut it short, where release-please listed such PRs twice. Production is merged in on every run because dev only allows squash merges, so the back-merge can never make production an ancestor of dev. release-please, its config and manifest, and the Release-As promotion-pin check are removed. A release-check job verifies every PR into production instead. Release PRs skip claude-review, like back-merge PRs, because the review action rejects bot actors. The Release workflow keeps the release-please.yml filename, because npm's trusted publisher is registered against it. * ci: keep the stable release PR open and current on every push to dev Promote to stable now also runs on every push to dev. It rebuilds one fixed branch, promote/cli-next, and opens the release PR into production or updates the open one, so the PR always carries all of dev with the version and changelog to match. Nothing ships until someone merges it. - A push with nothing releasable since the last release (docs, the back-merge) does nothing. - A version set by hand is kept on later runs (plan --keep) whenever it is above the derived one, so a major has to be given only once, and a breaking marker still never derives one. - If production moved during the run, nothing is pushed; the back-merge push rebuilds the PR. The force-push is leased against the branch tip the run saw, and skipped when the content is unchanged. - A PR into production from any other branch is left alone: push runs warn and stop. (cherry picked from commit 6bebbefd6c94df0191a72f0b5648c18951e3829d) * ci: lint PR titles on pull_request instead of pull_request_target (#308) GitHub blocks pull_request_target by default in public repositories from 2026-12-02. The PR title check only reads the event payload, so it runs on pull_request, which also fires for fork PRs with a read-only token. The CLA workflow has to write to fork PRs, so it stays on pull_request_target. A repository Actions policy allows that trigger for cla.yml only. Its header now says so. (cherry picked from commit 02d99b9274b7b8b4659bda94c2b94a7f14998fbd) * fix: treat dev-api.devicecloud.dev as the dev environment (#314) The dev API is now at dev-api.devicecloud.dev. Make it the dev apiUrl and keep api.dev.devicecloud.dev as a legacy URL, so saved configs and CI flags that name it still resolve to dev. inferEnvFromApiUrl only recognised 'api.dev.', so a dev-api URL fell through to prod and the Supabase copy of an upload would target the prod project. Both hostnames now map to dev. Co-authored-by: Claude Opus 5.5 (cherry picked from commit 25d09cab0f255ebfeadd74793a7984534126dbeb) * deps: raise the hono override to 4.13.16 for new moderate advisories Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 2476581042ff4a8b4c31bd3e40d9618fd810f31c) * chore: release 5.12.1 * chore: release 5.13.0 * chore: release 5.14.0 * chore: release 5.14.1 * chore: release 5.15.0 * chore: release 5.16.0 --------- Co-authored-by: finalerock44 Co-authored-by: finalerock44 <77282157+finalerock44@users.noreply.github.com> Co-authored-by: dcd-release-please[bot] <296541543+dcd-release-please[bot]@users.noreply.github.com> Co-authored-by: Tom Riglar Co-authored-by: Claude Opus 5.5 Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- CHANGELOG.md | 33 +++++++++++++++++++++++++++++++++ package.json | 2 +- server.json | 4 ++-- 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 473ce1e..0c4033c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,38 @@ # Changelog +## [5.16.0](https://github.com/devicecloud-dev/dcd-cli/compare/v5.15.0...v5.16.0) (2026-11-30) + + +### Features + +* **e2e:** link each test's video to its part of the session recording ([#362](https://github.com/devicecloud-dev/dcd-cli/issues/362)) ([924181e](https://github.com/devicecloud-dev/dcd-cli/commit/924181effca63f04bb7e16542988f862916560d6)) +* **e2e:** run e2e tests on DeviceCloud devices with @devicecloud.dev/dcd/e2e ([#346](https://github.com/devicecloud-dev/dcd-cli/issues/346)) ([d772c53](https://github.com/devicecloud-dev/dcd-cli/commit/d772c533bf56165292e30420a0598f21469af86a)) +* **e2e:** set the device's locale from the e2e provider ([#355](https://github.com/devicecloud-dev/dcd-cli/issues/355)) ([ba43df4](https://github.com/devicecloud-dev/dcd-cli/commit/ba43df49e655d54f3e78fab9d6ce853213c7d0e7)) +* **encryption:** always encrypt uploads; ignore --no-encrypt and DCD_ENCRYPT=0 ([#363](https://github.com/devicecloud-dev/dcd-cli/issues/363)) ([a2c4f76](https://github.com/devicecloud-dev/dcd-cli/commit/a2c4f76c19f471f363636bd2e8a3fbdf85e7016a)) +* **telemetry:** honour DO_NOT_TRACK, and document what telemetry sends ([#364](https://github.com/devicecloud-dev/dcd-cli/issues/364)) ([422012a](https://github.com/devicecloud-dev/dcd-cli/commit/422012a7c8ad73dbf1ffa1e7305e58e90c86668d)) +* **upload:** upload straight to the final storage path with a signed token ([#360](https://github.com/devicecloud-dev/dcd-cli/issues/360)) ([00b2807](https://github.com/devicecloud-dev/dcd-cli/commit/00b2807f59138737fb00a112d088d4c96a884fe2)) + + +### Bug Fixes + +* keep chalk's colour output in nested and multi-line text ([#353](https://github.com/devicecloud-dev/dcd-cli/issues/353)) ([bb273f0](https://github.com/devicecloud-dev/dcd-cli/commit/bb273f0f88d5cc7bc9d123f5e7eda50103df1993)) +* **artifacts:** save into a folder given as the artifacts path, and d… ([#354](https://github.com/devicecloud-dev/dcd-cli/issues/354)) ([9d9adc2](https://github.com/devicecloud-dev/dcd-cli/commit/9d9adc2065c9787399422651e5cfb57740b186b9)) +* **device:** drop iOS 17 from the help text ([#356](https://github.com/devicecloud-dev/dcd-cli/issues/356)) ([c3e0fdf](https://github.com/devicecloud-dev/dcd-cli/commit/c3e0fdfc49ffb73a9ee49e041ef6d929968d1f86)) +* **download:** show a manifest 400/403/404 instead of re-requesting the inline route ([#357](https://github.com/devicecloud-dev/dcd-cli/issues/357)) ([03c01df](https://github.com/devicecloud-dev/dcd-cli/commit/03c01dfc256081aede92d8250f1f2f398465250a)) +* **upload:** refresh the upload token when Storage reports it expired ([#361](https://github.com/devicecloud-dev/dcd-cli/issues/361)) ([161c428](https://github.com/devicecloud-dev/dcd-cli/commit/161c4284af227d119439ffe92420c387f11b2e1d)) +* **upload:** send resumable uploads to the configured Supabase URL ([#358](https://github.com/devicecloud-dev/dcd-cli/issues/358)) ([edf10a7](https://github.com/devicecloud-dev/dcd-cli/commit/edf10a7e9d46dcd50660188da8c4c02f00a8bfcf)) +* **upload:** send Storage uploads with fetch in the standalone binary ([#359](https://github.com/devicecloud-dev/dcd-cli/issues/359)) ([e03a78e](https://github.com/devicecloud-dev/dcd-cli/commit/e03a78ed4cdf25eeeb074d667b3b418646715019)) + + +### Dependencies + +* bump the minor-and-patch group with 3 updates ([#348](https://github.com/devicecloud-dev/dcd-cli/issues/348)) ([64f0942](https://github.com/devicecloud-dev/dcd-cli/commit/64f0942ab1244656aabec30785ca3ef30d04969e)) + + +### Code Refactoring + +* replace chalk with node:util styleText ([#352](https://github.com/devicecloud-dev/dcd-cli/issues/352)) ([2e2377b](https://github.com/devicecloud-dev/dcd-cli/commit/2e2377bfd357bdebfd7a69beb7122d65e8af4818)) + ## [5.15.0](https://github.com/devicecloud-dev/dcd-cli/compare/v5.14.1...v5.15.0) (2026-11-19) diff --git a/package.json b/package.json index 681f4e8..b9eb1c4 100644 --- a/package.json +++ b/package.json @@ -63,7 +63,7 @@ "test:unit": "node scripts/test-runner.mjs --unit", "typecheck": "tsc --noEmit -p tsconfig.test.json" }, - "version": "5.15.0", + "version": "5.16.0", "bugs": { "url": "https://discord.gg/gm3mJwcNw8" }, diff --git a/server.json b/server.json index ee9bf08..e150f71 100644 --- a/server.json +++ b/server.json @@ -2,7 +2,7 @@ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json", "name": "dev.devicecloud/dcd", "description": "Run Maestro mobile app tests on devicecloud.dev: submit flows, check status, download artifacts.", - "version": "5.15.0", + "version": "5.16.0", "repository": { "url": "https://github.com/devicecloud-dev/dcd-cli", "source": "github" @@ -11,7 +11,7 @@ { "registryType": "npm", "identifier": "@devicecloud.dev/dcd", - "version": "5.15.0", + "version": "5.16.0", "runtimeHint": "npx", "runtimeArguments": [ { From 1befc13da94c9ea29e4cf7f8fa1eb4ed3e27fd82 Mon Sep 17 00:00:00 2001 From: finalerock44 <77282157+finalerock44@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:08:23 +0000 Subject: [PATCH 02/12] chore(deps): bump glob and cross-spawn overrides for new advisories (#369) Two advisories published on 2026-12-01 turned `pnpm audit --audit-level moderate` red on dev without any tree change: - GHSA-ghv9-86vm-4v8m (critical, cross-spawn >=7.0.0 <7.1.0, Windows batch-file command injection), via eslint and @modelcontextprotocol/sdk. Pinned to 7.1.2 rather than 7.1.0: 7.1.1 fixes a second Windows injection (GHSA-w3gc-668g-rf8f, not yet in the advisory database) and 7.1.2 fixes a 7.1.0 regression for batch files found in PATH. - GHSA-qxr8-q827-836c (moderate, glob >=13.0.5 <=14.0.5), via mocha. Existing override bumped from 14.0.2 to 14.0.6. --- package.json | 3 ++- pnpm-lock.yaml | 23 ++++++++++++----------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/package.json b/package.json index b9eb1c4..00aa801 100644 --- a/package.json +++ b/package.json @@ -89,7 +89,8 @@ "pnpm": { "overrides": { "minimatch@>=10.0.0 <11.0.1": "11.0.1", - "glob@>=9.0.0 <14.0.2": "14.0.2" + "glob@>=9.0.0 <14.0.6": "14.0.6", + "cross-spawn@>=7.0.0 <7.1.2": "7.1.2" } } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c9ca986..e74fb37 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -6,7 +6,8 @@ settings: overrides: minimatch@>=10.0.0 <11.0.1: 11.0.1 - glob@>=9.0.0 <14.0.2: 14.0.2 + glob@>=9.0.0 <14.0.6: 14.0.6 + cross-spawn@>=7.0.0 <7.1.2: 7.1.2 importers: @@ -564,8 +565,8 @@ packages: resolution: {integrity: sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==} engines: {node: '>= 0.10'} - cross-spawn@7.0.6: - resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} + cross-spawn@7.1.2: + resolution: {integrity: sha512-8BPK2r+sKWC8sDinRwLwrFMq2lXTBBwzYYEB9LiCznfMurOi4FOvQflq3XOLGG+HPdMSVpe+k/s96+AtDEOgPg==} engines: {node: '>= 8'} custom-error-instance@2.1.1: @@ -775,8 +776,8 @@ packages: resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} engines: {node: '>=10.13.0'} - glob@14.0.2: - resolution: {integrity: sha512-vfMgTR2djMHPUchsJMLpZlYQvtjVL+mHpEr5wPpoCbQs2vr/FBNK+3Gnl9Ara1DSs4Aeg4eG9HiADb5/rkY/ZA==} + glob@14.0.6: + resolution: {integrity: sha512-OwXjVP2svY5EyLY75Vek96C8qK43gqrt4xsZ+qSILdnaEiJPXkd62mcfUSNx/TQErQRdu5uM5kF67sfONragKw==} engines: {node: 18 || 20 || >=22} gopd@1.2.0: @@ -1459,7 +1460,7 @@ snapshots: ajv-formats: 3.0.1(ajv@8.20.0) content-type: 1.0.5 cors: 2.8.6 - cross-spawn: 7.0.6 + cross-spawn: 7.1.2 eventsource: 3.0.7 eventsource-parser: 3.1.1 express: 5.3.0 @@ -1705,7 +1706,7 @@ snapshots: object-assign: 4.1.1 vary: 1.1.2 - cross-spawn@7.0.6: + cross-spawn@7.1.2: dependencies: path-key: 3.1.1 shebang-command: 2.0.0 @@ -1804,7 +1805,7 @@ snapshots: '@humanwhocodes/retry': 0.4.3 '@types/estree': 1.0.10 ajv: 6.14.0 - cross-spawn: 7.0.6 + cross-spawn: 7.1.2 debug: 4.4.3(supports-color@8.1.1) escape-string-regexp: 4.0.0 eslint-scope: 9.1.2 @@ -1976,9 +1977,9 @@ snapshots: dependencies: is-glob: 4.0.3 - glob@14.0.2: + glob@14.0.6: dependencies: - minimatch: 11.0.1 + minimatch: 11.0.9 minipass: 7.1.3 path-scurry: 3.0.0 @@ -2138,7 +2139,7 @@ snapshots: debug: 4.4.3(supports-color@8.1.1) diff: 9.0.0 find-up-simple: 1.0.1 - glob: 14.0.2 + glob: 14.0.6 is-path-inside: 4.0.0 is-unicode-supported: 0.1.0 js-yaml: 5.5.0 From e0d58278672cf381879641590f4da9429ecfd517 Mon Sep 17 00:00:00 2001 From: Tom Riglar Date: Tue, 1 Dec 2026 14:07:44 +0000 Subject: [PATCH 03/12] feat(retry): add dcd retry to rerun failed tests (#370) * feat(retry): add dcd retry to rerun failed tests Retry tests that already ran, without uploading anything: - `--upload-id ` retries every failed test in the upload. - `--upload-id --flow ` retries the failed attempts of one flow, on each device it failed on. The flow can be given as a file name with or without its extension, or as its path. - `--result-id ` retries one result. Each retry is a new, billed run, so the request is never resent automatically, and a --flow retry stops at the first refusal and says which retries went through. Co-Authored-By: Claude Opus 5.5 * fix(retry): say retries are free, not billed The API charges nothing for a retry. Correct the help text and comments. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- CLAUDE.md | 2 +- src/commands/retry.ts | 305 ++++++++++++++++++++++++++++++++ src/gateways/api-gateway.ts | 39 ++++ src/index.ts | 2 + test/unit/retry-command.test.ts | 305 ++++++++++++++++++++++++++++++++ 5 files changed, 652 insertions(+), 1 deletion(-) create mode 100644 src/commands/retry.ts create mode 100644 test/unit/retry-command.test.ts diff --git a/CLAUDE.md b/CLAUDE.md index f4aa91d..8cb26af 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -24,7 +24,7 @@ The package ships a **second bin, `dcd-mcp`** (`bin.dcd-mcp` → `dist/mcp/index ## Architecture -Top-level `defineCommand` in `src/index.ts` wires fourteen subcommands (`cloud`, `upload`, `list`, `status`, `settings`, `artifacts`, `device`, `mcp`, `live`, `upgrade`, plus the auth-related `login`, `logout`, `whoami`, `switch-org`). `live` is hidden and deprecated: it still works for old scripts, and prints a deprecation line on stderr pointing at `device`. `cloud` is the primary command and replicates `maestro cloud`; `upgrade` self-updates the standalone bun binary (no-op for npm installs, which it redirects to `npm install -g`). Note `src/index.ts` deliberately **reimplements** citty's `runMain` rather than calling it — see the Telemetry section for why. +Top-level `defineCommand` in `src/index.ts` wires fifteen subcommands (`cloud`, `upload`, `list`, `status`, `retry`, `settings`, `artifacts`, `device`, `mcp`, `live`, `upgrade`, plus the auth-related `login`, `logout`, `whoami`, `switch-org`). `live` is hidden and deprecated: it still works for old scripts, and prints a deprecation line on stderr pointing at `device`. `cloud` is the primary command and replicates `maestro cloud`; `upgrade` self-updates the standalone bun binary (no-op for npm installs, which it redirects to `npm install -g`). Note `src/index.ts` deliberately **reimplements** citty's `runMain` rather than calling it — see the Telemetry section for why. **Flag composition.** Flag definitions are split by domain in `src/config/flags/*.flags.ts` (api, binary, device, environment, execution, github, output) and re-exported as a single `flags` object from `src/constants.ts`. Commands that need the full cloud surface spread `...flags` into their citty `args`; subset commands import individual flag groups. diff --git a/src/commands/retry.ts b/src/commands/retry.ts new file mode 100644 index 0000000..c0a0a8f --- /dev/null +++ b/src/commands/retry.ts @@ -0,0 +1,305 @@ +/** + * `dcd retry` — run tests again that already ran, without uploading anything. + * + * - `--upload-id ` retries every failed test in that upload. + * - `--upload-id --flow ` retries only the failed attempts of one + * flow (on every device it failed on). + * - `--result-id ` retries exactly one result. + * + * A retry runs in the same upload as the original test, so `dcd status + * --upload-id` follows it. Retries are free: the API charges nothing for them. + */ +import { defineCommand } from 'citty'; +import * as path from 'node:path'; + +import { apiFlags } from '../config/flags/api.flags.js'; +import { jsonFlag } from '../config/flags/output.flags.js'; +import { ApiGateway } from '../gateways/api-gateway.js'; +import type { components } from '../types/generated/schema.types.js'; +import { resolveAuth } from '../utils/auth.js'; +import { CliError, logger } from '../utils/cli.js'; +import { resolveApiUrl } from '../utils/config-store.js'; +import { colors, formatId } from '../utils/styling.js'; +import { type Field, ui } from '../utils/ui.js'; + +type ResultRow = components['schemas']['TResultResponse']; + +/** One test the command retried, and the result that now runs it. */ +export interface RetriedTest { + /** The flow file, as the upload names it. Absent for `--result-id`. */ + name?: string; + /** The result that was retried. */ + resultId: number; + /** The new result created by the retry. */ + retryResultId?: number; +} + +const UUID = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i; + +/** How many flow names an error lists before it stops. */ +const MAX_LISTED = 20; + +/** + * Keep only the newest attempt of each test. A retry's `retry_of` can point + * at an earlier retry rather than the first attempt, so each row is followed + * back to the start of its chain first. + */ +export function latestAttempts(rows: ResultRow[]): ResultRow[] { + const byId = new Map(rows.map((row) => [row.id, row])); + const rootOf = (row: ResultRow): number => { + let current = row; + const seen = new Set([current.id]); + while (current.retry_of) { + const parent = byId.get(current.retry_of); + if (!parent || seen.has(parent.id)) return current.retry_of; + seen.add(parent.id); + current = parent; + } + + return current.id; + }; + + const newest = new Map(); + for (const row of rows) { + const root = rootOf(row); + const existing = newest.get(root); + if (!existing || row.id > existing.id) newest.set(root, row); + } + + return rows.filter((row) => newest.get(rootOf(row)) === row); +} + +function stripDotSlash(value: string): string { + return value.replace(/^(\.\/)+/, ''); +} + +/** Whether `name` (a flow file in the upload) is the flow the user typed. */ +function matchesFlow(name: string, flow: string): boolean { + const file = stripDotSlash(name); + const wanted = stripDotSlash(flow); + if (file === wanted || file.endsWith(`/${wanted}`)) return true; + + // A bare name: `login` or `login.yaml` for `flows/login.yaml`. + if (wanted.includes('/')) return false; + const base = path.posix.basename(file); + return base === wanted || base.replace(/\.ya?ml$/i, '') === wanted; +} + +function listNames(names: string[]): string { + const shown = names.slice(0, MAX_LISTED).map((name) => ` ${name}`); + if (names.length > MAX_LISTED) shown.push(` …and ${names.length - MAX_LISTED} more`); + return shown.join('\n'); +} + +/** + * The failed attempts of one flow in an upload: the newest attempt of each + * test whose file matches `flow`. A flow run on several devices has a test per + * device, so this can be more than one. Throws a {@link CliError} when the + * flow isn't in the upload, matches more than one file, or has no failed + * attempt to retry. + */ +export function failedAttemptsOfFlow(rows: ResultRow[], flow: string, uploadId: string): ResultRow[] { + const latest = latestAttempts(rows); + const matches = latest.filter((row) => matchesFlow(row.test_file_name, flow)); + const files = [...new Set(matches.map((row) => row.test_file_name))].sort(); + + if (files.length === 0) { + const all = [...new Set(latest.map((row) => row.test_file_name))].sort(); + throw new CliError( + all.length === 0 + ? `Upload ${uploadId} has no tests.` + : `No flow called "${flow}" in upload ${uploadId}. Its flows are:\n${listNames(all)}`, + ); + } + + if (files.length > 1) { + throw new CliError( + `"${flow}" matches more than one flow in upload ${uploadId}. Give its path instead:\n${listNames(files)}`, + ); + } + + const failed = matches.filter((row) => row.status === 'FAILED'); + if (failed.length === 0) { + const statuses = [...new Set(matches.map((row) => row.status.toLowerCase()))].join(', '); + throw new CliError( + `${files[0]} has no failed attempt to retry. Its latest attempt is ${statuses}.`, + ); + } + + return failed; +} + +function parseResultId(value: string): number { + const id = Number(value); + if (!/^\d+$/.test(value.trim()) || !Number.isSafeInteger(id) || id <= 0) { + throw new CliError(`--result-id must be a positive whole number, not "${value}".`); + } + + return id; +} + +function render(retried: RetriedTest[], uploadId: string | undefined): string[] { + const count = retried.length; + const lines = [ + ui.section('Retry'), + ui.branch([ui.success(`Retried ${count} test${count === 1 ? '' : 's'}`)]), + ]; + + const rows: Field[] = retried.map((test) => [ + test.name ?? `result ${test.resultId}`, + test.retryResultId === undefined + ? colors.dim('retrying') + : `new result ${formatId(String(test.retryResultId))}`, + ]); + if (rows.length > 0) lines.push(ui.branch(ui.fields(rows))); + + if (uploadId) { + lines.push('', ui.note(`Follow it with: dcd status --upload-id ${uploadId}`)); + } + + return lines; +} + +export const retryCommand = defineCommand({ + meta: { + name: 'retry', + description: 'Run failed tests again, from an upload or by result id (retries are free)', + }, + args: { + ...apiFlags, + flow: { + type: 'string', + description: + 'With --upload-id: retry only this flow, by file name or path (e.g. login, login.yaml or flows/login.yaml)', + }, + json: jsonFlag, + 'result-id': { + type: 'string', + description: 'Retry this one result, whatever its flow', + }, + 'upload-id': { + type: 'string', + description: 'Retry the failed tests in this upload', + }, + }, + async run({ args }) { + const apiKeyFlag = args['api-key'] as string | undefined; + const apiUrl = resolveApiUrl(args['api-url'] as string | undefined); + const json = Boolean(args.json); + + try { + await retryMain({ + apiKeyFlag, + apiUrl, + flow: args.flow as string | undefined, + json, + resultId: args['result-id'] as string | undefined, + uploadId: args['upload-id'] as string | undefined, + }); + } catch (error) { + logger.error(error as Error, { exit: 1, json }); + } + }, +}); + +async function retryMain({ + apiKeyFlag, + apiUrl, + flow, + json, + resultId, + uploadId, +}: { + apiKeyFlag: string | undefined; + apiUrl: string; + flow: string | undefined; + json: boolean; + resultId: string | undefined; + uploadId: string | undefined; +}): Promise { + if (uploadId && resultId) { + throw new CliError('Give --upload-id or --result-id, not both.'); + } + + if (!uploadId && !resultId) { + throw new CliError( + 'Say what to retry: --upload-id (its failed tests), --upload-id --flow (one flow), or --result-id .', + ); + } + + if (flow !== undefined && !uploadId) { + throw new CliError('--flow needs --upload-id: the upload whose flow to retry.'); + } + + if (flow !== undefined && flow.trim() === '') { + throw new CliError('--flow needs a flow name or path.'); + } + + if (uploadId && !UUID.test(uploadId)) { + throw new CliError(`--upload-id must be an upload's UUID, not "${uploadId}".`); + } + + const singleResult = resultId === undefined ? undefined : parseResultId(resultId); + const auth = await resolveAuth({ apiKeyFlag }); + + let retried: RetriedTest[]; + let retriedCount: number; + + if (singleResult !== undefined) { + const response = await ApiGateway.retryTest(apiUrl, auth, { resultId: singleResult }); + retried = [{ resultId: singleResult, retryResultId: response.id }]; + retriedCount = 1; + } else if (flow === undefined) { + const response = await ApiGateway.retryTest(apiUrl, auth, { uploadId }); + retriedCount = response.retriedCount ?? 0; + retried = []; + if (retriedCount === 0) { + if (json) { + logger.json({ retried: [], retriedCount: 0, uploadId }); + return; + } + + logger.log(ui.info(response.message || `Upload ${uploadId} has no failed tests to retry.`)); + return; + } + } else { + const { results } = await ApiGateway.getResultsForUpload(apiUrl, auth, uploadId as string); + const failed = failedAttemptsOfFlow(results ?? [], flow, uploadId as string); + + // One at a time: each starts a new run on a device, so stop at the first + // refusal rather than fire the rest, and say what did go through. + retried = []; + for (const row of failed) { + try { + const response = await ApiGateway.retryTest(apiUrl, auth, { resultId: row.id }); + retried.push({ name: row.test_file_name, resultId: row.id, retryResultId: response.id }); + } catch (error) { + if (retried.length === 0) throw error; + const done = retried.map((test) => `${test.resultId} → ${test.retryResultId ?? '?'}`).join(', '); + throw new CliError( + `${(error as Error).message}\nRetried before this failed: ${done}. Not retried: result ${row.id} and any after it.`, + ); + } + } + + retriedCount = retried.length; + } + + if (json) { + logger.json({ retried, retriedCount, uploadId }); + return; + } + + const lines = + retried.length > 0 + ? render(retried, uploadId) + : [ + ui.section('Retry'), + ui.branch([ui.success(`Retried ${retriedCount} failed test${retriedCount === 1 ? '' : 's'}`)]), + '', + ui.note(`Follow it with: dcd status --upload-id ${uploadId}`), + ]; + for (const line of lines) logger.log(line); +} + +export default retryCommand; diff --git a/src/gateways/api-gateway.ts b/src/gateways/api-gateway.ts index a5d1e43..e31d642 100644 --- a/src/gateways/api-gateway.ts +++ b/src/gateways/api-gateway.ts @@ -1126,6 +1126,45 @@ export const ApiGateway = { } }, + /** + * Retry tests that already ran (`POST /uploads/retryTest`). Give a + * `resultId` to retry that one result (the answer carries the new result's + * `id`), or an `uploadId` to retry every failed test in the upload (the + * answer carries `retriedCount`). The API charges nothing for a retry, but + * each one starts a new run on a device, so sending the request twice would + * run the test twice. This makes one attempt and never retries itself. + */ + async retryTest( + baseUrl: string, + auth: AuthContext, + body: components['schemas']['IRetryTestArgs'], + ) { + const url = `${baseUrl}/uploads/retryTest`; + try { + const res = await fetch(url, { + body: JSON.stringify(body), + headers: { + 'content-type': 'application/json', + ...auth.headers, + }, + method: 'POST', + }); + if (!res.ok) { + await this.handleApiError(res, 'Failed to retry'); + } + + return await parseJsonResponse< + paths['/uploads/retryTest']['post']['responses']['201']['content']['application/json'] + >(res, 'Failed to retry'); + } catch (error) { + if (error instanceof TypeError && error.message === 'fetch failed') { + throw this.enhanceFetchError(error, url); + } + + throw error; + } + }, + /** * How long one submit attempt may take (dcd#1617 follow-up). A submit * normally answers in a second or two; one held by a Supabase stall is diff --git a/src/index.ts b/src/index.ts index 90f8499..61ee643 100644 --- a/src/index.ts +++ b/src/index.ts @@ -11,6 +11,7 @@ import { liveCommand } from './commands/live.js'; import { loginCommand } from './commands/login.js'; import { logoutCommand } from './commands/logout.js'; import { mcpCommand } from './commands/mcp.js'; +import { retryCommand } from './commands/retry.js'; import { settingsCommand } from './commands/settings.js'; import { statusCommand } from './commands/status.js'; import { switchOrgCommand } from './commands/switch-org.js'; @@ -37,6 +38,7 @@ const main = defineCommand({ upload: uploadCommand, list: listCommand, status: statusCommand, + retry: retryCommand, settings: settingsCommand, artifacts: artifactsCommand, device: deviceCommand, diff --git a/test/unit/retry-command.test.ts b/test/unit/retry-command.test.ts new file mode 100644 index 0000000..ead8837 --- /dev/null +++ b/test/unit/retry-command.test.ts @@ -0,0 +1,305 @@ +import { expect } from 'chai'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { stripVTControlCharacters } from 'node:util'; + +import { + failedAttemptsOfFlow, + latestAttempts, + retryCommand, +} from '../../src/commands/retry.js'; +import type { components } from '../../src/types/generated/schema.types.js'; + +type ResultRow = components['schemas']['TResultResponse']; + +const API = 'https://api.devicecloud.dev'; +const UPLOAD = '3f2b8c1e-5d4a-4c6b-9e7f-0a1b2c3d4e5f'; + +const row = ( + id: number, + name: string, + status: string, + extra: Partial = {}, +): ResultRow => ({ id, test_file_name: name, status, ...extra }); + +interface Call { + body?: unknown; + headers: Record; + method: string; + url: string; +} + +type Route = (call: Call) => { body: unknown; status: number }; + +/** Answer each request with `route`, recording what was sent. */ +function stubFetch(route: Route): Call[] { + const calls: Call[] = []; + globalThis.fetch = (async (input: unknown, init?: RequestInit) => { + const call: Call = { + url: String(input), + method: init?.method ?? 'GET', + headers: (init?.headers ?? {}) as Record, + body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined, + }; + calls.push(call); + const { body, status } = route(call); + return new Response(JSON.stringify(body), { status }); + }) as typeof fetch; + return calls; +} + +class ExitError extends Error { + constructor(public code: number) { + super(`exit ${code}`); + } +} + +/** Run `dcd retry`, capturing stdout and the exit code. */ +async function run(args: Record): Promise<{ exit: number; out: string }> { + let out = ''; + const write = process.stdout.write.bind(process.stdout); + const errWrite = process.stderr.write.bind(process.stderr); + const log = console.log; + const error = console.error; + const exit = process.exit; + const capture = ((chunk: string) => { + out += chunk; + return true; + }) as typeof process.stdout.write; + process.stdout.write = capture; + process.stderr.write = capture; + console.log = (...parts: unknown[]) => { + out += parts.join(' ') + '\n'; + }; + console.error = console.log; + process.exit = ((code?: number) => { + throw new ExitError(code ?? 0); + }) as typeof process.exit; + let code = 0; + try { + await (retryCommand.run as (c: unknown) => Promise)({ + args: { 'api-key': 'k', 'api-url': API, ...args }, + rawArgs: [], + }); + } catch (error_) { + if (!(error_ instanceof ExitError)) throw error_; + code = error_.code; + } finally { + process.stdout.write = write; + process.stderr.write = errWrite; + console.log = log; + console.error = error; + process.exit = exit; + } + + return { exit: code, out: stripVTControlCharacters(out) }; +} + +describe('dcd retry', () => { + const realFetch = globalThis.fetch; + const ORIGINAL_ENV = { ...process.env }; + let tempDir: string; + + beforeEach(() => { + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'dcd-retry-test-')); + process.env.DCD_CONFIG_DIR = tempDir; + process.env.DCD_TELEMETRY_DISABLED = '1'; + delete process.env.DEVICE_CLOUD_API_KEY; + }); + + afterEach(() => { + globalThis.fetch = realFetch; + process.env = { ...ORIGINAL_ENV }; + fs.rmSync(tempDir, { force: true, recursive: true }); + }); + + describe('latestAttempts', () => { + it('keeps the newest attempt of each test, following retry chains', () => { + const rows = [ + row(1, 'a.yaml', 'FAILED'), + row(2, 'b.yaml', 'PASSED'), + row(3, 'a.yaml', 'FAILED', { retry_of: 1 }), + row(4, 'a.yaml', 'PASSED', { retry_of: 3 }), + ]; + expect(latestAttempts(rows).map((r) => r.id)).to.deep.equal([2, 4]); + }); + + it('treats the same flow on two devices as two tests', () => { + const rows = [ + row(1, 'a.yaml', 'FAILED', { simulator_name: 'pixel' }), + row(2, 'a.yaml', 'FAILED', { simulator_name: 'iphone' }), + ]; + expect(latestAttempts(rows).map((r) => r.id)).to.deep.equal([1, 2]); + }); + }); + + describe('failedAttemptsOfFlow', () => { + const rows = [ + row(1, 'flows/login.yaml', 'FAILED'), + row(2, 'flows/checkout.yaml', 'PASSED'), + row(3, 'flows/login.yaml', 'FAILED', { retry_of: 1 }), + row(4, 'other/login.yml', 'FAILED'), + row(5, 'flows/search.yaml', 'FAILED', { simulator_name: 'pixel' }), + row(6, 'flows/search.yaml', 'PASSED', { simulator_name: 'iphone' }), + ]; + + for (const flow of ['flows/login.yaml', './flows/login.yaml']) { + it(`matches the full path "${flow}" and returns only the newest failed attempt`, () => { + expect(failedAttemptsOfFlow(rows, flow, UPLOAD).map((r) => r.id)).to.deep.equal([3]); + }); + } + + for (const flow of ['search', 'search.yaml', 'flows/search.yaml']) { + it(`matches "${flow}" and returns only the devices it failed on`, () => { + expect(failedAttemptsOfFlow(rows, flow, UPLOAD).map((r) => r.id)).to.deep.equal([5]); + }); + } + + it('refuses a bare name that matches two files, and lists them', () => { + expect(() => failedAttemptsOfFlow(rows, 'login', UPLOAD)).to.throw( + /matches more than one flow[\s\S]*flows\/login\.yaml[\s\S]*other\/login\.yml/, + ); + }); + + it('says which flows the upload has when none matches', () => { + expect(() => failedAttemptsOfFlow(rows, 'nope', UPLOAD)).to.throw( + /No flow called "nope"[\s\S]*flows\/checkout\.yaml/, + ); + }); + + it('refuses a flow whose latest attempt did not fail', () => { + expect(() => failedAttemptsOfFlow(rows, 'checkout', UPLOAD)).to.throw( + /flows\/checkout\.yaml has no failed attempt to retry\. Its latest attempt is passed\./, + ); + }); + + it('does not match a path suffix that is only part of a folder name', () => { + expect(() => failedAttemptsOfFlow([row(1, 'myflows/login.yaml', 'FAILED')], 'flows/login.yaml', UPLOAD)) + .to.throw(/No flow called/); + }); + }); + + describe('arguments', () => { + const cases: Array<[string, Record, RegExp]> = [ + ['nothing to retry', {}, /Say what to retry/], + ['both ids', { 'upload-id': UPLOAD, 'result-id': '5' }, /not both/], + ['--flow without an upload', { flow: 'login', 'result-id': '5' }, /--flow needs --upload-id/], + ['an empty --flow', { flow: ' ', 'upload-id': UPLOAD }, /--flow needs a flow name/], + ['an upload id that is not a UUID', { 'upload-id': 'abc' }, /must be an upload's UUID/], + ['a result id that is not a number', { 'result-id': '12a' }, /positive whole number/], + ['a result id of 0', { 'result-id': '0' }, /positive whole number/], + ]; + + for (const [label, args, message] of cases) { + it(`refuses ${label} without calling the API`, async () => { + const calls = stubFetch(() => ({ body: {}, status: 500 })); + + const { exit, out } = await run(args); + + expect(exit).to.equal(1); + expect(out).to.match(message); + expect(calls).to.have.length(0); + }); + } + }); + + it('retries one result with --result-id', async () => { + const calls = stubFetch(() => ({ body: { id: 99, message: 'Retry in progress' }, status: 201 })); + + const { exit, out } = await run({ json: true, 'result-id': '42' }); + + expect(exit).to.equal(0); + expect(calls).to.have.length(1); + expect(calls[0].url).to.equal(`${API}/uploads/retryTest`); + expect(calls[0].method).to.equal('POST'); + expect(calls[0].headers['x-app-api-key']).to.equal('k'); + expect(calls[0].body).to.deep.equal({ resultId: 42 }); + expect(JSON.parse(out)).to.deep.equal({ + retried: [{ resultId: 42, retryResultId: 99 }], + retriedCount: 1, + }); + }); + + it("retries an upload's failed tests with --upload-id", async () => { + const calls = stubFetch(() => ({ body: { retriedCount: 3, success: true }, status: 201 })); + + const { exit, out } = await run({ 'upload-id': UPLOAD }); + + expect(exit).to.equal(0); + expect(calls).to.have.length(1); + expect(calls[0].body).to.deep.equal({ uploadId: UPLOAD }); + expect(out).to.include('Retried 3 failed tests'); + expect(out).to.include(`dcd status --upload-id ${UPLOAD}`); + }); + + it('says so when an upload has nothing to retry, and exits 0', async () => { + stubFetch(() => ({ + body: { message: 'No failed tests to retry', retriedCount: 0, success: true }, + status: 201, + })); + + const { exit, out } = await run({ 'upload-id': UPLOAD }); + + expect(exit).to.equal(0); + expect(out).to.include('No failed tests to retry'); + }); + + it('retries each device a flow failed on with --flow, one at a time', async () => { + const results = [ + row(10, 'flows/search.yaml', 'FAILED', { simulator_name: 'pixel' }), + row(11, 'flows/search.yaml', 'FAILED', { simulator_name: 'iphone' }), + row(12, 'flows/login.yaml', 'FAILED'), + ]; + const calls = stubFetch((call) => + call.method === 'GET' + ? { body: { results, status: 'FAILED' }, status: 200 } + : { body: { id: 100 + (call.body as { resultId: number }).resultId }, status: 201 }, + ); + + const { exit, out } = await run({ flow: 'search', json: true, 'upload-id': UPLOAD }); + + expect(exit).to.equal(0); + expect(calls.map((c) => c.method)).to.deep.equal(['GET', 'POST', 'POST']); + expect(calls[0].url).to.equal(`${API}/results/${UPLOAD}?view=summary`); + expect(calls.slice(1).map((c) => c.body)).to.deep.equal([{ resultId: 10 }, { resultId: 11 }]); + expect(JSON.parse(out)).to.deep.equal({ + retried: [ + { name: 'flows/search.yaml', resultId: 10, retryResultId: 110 }, + { name: 'flows/search.yaml', resultId: 11, retryResultId: 111 }, + ], + retriedCount: 2, + uploadId: UPLOAD, + }); + }); + + it('stops at the first refused retry and says which went through', async () => { + const results = [ + row(10, 'flows/search.yaml', 'FAILED', { simulator_name: 'pixel' }), + row(11, 'flows/search.yaml', 'FAILED', { simulator_name: 'iphone' }), + ]; + const calls = stubFetch((call) => { + if (call.method === 'GET') return { body: { results }, status: 200 }; + return (call.body as { resultId: number }).resultId === 10 + ? { body: { id: 110 }, status: 201 } + : { body: { message: 'Binary upload deleted' }, status: 400 }; + }); + + const { exit, out } = await run({ flow: 'search', 'upload-id': UPLOAD }); + + expect(exit).to.equal(1); + expect(calls.filter((c) => c.method === 'POST')).to.have.length(2); + expect(out).to.include('Binary upload deleted'); + expect(out).to.include('Retried before this failed: 10 → 110'); + expect(out).to.include('Not retried: result 11'); + }); + + it("shows the API's reason when it refuses a retry", async () => { + stubFetch(() => ({ body: { message: 'Binary upload deleted' }, status: 400 })); + + const { exit, out } = await run({ 'result-id': '42' }); + + expect(exit).to.equal(1); + expect(out).to.include('Binary upload deleted'); + }); +}); From d36dac2b2711ad96566d4c8b009aba9596713d67 Mon Sep 17 00:00:00 2001 From: finalerock44 <77282157+finalerock44@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:22:15 +0000 Subject: [PATCH 04/12] chore(deps): bump tar to 8 and the mocha minimatch override to 11.0.9 (#375) `pnpm audit --audit-level moderate` fails on every branch since advisories published after dev's last green run (12-01 14:07Z): - tar <8.0.0 (direct dependency, 7.5.23): 18 advisories, symlink escapes and PAX/parser differentials among them, fixed only in tar 8. The CLI calls `tar.extract({ cwd, file })` on Expo/EAS .tar.gz builds (src/utils/expo.ts), which tar 8 still takes: it returns a promise, reads `file` and detects gzip. Node >=22 matches our engines. ^8.0.5, not 8.0.2: 8.0.3-8.0.5 add parser hardening listed in tar's security notes. tar 8 has no runtime dependencies, so minipass, minizlib, chownr, yallist and @isaacs/fs-minipass leave the lockfile. - minimatch 11.0.1 via mocha (dev only): GHSA-cf2h-pxjq-68xw (>=11.0.7) and GHSA-c859-jr93-m5j4 (>=11.0.8). The override goes to 11.0.9, which the rest of the tree already resolves to. Checked: audit clean, lint, typecheck, 787 unit tests, build, dcd-mcp tools/list (6 tools), and the built extractTarGz on a packed copy of the testing repo's iOS fixture app: 304 paths byte-identical with tar 7's output, and a symlink pointing outside the bundle refused. --- package.json | 4 +-- pnpm-lock.yaml | 66 +++++++------------------------------------------- 2 files changed, 11 insertions(+), 59 deletions(-) diff --git a/package.json b/package.json index 00aa801..ebb9f7f 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,7 @@ "js-yaml": "^5.2.2", "node-stream-zip": "^1.15.0", "plist": "^5.0.0", - "tar": "^7.5.16", + "tar": "^8.0.5", "tus-js-client": "^4.3.1", "yazl": "^3.3.1", "zod": "^4.4.3" @@ -88,7 +88,7 @@ "packageManager": "pnpm@10.17.1", "pnpm": { "overrides": { - "minimatch@>=10.0.0 <11.0.1": "11.0.1", + "minimatch@>=10.0.0 <11.0.9": "11.0.9", "glob@>=9.0.0 <14.0.6": "14.0.6", "cross-spawn@>=7.0.0 <7.1.2": "7.1.2" } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e74fb37..f68dec0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -5,7 +5,7 @@ settings: excludeLinksFromLockfile: false overrides: - minimatch@>=10.0.0 <11.0.1: 11.0.1 + minimatch@>=10.0.0 <11.0.9: 11.0.9 glob@>=9.0.0 <14.0.6: 14.0.6 cross-spawn@>=7.0.0 <7.1.2: 7.1.2 @@ -35,8 +35,8 @@ importers: specifier: ^5.0.0 version: 5.1.2 tar: - specifier: ^7.5.16 - version: 7.5.23 + specifier: ^8.0.5 + version: 8.0.5 tus-js-client: specifier: ^4.3.1 version: 4.3.1 @@ -327,13 +327,6 @@ packages: resolution: {integrity: sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==} engines: {node: '>=18.18'} - '@isaacs/fs-minipass@4.0.1': - resolution: {integrity: sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==} - engines: {node: '>=18.0.0'} - - '@isaacs/nonrecursive-glob-match@1.0.3': - resolution: {integrity: sha512-SI7kyKHq4XXDRozw+r9GlRZkia1ZkFrpLW98r2IC2Bpr8YkFGE3fvjzmxCG0x78A++69HmDNrDvSMYBZmHGpKA==} - '@isaacs/nonrecursive-glob-match@1.1.0': resolution: {integrity: sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==} @@ -531,10 +524,6 @@ packages: resolution: {integrity: sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==} engines: {node: '>= 20.19.0'} - chownr@3.0.0: - resolution: {integrity: sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==} - engines: {node: '>=18'} - citty@0.2.2: resolution: {integrity: sha512-+6vJA3L98yv+IdfKGZHBNiGW5KHn22e/JwID0Strsz8h4S/csAu/OuICwxrg44k5MRiZHWIo8XXuJgQTriRP4w==} @@ -956,10 +945,6 @@ packages: resolution: {integrity: sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==} engines: {node: '>=18'} - minimatch@11.0.1: - resolution: {integrity: sha512-t+Vn6DX4wPCxS23y03C0uhF7S1jpi1GfqPrnlEipCJaA2ykiNbMkVlDutZtmvLfRcUN6R8AYVlzTsQrT4RZoLQ==} - engines: {node: 18 || 20 || >=22} - minimatch@11.0.9: resolution: {integrity: sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==} engines: {node: 20 || >=22} @@ -968,10 +953,6 @@ packages: resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==} engines: {node: '>=16 || 14 >=14.17'} - minizlib@3.1.0: - resolution: {integrity: sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==} - engines: {node: '>= 18'} - mocha@12.0.3: resolution: {integrity: sha512-beammieDdiWdkjANWeWPpkxUROYGi5FN88fPOkLiticz7HTg3Y+Pho3EYE6SUdcuWnZ3h2WD8EXCA55JF4o6wg==} engines: {node: ^20.19.0 || >=22.12.0} @@ -1176,9 +1157,9 @@ packages: resolution: {integrity: sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==} engines: {node: '>=10'} - tar@7.5.23: - resolution: {integrity: sha512-lkukzdoGngZHJZXxW4S/E4Fp9ghTDlyZXrQGRNoJ/LXvDKcXUTq2sg5yQe74po7Voea6n/IN09+wE/QvJMiifA==} - engines: {node: '>=18'} + tar@8.0.5: + resolution: {integrity: sha512-iYroSHv/iVs5Bfy7uXCZVTye64oecqEETP3jvxksDcJlf8E3hreHYyhT+Qu7b+JgniditLaQbk4ZujNAnPEX9w==} + engines: {node: '>=22'} tinyglobby@0.2.17: resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} @@ -1259,10 +1240,6 @@ packages: resolution: {integrity: sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==} engines: {node: '>=8.0'} - yallist@5.0.0: - resolution: {integrity: sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==} - engines: {node: '>=18'} - yazl@3.3.1: resolution: {integrity: sha512-BbETDVWG+VcMUle37k5Fqp//7SDOK2/1+T7X8TD96M3D9G8jK5VLUdQVdVjGi8im7FGkazX7kk5hkU8X4L5Bng==} @@ -1437,12 +1414,6 @@ snapshots: '@humanwhocodes/retry@0.4.3': {} - '@isaacs/fs-minipass@4.0.1': - dependencies: - minipass: 7.1.3 - - '@isaacs/nonrecursive-glob-match@1.0.3': {} - '@isaacs/nonrecursive-glob-match@1.1.0': {} '@keyv/bigmap@1.3.1(keyv@5.6.0)': @@ -1568,7 +1539,7 @@ snapshots: '@typescript-eslint/types': 8.73.0 '@typescript-eslint/visitor-keys': 8.73.0 debug: 4.4.3(supports-color@8.1.1) - minimatch: 11.0.1 + minimatch: 11.0.9 semver: 7.8.6 tinyglobby: 0.2.17 ts-api-utils: 2.5.0(typescript@6.0.3) @@ -1682,8 +1653,6 @@ snapshots: dependencies: readdirp: 5.1.1 - chownr@3.0.0: {} - citty@0.2.2: {} combine-errors@3.0.3: @@ -2116,11 +2085,6 @@ snapshots: dependencies: mime-db: 1.54.0 - minimatch@11.0.1: - dependencies: - '@isaacs/nonrecursive-glob-match': 1.0.3 - brace-expansion: 5.0.12 - minimatch@11.0.9: dependencies: '@isaacs/nonrecursive-glob-match': 1.1.0 @@ -2128,10 +2092,6 @@ snapshots: minipass@7.1.3: {} - minizlib@3.1.0: - dependencies: - minipass: 7.1.3 - mocha@12.0.3: dependencies: browser-stdout: 1.3.1 @@ -2143,7 +2103,7 @@ snapshots: is-path-inside: 4.0.0 is-unicode-supported: 0.1.0 js-yaml: 5.5.0 - minimatch: 11.0.1 + minimatch: 11.0.9 ms: 2.1.3 picocolors: 1.1.1 serialize-javascript: 7.1.4 @@ -2348,13 +2308,7 @@ snapshots: dependencies: has-flag: 4.0.0 - tar@7.5.23: - dependencies: - '@isaacs/fs-minipass': 4.0.1 - chownr: 3.0.0 - minipass: 7.1.3 - minizlib: 3.1.0 - yallist: 5.0.0 + tar@8.0.5: {} tinyglobby@0.2.17: dependencies: @@ -2434,8 +2388,6 @@ snapshots: xmlbuilder@15.1.1: {} - yallist@5.0.0: {} - yazl@3.3.1: dependencies: buffer-crc32: 1.0.0 From ee995df83288a2309ebf1f721d09dd9d490eb6c9 Mon Sep 17 00:00:00 2001 From: finalerock44 <77282157+finalerock44@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:24:09 +0000 Subject: [PATCH 05/12] feat(device): show the session's locale in dcd device status (#374) The API's session block now carries `locale` (the locale the device was set to, null when none was asked for) and `os_version` (the iOS version or Android API level). Type both as optional, since older APIs don't send them, and print a `locale` line when one is set. `model` already shows the version, so there is no separate OS line. --json passes both through. --- src/types/domain/device-session.types.ts | 10 ++++++++++ src/utils/device-output.ts | 1 + test/unit/device-command.test.ts | 11 +++++++++++ 3 files changed, 22 insertions(+) diff --git a/src/types/domain/device-session.types.ts b/src/types/domain/device-session.types.ts index 56ae993..aa896e1 100644 --- a/src/types/domain/device-session.types.ts +++ b/src/types/domain/device-session.types.ts @@ -27,6 +27,16 @@ export interface DeviceSession { release_reason: null | string; platform: string; model: null | string; + /** + * The iOS version ("26.5"), or the Android API level ("36"). Also part of + * `model`. Absent from older APIs. + */ + os_version?: null | string; + /** + * The locale the device was set to, e.g. "de_DE"; null when none was asked + * for (the device's own default). Absent from older APIs. + */ + locale?: null | string; client_label: null | string; created_at: string; /** When a device was assigned (billing starts); null while queued. Absent from older APIs. */ diff --git a/src/utils/device-output.ts b/src/utils/device-output.ts index a2b19fe..837ec1e 100644 --- a/src/utils/device-output.ts +++ b/src/utils/device-output.ts @@ -305,6 +305,7 @@ export function sessionFields(session: DeviceSession): Field[] { ['platform', session.platform], ]; if (session.model) fields.push(['model', printable(session.model, { oneLine: true })]); + if (session.locale) fields.push(['locale', printable(session.locale, { oneLine: true })]); if (session.client_label) fields.push(['client', printable(session.client_label, { oneLine: true })]); if (session.started_by) fields.push(['started', startedByLabel(session.started_by)]); if (session.queue) { diff --git a/test/unit/device-command.test.ts b/test/unit/device-command.test.ts index 585864a..30090b2 100644 --- a/test/unit/device-command.test.ts +++ b/test/unit/device-command.test.ts @@ -1166,6 +1166,17 @@ describe('dcd device', () => { expect(await runText('status', { id: 'a-b-c' })).to.include('A person has control'); }); + it('status shows the locale the device was set to, and no line when none was', async () => { + stubFetch(() => ({ body: { session: session('a-b-c', { locale: 'de_DE', os_version: '26.5' }) } })); + expect(await runText('status', { id: 'a-b-c' })).to.match(/locale\s+de_DE/); + + stubFetch(() => ({ body: { session: session('a-b-c', { locale: null }) } })); + expect(await runText('status', { id: 'a-b-c' })).not.to.include('locale'); + + stubFetch(() => ({ body: { session: session('a-b-c') } })); + expect(await runText('status', { id: 'a-b-c' })).not.to.include('locale'); + }); + it('status still works on an API without the human route', async () => { stubFetch((call) => call.url.endsWith('/human') ? { status: 404, body: { statusCode: 404, message: 'Not Found' } } : { body: { session: session('a-b-c') } }, From 6776b6e63265c25e2d514f9ef70d0751bf179754 Mon Sep 17 00:00:00 2001 From: finalerock44 <77282157+finalerock44@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:27:46 +0000 Subject: [PATCH 06/12] fix(cloud): mask -e values in the options summary and debug log (#376) `dcd cloud` printed every `-e KEY=VALUE` pair in plain text: in the Options summary it shows before submitting, and in the `--debug` line that lists the run's environment variables. `-e` is how secrets reach flows, and that output ends up in CI logs and agent transcripts. Both now show each name with its value masked (`KEY=***`). The values sent with the run are unchanged. The summary rows are built by `optionsSummaryFields` in `src/utils/options-summary.ts`, so they can be unit-tested. Closes #372 --- src/commands/cloud.ts | 61 ++++----- src/services/test-submission.service.ts | 5 +- src/utils/options-summary.ts | 67 ++++++++++ test/unit/options-summary.test.ts | 156 ++++++++++++++++++++++++ 4 files changed, 249 insertions(+), 40 deletions(-) create mode 100644 src/utils/options-summary.ts create mode 100644 test/unit/options-summary.test.ts diff --git a/src/commands/cloud.ts b/src/commands/cloud.ts index 59cc44f..5eb7cfb 100644 --- a/src/commands/cloud.ts +++ b/src/commands/cloud.ts @@ -60,6 +60,7 @@ import { import { platformFromAppFile, renderNotices } from '../services/notices.service.js'; import { resolveApiUrl } from '../utils/config-store.js'; import { downloadExpoUrl, extractTarGz, findAppBundle, isUrl } from '../utils/expo.js'; +import { optionsSummaryFields } from '../utils/options-summary.js'; import { colors, formatId, @@ -702,40 +703,23 @@ export const cloudCommand = defineCommand({ } } - const flagLogs: string[] = []; - // app-url carries a signed (bearer-style) download URL — treat as secret. - const sensitiveFlags = new Set([ - 'api-key', - 'apiKey', - 'moropo-v1-api-key', - 'app-url', - 'appUrl', - ]); - // Only log canonical flag keys (skip citty-populated alias duplicates like apiURL/apiUrl). - const canonicalFlagKeys = new Set(Object.keys(allFlags)); - // Repeatable flags are recovered from rawArgs (args.* only holds the last - // occurrence), so echo the fully-collected values rather than args.*. - const repeatableDisplay: Record = { - env, - metadata, - 'include-tags': includeTags, - 'exclude-tags': excludeTags, - 'exclude-flows': excludeFlows, - 'ios-device-matrix': iosMatrixFlags, - 'android-device-matrix': androidMatrixFlags, - }; - for (const [k, v] of Object.entries(args)) { - if (!canonicalFlagKeys.has(k)) continue; - if (k in repeatableDisplay) continue; - if (v === undefined || v === null || v === false) continue; - const asString = String(v); - if (asString.length > 0 && !sensitiveFlags.has(k)) { - flagLogs.push(`${k}: ${asString}`); - } - } - for (const [k, values] of Object.entries(repeatableDisplay)) { - if (values.length > 0) flagLogs.push(`${k}: ${values.join(', ')}`); - } + // Credentials are left out and --env values masked (options-summary.ts). + const optionRows = optionsSummaryFields({ + args, + // Skips citty's alias duplicates (apiURL/apiUrl). + canonicalKeys: new Set(Object.keys(allFlags)), + // Repeatable flags are recovered from rawArgs (args.* only holds the + // last occurrence), so show the fully-collected values. + repeatable: { + env, + metadata, + 'include-tags': includeTags, + 'exclude-tags': excludeTags, + 'exclude-flows': excludeFlows, + 'ios-device-matrix': iosMatrixFlags, + 'android-device-matrix': androidMatrixFlags, + }, + }); const overridesEntries = Object.entries(flowOverrides); const hasOverrides = overridesEntries.some( @@ -747,14 +731,13 @@ export const cloudCommand = defineCommand({ ['app', colors.highlight(appBinaryId || finalAppFile || '')], ]); - if (flagLogs.length > 0) { + if (optionRows.length > 0) { submitRows.push('', colors.bold('Options')); submitRows.push( ...ui.fields( - flagLogs.map((flagLog) => { - const [key, ...valueParts] = flagLog.split(': '); - return [key, colors.highlight(valueParts.join(': '))] as Field; - }), + optionRows.map( + ([key, value]) => [key, colors.highlight(value)] as Field, + ), ), ); } diff --git a/src/services/test-submission.service.ts b/src/services/test-submission.service.ts index 54aa4c6..59590b2 100644 --- a/src/services/test-submission.service.ts +++ b/src/services/test-submission.service.ts @@ -9,6 +9,7 @@ import { encryptFlowBuffer, resolveKekPublicKey, } from '../utils/envelope.js'; +import { maskEnvValues } from '../utils/options-summary.js'; import { toPortableRelativePath } from '../utils/paths.js'; import { IExecutionPlan } from './execution-plan.service.js'; @@ -160,7 +161,9 @@ export class TestSubmissionService { this.logDebug( debug, logger, - `[DEBUG] Environment variables: ${JSON.stringify(envObject)}`, + // Values masked: they are often secrets, and debug output ends up in + // CI logs. + `[DEBUG] Environment variables: ${maskEnvValues(env).join(', ')}`, ); } diff --git a/src/utils/options-summary.ts b/src/utils/options-summary.ts new file mode 100644 index 0000000..0e252f4 --- /dev/null +++ b/src/utils/options-summary.ts @@ -0,0 +1,67 @@ +/** + * The "Options" rows `dcd cloud` prints before it submits a run. + * + * That output lands in terminal scrollback, CI logs and agent transcripts, so + * it must never carry a secret. Flags whose value is a credential are left + * out, and `--env` shows each variable's name with its value masked: `-e` is + * how passwords and tokens reach flows, and the upload encrypts them. + */ + +/** Flags left out of the summary: their value is a credential. */ +const SENSITIVE_FLAGS = new Set([ + 'api-key', + 'apiKey', + 'moropo-v1-api-key', + // A signed (bearer-style) download URL. + 'app-url', + 'appUrl', +]); + +const MASK = '***'; + +/** + * `KEY=VALUE` pairs with each value replaced by `***`, for output. The key is + * everything before the first `=`, as the submission parses it. An entry with + * no `=` is sent as an empty variable of that name, so it is shown as is. + */ +export function maskEnvValues(pairs: string[]): string[] { + return pairs.map((pair) => { + const eq = pair.indexOf('='); + return eq === -1 ? pair : `${pair.slice(0, eq)}=${MASK}`; + }); +} + +export interface OptionsSummaryInput { + /** The parsed flags, as citty gives them. */ + args: Record; + /** The flag names the command defines (citty adds alias duplicates to `args`). */ + canonicalKeys: ReadonlySet; + /** + * Repeatable flags, with every occurrence collected from argv (`args` only + * holds the last one). Shown from here instead of from `args`. + */ + repeatable: Record; +} + +/** The summary's `[flag, value]` rows: set flags only, secrets left out or masked. */ +export function optionsSummaryFields({ + args, + canonicalKeys, + repeatable, +}: OptionsSummaryInput): Array<[string, string]> { + const rows: Array<[string, string]> = []; + for (const [key, value] of Object.entries(args)) { + if (!canonicalKeys.has(key)) continue; + if (key in repeatable) continue; + if (SENSITIVE_FLAGS.has(key)) continue; + if (value === undefined || value === null || value === false) continue; + const asString = String(value); + if (asString.length > 0) rows.push([key, asString]); + } + for (const [key, values] of Object.entries(repeatable)) { + if (values.length === 0) continue; + const shown = key === 'env' ? maskEnvValues(values) : values; + rows.push([key, shown.join(', ')]); + } + return rows; +} diff --git a/test/unit/options-summary.test.ts b/test/unit/options-summary.test.ts new file mode 100644 index 0000000..7456504 --- /dev/null +++ b/test/unit/options-summary.test.ts @@ -0,0 +1,156 @@ +import { expect } from 'chai'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; + +import type { IExecutionPlan } from '../../src/services/execution-plan.service.js'; +import { TestSubmissionService } from '../../src/services/test-submission.service.js'; +import { + maskEnvValues, + optionsSummaryFields, +} from '../../src/utils/options-summary.js'; + +/** + * `dcd cloud` prints its options before it submits a run, and that output + * reaches CI logs and agent transcripts. `-e` is how secrets reach flows, so + * no `-e` value may appear in it, at any log level. + */ +describe('options summary', () => { + const SECRET = 'abc123'; + + describe('maskEnvValues', () => { + it('keeps each name and masks its value', () => { + expect(maskEnvValues([`SECRET=${SECRET}`, 'USER=me'])).to.deep.equal([ + 'SECRET=***', + 'USER=***', + ]); + }); + + it('splits on the first = only, as the submission does', () => { + expect(maskEnvValues(['TOKEN=a=b=c'])).to.deep.equal(['TOKEN=***']); + }); + + it('masks an empty value too', () => { + expect(maskEnvValues(['EMPTY='])).to.deep.equal(['EMPTY=***']); + }); + + it('shows an entry without = as its name', () => { + expect(maskEnvValues(['FLAG'])).to.deep.equal(['FLAG']); + }); + }); + + describe('optionsSummaryFields', () => { + const summarize = ( + args: Record, + repeatable: Record = {}, + ) => + optionsSummaryFields({ + args, + canonicalKeys: new Set([ + 'android-device', + 'api-key', + 'app-url', + 'async', + 'env', + 'json', + 'metadata', + 'moropo-v1-api-key', + 'name', + ]), + repeatable, + }); + + it('masks every --env value and keeps the names', () => { + const rows = summarize( + { env: 'B=x=y' }, + { env: [`SECRET=${SECRET}`, 'B=x=y'] }, + ); + expect(rows).to.deep.equal([['env', 'SECRET=***, B=***']]); + expect(JSON.stringify(rows)).not.to.include(SECRET); + expect(JSON.stringify(rows)).not.to.include('x=y'); + }); + + it('leaves out flags whose value is a credential', () => { + const rows = summarize({ + 'api-key': 'key-value', + 'app-url': 'https://example.com/app.apk?X-Amz-Signature=sig', + 'moropo-v1-api-key': 'moropo-key', + name: 'nightly', + }); + expect(rows).to.deep.equal([['name', 'nightly']]); + }); + + it('shows other repeatable flags as given', () => { + expect( + summarize({}, { metadata: ['team=mobile', 'build=42'] }), + ).to.deep.equal([['metadata', 'team=mobile, build=42']]); + }); + + it('passes ordinary flags through and skips unset ones', () => { + expect( + summarize({ + 'android-device': 'pixel-7', + async: true, + json: false, + name: '', + }), + ).to.deep.equal([ + ['android-device', 'pixel-7'], + ['async', 'true'], + ]); + }); + + it("skips citty's alias duplicates", () => { + expect( + summarize({ androidDevice: 'pixel-7', 'android-device': 'pixel-7' }), + ).to.deep.equal([['android-device', 'pixel-7']]); + }); + + it('leaves out an empty repeatable flag', () => { + expect(summarize({}, { env: [] })).to.deep.equal([]); + }); + }); + + describe('--debug submission log', () => { + let workspace: string; + let flowFile: string; + + before(() => { + workspace = fs.mkdtempSync(path.join(os.tmpdir(), 'dcd-env-mask-')); + flowFile = path.join(workspace, 'flow.yaml'); + fs.writeFileSync(flowFile, 'appId: com.example\n---\n- launchApp\n'); + }); + + after(() => { + fs.rmSync(workspace, { force: true, recursive: true }); + }); + + it('masks env values in the log but sends them unchanged', async () => { + const executionPlan: IExecutionPlan = { + flowMetadata: {}, + flowOverrides: {}, + flowsToRun: [flowFile], + includedFiles: [], + referencedFiles: [], + totalFlowFiles: 1, + }; + const lines: string[] = []; + const { fields } = await new TestSubmissionService().buildTestPayload({ + appBinaryId: 'binary-1', + cliVersion: '0.0.0-test', + commonRoot: workspace, + debug: true, + encrypt: false, + env: [`SECRET=${SECRET}`], + executionPlan, + flowFile, + logger: (message: string) => lines.push(message), + maestroVersion: '2.10.0', + }); + + expect(lines.join('\n')).not.to.include(SECRET); + expect(lines).to.include('[DEBUG] Environment variables: SECRET=***'); + expect(JSON.parse(fields.env)).to.deep.equal({ SECRET }); + }); + }); +}); From ed3c2554132c8e3e58865ecf1fa73bb54f8c3d71 Mon Sep 17 00:00:00 2001 From: finalerock44 <77282157+finalerock44@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:46:48 +0000 Subject: [PATCH 07/12] feat(api): send the runtime (bun or node) with the CLI identity headers (#377) Every API request now carries x-dcd-cli-runtime next to x-dcd-cli-version: bun for the standalone binary, node for the npm package. A bug that only one build has can then be traced to the requests and uploads it affected. The header is set in resolveAuth's client headers, which covers the --api-key, env, session, refresh and MCP paths, and in the e2e provider, which builds its own headers. getRuntime() is now the one place that tells the two builds apart; getInstallMethod() uses it. --- CLAUDE.md | 2 +- src/e2e/index.ts | 4 +++- src/e2e/provider.ts | 4 ++++ src/utils/auth.ts | 5 ++++- src/utils/cli.ts | 12 ++++++++---- test/unit/auth.test.ts | 4 +++- test/unit/e2e-provider.test.ts | 2 ++ test/unit/runtime.test.ts | 18 ++++++++++++++++++ 8 files changed, 43 insertions(+), 8 deletions(-) create mode 100644 test/unit/runtime.test.ts diff --git a/CLAUDE.md b/CLAUDE.md index 8cb26af..0575094 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -43,7 +43,7 @@ Top-level `defineCommand` in `src/index.ts` wires fifteen subcommands (`cloud`, **Cloud command workflow** (the canonical shape other commands mirror): upload binary with SHA dedup → extract metadata / validate devices → build execution plan → submit tests → poll results every 10s → download artifacts (reports/videos/logs). `RunFailedError` from the polling service is the signal for a failed test run (distinct from infra errors). -**Auth.** Every command calls `resolveAuth({ apiKeyFlag })` (`src/utils/auth.ts`) once and threads the returned `AuthContext` into gateways/services. `ApiGateway` and `fetchCompatibilityData` spread `auth.headers` into fetch headers — they no longer accept a raw api key. The same headers carry the CLI's identity on every request (`x-dcd-cli-version`, plus `x-dcd-ci-provider` / `x-dcd-ci-wrapper-version` from `detectCiContext`), which the API uses for notice targeting and records on each upload and binary (dcd#1622). Precedence: `--api-key` flag > `DEVICE_CLOUD_API_KEY` env > stored session from `dcd login`. `resolveAuth` refreshes expiring Supabase sessions via `CliAuthGateway.refresh`, which posts the refresh token to the API's `POST /cli-login/refresh` (no Supabase key needed; a 401 or 400 is final, anything else keeps the stored session for a retry), and rewrites the config atomically. A session's access token lasts about an hour, so code that can outlive it re-checks with `isAuthExpiring` / `refreshAuth`: the `dcd cloud` poll loop and the report downloads after it, the MCP context, and `dcd_run_cloud_test`'s wait loop. `refreshAuth` keeps the org the command started with and leaves API-key contexts untouched. +**Auth.** Every command calls `resolveAuth({ apiKeyFlag })` (`src/utils/auth.ts`) once and threads the returned `AuthContext` into gateways/services. `ApiGateway` and `fetchCompatibilityData` spread `auth.headers` into fetch headers — they no longer accept a raw api key. The same headers carry the CLI's identity on every request (`x-dcd-cli-version`, `x-dcd-cli-runtime` (`bun` for the standalone binary, `node` for the npm package, from `getRuntime`), plus `x-dcd-ci-provider` / `x-dcd-ci-wrapper-version` from `detectCiContext`), which the API uses for notice targeting and records on each upload and binary (dcd#1622). Precedence: `--api-key` flag > `DEVICE_CLOUD_API_KEY` env > stored session from `dcd login`. `resolveAuth` refreshes expiring Supabase sessions via `CliAuthGateway.refresh`, which posts the refresh token to the API's `POST /cli-login/refresh` (no Supabase key needed; a 401 or 400 is final, anything else keeps the stored session for a retry), and rewrites the config atomically. A session's access token lasts about an hour, so code that can outlive it re-checks with `isAuthExpiring` / `refreshAuth`: the `dcd cloud` poll loop and the report downloads after it, the MCP context, and `dcd_run_cloud_test`'s wait loop. `refreshAuth` keeps the org the command started with and leaves API-key contexts untouched. **Config store.** `dcd login` writes `$XDG_CONFIG_HOME/dcd/config.json` (fallback `~/.dcd/config.json`, 0600). Shape: `{ version, env, api_url, supabase_url, session: { access_token, refresh_token, expires_at, user_email, user_id }, current_org_id, current_org_name }`. `DCD_CONFIG_DIR` overrides the directory (used by tests). The login command itself (`src/commands/login.ts`) uses PKCE (S256) with a server rendezvous — no loopback server: it mints `state`, `code_verifier`, and `code_challenge`, opens `/cli-login?state=...&code_challenge=...`, then polls the dcd API's `POST /cli-login/claim` with `{state, code_verifier}` while the frontend POSTs proof of identity (the browser's access token) to `POST /cli-login/handoff`; the API verifies the token, **mints a dedicated Supabase session for the CLI** (its own refresh-token family — sharing the browser's tokens caused "Invalid Refresh Token: Already Used" whenever either client rotated them), stores it keyed by state, then on claim verifies `sha256(verifier) === challenge` and returns it. After claiming, the CLI fetches `/me/orgs` and picks the org with `selectOrg` (`src/utils/orgs.ts`): `--org ` if given, else the only org, else the picker `dcd switch-org` uses, starting on the last login's org. That org only counts when the stored `api_url` matches, because org ids are per environment. Without a TTY (`canPrompt` in `src/utils/ci.ts`) the prompts can't be answered: the "already logged in" confirm takes its default and signs in again, the last login's org is used, and with none the command fails pointing at `--org`. `dcd logout` deletes the whole config, so nothing is remembered after it. The frontend lives in `../dcd/frontend/app/features/cli-login/CliLoginScreen.tsx`. diff --git a/src/e2e/index.ts b/src/e2e/index.ts index febcb7d..1a90475 100644 --- a/src/e2e/index.ts +++ b/src/e2e/index.ts @@ -16,7 +16,7 @@ * Importing this module has no side effects; it does not start the CLI. */ import { uploadLocalApp } from '../utils/app-upload.js'; -import { getCliVersion } from '../utils/cli.js'; +import { getCliVersion, getRuntime } from '../utils/cli.js'; import { createProvider, @@ -50,6 +50,7 @@ export function deviceCloud( headers: { 'x-app-api-key': apiKey, 'x-dcd-cli-version': getCliVersion(), + 'x-dcd-cli-runtime': getRuntime(), }, mode: 'apiKey', }, @@ -57,6 +58,7 @@ export function deviceCloud( log, showProgress: false, }), + runtime: getRuntime(), version: getCliVersion(), }); } diff --git a/src/e2e/provider.ts b/src/e2e/provider.ts index 96e4a78..db56495 100644 --- a/src/e2e/provider.ts +++ b/src/e2e/provider.ts @@ -24,6 +24,7 @@ * `mobile({ device })`. */ import { checkApiUrl } from '../utils/api-url.js'; +import type { CliRuntime } from '../utils/cli.js'; /** What e2e asks for: one device for one worker slot of a run. */ export interface E2eDeviceRequest { @@ -137,6 +138,8 @@ export interface ProviderDeps { }) => Promise; /** Sent as `x-dcd-cli-version`, so the API knows which provider version called. */ version: string; + /** Sent as `x-dcd-cli-runtime`: what the test runner runs on, `bun` or `node`. */ + runtime: CliRuntime; /** Between polls. */ pollMs: number; /** How long a session may take to be ready: queued, starting, installing. */ @@ -276,6 +279,7 @@ export function createProvider( headers: { 'x-app-api-key': apiKey, 'x-dcd-cli-version': deps.version, + 'x-dcd-cli-runtime': deps.runtime, 'x-dcd-source': 'cli', ...(body === undefined ? {} diff --git a/src/utils/auth.ts b/src/utils/auth.ts index 1875c41..bd2e8bf 100644 --- a/src/utils/auth.ts +++ b/src/utils/auth.ts @@ -19,7 +19,7 @@ import { telemetry } from '../services/telemetry.service.js'; import type { AuthContext } from '../types/domain/auth.types.js'; import { detectCiContext } from './ci.js'; -import { CliError, getCliVersion } from './cli.js'; +import { CliError, getCliVersion, getRuntime } from './cli.js'; import { StoredConfig, StoredSession, @@ -63,12 +63,15 @@ export function apiKeyOverride( /** * Who is calling, sent with every request next to the credential: the API * targets notices by it and records it on each upload and binary. + * The runtime tells the standalone binary (`bun`) from the npm package + * (`node`) at the same version. * The CI headers are sent only when a DCD wrapper forwarded them or the * provider could be inferred. */ function clientHeaders(): Record { const headers: Record = { 'x-dcd-cli-version': getCliVersion(), + 'x-dcd-cli-runtime': getRuntime(), }; const ci = detectCiContext(); if (ci.provider) headers['x-dcd-ci-provider'] = ci.provider; diff --git a/src/utils/cli.ts b/src/utils/cli.ts index 71d6da9..edb3bd0 100644 --- a/src/utils/cli.ts +++ b/src/utils/cli.ts @@ -37,13 +37,17 @@ export function getCliVersion(): string { } export type InstallMethod = 'binary' | 'npm'; +export type CliRuntime = 'bun' | 'node'; // The Bun runtime sets process.versions.bun; bun-compiled standalone binaries -// inherit this. Node-run installs (npm/pnpm/npx/tsx) don't expose it. +// inherit this. Node-run installs (npm/pnpm/npx/tsx) don't expose it. Sent to +// the API as `x-dcd-cli-runtime`, so a bug in one build can be counted. +export function getRuntime(versions: object = process.versions): CliRuntime { + return typeof (versions as { bun?: unknown }).bun === 'string' ? 'bun' : 'node'; +} + export function getInstallMethod(): InstallMethod { - return typeof (process.versions as { bun?: string }).bun === 'string' - ? 'binary' - : 'npm'; + return getRuntime() === 'bun' ? 'binary' : 'npm'; } export function getUpgradeCommand(): string { diff --git a/test/unit/auth.test.ts b/test/unit/auth.test.ts index ba8c808..eef2820 100644 --- a/test/unit/auth.test.ts +++ b/test/unit/auth.test.ts @@ -290,7 +290,7 @@ describe('resolveAuth client identity headers', () => { process.env = { ...ORIGINAL_ENV }; }); - it('sends the CLI version on the --api-key, env and session paths', async () => { + it('sends the CLI version and runtime on the --api-key, env and session paths', async () => { await withTempConfigDir(async () => { writeConfig({ version: 1, @@ -314,6 +314,8 @@ describe('resolveAuth client identity headers', () => { for (const auth of [flag, env, session]) { expect(auth.headers['x-dcd-cli-version']).to.equal(cliVersion); + // The suite runs under Node, so this is the npm package's value. + expect(auth.headers['x-dcd-cli-runtime']).to.equal('node'); expect(auth.headers).to.not.have.property('x-dcd-ci-provider'); expect(auth.headers).to.not.have.property('x-dcd-ci-wrapper-version'); } diff --git a/test/unit/e2e-provider.test.ts b/test/unit/e2e-provider.test.ts index fbae704..49ef45e 100644 --- a/test/unit/e2e-provider.test.ts +++ b/test/unit/e2e-provider.test.ts @@ -98,6 +98,7 @@ function setup( uploads.push(filePath); return 'uploaded-binary-id'; }, + runtime: 'node', version: '9.9.9', ...deps, }); @@ -159,6 +160,7 @@ describe('the e2e device provider', () => { expect(start.headers).to.include({ 'x-app-api-key': 'key-from-env', 'x-dcd-cli-version': '9.9.9', + 'x-dcd-cli-runtime': 'node', }); // Two reads until ready, then the engine twice (425, then 200). Nothing stopped. expect(api.calls.map((c) => `${c.method} ${c.path}`)).to.deep.equal([ diff --git a/test/unit/runtime.test.ts b/test/unit/runtime.test.ts new file mode 100644 index 0000000..4077026 --- /dev/null +++ b/test/unit/runtime.test.ts @@ -0,0 +1,18 @@ +import { expect } from 'chai'; + +import { getInstallMethod, getRuntime } from '../../src/utils/cli.js'; + +describe('getRuntime', () => { + it('is bun when the runtime reports a Bun version', () => { + expect(getRuntime({ node: '24.3.0', bun: '1.4.5' })).to.equal('bun'); + }); + + it('is node when there is no Bun version', () => { + expect(getRuntime({ node: '24.3.0' })).to.equal('node'); + }); + + it('is node for this suite, which runs under Node', () => { + expect(getRuntime()).to.equal('node'); + expect(getInstallMethod()).to.equal('npm'); + }); +}); From 1d3f2b4a525f6dc936d5f2deff40eb079593fa06 Mon Sep 17 00:00:00 2001 From: Tom Riglar Date: Fri, 4 Dec 2026 10:49:43 +0000 Subject: [PATCH 08/12] feat(upload): record iOS executable architectures in binary metadata (#380) * feat(upload): record iOS executable architectures in binary metadata Read the Mach-O header of the app's main executable (CFBundleExecutable) and send its CPU families as `architectures`, the same field APKs already use. Only the first 4 KB of the executable is inflated. An iOS simulator build with only an x86_64 slice runs under Rosetta on Apple Silicon. Apple removes general-purpose Rosetta in macOS 28, so the platform needs to know which builds have no arm64 slice before hosts move there (dcd#1511). The CLI sees the build before it is encrypted, so this works for encrypted uploads too. Unknown stays unknown: a missing or unreadable executable leaves the field out and never fails the upload. Co-Authored-By: Claude Opus 5.5 * docs(types): drop a private issue reference from the architectures comment Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- src/services/metadata-extractor.service.ts | 207 +++++++++++++++---- src/types.ts | 6 +- test/unit/metadata-extractor.service.test.ts | 187 +++++++++++++++++ 3 files changed, 353 insertions(+), 47 deletions(-) diff --git a/src/services/metadata-extractor.service.ts b/src/services/metadata-extractor.service.ts index 533c466..5ad4143 100644 --- a/src/services/metadata-extractor.service.ts +++ b/src/services/metadata-extractor.service.ts @@ -1,6 +1,7 @@ import { parseBuffer } from 'bplist-parser'; -import { readFile, rm } from 'node:fs/promises'; +import { open, readFile, rm } from 'node:fs/promises'; import * as path from 'node:path'; +import type { Readable } from 'node:stream'; import StreamZip from 'node-stream-zip'; import { parse } from 'plist'; @@ -12,7 +13,11 @@ export interface TAppMetadata { /** APK only: the native ABIs shipped under `lib//`, sorted. */ abis?: string[]; appId: string; - /** APK only: the CPU families the APK can run on. See `apkArchitectures`. */ + /** + * The CPU families the app can run on. APK: see `apkArchitectures`. iOS: + * the slices in the main executable, see `machOArchitectures`. Left out when + * an iOS executable can't be read. + */ architectures?: CpuArchitecture[]; platform: 'android' | 'ios'; } @@ -29,7 +34,10 @@ export interface IMetadataExtractor { * Parses an Info.plist buffer (XML, UTF-8 BOM'd XML, or binary bplist). * Shared by the .app and .zip extractors. */ -function parseInfoPlist(buffer: Buffer): { CFBundleIdentifier: string } { +function parseInfoPlist(buffer: Buffer): { + CFBundleExecutable?: string; + CFBundleIdentifier: string; +} { let data; const bufferType = buffer[0]; // 60 = '<' (XML plist), 239 = UTF-8 BOM, 98 = 'b' (binary "bplist") @@ -44,6 +52,121 @@ function parseInfoPlist(buffer: Buffer): { CFBundleIdentifier: string } { return data; } +/** + * How many bytes of an iOS executable to read. A fat header is 8 bytes plus + * 20 (or 32) per slice, and a thin header puts the CPU type at byte 4, so + * this covers any real binary many times over. + */ +export const MACH_O_HEADER_BYTES = 4096; + +const CPU_ARCH_ABI64 = 0x01_00_00_00; +const CPU_TYPE_X86 = 7; +const CPU_TYPE_ARM = 12; + +function cpuFamily(cpuType: number): CpuArchitecture | undefined { + switch (cpuType & ~CPU_ARCH_ABI64) { + case CPU_TYPE_ARM: { + return 'arm'; + } + + case CPU_TYPE_X86: { + return 'x86'; + } + + default: { + return undefined; + } + } +} + +/** + * The CPU families in a Mach-O executable, from the start of the file: one + * for a thin binary, one per slice for a fat (universal) one. Undefined when + * the bytes are not a Mach-O header we know. + * + * WHY: an iOS simulator build with only an x86_64 slice runs under Rosetta on + * an Apple Silicon Mac. Apple drops general-purpose Rosetta in macOS 28, so + * the platform needs to know which uploads have no arm64 slice before its + * hosts move there. Simulator and device arm64 slices share a CPU type; a + * device-only build never reaches a simulator, so `arm` is enough. + */ +export function machOArchitectures(header: Buffer): CpuArchitecture[] | undefined { + if (header.length < 8) return undefined; + const found = new Set(); + const magicBE = header.readUInt32BE(0); + + if (magicBE === 0xca_fe_ba_be || magicBE === 0xca_fe_ba_bf) { + // Fat header: big-endian, then one fat_arch (20 bytes) or fat_arch_64 + // (32 bytes) per slice, each starting with its CPU type. + const stride = magicBE === 0xca_fe_ba_be ? 20 : 32; + const count = header.readUInt32BE(4); + if (count === 0 || 8 + count * stride > header.length) return undefined; + for (let i = 0; i < count; i++) { + const family = cpuFamily(header.readUInt32BE(8 + i * stride)); + if (family) found.add(family); + } + } else { + // Thin header: 0xfeedface / 0xfeedfacf, stored little-endian on every + // CPU Apple ships, with the CPU type straight after the magic. + const magicLE = header.readUInt32LE(0); + if (magicLE !== 0xfe_ed_fa_ce && magicLE !== 0xfe_ed_fa_cf) return undefined; + const family = cpuFamily(header.readUInt32LE(4)); + if (family) found.add(family); + } + + return (['arm', 'x86'] as const).filter((arch) => found.has(arch)); +} + +/** The first `bytes` bytes of a file, or fewer if it is shorter. */ +async function readFileStart(filePath: string, bytes: number): Promise { + const handle = await open(filePath, 'r'); + try { + const buffer = Buffer.alloc(bytes); + const { bytesRead } = await handle.read(buffer, 0, bytes, 0); + return buffer.subarray(0, bytesRead); + } finally { + await handle.close(); + } +} + +/** The first `bytes` bytes of a zip entry, without inflating the rest of it. */ +async function readZipEntryStart( + zip: InstanceType, + name: string, + bytes: number, +): Promise { + // node-stream-zip types it as NodeJS.ReadableStream; it is a Readable. + const stream = (await zip.stream(name)) as Readable; + const chunks: Buffer[] = []; + let total = 0; + try { + for await (const chunk of stream) { + const buffer = chunk as Buffer; + chunks.push(buffer); + total += buffer.length; + if (total >= bytes) break; + } + } finally { + stream.destroy(); + } + + return Buffer.concat(chunks).subarray(0, bytes); +} + +/** Adds `architectures` when the executable's header can be read. */ +async function withArchitectures( + metadata: TAppMetadata, + readHeader: () => Promise, +): Promise { + try { + const architectures = machOArchitectures(await readHeader()); + return architectures ? { ...metadata, architectures } : metadata; + } catch { + // Unknown is fine: the platform treats a missing value as "runs anywhere". + return metadata; + } +} + const ABI_ARCHITECTURE: Record = { armeabi: 'arm', 'armeabi-v7a': 'arm', @@ -144,8 +267,12 @@ export class IosAppMetadataExtractor implements IMetadataExtractor { const infoPlistPath = path.normalize(path.join(filePath, 'Info.plist')); const buffer = await readFile(infoPlistPath); const data = parseInfoPlist(buffer); - const appId = data.CFBundleIdentifier; - return { appId, platform: 'ios' }; + const metadata: TAppMetadata = { appId: data.CFBundleIdentifier, platform: 'ios' }; + const executable = data.CFBundleExecutable; + if (!executable) return metadata; + return withArchitectures(metadata, () => + readFileStart(path.join(filePath, executable), MACH_O_HEADER_BYTES), + ); } } @@ -158,46 +285,36 @@ export class IosZipMetadataExtractor implements IMetadataExtractor { } async extract(filePath: string): Promise { - return new Promise((resolve, reject) => { - const zip = new StreamZip({ file: filePath }); - - // A throw inside an emitter callback escapes the caller's try/catch and - // crashes the process, so route all failures through reject explicitly. - zip.on('ready', () => { - try { - // Get all entries and sort them by path depth - const entries = Object.values(zip.entries()); - const sortedEntries = entries.sort((a, b) => { - const aDepth = a.name.split('/').length; - const bDepth = b.name.split('/').length; - return aDepth - bDepth; - }); - - // Find the first Info.plist in the shallowest directory - const infoPlist = sortedEntries.find((e) => - e.name.endsWith('.app/Info.plist'), - ); - - if (!infoPlist) { - reject(new Error('Failed to find info plist')); - return; - } - - const buffer = zip.entryDataSync(infoPlist.name); - const data = parseInfoPlist(buffer); - resolve({ appId: data.CFBundleIdentifier, platform: 'ios' }); - } catch (error) { - reject(error); - } finally { - zip.close(); - } - }); - - zip.on('error', (error) => { - zip.close(); - reject(error); - }); - }); + const zip = new StreamZip.async({ file: filePath }); + try { + // The first Info.plist in the shallowest directory is the app's own; + // deeper ones belong to frameworks and plugins inside it. + const entries = Object.values(await zip.entries()); + const infoPlist = entries + .filter((e) => e.name.endsWith('.app/Info.plist')) + .sort((a, b) => a.name.split('/').length - b.name.split('/').length)[0]; + + if (!infoPlist) { + throw new Error('Failed to find info plist'); + } + + const data = parseInfoPlist(await zip.entryData(infoPlist.name)); + const metadata: TAppMetadata = { + appId: data.CFBundleIdentifier, + platform: 'ios', + }; + const executable = data.CFBundleExecutable; + if (!executable) return metadata; + const executableEntry = path.posix.join( + path.posix.dirname(infoPlist.name), + executable, + ); + return await withArchitectures(metadata, () => + readZipEntryStart(zip, executableEntry, MACH_O_HEADER_BYTES), + ); + } finally { + await zip.close().catch(() => {}); + } } } diff --git a/src/types.ts b/src/types.ts index 96ea274..16760de 100644 --- a/src/types.ts +++ b/src/types.ts @@ -9,8 +9,10 @@ export type TAppMetadata = { abis?: string[]; appId: string; /** - * APK only: the CPU families the APK can run on, `arm`, `x86` or both. - * Stored on `binaries.metadata.architectures`. Both when it has no native code. + * The CPU families the app can run on, `arm`, `x86` or both. APK: from its + * native ABIs, both when it has none. iOS: the slices in the main executable, + * left out when it can't be read. + * Stored on `binaries.metadata.architectures`. */ architectures?: CpuArchitecture[]; platform: 'android' | 'ios'; diff --git a/test/unit/metadata-extractor.service.test.ts b/test/unit/metadata-extractor.service.test.ts index 7978632..e1fbbb6 100644 --- a/test/unit/metadata-extractor.service.test.ts +++ b/test/unit/metadata-extractor.service.test.ts @@ -3,14 +3,71 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; +import yazl from 'yazl'; + import { AndroidMetadataExtractor, apkAbis, apkArchitectures, + IosAppMetadataExtractor, + IosZipMetadataExtractor, + machOArchitectures, MetadataExtractorService, } from '../../src/services/metadata-extractor.service.js'; const WIKIPEDIA_APK = path.resolve('test/fixtures/wikipedia.apk'); +// Its main executable is x86_64 only (`lipo -archs` says so). +const WIKIPEDIA_IOS_ZIP = path.resolve('test/fixtures/wikipedia.zip'); + +const CPU_X86_64 = 0x01_00_00_07; +const CPU_ARM64 = 0x01_00_00_0c; + +/** A thin 64-bit Mach-O header for one CPU type, padded like a real file. */ +function thinMachO(cpuType: number): Buffer { + const buffer = Buffer.alloc(64); + buffer.writeUInt32LE(0xfe_ed_fa_cf, 0); + buffer.writeUInt32LE(cpuType, 4); + return buffer; +} + +/** A fat header with one slice per CPU type. */ +function fatMachO(cpuTypes: number[], wide = false): Buffer { + const stride = wide ? 32 : 20; + const buffer = Buffer.alloc(8 + cpuTypes.length * stride + 64); + buffer.writeUInt32BE(wide ? 0xca_fe_ba_bf : 0xca_fe_ba_be, 0); + buffer.writeUInt32BE(cpuTypes.length, 4); + for (const [i, cpuType] of cpuTypes.entries()) { + buffer.writeUInt32BE(cpuType, 8 + i * stride); + } + + return buffer; +} + +function infoPlist(executable?: string): Buffer { + const exe = executable + ? `CFBundleExecutable${executable}` + : ''; + return Buffer.from( + `` + + `CFBundleIdentifiercom.example.app${exe}` + + ``, + ); +} + +async function writeZip( + zipPath: string, + files: Record, +): Promise { + const zip = new yazl.ZipFile(); + for (const [name, data] of Object.entries(files)) zip.addBuffer(data, name); + zip.end(); + await new Promise((resolve, reject) => { + zip.outputStream + .pipe(fs.createWriteStream(zipPath)) + .on('close', resolve) + .on('error', reject); + }); +} describe('AndroidMetadataExtractor', () => { const extractor = new AndroidMetadataExtractor(); @@ -126,3 +183,133 @@ describe('MetadataExtractorService (APK path)', () => { } }); }); + +describe('machOArchitectures', () => { + it('reads a thin arm64 binary', () => { + expect(machOArchitectures(thinMachO(CPU_ARM64))).to.deep.equal(['arm']); + }); + + it('reads a thin x86_64 binary', () => { + expect(machOArchitectures(thinMachO(CPU_X86_64))).to.deep.equal(['x86']); + }); + + it('reads every slice of a fat binary', () => { + expect(machOArchitectures(fatMachO([CPU_X86_64, CPU_ARM64]))).to.deep.equal([ + 'arm', + 'x86', + ]); + }); + + it('reads a fat binary with 64-bit slice entries', () => { + expect(machOArchitectures(fatMachO([CPU_ARM64], true))).to.deep.equal(['arm']); + }); + + it('is undefined for bytes that are not Mach-O', () => { + expect(machOArchitectures(Buffer.from('#!/bin/sh\necho hi\n'))).to.equal( + undefined, + ); + expect(machOArchitectures(Buffer.alloc(4))).to.equal(undefined); + }); + + it('is undefined for a fat header whose slices run past the bytes read', () => { + const header = fatMachO([CPU_ARM64]); + header.writeUInt32BE(10_000, 4); + expect(machOArchitectures(header)).to.equal(undefined); + }); +}); + +describe('IosZipMetadataExtractor', () => { + const extractor = new IosZipMetadataExtractor(); + let tempDir: string; + + beforeEach(() => { + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'dcd-ios-zip-test-')); + }); + + afterEach(() => { + fs.rmSync(tempDir, { recursive: true, force: true }); + }); + + it('records the executable of a real x86_64-only simulator build', async () => { + const result = await extractor.extract(WIKIPEDIA_IOS_ZIP); + expect(result).to.deep.equal({ + appId: 'org.wikimedia.wikipedia', + architectures: ['x86'], + platform: 'ios', + }); + }); + + it('reads the app executable, not a nested framework', async () => { + const zipPath = path.join(tempDir, 'app.zip'); + await writeZip(zipPath, { + 'Build/Products/My.app/Frameworks/X.framework/Info.plist': infoPlist('X'), + 'Build/Products/My.app/Frameworks/X.framework/X': thinMachO(CPU_X86_64), + 'Build/Products/My.app/Info.plist': infoPlist('My'), + 'Build/Products/My.app/My': fatMachO([CPU_ARM64, CPU_X86_64]), + }); + const result = await extractor.extract(zipPath); + expect(result).to.deep.equal({ + appId: 'com.example.app', + architectures: ['arm', 'x86'], + platform: 'ios', + }); + }); + + it('leaves architectures out when the executable is missing or unreadable', async () => { + const missing = path.join(tempDir, 'missing.zip'); + await writeZip(missing, { 'My.app/Info.plist': infoPlist('My') }); + expect(await extractor.extract(missing)).to.deep.equal({ + appId: 'com.example.app', + platform: 'ios', + }); + + const notMachO = path.join(tempDir, 'script.zip'); + await writeZip(notMachO, { + 'My.app/Info.plist': infoPlist('My'), + 'My.app/My': Buffer.from('#!/bin/sh\n'), + }); + expect(await extractor.extract(notMachO)).to.deep.equal({ + appId: 'com.example.app', + platform: 'ios', + }); + + const noKey = path.join(tempDir, 'nokey.zip'); + await writeZip(noKey, { 'My.app/Info.plist': infoPlist() }); + expect(await extractor.extract(noKey)).to.deep.equal({ + appId: 'com.example.app', + platform: 'ios', + }); + }); + + it('rejects a zip with no app bundle', async () => { + const zipPath = path.join(tempDir, 'empty.zip'); + await writeZip(zipPath, { 'README.txt': Buffer.from('hi') }); + let threw = false; + try { + await extractor.extract(zipPath); + } catch { + threw = true; + } + + expect(threw).to.equal(true); + }); +}); + +describe('IosAppMetadataExtractor', () => { + it('records the executable architectures of an .app directory', async () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'dcd-ios-app-test-')); + try { + const appDir = path.join(tempDir, 'My.app'); + fs.mkdirSync(appDir); + fs.writeFileSync(path.join(appDir, 'Info.plist'), infoPlist('My')); + fs.writeFileSync(path.join(appDir, 'My'), thinMachO(CPU_ARM64)); + expect(await new IosAppMetadataExtractor().extract(appDir)).to.deep.equal({ + appId: 'com.example.app', + architectures: ['arm'], + platform: 'ios', + }); + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }); +}); From 9807beb566246729822d8709025534f538315139 Mon Sep 17 00:00:00 2001 From: finalerock44 <77282157+finalerock44@users.noreply.github.com> Date: Fri, 4 Dec 2026 13:40:32 +0000 Subject: [PATCH 09/12] build: pin Bun for release binaries (#381) The standalone binaries embed the Bun runtime, and both release workflows installed it from a floating '1.3' range, so a release could pick up a new runtime without any change in this repo. Pin it exactly in .bun-version (1.4.5) and read that file from both workflows. Also ignore dist-bin/ and Bun's *.bun-build temp files. --- .bun-version | 1 + .github/workflows/release-beta.yml | 4 +++- .github/workflows/release-binaries.yml | 4 +++- .gitignore | 2 ++ CLAUDE.md | 2 +- 5 files changed, 10 insertions(+), 3 deletions(-) create mode 100644 .bun-version diff --git a/.bun-version b/.bun-version new file mode 100644 index 0000000..e516bb9 --- /dev/null +++ b/.bun-version @@ -0,0 +1 @@ +1.4.5 diff --git a/.github/workflows/release-beta.yml b/.github/workflows/release-beta.yml index a42a53f..f51fc01 100644 --- a/.github/workflows/release-beta.yml +++ b/.github/workflows/release-beta.yml @@ -129,10 +129,12 @@ jobs: node -e 'const fs=require("node:fs");const p=JSON.parse(fs.readFileSync("package.json","utf8"));p.version=process.env.VERSION;fs.writeFileSync("package.json",JSON.stringify(p,null,2)+"\n")' node -p '"package.json is now " + require("./package.json").version' + # Bun is compiled into every binary we ship, so its version is pinned + # exactly in .bun-version rather than floating with a minor range. - name: Setup Bun uses: oven-sh/setup-bun@v2 with: - bun-version: '1.3' + bun-version-file: .bun-version # Built before anything is published so a broken build fails the run # without leaving a half-release behind. build-binaries.mjs stamps diff --git a/.github/workflows/release-binaries.yml b/.github/workflows/release-binaries.yml index 251ff77..39f200c 100644 --- a/.github/workflows/release-binaries.yml +++ b/.github/workflows/release-binaries.yml @@ -40,10 +40,12 @@ jobs: - run: pnpm install --frozen-lockfile + # Bun is compiled into every binary we ship, so its version is pinned + # exactly in .bun-version rather than floating with a minor range. - name: Setup Bun uses: oven-sh/setup-bun@v2 with: - bun-version: '1.3' + bun-version-file: .bun-version - name: Build binaries for all platforms run: node scripts/build-binaries.mjs diff --git a/.gitignore b/.gitignore index 864dab5..1a5bc18 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,8 @@ /.idea /.nyc_output /dist +/dist-bin +*.bun-build /lib /package-lock.json /tmp diff --git a/CLAUDE.md b/CLAUDE.md index 0575094..627eac5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -6,7 +6,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co - `pnpm dcd ` — run the CLI from source via `tsx`. - `pnpm build` — clean, compile TypeScript to `dist/`, and `chmod +x dist/index.js dist/mcp/index.js` so both published binaries are directly executable. -- `pnpm build:binaries` — `scripts/build-binaries.mjs` produces the bun-compiled, self-contained `dcd--` binaries published to GitHub Releases (the install `dcd upgrade` self-updates). The platform/arch keys must stay in sync with `ASSET_BY_PLATFORM` in `src/commands/upgrade.ts`. +- `pnpm build:binaries` — `scripts/build-binaries.mjs` produces the bun-compiled, self-contained `dcd--` binaries published to GitHub Releases (the install `dcd upgrade` self-updates). The platform/arch keys must stay in sync with `ASSET_BY_PLATFORM` in `src/commands/upgrade.ts`. The Bun that compiles them is pinned exactly in `.bun-version`, which both release workflows read; bump it in its own PR and cut a beta before a stable release ships it. - `pnpm lint` — ESLint over `src/` and `test/`. - `pnpm typecheck` — `tsc --noEmit -p tsconfig.test.json` over `src/` and `test/` (strict mode; `pnpm build` only compiles `src/`). Requires Node `>=22.8`. - `pnpm test` — runs `scripts/test-runner.mjs`: builds the CLI, boots the mock API if one is available, then runs mocha. TypeScript is loaded by **tsx** (`.mocharc.json`'s `node-option: ["import=tsx"]`), *not* ts-node — Mocha 11 imports specs as ESM, which bypasses the `require: ts-node/register` hook. The runner isolates `DCD_CONFIG_DIR` to a temp dir so tests never touch your real `dcd login` session. From 9da76376df9bd61bfc31fbea3b37ad51f9968ce5 Mon Sep 17 00:00:00 2001 From: finalerock44 <77282157+finalerock44@users.noreply.github.com> Date: Fri, 4 Dec 2026 13:40:32 +0000 Subject: [PATCH 10/12] feat: sign release binaries (#382) * feat: sign standalone release binaries and verify signatures on upgrade and install Every standalone release now carries SHA256SUMS.sig: an ECDSA P-256 and an ML-DSA-65 signature over the release version and the SHA-256 of SHA256SUMS. The public keys are built into the CLI and the install scripts, and are in release-keys/. - dcd upgrade checks both signatures before it downloads the binary, then checks the binary against the signed SHA256SUMS. A release with no signature, a bad signature, or a signature for another version is refused and the running binary is left alone. - install.sh and install.ps1 check the P-256 signature. A bad signature always aborts. A missing signature is fatal from the first signed release on; for older pinned versions, or with no openssl on the machine, they warn, and DCD_REQUIRE_SIGNATURE=1 makes that fatal too. - Stable releases are signed from production in the cli-release-signing environment, betas from dev in cli-beta-signing with keys that are only valid for prerelease versions. Signing runs in its own job with no write token and no package install; a keyless job checks the result on the pinned Bun before anything is uploaded. - Betas are cut from dev only. * ci: take the pnpm version from packageManager in the signing test jobs * test: give each PowerShell its own PSModulePath in the install.ps1 tests * test: pass the shell key ids from the source keys, not from file names --- .gitattributes | 3 + .github/workflows/cli-ci.yml | 64 +++ .github/workflows/release-beta.yml | 275 +++++++++--- .github/workflows/release-binaries.yml | 189 +++++++- CLAUDE.md | 6 + SECURITY.md | 34 ++ install.ps1 | 194 ++++++++- install.sh | 219 +++++++++- release-keys/beta-mldsa65-a.pem | 44 ++ release-keys/beta-p256-a.pem | 4 + release-keys/stable-mldsa65-a.pem | 44 ++ release-keys/stable-mldsa65-b.pem | 44 ++ release-keys/stable-p256-a.pem | 4 + release-keys/stable-p256-b.pem | 4 + scripts/build-binaries.mjs | 4 +- scripts/sign-release.d.mts | 21 + scripts/sign-release.mjs | 145 +++++++ scripts/verify-release.ts | 107 +++++ src/commands/upgrade.ts | 182 ++++++-- src/config/release-keys.ts | 207 +++++++++ src/utils/release-signature.ts | 235 ++++++++++ .../release-signature/beta/SHA256SUMS | 5 + .../release-signature/beta/SHA256SUMS.sig | 3 + .../release-signature/beta/dcd-darwin-arm64 | 2 + .../release-signature/beta/dcd-darwin-x64 | 2 + .../release-signature/beta/dcd-linux-arm64 | 2 + .../release-signature/beta/dcd-linux-x64 | 2 + .../beta/dcd-windows-x64.exe | 2 + test/fixtures/release-signature/generate.mjs | 69 +++ test/fixtures/release-signature/keys.json | 22 + .../release-signature/stable/SHA256SUMS | 5 + .../release-signature/stable/SHA256SUMS.sig | 3 + .../release-signature/stable/dcd-darwin-arm64 | 2 + .../release-signature/stable/dcd-darwin-x64 | 2 + .../release-signature/stable/dcd-linux-arm64 | 2 + .../release-signature/stable/dcd-linux-x64 | 2 + .../stable/dcd-windows-x64.exe | 2 + .../release-signature/test-beta-p256-a.pem | 4 + .../release-signature/test-stable-p256-a.pem | 4 + test/helpers/release-fixture-server.ts | 94 ++++ test/unit/install-ps1.test.ts | 178 ++++++++ test/unit/install-sh.test.ts | 277 ++++++++++++ test/unit/release-signature.test.ts | 404 ++++++++++++++++++ test/unit/upgrade.test.ts | 179 ++++++++ 44 files changed, 3142 insertions(+), 154 deletions(-) create mode 100644 .gitattributes create mode 100644 release-keys/beta-mldsa65-a.pem create mode 100644 release-keys/beta-p256-a.pem create mode 100644 release-keys/stable-mldsa65-a.pem create mode 100644 release-keys/stable-mldsa65-b.pem create mode 100644 release-keys/stable-p256-a.pem create mode 100644 release-keys/stable-p256-b.pem create mode 100644 scripts/sign-release.d.mts create mode 100644 scripts/sign-release.mjs create mode 100644 scripts/verify-release.ts create mode 100644 src/config/release-keys.ts create mode 100644 src/utils/release-signature.ts create mode 100644 test/fixtures/release-signature/beta/SHA256SUMS create mode 100644 test/fixtures/release-signature/beta/SHA256SUMS.sig create mode 100755 test/fixtures/release-signature/beta/dcd-darwin-arm64 create mode 100755 test/fixtures/release-signature/beta/dcd-darwin-x64 create mode 100755 test/fixtures/release-signature/beta/dcd-linux-arm64 create mode 100755 test/fixtures/release-signature/beta/dcd-linux-x64 create mode 100755 test/fixtures/release-signature/beta/dcd-windows-x64.exe create mode 100644 test/fixtures/release-signature/generate.mjs create mode 100644 test/fixtures/release-signature/keys.json create mode 100644 test/fixtures/release-signature/stable/SHA256SUMS create mode 100644 test/fixtures/release-signature/stable/SHA256SUMS.sig create mode 100755 test/fixtures/release-signature/stable/dcd-darwin-arm64 create mode 100755 test/fixtures/release-signature/stable/dcd-darwin-x64 create mode 100755 test/fixtures/release-signature/stable/dcd-linux-arm64 create mode 100755 test/fixtures/release-signature/stable/dcd-linux-x64 create mode 100755 test/fixtures/release-signature/stable/dcd-windows-x64.exe create mode 100644 test/fixtures/release-signature/test-beta-p256-a.pem create mode 100644 test/fixtures/release-signature/test-stable-p256-a.pem create mode 100644 test/helpers/release-fixture-server.ts create mode 100644 test/unit/install-ps1.test.ts create mode 100644 test/unit/install-sh.test.ts create mode 100644 test/unit/release-signature.test.ts create mode 100644 test/unit/upgrade.test.ts diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..79cc1ce --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +# Signed test releases: their bytes are hashed and signed, so no line-ending +# conversion on checkout (Windows runners check out with autocrlf). +test/fixtures/release-signature/** -text diff --git a/.github/workflows/cli-ci.yml b/.github/workflows/cli-ci.yml index cdd1a83..086d608 100644 --- a/.github/workflows/cli-ci.yml +++ b/.github/workflows/cli-ci.yml @@ -91,6 +91,18 @@ jobs: working-directory: ./cli run: pnpm test:unit + # Release signatures as the standalone binaries check them: on the Bun in + # .bun-version, the runtime compiled into them. A Bun that can't read the + # ML-DSA keys would ship binaries that can never upgrade. + - name: Setup Bun + uses: oven-sh/setup-bun@v2 + with: + bun-version-file: cli/.bun-version + + - name: Check release signatures on the shipped Bun + working-directory: ./cli + run: bun scripts/verify-release.ts --vectors + - name: Note skipped integration tests run: echo "::notice::Integration tests are not run in CI — they need a mock of the dcd API, and this public repo does not reach into the private one. Lint, typecheck, unit tests, build and audit all ran." @@ -102,6 +114,58 @@ jobs: working-directory: ./cli run: pnpm audit --audit-level moderate + # The ML-DSA half of the release-signature tests, which skip on Node 22 (it + # has no ML-DSA). Node 24 is also what signs releases. + release-signing: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + + # The pnpm version comes from package.json's packageManager field. + - name: Setup pnpm + uses: pnpm/action-setup@v6.1.0 + with: + run_install: false + + - uses: actions/setup-node@v7 + with: + node-version: '24.x' + cache: 'pnpm' + cache-dependency-path: './pnpm-lock.yaml' + + - run: pnpm install --frozen-lockfile + + - name: Release signature, upgrade and install.sh tests + run: >- + pnpm exec mocha --no-config --node-option import=tsx/esm --extension ts --timeout 60000 + test/unit/release-signature.test.ts test/unit/upgrade.test.ts test/unit/install-sh.test.ts + + # install.ps1 under Windows PowerShell 5.1 and PowerShell 7, against the + # signed test releases. Only CI runs these: the installer writes the user PATH. + install-ps1: + runs-on: windows-latest + steps: + - uses: actions/checkout@v7 + + # The pnpm version comes from package.json's packageManager field. + - name: Setup pnpm + uses: pnpm/action-setup@v6.1.0 + with: + run_install: false + + - uses: actions/setup-node@v7 + with: + node-version: '22' + cache: 'pnpm' + cache-dependency-path: './pnpm-lock.yaml' + + - run: pnpm install --frozen-lockfile + + - name: install.ps1 tests + run: >- + pnpm exec mocha --no-config --node-option import=tsx/esm --extension ts --timeout 120000 + --fail-zero test/unit/install-ps1.test.ts + # Every PR into `production` is a release, built by promote.yml: `dev` with # `production` merged in, plus a commit that sets a new version in # package.json and server.json and adds its CHANGELOG.md section. This checks diff --git a/.github/workflows/release-beta.yml b/.github/workflows/release-beta.yml index f51fc01..afb17dc 100644 --- a/.github/workflows/release-beta.yml +++ b/.github/workflows/release-beta.yml @@ -33,55 +33,46 @@ on: default: false type: boolean +# A beta is published only after its binaries are signed and verified, so a +# failure anywhere before `publish` leaves nothing behind: no npm version, no +# tag, no release. +# +# build resolve the version, build the binaries and the npm tarball no secrets +# sign sign SHA256SUMS `cli-beta-signing` environment +# verify check the signature and every hash, as `dcd upgrade` would +# publish npm, then the GitHub prerelease and its assets +# +# Beta keys may only sign prereleases, and `cli-beta-signing` admits only the +# `dev` branch, so betas are cut from `dev`. permissions: - contents: write - # Trusted publishing: npm mints a short-lived token from the OIDC claim rather - # than a long-lived NPM_TOKEN. - # - # The trusted publisher registered on npmjs.com must name the workflow that - # STARTED the run, so this file needs its own publisher entry — the existing - # one names release-please.yml and will NOT cover this workflow. Without it npm - # rejects the write as `E404 ... PUT /@devicecloud.dev%2fdcd`, which reads like - # a missing package rather than an auth failure. - # See https://docs.npmjs.com/trusted-publishers - id-token: write + contents: read jobs: - release-beta: + build: runs-on: ubuntu-latest + outputs: + version: ${{ steps.version.outputs.version }} steps: - # Betas come off `dev` or a feature branch. `production` is the stable line - # and the release PR sets its package.json version there; cutting a beta - # from it would build from a tree that another process is also writing. - - name: Reject beta releases from production - if: github.ref_name == 'production' + # `production` is the stable line, and a feature branch would publish a + # build nobody reviewed; both would also fail later, at `sign`. + - name: Only dev cuts betas run: | - echo "Error: beta releases may not be cut from 'production'. Dispatch from 'dev' or a feature branch." - exit 1 + if [ "$GITHUB_REF" != refs/heads/dev ]; then + echo "::error::Betas are cut from dev (this run is on ${GITHUB_REF})." + exit 1 + fi - uses: actions/checkout@v7 with: # Full history so the tag-collision check below sees every tag. fetch-depth: 0 + persist-credentials: false - name: Setup pnpm uses: pnpm/action-setup@v6.1.0 with: run_install: false - # Node 24 for its bundled npm 11: trusted publishing needs npm >= 11.5.1 - # and Node 22 ships npm 10.9. - # - # Deliberately NO `registry-url`. It looks harmless — npmjs.org is the - # default registry anyway — but it makes setup-node write an .npmrc - # containing `//registry.npmjs.org/:_authToken=${NODE_AUTH_TOKEN}`. With no - # NODE_AUTH_TOKEN in the env (the whole point of trusted publishing) that - # expands to an EMPTY token, npm sees auth as already configured, never - # performs the OIDC exchange, and PUTs unauthenticated. npm answers an - # unauthorised write to an existing package with 404, not 403, so the - # symptom is a bare `E404 ... PUT /@devicecloud.dev%2fdcd` and a log with no - # mention of OIDC at all. That is what broke 5.6.0-beta.1 and beta.2. - # See actions/setup-node#1551 and npm/documentation#1960. - uses: actions/setup-node@v7 with: node-version: '24.x' @@ -102,6 +93,17 @@ jobs: node scripts/next-beta-version.mjs --bump "$INPUT_BUMP" fi + # Beta keys can only sign a prerelease, and the CLI refuses a beta-signed + # stable version, so catch it here rather than at `sign`. + - name: Refuse a version that is not a prerelease + env: + VERSION: ${{ steps.version.outputs.version }} + run: | + case "$VERSION" in + *-*) echo "${VERSION} is a prerelease" ;; + *) echo "::error::${VERSION} is not a prerelease; stable releases go through the release PR."; exit 1 ;; + esac + # The registry knows what has been PUBLISHED; it does not know what has # been TAGGED. v5.6.0-beta.1 and v5.6.0-beta.2 are tags whose npm publish # failed, so a derived version can collide with one — and `gh release @@ -136,13 +138,178 @@ jobs: with: bun-version-file: .bun-version - # Built before anything is published so a broken build fails the run - # without leaving a half-release behind. build-binaries.mjs stamps - # __DCD_CLI_VERSION__ from package.json, which is why the step above has to - # run first. + # build-binaries.mjs stamps __DCD_CLI_VERSION__ from package.json, which + # is why the step above has to run first. - name: Build binaries for all platforms run: node scripts/build-binaries.mjs + # A binary that lost the stamp would call itself the last stable and + # upgrade on the stable channel. + - name: Check the binary reports the beta version + env: + VERSION: ${{ steps.version.outputs.version }} + run: | + reported=$(./dist-bin/dcd-linux-x64 --version) + if [ "$reported" != "$VERSION" ]; then + echo "::error::dcd-linux-x64 --version says '${reported}', expected '${VERSION}'." + exit 1 + fi + + # Packed here, published as-is in `publish`, so npm gets exactly what was + # built alongside the signed binaries. + - name: Pack the npm package + run: | + mkdir npm-pack + npm pack --pack-destination npm-pack + + - uses: actions/upload-artifact@v7 + with: + name: binaries + path: dist-bin/ + if-no-files-found: error + overwrite: true + + - uses: actions/upload-artifact@v7 + with: + name: npm-package + path: npm-pack/ + if-no-files-found: error + overwrite: true + + - name: Summary (dry run) + if: ${{ inputs.dry_run }} + env: + VERSION: ${{ steps.version.outputs.version }} + run: | + { + echo "### Beta ${VERSION}" + echo + echo "**Dry run** — built, but nothing was signed, published or tagged." + } >> "$GITHUB_STEP_SUMMARY" + + sign: + needs: build + if: ${{ !inputs.dry_run }} + runs-on: ubuntu-latest + environment: cli-beta-signing + steps: + - name: Only dev signs betas + run: | + if [ "$GITHUB_REF" != refs/heads/dev ]; then + echo "::error::Betas are signed from dev only (this run is on ${GITHUB_REF})." + exit 1 + fi + + # For scripts/sign-release.mjs and the public keys in release-keys/. + - uses: actions/checkout@v7 + with: + persist-credentials: false + + # Node 24 for ML-DSA in node:crypto. sign-release.mjs uses built-ins only, + # so nothing is installed into this job. + - uses: actions/setup-node@v7 + with: + node-version: '24.x' + + - uses: actions/download-artifact@v7 + with: + name: binaries + path: dist-bin + + - name: Sign SHA256SUMS + env: + CLI_SIGNING_KEY_P256: ${{ secrets.CLI_SIGNING_KEY_P256 }} + CLI_SIGNING_KEY_MLDSA65: ${{ secrets.CLI_SIGNING_KEY_MLDSA65 }} + CLI_SIGNING_KEY_ID_P256: ${{ vars.CLI_SIGNING_KEY_ID_P256 }} + CLI_SIGNING_KEY_ID_MLDSA65: ${{ vars.CLI_SIGNING_KEY_ID_MLDSA65 }} + VERSION: ${{ needs.build.outputs.version }} + run: node scripts/sign-release.mjs --version "$VERSION" --channel beta --dir dist-bin + + - uses: actions/upload-artifact@v7 + with: + name: signature + path: dist-bin/SHA256SUMS.sig + if-no-files-found: error + overwrite: true + + verify: + needs: [build, sign] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Setup Bun + uses: oven-sh/setup-bun@v2 + with: + bun-version-file: .bun-version + + - uses: actions/download-artifact@v7 + with: + name: binaries + path: dist-bin + + - uses: actions/download-artifact@v7 + with: + name: signature + path: dist-bin + + # The keys built into the CLI, on the Bun the binaries embed: if this + # passes, `dcd upgrade` on these binaries accepts this release. + - name: Verify the signature and every hash + env: + VERSION: ${{ needs.build.outputs.version }} + run: bun scripts/verify-release.ts "$VERSION" dist-bin + + publish: + needs: [build, verify] + runs-on: ubuntu-latest + permissions: + contents: write + # Trusted publishing: npm mints a short-lived token from the OIDC claim rather + # than a long-lived NPM_TOKEN. + # + # The trusted publisher registered on npmjs.com must name the workflow that + # STARTED the run, so this file needs its own publisher entry — the existing + # one names release-please.yml and will NOT cover this workflow. Without it npm + # rejects the write as `E404 ... PUT /@devicecloud.dev%2fdcd`, which reads like + # a missing package rather than an auth failure. + # See https://docs.npmjs.com/trusted-publishers + id-token: write + steps: + # Node 24 for its bundled npm 11: trusted publishing needs npm >= 11.5.1 + # and Node 22 ships npm 10.9. + # + # Deliberately NO `registry-url`. It looks harmless — npmjs.org is the + # default registry anyway — but it makes setup-node write an .npmrc + # containing `//registry.npmjs.org/:_authToken=${NODE_AUTH_TOKEN}`. With no + # NODE_AUTH_TOKEN in the env (the whole point of trusted publishing) that + # expands to an EMPTY token, npm sees auth as already configured, never + # performs the OIDC exchange, and PUTs unauthenticated. npm answers an + # unauthorised write to an existing package with 404, not 403, so the + # symptom is a bare `E404 ... PUT /@devicecloud.dev%2fdcd` and a log with no + # mention of OIDC at all. That is what broke 5.6.0-beta.1 and beta.2. + # See actions/setup-node#1551 and npm/documentation#1960. + - uses: actions/setup-node@v7 + with: + node-version: '24.x' + + - uses: actions/download-artifact@v7 + with: + name: npm-package + path: npm-pack + + - uses: actions/download-artifact@v7 + with: + name: binaries + path: dist-bin + + - uses: actions/download-artifact@v7 + with: + name: signature + path: dist-bin + # npm BEFORE the GitHub release, deliberately. The old pipeline created the # tag and release first and published second, so when the npm leg failed it # left v5.6.0-beta.1 and v5.6.0-beta.2 as releases carrying binaries for @@ -153,14 +320,13 @@ jobs: # v11 and this repo pins pnpm 10.17 in packageManager. No NODE_AUTH_TOKEN on # this step — its presence would take precedence over the OIDC token. - name: Publish to npm - if: ${{ !inputs.dry_run }} - run: npm publish --tag beta + run: npm publish npm-pack/*.tgz --tag beta - name: Create the GitHub prerelease - if: ${{ !inputs.dry_run }} env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - VERSION: ${{ steps.version.outputs.version }} + GH_REPO: ${{ github.repository }} + VERSION: ${{ needs.build.outputs.version }} run: | gh release create "v${VERSION}" \ --prerelease \ @@ -168,29 +334,28 @@ jobs: --title "v${VERSION}" \ --generate-notes + # Binaries first, then the signature, then SHA256SUMS: a client that + # finds SHA256SUMS finds everything it checks against it. The globs take + # whatever build-binaries.mjs wrote, so a new target is added in one place. - name: Upload binaries to the prerelease - if: ${{ !inputs.dry_run }} env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - VERSION: ${{ steps.version.outputs.version }} - # Glob rather than a hand-listed set: build-binaries.mjs rm -rf's - # dist-bin and then writes exactly the five binaries plus SHA256SUMS, so - # the directory IS the asset list. Naming them here as well would mean a - # new target had to be added in three places instead of one. - run: gh release upload "v${VERSION}" dist-bin/* --clobber + GH_REPO: ${{ github.repository }} + VERSION: ${{ needs.build.outputs.version }} + run: | + set -euo pipefail + shopt -s extglob + gh release upload "v${VERSION}" dist-bin/!(SHA256SUMS|SHA256SUMS.sig) --clobber + gh release upload "v${VERSION}" dist-bin/SHA256SUMS.sig --clobber + gh release upload "v${VERSION}" dist-bin/SHA256SUMS --clobber - name: Summary env: - VERSION: ${{ steps.version.outputs.version }} - DRY_RUN: ${{ inputs.dry_run }} + VERSION: ${{ needs.build.outputs.version }} run: | { echo "### Beta ${VERSION}" echo - if [ "${DRY_RUN}" = "true" ]; then - echo "**Dry run** — nothing was published or tagged." - else - echo "- npm: \`npx @devicecloud.dev/dcd@${VERSION}\` (dist-tag \`beta\`)" - echo "- release: ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/releases/tag/v${VERSION}" - fi + echo "- npm: \`npx @devicecloud.dev/dcd@${VERSION}\` (dist-tag \`beta\`)" + echo "- release: ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/releases/tag/v${VERSION}" } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/release-binaries.yml b/.github/workflows/release-binaries.yml index 39f200c..d3991c8 100644 --- a/.github/workflows/release-binaries.yml +++ b/.github/workflows/release-binaries.yml @@ -2,9 +2,21 @@ name: Publish standalone binaries # Invoked by release-please.yml (the Release workflow) after it creates the # GitHub Release, so a single release produces both the npm package and the -# standalone binaries. The infra Railway proxy (`get.devicecloud.dev`) reads -# from the GitHub Releases API at runtime, so no separate manifest deploy is -# needed. +# standalone binaries. get.devicecloud.dev redirects downloads to these release +# assets, so no separate manifest deploy is needed. +# +# Every release is signed: SHA256SUMS.sig carries an ECDSA P-256 and an +# ML-DSA-65 signature over SHA256SUMS (format: src/utils/release-signature.ts). +# The jobs are split so the signing keys never share a job with a write token, +# a package install or a non-GitHub action: +# +# build compile the binaries and SHA256SUMS no secrets +# sign sign SHA256SUMS `cli-release-signing` environment +# verify check the signature and every hash, as `dcd upgrade` would +# upload attach the assets to the release contents: write +# +# The `cli-release-signing` environment admits only the `production` branch, so +# a run from any other ref stops at `sign` and uploads nothing. on: workflow_call: inputs: @@ -19,13 +31,48 @@ on: required: false type: string +permissions: + contents: read + jobs: - build-binaries: + build: runs-on: ubuntu-latest - permissions: - contents: write # Required to upload release assets + outputs: + tag: ${{ steps.tag.outputs.tag }} + version: ${{ steps.tag.outputs.version }} steps: - uses: actions/checkout@v7 + with: + # Tags, to check the release tag points at the commit being built. + fetch-depth: 0 + persist-credentials: false + + # Only this commit's own version, from this commit: binaries signed as + # one version but built from another commit would be a valid-looking + # release of the wrong code. + - name: Check the release tag matches this commit + id: tag + env: + INPUT_TAG: ${{ inputs.tag_name }} + run: | + set -euo pipefail + version=$(node -p "require('./package.json').version") + tag="${INPUT_TAG:-v${version}}" + if [ "$tag" != "v${version}" ]; then + echo "::error::Tag ${tag} is not this commit's version (package.json says ${version})." + exit 1 + fi + case "$version" in + *-*) echo "::error::${version} is a prerelease; betas are published by release-beta.yml."; exit 1 ;; + esac + tag_commit=$(git rev-parse -q --verify "refs/tags/${tag}^{commit}") \ + || { echo "::error::Tag ${tag} does not exist."; exit 1; } + if [ "$tag_commit" != "$GITHUB_SHA" ]; then + echo "::error::Tag ${tag} points at ${tag_commit}, not at ${GITHUB_SHA}." + exit 1 + fi + echo "tag=${tag}" >> "$GITHUB_OUTPUT" + echo "version=${version}" >> "$GITHUB_OUTPUT" - name: Setup pnpm uses: pnpm/action-setup@v6.1.0 @@ -50,21 +97,125 @@ jobs: - name: Build binaries for all platforms run: node scripts/build-binaries.mjs - - name: Resolve release tag - id: tag + - name: Check the binary reports the release version + env: + VERSION: ${{ steps.tag.outputs.version }} + run: | + reported=$(./dist-bin/dcd-linux-x64 --version) + if [ "$reported" != "$VERSION" ]; then + echo "::error::dcd-linux-x64 --version says '${reported}', expected '${VERSION}'." + exit 1 + fi + + - uses: actions/upload-artifact@v7 + with: + name: binaries + path: dist-bin/ + if-no-files-found: error + overwrite: true + + sign: + needs: build + runs-on: ubuntu-latest + environment: cli-release-signing + steps: + # The environment's branch policy already holds this; say so plainly if + # the policy is ever loosened. + - name: Only production signs stable releases run: | - if [ -n "${{ inputs.tag_name }}" ]; then - echo "name=${{ inputs.tag_name }}" >> "$GITHUB_OUTPUT" - else - VERSION=$(node -p "require('./package.json').version") - echo "name=v${VERSION}" >> "$GITHUB_OUTPUT" + if [ "$GITHUB_REF" != refs/heads/production ]; then + echo "::error::Stable releases are signed from production only (this run is on ${GITHUB_REF})." + exit 1 fi - # Glob rather than a hand-listed set: build-binaries.mjs rm -rf's dist-bin - # and then writes exactly the five binaries plus SHA256SUMS, so the - # directory IS the asset list. release-beta.yml uploads the same way. - - name: Upload binaries to GitHub Release + # For scripts/sign-release.mjs and the public keys in release-keys/. + - uses: actions/checkout@v7 + with: + persist-credentials: false + + # Node 24 for ML-DSA in node:crypto. sign-release.mjs uses built-ins only, + # so nothing is installed into this job. + - uses: actions/setup-node@v7 + with: + node-version: '24.x' + + - uses: actions/download-artifact@v7 + with: + name: binaries + path: dist-bin + + - name: Sign SHA256SUMS + env: + CLI_SIGNING_KEY_P256: ${{ secrets.CLI_SIGNING_KEY_P256 }} + CLI_SIGNING_KEY_MLDSA65: ${{ secrets.CLI_SIGNING_KEY_MLDSA65 }} + CLI_SIGNING_KEY_ID_P256: ${{ vars.CLI_SIGNING_KEY_ID_P256 }} + CLI_SIGNING_KEY_ID_MLDSA65: ${{ vars.CLI_SIGNING_KEY_ID_MLDSA65 }} + VERSION: ${{ needs.build.outputs.version }} + run: node scripts/sign-release.mjs --version "$VERSION" --channel stable --dir dist-bin + + - uses: actions/upload-artifact@v7 + with: + name: signature + path: dist-bin/SHA256SUMS.sig + if-no-files-found: error + overwrite: true + + verify: + needs: [build, sign] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Setup Bun + uses: oven-sh/setup-bun@v2 + with: + bun-version-file: .bun-version + + - uses: actions/download-artifact@v7 + with: + name: binaries + path: dist-bin + + - uses: actions/download-artifact@v7 + with: + name: signature + path: dist-bin + + # The keys built into the CLI, on the Bun the binaries embed: if this + # passes, `dcd upgrade` on these binaries accepts this release. + - name: Verify the signature and every hash + env: + VERSION: ${{ needs.build.outputs.version }} + run: bun scripts/verify-release.ts "$VERSION" dist-bin + + upload: + needs: [build, verify] + runs-on: ubuntu-latest + permissions: + contents: write # Required to upload release assets + steps: + - uses: actions/download-artifact@v7 + with: + name: binaries + path: dist-bin + + - uses: actions/download-artifact@v7 + with: + name: signature + path: dist-bin + + # Binaries first, then the signature, then SHA256SUMS: a client that + # finds SHA256SUMS finds everything it checks against it. + - name: Upload the assets to the GitHub Release env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - TAG: ${{ steps.tag.outputs.name }} - run: gh release upload "$TAG" dist-bin/* --clobber + GH_REPO: ${{ github.repository }} + TAG: ${{ needs.build.outputs.tag }} + run: | + set -euo pipefail + shopt -s extglob + gh release upload "$TAG" dist-bin/!(SHA256SUMS|SHA256SUMS.sig) --clobber + gh release upload "$TAG" dist-bin/SHA256SUMS.sig --clobber + gh release upload "$TAG" dist-bin/SHA256SUMS --clobber diff --git a/CLAUDE.md b/CLAUDE.md index 627eac5..1ef0810 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -82,6 +82,12 @@ Full guide in `CONTRIBUTING.md`; the operationally important parts (the ones tha **Cutting a stable release.** You don't start one: you merge the open `chore: release X.Y.Z` PR from `promote/cli-next` into `production`. Use a **merge commit**, the only method `production` allows. That push runs `release-please.yml`. It finds an untagged version on `production`, tags it, and creates the GitHub Release from the changelog section. It then **chains** into `npm-publish.yml` and `release-binaries.yml` as `needs:` jobs, because a `GITHUB_TOKEN`-created release won't fire `release: published`. Last, it opens a **back-merge PR** into `dev`. If that merge conflicts only in `package.json`, `server.json` or `CHANGELOG.md`, it takes `production`'s side, which holds the version just released. A conflict in any other file stops the job, and you build the back-merge by hand. `get.devicecloud.dev` serves the binaries by reading the GitHub Releases API at runtime, so there's no separate manifest to deploy. To hold a release, just don't merge the PR. Closing it doesn't pause releases, because the next push to `dev` opens a new one. +**Release signatures.** Every release's binaries come with `SHA256SUMS.sig`, an ECDSA P-256 and an ML-DSA-65 signature over `dcd-cli-release/v1`, the version and the SHA-256 of `SHA256SUMS` (format: `src/utils/release-signature.ts`). `dcd upgrade` requires both before it trusts any checksum. `install.sh` and `install.ps1` check the P-256 one, warn when they can't (no `openssl`, or a release older than their `FIRST_SIGNED`), and refuse a missing signature from `FIRST_SIGNED` on, or any signature that fails. +- **Keys.** The public keys live in three places that a test keeps equal: `src/config/release-keys.ts`, `release-keys/*.pem`, and the `release keys` blocks in both install scripts (P-256 only). Ids are `--`. A `beta` key may only sign a prerelease. +- **Signing.** `release-binaries.yml` and `release-beta.yml` split into build → sign → verify → upload/publish. Only `sign` holds keys, from the GitHub environment `cli-release-signing` (branch policy `production`) or `cli-beta-signing` (`dev`): secrets `CLI_SIGNING_KEY_P256` and `CLI_SIGNING_KEY_MLDSA65`, vars `CLI_SIGNING_KEY_ID_P256` and `CLI_SIGNING_KEY_ID_MLDSA65`. It runs `scripts/sign-release.mjs` on Node 24 and installs nothing. `verify` runs `scripts/verify-release.ts` on the pinned Bun with the built-in keys, so a release that `dcd upgrade` would refuse never uploads. Assets upload binaries first, then `SHA256SUMS.sig`, then `SHA256SUMS`. +- **Rotation.** `-a` signs and `-b` is the offline standby. A client trusts only the keys built into it, so a new key has to ship in a release signed with a key the installed base already trusts: point the environment at `-b`, release, then replace `-a` in all three places. +- **Bun.** The pinned Bun must verify ML-DSA. CI runs `bun scripts/verify-release.ts --vectors` against the golden vectors in `test/fixtures/release-signature/` (regenerate them with `generate.mjs` there, on Node 24+, only when the format changes). The ML-DSA unit tests skip on Node 22, so a `release-signing` CI job runs them on Node 24, and an `install-ps1` job runs the PowerShell installer on Windows. + **How the release PR is kept current.** `promote.yml` runs on every push to `dev`. It rebuilds `promote/cli-next` from `origin/dev`, with `origin/production` merged in, plus one `chore: release X.Y.Z` commit that sets the version in `package.json` and `server.json` and adds the `CHANGELOG.md` section. Then it force-pushes the branch and opens the PR, or updates the open one's title and body. So the PR always carries all of `dev`, and its version moves up as `feat`s land. A push with nothing releasable since the last release, such as a docs change or the back-merge, does nothing. If `production` moved during the run because a release just merged, the run pushes nothing, and the back-merge's push into `dev` rebuilds the PR. If an open PR into `production` came from another branch, push runs warn and leave it alone. The workflow can also be run by hand (`gh workflow run promote.yml --ref dev`, or the Actions tab) to set the `version`. `dry_run: true` shows the version and changelog in the run summary and pushes nothing. The `CHANGELOG.md` date is the day the PR was last rebuilt. `scripts/stable-release.mjs` does the version and changelog work (`plan`, `apply`, `verify`, `notes`). `test/unit/stable-release.test.ts` drives it against throwaway git repos. diff --git a/SECURITY.md b/SECURITY.md index 047affc..1918894 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -18,6 +18,40 @@ $ dcd upgrade # binary install | Latest `5.x` | :white_check_mark: | | Older majors | :x: | +## Verifying downloads + +Every standalone release from 5.17.0 on publishes `SHA256SUMS.sig` next to its +binaries and `SHA256SUMS`. It holds two signatures, ECDSA P-256 and ML-DSA-65 +(FIPS 204), over this message: + +``` +dcd-cli-release/v1 +version= +sha256sums= +``` + +- `dcd upgrade` checks both signatures against the public keys built into the + binary before it trusts any checksum, and refuses a release that fails. +- `install.sh` checks the P-256 signature with `openssl`, and `install.ps1` + with .NET. If they can't check it (no `openssl`, or a release from before + 5.17.0) they say so and fall back to the SHA-256 check. Set + `DCD_REQUIRE_SIGNATURE=1` to make them refuse instead. + +The public keys are in [`release-keys/`](release-keys/): `stable-*` keys sign +releases, and `beta-*` keys sign prereleases only. To check a download by hand: + +```sh +v=5.17.0 +curl -fsSL -O "https://get.devicecloud.dev/download/$v/SHA256SUMS" \ + -O "https://get.devicecloud.dev/download/$v/SHA256SUMS.sig" \ + -O "https://raw.githubusercontent.com/devicecloud-dev/dcd-cli/production/release-keys/stable-p256-a.pem" +printf 'dcd-cli-release/v1\nversion=%s\nsha256sums=%s\n' "$v" \ + "$(shasum -a 256 SHA256SUMS | cut -d' ' -f1)" > message +grep '^ecdsa-p256-sha256 stable-p256-a ' SHA256SUMS.sig | cut -d' ' -f3 | openssl base64 -d -A > signature +openssl dgst -sha256 -verify stable-p256-a.pem -signature signature message # Verified OK +grep ' dcd-darwin-arm64$' SHA256SUMS | shasum -a 256 -c # your binary +``` + ## Reporting a Vulnerability **Please do not open a public GitHub issue, pull request, or Discord message for diff --git a/install.ps1 b/install.ps1 index 039ea36..fdcb7b8 100644 --- a/install.ps1 +++ b/install.ps1 @@ -8,9 +8,142 @@ # DCD_BETA Set to any value to install the latest beta/prerelease (opt-in) # DCD_INSTALL_DIR Override install location (default: $env:USERPROFILE\.dcd\bin) # DCD_DOWNLOAD_BASE Override the download host (default: https://get.devicecloud.dev) +# DCD_REQUIRE_SIGNATURE +# Set to any value to refuse to install when the release +# signature can't be checked (a release from before releases +# were signed, or a .NET without ECDSA support) +# +# Every release since $FirstSigned (below) carries SHA256SUMS.sig, a signature +# over its SHA256SUMS. The installer checks it with the P-256 keys below before +# trusting any checksum in SHA256SUMS. A signature that doesn't verify always +# stops the install. $ErrorActionPreference = 'Stop' +# The first release published with SHA256SUMS.sig. A release at or above it with +# no signature is refused; an older one installs with a warning. A prerelease of +# this version counts as older. +$FirstSigned = '5.17.0' + +# >>> release keys >>> +# P-256 public keys that sign releases, as the curve point's X and Y: the same +# keys as release-keys/*.pem in the dcd-cli repo (test/unit/release-signature.test.ts +# checks they match). A beta key may only sign a prerelease. +$ReleaseKeys = @{ + 'stable-p256-a' = @{ Scope = 'stable'; X = '7Iv4hlBLgONlWN0yT2EdgndGG/+ULTc9+6vTMugGeIE='; Y = 'cQjM3eA2tOfVbtOiOOzZa7hXimlgIY/Uf+us1Y7PdQY=' } + 'stable-p256-b' = @{ Scope = 'stable'; X = 'V89JSdgJbq1LWLOpOA3p1whizFjdRPaTiHKLd1im7oU='; Y = 'vAly0mEZXuOjIuiKUo1Xl635UHlyabMFlBVetPtu+ZU=' } + 'beta-p256-a' = @{ Scope = 'beta'; X = '8O2oBUy5wLgDZCJvdH74Han/HE4N5tWijNfL4kIoM3I='; Y = 'hH6cxm3FaPotP7XRRfTn+zXUswSkTnX9awYAM/LAfFE=' } +} +# <<< release keys <<< + +# Whether $Version is at or above $Minimum (X.Y.Z). A prerelease of $Minimum +# counts as below it. +function Test-VersionAtLeast([string]$Version, [string]$Minimum) { + $core = ($Version -split '-', 2)[0] + if ($core -eq $Minimum -and $core -ne $Version) { return $false } + return ([version]$core) -ge ([version]$Minimum) +} + +# The signature could not be checked: refuse if DCD_REQUIRE_SIGNATURE is set, +# otherwise warn and carry on with the SHA-256 check alone. +function Skip-SignatureCheck([string]$Reason) { + if ($env:DCD_REQUIRE_SIGNATURE) { + throw "Could not check the release signature: $Reason. Not installing, because DCD_REQUIRE_SIGNATURE is set." + } + Write-Warning "Release signature not checked: $Reason. The SHA-256 checksum is still checked." +} + +# An ECDSA signature arrives DER-encoded (SEQUENCE of two INTEGERs); .NET wants +# r and s as two 32-byte big-endian halves. +function ConvertFrom-DerSignature([byte[]]$Der) { + $bad = 'SHA256SUMS.sig has an invalid signature.' + if ($Der.Length -lt 8 -or $Der.Length -gt 72 -or $Der[0] -ne 0x30 -or $Der[1] -ne ($Der.Length - 2)) { throw $bad } + $out = New-Object byte[] 64 + $pos = 2 + foreach ($half in 0, 1) { + if ($pos + 2 -gt $Der.Length -or $Der[$pos] -ne 0x02) { throw $bad } + $len = [int]$Der[$pos + 1] + $start = $pos + 2 + if ($len -lt 1 -or $start + $len -gt $Der.Length) { throw $bad } + $skip = 0 + while ($skip -lt $len - 1 -and $Der[$start + $skip] -eq 0) { $skip++ } + $size = $len - $skip + if ($size -gt 32) { throw $bad } + [Array]::Copy($Der, $start + $skip, $out, $half * 32 + 32 - $size, $size) + $pos = $start + $len + } + if ($pos -ne $Der.Length) { throw $bad } + return ,$out +} + +# Builds a verifier for one key, or returns $null when this .NET can't (CNG +# ECDSA needs .NET Framework 4.6 or later, which Windows 10 has). +function New-ReleaseVerifier([hashtable]$Key) { + try { + $blob = New-Object byte[] 72 + [BitConverter]::GetBytes([uint32]0x31534345).CopyTo($blob, 0) # BCRYPT_ECDSA_PUBLIC_P256_MAGIC + [BitConverter]::GetBytes([uint32]32).CopyTo($blob, 4) + [Convert]::FromBase64String($Key.X).CopyTo($blob, 8) + [Convert]::FromBase64String($Key.Y).CopyTo($blob, 40) + $cngKey = [System.Security.Cryptography.CngKey]::Import( + $blob, [System.Security.Cryptography.CngKeyBlobFormat]::EccPublicBlob) + return New-Object System.Security.Cryptography.ECDsaCng($cngKey) + } catch { + return $null + } +} + +# Checks SHA256SUMS.sig against SHA256SUMS for $Version. Throws when the +# signature is present but wrong. Lines for other algorithms (the CLI also +# checks an ML-DSA-65 signature) and for keys this script doesn't know are +# skipped. +function Assert-ReleaseSignature([string]$Version, [string]$SumsPath, [string]$SigPath, [int]$SigStatus) { + if ($SigStatus -eq 404) { + if (Test-VersionAtLeast $Version $FirstSigned) { + throw "Release $Version has no SHA256SUMS.sig. It may still be publishing, so try again in a few minutes. If this persists, don't install it: report it to DeviceCloud support." + } + Skip-SignatureCheck "release $Version is older than signed releases ($FirstSigned)" + return + } + + $sigBytes = [IO.File]::ReadAllBytes($SigPath) + if ($sigBytes.Length -gt 65536) { throw "SHA256SUMS.sig for $Version is too large." } + $rows = [Text.Encoding]::UTF8.GetString($sigBytes) -split "`n" + if ($rows.Length -gt 1 -and $rows[-1] -eq '') { $rows = $rows[0..($rows.Length - 2)] } + if ($rows[0] -cne 'dcd-cli-release-signature/v1') { throw "SHA256SUMS.sig for $Version is not a release signature file." } + if ($rows.Length -gt 17) { throw "SHA256SUMS.sig for $Version has too many lines." } + + $sumsSha = (Get-FileHash -Path $SumsPath -Algorithm SHA256).Hash.ToLowerInvariant() + $message = [Text.Encoding]::ASCII.GetBytes("dcd-cli-release/v1`nversion=$Version`nsha256sums=$sumsSha`n") + $verified = @() + foreach ($row in ($rows | Select-Object -Skip 1)) { + if ($row -cnotmatch '^[a-z0-9-]{1,32} [a-z0-9-]{1,64} [A-Za-z0-9+/]+={0,2}\z') { + throw "SHA256SUMS.sig for $Version has a malformed line." + } + $alg, $keyId, $b64 = $row -split ' ' + if ($alg -cne 'ecdsa-p256-sha256' -or -not $ReleaseKeys.ContainsKey($keyId)) { continue } + $key = $ReleaseKeys[$keyId] + if ($key.Scope -eq 'beta' -and $Version -notmatch '-') { + throw "SHA256SUMS.sig for $Version is signed with beta key $keyId, which can't sign a stable release." + } + try { $der = [Convert]::FromBase64String($b64) } catch { throw "SHA256SUMS.sig for $Version has an invalid signature." } + $signature = ConvertFrom-DerSignature $der + $verifier = New-ReleaseVerifier $key + if (-not $verifier) { + Skip-SignatureCheck 'this PowerShell cannot check ECDSA signatures' + return + } + if (-not $verifier.VerifyData($message, $signature, [System.Security.Cryptography.HashAlgorithmName]::SHA256)) { + throw "The signature from $keyId does not match release $Version. Don't install it: the release files may have been altered. Report it to DeviceCloud support." + } + $verified += $keyId + } + if ($verified.Count -eq 0) { + throw "SHA256SUMS.sig for $Version has no signature from a key this installer trusts. Download the latest installer and try again." + } + Write-Host " Release signature verified ($($verified -join ', '))" +} + # Windows PowerShell 5.x defaults to TLS 1.0/1.1, which modern hosts reject. # PowerShell 6+ negotiates TLS correctly on its own, so only patch 5.x. if ($PSVersionTable.PSVersion.Major -lt 6) { @@ -27,6 +160,7 @@ $asset = 'dcd-windows-x64.exe' # --- resolve version --- # Precedence: explicit DCD_VERSION pin > DCD_BETA opt-in > latest stable. +$channel = 'pinned' if ($env:DCD_VERSION) { $version = $env:DCD_VERSION } else { @@ -61,50 +195,76 @@ No stable dcd release is available yet. } } -# Only a release version goes into the download URLs below. +# Only a release version goes into the download URLs below. The signed message +# names it without the v, so drop one here. if ($version -cnotmatch '^v?[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?\z') { throw "Invalid version '$version'. Use a release version such as 5.0.0 or 5.0.0-beta.1." } +$version = $version -replace '^v', '' + +# Stable is never a prerelease. latest.json goes by GitHub's prerelease flag, so +# don't let a mislabelled beta through as stable. +if ($channel -eq 'stable' -and $version -match '-') { + throw "The stable channel returned prerelease $version. Not installing it." +} $url = "$DownloadBase/download/$version/$asset" $sumsUrl = "$DownloadBase/download/$version/SHA256SUMS" +$sigUrl = "$DownloadBase/download/$version/SHA256SUMS.sig" Write-Host "Installing dcd $version (windows-x64)" Write-Host " from: $url" Write-Host " to: $InstallDir\dcd.exe" -# --- download --- +# Everything is downloaded into one private directory, removed afterwards. if (-not (Test-Path $InstallDir)) { New-Item -ItemType Directory -Path $InstallDir -Force | Out-Null } -$tmp = Join-Path ([System.IO.Path]::GetTempPath()) ([System.IO.Path]::GetRandomFileName() + '.exe') +$work = Join-Path ([System.IO.Path]::GetTempPath()) ('dcd-' + [System.IO.Path]::GetRandomFileName()) +New-Item -ItemType Directory -Path $work | Out-Null try { + # --- release signature --- + # Checked before any checksum in SHA256SUMS is trusted. Both files are saved + # with -OutFile and read as bytes: the signature covers the exact bytes, and + # the response's .Content is a string or a byte[] depending on the + # PowerShell version and content type. + $sumsPath = Join-Path $work 'SHA256SUMS' + $sigPath = Join-Path $work 'SHA256SUMS.sig' + try { + Invoke-WebRequest -Uri $sumsUrl -OutFile $sumsPath -UseBasicParsing + } catch { + throw "Could not fetch checksums: $sumsUrl (if the release was just published, try again in a few minutes)" + } + $sigStatus = 200 + try { + Invoke-WebRequest -Uri $sigUrl -OutFile $sigPath -UseBasicParsing + } catch { + $response = $_.Exception.Response + $sigStatus = if ($response) { [int]$response.StatusCode } else { 0 } + if ($sigStatus -ne 404) { throw "Could not fetch the release signature: $sigUrl ($($_.Exception.Message))" } + } + Assert-ReleaseSignature $version $sumsPath $sigPath $sigStatus + + # --- download --- + $tmp = Join-Path $work 'dcd.exe' Invoke-WebRequest -Uri $url -OutFile $tmp -UseBasicParsing # --- verify checksum --- - # GitHub serves SHA256SUMS as application/octet-stream, so under - # -UseBasicParsing on Windows PowerShell 5.x .Content comes back as a - # Byte[] (not a string) and -split would never match. Decode to UTF-8 text. - $sumsResp = Invoke-WebRequest -Uri $sumsUrl -UseBasicParsing - $sums = if ($sumsResp.Content -is [byte[]]) { - [System.Text.Encoding]::UTF8.GetString($sumsResp.Content) - } else { - [string]$sumsResp.Content - } + $sums = [System.Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($sumsPath)) $expected = ($sums -split "`n" | - Where-Object { $_ -match "^([a-f0-9]{64})\s+$([regex]::Escape($asset))\s*$" } | + Where-Object { $_ -cmatch "^([a-f0-9]{64}) $([regex]::Escape($asset))\r?\z" } | ForEach-Object { $matches[1] } | Select-Object -First 1) if (-not $expected) { throw "SHA256SUMS has no entry for $asset" } - $actual = (Get-FileHash -Path $tmp -Algorithm SHA256).Hash.ToLower() + $actual = (Get-FileHash -Path $tmp -Algorithm SHA256).Hash.ToLowerInvariant() if ($expected -ne $actual) { throw "Checksum mismatch for ${asset}: expected $expected, got $actual" } + Write-Host ' Checksum verified (SHA-256)' # --- install --- $target = Join-Path $InstallDir 'dcd.exe' Move-Item -Path $tmp -Destination $target -Force -} catch { - if (Test-Path $tmp) { Remove-Item $tmp -Force -ErrorAction SilentlyContinue } - throw +} finally { + Remove-Item $work -Recurse -Force -ErrorAction SilentlyContinue } # --- PATH update (user scope) --- diff --git a/install.sh b/install.sh index 19444b9..1e47880 100755 --- a/install.sh +++ b/install.sh @@ -9,12 +9,60 @@ # DCD_BETA Set to any value to install the latest beta/prerelease (opt-in) # DCD_INSTALL_DIR Override install location (default: $HOME/.dcd/bin) # DCD_DOWNLOAD_BASE Override the download host (default: https://get.devicecloud.dev) +# DCD_REQUIRE_SIGNATURE +# Set to any value to refuse to install when the release +# signature can't be checked (no openssl, or a release from +# before releases were signed) +# +# Every release since FIRST_SIGNED (below) carries SHA256SUMS.sig, a signature +# over its SHA256SUMS. When openssl is available, the installer checks it with +# the P-256 keys below before trusting any checksum in SHA256SUMS. A signature +# that doesn't verify always stops the install. # # The whole script is wrapped in main() and only invoked on the last line, so # a truncated download (curl | sh executes as it streams) runs nothing at all. set -eu +# The first release published with SHA256SUMS.sig. A release at or above it +# with no signature is refused; an older one installs with a warning. A +# prerelease of this version counts as older. +FIRST_SIGNED=5.17.0 + +# >>> release keys >>> +# P-256 public keys that sign releases: release-keys/*.pem in the dcd-cli +# repo (test/unit/release-signature.test.ts checks these match). A beta key may +# only sign a prerelease. +release_key_pem() { + case "$1" in + stable-p256-a) printf '%s\n' \ + '-----BEGIN PUBLIC KEY-----' \ + 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE7Iv4hlBLgONlWN0yT2EdgndGG/+U' \ + 'LTc9+6vTMugGeIFxCMzd4Da059Vu06I47NlruFeKaWAhj9R/66zVjs91Bg==' \ + '-----END PUBLIC KEY-----' ;; + stable-p256-b) printf '%s\n' \ + '-----BEGIN PUBLIC KEY-----' \ + 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV89JSdgJbq1LWLOpOA3p1whizFjd' \ + 'RPaTiHKLd1im7oW8CXLSYRle46Mi6IpSjVeXrflQeXJpswWUFV60+275lQ==' \ + '-----END PUBLIC KEY-----' ;; + beta-p256-a) printf '%s\n' \ + '-----BEGIN PUBLIC KEY-----' \ + 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE8O2oBUy5wLgDZCJvdH74Han/HE4N' \ + '5tWijNfL4kIoM3KEfpzGbcVo+i0/tdFF9Of7NdSzBKROdf1rBgAz8sB8UQ==' \ + '-----END PUBLIC KEY-----' ;; + *) return 1 ;; + esac +} + +release_key_scope() { + case "$1" in + stable-p256-a | stable-p256-b) printf 'stable\n' ;; + beta-p256-a) printf 'beta\n' ;; + *) return 1 ;; + esac +} +# <<< release keys <<< + # Colours are on only for a real terminal: not when output is piped or logged # (CI), not when NO_COLOR is set (https://no-color.org), and not on a dumb # terminal. stdout and stderr are checked separately, because either can be @@ -22,7 +70,7 @@ set -eu # output is the same text with no escape codes. setup_colors() { BOLD='' DIM='' GREEN='' YELLOW='' CYAN='' RESET='' - ERR_RED='' ERR_RESET='' + ERR_RED='' ERR_YELLOW='' ERR_RESET='' if [ -z "${NO_COLOR:-}" ] && [ "${TERM:-dumb}" != dumb ]; then if [ -t 1 ]; then BOLD=$(printf '\033[1m') @@ -34,6 +82,7 @@ setup_colors() { fi if [ -t 2 ]; then ERR_RED=$(printf '\033[31m') + ERR_YELLOW=$(printf '\033[33m') ERR_RESET=$(printf '\033[0m') fi fi @@ -71,6 +120,12 @@ warn() { printf '%s!%s %s\n' "$YELLOW" "$RESET" "$1" } +# Warnings about the download itself go to stderr, so a CI log that keeps only +# stderr (or pipes stdout away) still shows them. +warn_err() { + printf ' %s!%s %s\n' "$ERR_YELLOW" "$ERR_RESET" "$1" >&2 +} + banner() { printf '\n %sdcd%s %s·%s DeviceCloud installer\n' "$BOLD$CYAN" "$RESET" "$DIM" "$RESET" } @@ -96,6 +151,111 @@ valid_version() { printf '%s\n' "$1" | grep -Eq '^v?[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$' } +# Prints the SHA-256 of a file in lowercase hex. +sha256_of() { + if command -v sha256sum >/dev/null 2>&1; then + sha256sum "$1" | awk '{print $1}' + else + shasum -a 256 "$1" | awk '{print $1}' + fi +} + +# Whether version $1 is at or above $2 (both X.Y.Z, $1 may have a prerelease +# part). A prerelease of $2 counts as below it. +version_at_least() { + vc_core=${1%%-*} + if [ "$vc_core" = "$2" ] && [ "$vc_core" != "$1" ]; then + return 1 + fi + vc_ifs=$IFS + IFS=. + # shellcheck disable=SC2086 # split on the dots on purpose + set -- $vc_core $2 + IFS=$vc_ifs + if [ "$1" -ne "$4" ]; then [ "$1" -gt "$4" ]; return; fi + if [ "$2" -ne "$5" ]; then [ "$2" -gt "$5" ]; return; fi + [ "$3" -ge "$6" ] +} + +# The signature could not be checked: refuse if DCD_REQUIRE_SIGNATURE is set, +# otherwise warn and carry on with the SHA-256 check alone. +signature_unchecked() { + if [ -n "${DCD_REQUIRE_SIGNATURE:-}" ]; then + err "Could not check the release signature: $1. Not installing, because DCD_REQUIRE_SIGNATURE is set." + fi + warn_err "Release signature not checked: $1. The SHA-256 checksum is still checked." +} + +# Checks $work/sig (SHA256SUMS.sig, fetched with HTTP status $1) against +# $work/sums for $version. Exits through err() when the signature is present +# but wrong. Lines for other algorithms (the CLI also checks an ML-DSA-65 +# signature) and for keys this script doesn't know are skipped. +check_release_signature() { + if [ "$1" = 404 ]; then + if version_at_least "$version" "$FIRST_SIGNED"; then + err "Release $version has no SHA256SUMS.sig. It may still be publishing, so try again in a few minutes. If this persists, don't install it: report it to DeviceCloud support." + fi + signature_unchecked "release $version is older than signed releases ($FIRST_SIGNED)" + return 0 + fi + if ! command -v openssl >/dev/null 2>&1; then + signature_unchecked "openssl is not installed" + return 0 + fi + + printf 'dcd-cli-release/v1\nversion=%s\nsha256sums=%s\n' \ + "$version" "$(sha256_of "$work/sums")" > "$work/message" + + sv_first=1 + sv_verified='' + while IFS= read -r sv_line || [ -n "$sv_line" ]; do + if [ "$sv_first" = 1 ]; then + [ "$sv_line" = 'dcd-cli-release-signature/v1' ] \ + || err "SHA256SUMS.sig for $version is not a release signature file." + sv_first=0 + continue + fi + # Only the characters the format allows, single spaces between fields: + # this also keeps the unquoted split below free of glob characters. + case "$sv_line" in + '' | ' '* | *' ' | *' '* | *[!A-Za-z0-9+/=\ -]*) + err "SHA256SUMS.sig for $version has a malformed line." ;; + esac + # shellcheck disable=SC2086 # split the line into its three fields + set -- $sv_line + [ $# -eq 3 ] || err "SHA256SUMS.sig for $version has a malformed line." + [ "$1" = ecdsa-p256-sha256 ] || continue + sv_pem=$(release_key_pem "$2") || continue + sv_scope=$(release_key_scope "$2") + if [ "$sv_scope" = beta ]; then + case "$version" in + *-*) ;; + *) err "SHA256SUMS.sig for $version is signed with beta key $2, which can't sign a stable release." ;; + esac + fi + case "$3" in + *[!A-Za-z0-9+/=]*) err "SHA256SUMS.sig for $version has an invalid signature." ;; + esac + printf '%s\n' "$sv_pem" > "$work/key.pem" + printf '%s' "$3" | openssl base64 -d -A > "$work/sig.der" 2>/dev/null \ + || err "SHA256SUMS.sig for $version has an invalid signature." + sv_size=$(wc -c < "$work/sig.der" | tr -d ' ') + if [ "$sv_size" -lt 8 ] || [ "$sv_size" -gt 72 ]; then + err "SHA256SUMS.sig for $version has an invalid signature." + fi + if ! openssl dgst -sha256 -verify "$work/key.pem" -signature "$work/sig.der" \ + "$work/message" >/dev/null 2>&1; then + err "The signature from $2 does not match release $version. Don't install it: the release files may have been altered. Report it to DeviceCloud support." + fi + sv_verified="${sv_verified:+$sv_verified, }$2" + done < "$work/sig" + + [ "$sv_first" = 0 ] || err "SHA256SUMS.sig for $version is empty." + [ -n "$sv_verified" ] \ + || err "SHA256SUMS.sig for $version has no signature from a key this installer trusts. Download the latest installer and try again." + success "Release signature verified ${DIM}(${sv_verified})${RESET}" +} + # Find a dcd on PATH other than the one we just installed — usually a leftover # `npm install -g @devicecloud.dev/dcd` that can shadow this binary. Runs in a # subshell so the temporary IFS change never leaks back to the caller. @@ -199,6 +359,7 @@ main() { # --- resolve version --- # Precedence: explicit DCD_VERSION pin > DCD_BETA opt-in > latest stable. step "Resolving version" + channel=pinned if [ -n "${DCD_VERSION:-}" ]; then version="$DCD_VERSION" detail "${CYAN}${version}${RESET} ${DIM}(pinned by DCD_VERSION)${RESET}" @@ -234,48 +395,64 @@ main() { detail "${CYAN}${version}${RESET} ${DIM}(latest ${channel})${RESET}" fi - # Only a release version goes into the download URLs below. + # Only a release version goes into the download URLs below. The signed + # message names it without the v, so drop one here. valid_version "$version" \ || err "Invalid version '$version'. Use a release version such as 5.0.0 or 5.0.0-beta.1." + version=${version#v} + + # Stable is never a prerelease. latest.json goes by GitHub's prerelease flag, + # so don't let a mislabelled beta through as stable. + if [ "$channel" = stable ]; then + case "$version" in + *-*) err "The stable channel returned prerelease $version. Not installing it." ;; + esac + fi + + command -v sha256sum >/dev/null 2>&1 || command -v shasum >/dev/null 2>&1 \ + || err "Need sha256sum or shasum to verify download" url="$DOWNLOAD_BASE/download/${version}/${asset}" sums_url="$DOWNLOAD_BASE/download/${version}/SHA256SUMS" + sig_url="$DOWNLOAD_BASE/download/${version}/SHA256SUMS.sig" step "Downloading dcd ${version} ${DIM}(${os_id}-${arch_id})${RESET}" detail "${DIM}from${RESET} $url" detail_more "${DIM}to${RESET} $INSTALL_DIR/dcd" - # --- download --- + # Everything is downloaded into one private directory, removed on exit. mkdir -p "$INSTALL_DIR" - tmp=$(mktemp "${TMPDIR:-/tmp}/dcd-XXXXXX") - trap 'rm -f "$tmp" "$tmp.sums"' EXIT - curl -fSL --progress-bar "$url" -o "$tmp" \ + work=$(mktemp -d "${TMPDIR:-/tmp}/dcd-XXXXXX") + trap 'rm -rf "$work"' EXIT + + # --- release signature --- + # Checked before any checksum in SHA256SUMS is trusted. + curl -fsSL "$sums_url" -o "$work/sums" \ + || err "Could not fetch checksums: $sums_url (if the release was just published, try again in a few minutes)" + sig_status=$(curl -sSL -o "$work/sig" -w '%{http_code}' "$sig_url") || sig_status=000 + case "$sig_status" in + 200 | 404) ;; + *) err "Could not fetch the release signature: $sig_url (HTTP $sig_status)" ;; + esac + check_release_signature "$sig_status" + + # --- download --- + curl -fSL --progress-bar "$url" -o "$work/dcd" \ || err "Download failed: $url" success "Downloaded" # --- verify checksum --- - curl -fsSL "$sums_url" -o "$tmp.sums" \ - || err "Could not fetch checksums: $sums_url" - expected=$(grep -F " ${asset}" "$tmp.sums" | awk '{print $1}' | head -n1) + expected=$(grep -F " ${asset}" "$work/sums" | awk '{print $1}' | head -n1) [ -z "$expected" ] && err "SHA256SUMS has no entry for $asset" - - if command -v sha256sum >/dev/null 2>&1; then - actual=$(sha256sum "$tmp" | awk '{print $1}') - elif command -v shasum >/dev/null 2>&1; then - actual=$(shasum -a 256 "$tmp" | awk '{print $1}') - else - err "Need sha256sum or shasum to verify download" - fi - + actual=$(sha256_of "$work/dcd") if [ "$expected" != "$actual" ]; then err "Checksum mismatch for $asset: expected $expected, got $actual" fi success "Checksum verified ${DIM}(SHA-256)${RESET}" # --- install --- - chmod +x "$tmp" - mv "$tmp" "$INSTALL_DIR/dcd" - trap - EXIT # tmp has been moved; nothing to clean up + chmod +x "$work/dcd" + mv "$work/dcd" "$INSTALL_DIR/dcd" # --- PATH setup --- path_line="export PATH=\"$INSTALL_DIR:\$PATH\"" diff --git a/release-keys/beta-mldsa65-a.pem b/release-keys/beta-mldsa65-a.pem new file mode 100644 index 0000000..4c9faa6 --- /dev/null +++ b/release-keys/beta-mldsa65-a.pem @@ -0,0 +1,44 @@ +-----BEGIN PUBLIC KEY----- +MIIHsjALBglghkgBZQMEAxIDggehANpvPsFuc3Ijsgjs3xFVCs9vQiLSC0WLA6nI +7B3WQhOtbWJUkwL1FUnXOxjENqTSKAAZ80Y+0e3MLr1Df8tGsWJzSe5NEAkmDyUi +ZNADPNZ+MeEqBj/NRPcsHCgv1O5jwnl7mec8lkEcK1Zx9Y30jBHV4LHBe+V+/8vZ +f6BNruJzC6i+iFW5jUPZdzb5sRy/cZNGMyX94h7ZMVWyUb3wR0/hCEiqMI3K4Tt8 +i7VD3wIjqwsgtlZg5sfHx3yEqaQFrYMqsMrSHa+QQS0UR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w+7eYcnJ/CpePt42X8gscC3gRNvCMaMk71Q9K2nlk3kigVKzvOBDIE/1/V +K8HKtehAwa/l8FQ/PoLJNO6za2OUkwAe0OvxHPaAOgmU/JIOoB9Wscny3X+V1S3M +FWFJSr2AlcGD8+gbN7XxpJlOUAxgW85hEVH4ayjhE3ws8Kvy+UEVVlaq9ZmWUIb0 +bwHlJJrd +-----END PUBLIC KEY----- diff --git a/release-keys/beta-p256-a.pem b/release-keys/beta-p256-a.pem new file mode 100644 index 0000000..1c71577 --- /dev/null +++ b/release-keys/beta-p256-a.pem @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE8O2oBUy5wLgDZCJvdH74Han/HE4N +5tWijNfL4kIoM3KEfpzGbcVo+i0/tdFF9Of7NdSzBKROdf1rBgAz8sB8UQ== +-----END PUBLIC KEY----- diff --git a/release-keys/stable-mldsa65-a.pem b/release-keys/stable-mldsa65-a.pem new file mode 100644 index 0000000..1142427 --- /dev/null +++ b/release-keys/stable-mldsa65-a.pem @@ -0,0 +1,44 @@ +-----BEGIN PUBLIC KEY----- +MIIHsjALBglghkgBZQMEAxIDggehADJlhCXmJVqiWsyma2Dkd+N9/r+Cs2oWdxef +h4BZs1ZR2IeWkjCtx+k8p6S1iovDUDfiF0Iy+HH7o9TUi9Sk0Dflyi34FwHYiWzj +hPXelx49+UY15Je1PEgNRDxvJByUjCvy5/pcKrGL8pK4szzE8vOu/yY5DYC2c3KS +CClfLLgGt+RN9pDJvZLis5a6ezFnfwyHZmkiJflKTmezgjYxMhy2FQpvrl7NqgnM +XOd84LB7DKrXepjlygjdhtSwVO0lKyoBCX+2wD0JjCIz51+PoKZC4a/T6CU2YUKf +qoYbK0C/UtYi5wHdR2zGj54KtdLlp5qVLlp8dGSmi0Vulc+uRiXf/g83kpK5GXYb +iPfAWu5ztvsB1m6iLHXpZvoAdQ+JmWh83w+h1smRur/n3lrEdKXILNlp9pQ+wxW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NQxUHb/dfhQTeoE7y+aEZ8nNWht630SwdT6fhGVxFVj08mOxfIRA +tikfDhwd +-----END PUBLIC KEY----- diff --git a/release-keys/stable-mldsa65-b.pem b/release-keys/stable-mldsa65-b.pem new file mode 100644 index 0000000..261b4b8 --- /dev/null +++ b/release-keys/stable-mldsa65-b.pem @@ -0,0 +1,44 @@ +-----BEGIN PUBLIC KEY----- +MIIHsjALBglghkgBZQMEAxIDggehACB6msp39uVdGBm20hXUUw73+0tnsoiaITNf +85z/4mjCNbnYFYp05gUImKH8ZxkxsqQgxqjs0EX7y+ia/YPDNO2zbB8cg/EDljT3 +xpQsTmW0dH3Yo4aZI3Mc/BbHl/715lgFLWv/m7Qx4+kQ4rz5yTFQVeAdUuNXaUDD +UiiEl0IBnl+KvlPJTOaeNb2cUk6YS01ZEDFtiKl8NgnsHEwiozE/TJEituCnG5Gr ++Qaf+zPpV934dBfdU4dNQJIqLgU7rIwLCRy98REF30MIC6NtLViKWeQzIc1bXH/0 +q8GKCEXYvgqtSsaIsmGigDelzzASC15pkOfEYmJWf5yJgizPc/VIkEGdwIrB0wsY +ZhZCjkykomo0v2mavjcj226y7USHy2UN8nZHqWBZJ7uXCJUunLzmK9JwNbRUWtkn +Rixghf4q8Ct1fNr1+OpjPu86gpMdk1Fo/vYIRdkOQuTEXraP7rAdky7/icnEibHt +1/gdOqjmR293/5UK8FZiuyXZS7/98FTQGI3IrGwRcy33BjFz42tZzPUEueTvGTzp +jzBpqIMgUGMaYm7dvn5RNtGZizSEQC0oCnKy1gNHm5yiP8T3Hjjm/omYWs9m9sm9 +4HggbeRqjyNqH3UMBjf2zAzkd+YMcjo7t9gN5JwdWP93ynZFwUU1tCpjzq+mnxOC +JKA/WuXSMhniuS7EkHtE0DS78NIl0ab7lIPGi5eiGuAaVG6BfHSQbbYm018Ibn85 +uRL1gE1d/QdneYw6REgkWs4MGT0KOz/1CoqrYfu8XwV0w55yflMa7F+NJ09CddIJ +d0NzgJRRyti6a0wMxPMhiZnD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RGO17GPgePsebhzqvgb +vSJm94VboaHDddpb2N1pm24m+RWohaxI/X+5wFdIdkbiu5oj8KYMmVpdLec22wL9 +hm5Mb4CPJFbjaJR/1z4Zqw2V8ppRiKr1GwRQ7nxrk0e4t44XjE8u9SJM1h+4SGo2 +7avF69wGTvw23xi301Oe6O3IQG3AF/wN8sfuLfttHvbRVVloks8h8g8PYGmR/3vS +jlUlHot+zL2xo21g7WHrYmxSGg71A+eO5en7hfDXUt6DAnQRKYkOg+iFE2wQArfs +szZWnGERSe29Z9JGU3xOLyI0jCAsYBEg6aD0eunqz1hsOK8DYuq6josZV+iBM++t +w9/bHsT7kfMXKVI6WiIwRrTF2kNUNBSTQi1Ulcyk8ULCqnDk9XC6283HG1F2zWnc +krF36Fztt37QukhNAgoY4qb9lpKwvPze/zFlldOVBKlhfzI6F1HlofoHCmvQwu0e +z2EmDPrEtQ7/Venurbp7NA/m1PF5YAaU2ER2RbE3XpudKM7mvrSorSvMFx8frloz +Z17mXaRoDSLcRJ6nTe5WmXZypaRM1JwCSArEctxA7l8xatWahh/p7XSjsTfkcs/5 +KpWh4o8vh/sBTGioRbNHIObu74MQLS6qKpcQKoX+odIsGGpcwMA+2xmBPmgKBM4p +ZoItSvhaMLCLjRh9ylD3Zcsve2rRxGkqggC6pJ++xPXIvXM/0ecsAbr6MFu31xST +f+MhObaH +-----END PUBLIC KEY----- diff --git a/release-keys/stable-p256-a.pem b/release-keys/stable-p256-a.pem new file mode 100644 index 0000000..ea701a1 --- /dev/null +++ b/release-keys/stable-p256-a.pem @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE7Iv4hlBLgONlWN0yT2EdgndGG/+U +LTc9+6vTMugGeIFxCMzd4Da059Vu06I47NlruFeKaWAhj9R/66zVjs91Bg== +-----END PUBLIC KEY----- diff --git a/release-keys/stable-p256-b.pem b/release-keys/stable-p256-b.pem new file mode 100644 index 0000000..29da163 --- /dev/null +++ b/release-keys/stable-p256-b.pem @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV89JSdgJbq1LWLOpOA3p1whizFjd +RPaTiHKLd1im7oW8CXLSYRle46Mi6IpSjVeXrflQeXJpswWUFV60+275lQ== +-----END PUBLIC KEY----- diff --git a/scripts/build-binaries.mjs b/scripts/build-binaries.mjs index f9dae78..09f00b2 100644 --- a/scripts/build-binaries.mjs +++ b/scripts/build-binaries.mjs @@ -2,7 +2,9 @@ /** * Cross-compile the CLI to single-file binaries for all published platforms * using `bun build --compile`. Writes outputs to dist-bin/ and a SHA256SUMS - * manifest used by `dcd upgrade` to verify downloads. + * manifest. The release workflows sign SHA256SUMS (scripts/sign-release.mjs, + * which writes SHA256SUMS.sig), and `dcd upgrade` and the install scripts check + * that signature before trusting the checksums in it. * * Run locally: pnpm build:binaries (or: node scripts/build-binaries.mjs) * Run in CI: .github/workflows/release-binaries.yml diff --git a/scripts/sign-release.d.mts b/scripts/sign-release.d.mts new file mode 100644 index 0000000..f3f9f5d --- /dev/null +++ b/scripts/sign-release.d.mts @@ -0,0 +1,21 @@ +// Types for scripts/sign-release.mjs, which test/unit/release-signature.test.ts imports. + +export const RELEASE_MESSAGE_HEADER: string; +export const SIGNATURE_FILE_HEADER: string; + +export const SIGNERS: ReadonlyArray<{ + alg: 'ecdsa-p256-sha256' | 'ml-dsa-65'; + env: string; + idPart: string; + keyType: string; +}>; + +export function releaseMessage(version: string, sumsSha256: string): Buffer; + +export function signRelease(options: { + channel: 'beta' | 'stable'; + keys: { keyId: string; privateKeyPem: string }[]; + publicKeyPem: (keyId: string) => string; + sums: Buffer; + version: string; +}): string; diff --git a/scripts/sign-release.mjs b/scripts/sign-release.mjs new file mode 100644 index 0000000..b92ce61 --- /dev/null +++ b/scripts/sign-release.mjs @@ -0,0 +1,145 @@ +#!/usr/bin/env node +/** + * Signs a release's SHA256SUMS and writes SHA256SUMS.sig next to it. + * + * node scripts/sign-release.mjs --version 5.17.0 --channel stable --dir dist-bin + * + * Runs in the signing job of the release workflows, which holds the keys in a + * GitHub environment that only one branch may use (stable: `production`, + * beta: `dev`). Reads: + * + * CLI_SIGNING_KEY_P256 PKCS#8 PEM, ECDSA P-256 + * CLI_SIGNING_KEY_MLDSA65 PKCS#8 PEM, ML-DSA-65 + * CLI_SIGNING_KEY_ID_P256 e.g. stable-p256-a + * CLI_SIGNING_KEY_ID_MLDSA65 e.g. stable-mldsa65-a + * + * It refuses a key id that doesn't belong to the channel, a private key whose + * public half isn't the one committed in release-keys/.pem, a stable + * channel version with a prerelease part, and a beta version without one. + * + * Node built-ins only (ML-DSA needs Node 24 or later), so the signing job + * installs no packages. The format is described in + * src/utils/release-signature.ts; scripts/verify-release.ts checks the output + * with the same code the CLI runs. + */ +import { createHash, createPrivateKey, createPublicKey, sign, verify } from 'node:crypto'; +import { readFileSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { parseArgs } from 'node:util'; + +export const RELEASE_MESSAGE_HEADER = 'dcd-cli-release/v1'; +export const SIGNATURE_FILE_HEADER = 'dcd-cli-release-signature/v1'; +const VERSION_RE = /^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$/; +const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); + +/** The algorithms a release is signed with, and how each key id is named. */ +export const SIGNERS = [ + { alg: 'ecdsa-p256-sha256', idPart: 'p256', keyType: 'ec', env: 'P256' }, + { alg: 'ml-dsa-65', idPart: 'mldsa65', keyType: 'ml-dsa-65', env: 'MLDSA65' }, +]; + +export function releaseMessage(version, sumsSha256) { + return Buffer.from( + `${RELEASE_MESSAGE_HEADER}\nversion=${version}\nsha256sums=${sumsSha256}\n`, + 'utf8', + ); +} + +function signWith(alg, key, message) { + return alg === 'ecdsa-p256-sha256' + ? sign('sha256', message, { key, dsaEncoding: 'der' }) + : sign(null, message, key); +} + +function verifyWith(alg, key, message, signature) { + return alg === 'ecdsa-p256-sha256' + ? verify('sha256', message, { key, dsaEncoding: 'der' }, signature) + : verify(null, message, key, signature); +} + +/** + * @param {object} options + * @param {string} options.version no leading `v` + * @param {'stable'|'beta'} options.channel + * @param {Buffer} options.sums the exact SHA256SUMS bytes + * @param {{ keyId: string, privateKeyPem: string }[]} options.keys one per SIGNERS entry, same order + * @param {(keyId: string) => string} options.publicKeyPem the committed public key for an id + * @returns {string} the SHA256SUMS.sig contents + */ +export function signRelease({ version, channel, sums, keys, publicKeyPem }) { + if (!VERSION_RE.test(version)) throw new Error(`'${version}' is not a release version (no leading v)`); + if (channel !== 'stable' && channel !== 'beta') throw new Error(`unknown channel '${channel}'`); + const prerelease = version.includes('-'); + if (channel === 'stable' && prerelease) throw new Error(`stable releases can't be prereleases (${version})`); + if (channel === 'beta' && !prerelease) throw new Error(`beta releases must be prereleases (${version})`); + if (keys.length !== SIGNERS.length) throw new Error(`expected ${SIGNERS.length} keys, got ${keys.length}`); + + const message = releaseMessage(version, createHash('sha256').update(sums).digest('hex')); + const lines = [SIGNATURE_FILE_HEADER]; + SIGNERS.forEach((signer, index) => { + const { keyId, privateKeyPem } = keys[index]; + const idRe = new RegExp(`^${channel}-${signer.idPart}-[a-z]$`); + if (!idRe.test(keyId ?? '')) { + throw new Error(`key id '${keyId}' is not a ${channel} ${signer.alg} key id (${idRe})`); + } + const privateKey = createPrivateKey(privateKeyPem); + if (privateKey.asymmetricKeyType !== signer.keyType) { + throw new Error(`${keyId}: expected a ${signer.keyType} key, got ${privateKey.asymmetricKeyType}`); + } + if (signer.keyType === 'ec' && privateKey.asymmetricKeyDetails?.namedCurve !== 'prime256v1') { + throw new Error(`${keyId}: expected a P-256 key`); + } + const committed = createPublicKey(publicKeyPem(keyId)); + const derived = createPublicKey(privateKey); + const der = (key) => key.export({ type: 'spki', format: 'der' }); + if (!der(derived).equals(der(committed))) { + throw new Error(`${keyId}: the private key does not match release-keys/${keyId}.pem`); + } + const signature = signWith(signer.alg, privateKey, message); + if (!verifyWith(signer.alg, committed, message, signature)) { + throw new Error(`${keyId}: the new signature does not verify`); + } + lines.push(`${signer.alg} ${keyId} ${signature.toString('base64')}`); + }); + return `${lines.join('\n')}\n`; +} + +function main() { + const { values } = parseArgs({ + options: { + channel: { type: 'string' }, + dir: { type: 'string' }, + version: { type: 'string' }, + }, + }); + if (!values.version || !values.channel || !values.dir) { + throw new Error('usage: sign-release.mjs --version X.Y.Z --channel stable|beta --dir dist-bin'); + } + const keys = SIGNERS.map((signer) => { + const privateKeyPem = process.env[`CLI_SIGNING_KEY_${signer.env}`]; + const keyId = process.env[`CLI_SIGNING_KEY_ID_${signer.env}`]; + if (!privateKeyPem) throw new Error(`CLI_SIGNING_KEY_${signer.env} is not set`); + if (!keyId) throw new Error(`CLI_SIGNING_KEY_ID_${signer.env} is not set`); + return { keyId, privateKeyPem }; + }); + const sumsPath = path.join(values.dir, 'SHA256SUMS'); + const signatureFile = signRelease({ + version: values.version, + channel: values.channel, + sums: readFileSync(sumsPath), + keys, + publicKeyPem: (keyId) => readFileSync(path.join(REPO_ROOT, 'release-keys', `${keyId}.pem`), 'utf8'), + }); + writeFileSync(path.join(values.dir, 'SHA256SUMS.sig'), signatureFile); + console.log(`Signed ${values.version} (${values.channel}) with ${keys.map((k) => k.keyId).join(', ')}`); +} + +if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) { + try { + main(); + } catch (error) { + console.error(`sign-release: ${error.message}`); + process.exit(1); + } +} diff --git a/scripts/verify-release.ts b/scripts/verify-release.ts new file mode 100644 index 0000000..1e0a822 --- /dev/null +++ b/scripts/verify-release.ts @@ -0,0 +1,107 @@ +/** + * Checks release signatures with the same code `dcd upgrade` runs. + * + * bun scripts/verify-release.ts + * Verifies /SHA256SUMS.sig with the keys built into the CLI, then + * checks every file in is listed in SHA256SUMS with the right hash. + * The release workflows run this on the signed assets before uploading. + * + * bun scripts/verify-release.ts --vectors + * Checks this runtime can load every built-in key and verify the golden + * vector in test/fixtures/release-signature/. CI runs it on the Bun pinned + * in .bun-version, the runtime compiled into the binaries, so a Bun that + * can't verify ML-DSA never ships. + */ +import { createHash } from 'node:crypto'; +import { readFileSync, readdirSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import type { ReleaseKey } from '../src/config/release-keys.js'; +import { + SIGNATURE_FILE_NAME, + checkReleaseKeys, + parseSums, + verifyReleaseSignature, +} from '../src/utils/release-signature.js'; + +const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const FIXTURES = path.join(REPO_ROOT, 'test', 'fixtures', 'release-signature'); + +function runtimeName(): string { + const versions = process.versions as { bun?: string; node: string }; + return versions.bun ? `bun ${versions.bun}` : `node ${versions.node}`; +} + +function verifyDirectory(version: string, dir: string, keys?: Readonly>): string[] { + const sums = readFileSync(path.join(dir, 'SHA256SUMS')); + const sigFile = readFileSync(path.join(dir, SIGNATURE_FILE_NAME)); + const result = verifyReleaseSignature({ keys, sigFile, sums, version }); + if (!result.ok) return [`signature: ${result.reason}`]; + console.log(`signature OK for ${version} (${result.keyIds.join(', ')})`); + + const problems: string[] = []; + const entries = parseSums(sums); + const listed = new Set(entries.map((entry) => entry.asset)); + for (const file of readdirSync(dir)) { + if (file === 'SHA256SUMS' || file === SIGNATURE_FILE_NAME) continue; + if (!listed.has(file)) problems.push(`${file} is not listed in SHA256SUMS`); + } + for (const { asset, sha256 } of entries) { + let actual: string; + try { + actual = createHash('sha256').update(readFileSync(path.join(dir, asset))).digest('hex'); + } catch { + problems.push(`${asset} is listed in SHA256SUMS but missing`); + continue; + } + if (actual !== sha256) problems.push(`${asset}: SHA-256 is ${actual}, SHA256SUMS says ${sha256}`); + } + return problems; +} + +function checkVectors(): string[] { + const problems = checkReleaseKeys().map((problem) => `built-in key ${problem}`); + const keys = JSON.parse(readFileSync(path.join(FIXTURES, 'keys.json'), 'utf8')) as Record; + problems.push(...checkReleaseKeys(keys).map((problem) => `fixture key ${problem}`)); + + for (const { dir, version } of [ + { dir: 'stable', version: '9.9.0' }, + { dir: 'beta', version: '9.9.1-beta.1' }, + ]) { + const releaseDir = path.join(FIXTURES, dir); + problems.push(...verifyDirectory(version, releaseDir, keys).map((p) => `${dir} vector: ${p}`)); + + // The same files must fail as another version, or with one byte changed. + const sums = readFileSync(path.join(releaseDir, 'SHA256SUMS')); + const sigFile = readFileSync(path.join(releaseDir, SIGNATURE_FILE_NAME)); + const tampered = Buffer.from(sums); + tampered[0] ^= 1; + for (const [label, attempt] of [ + ['another version', { keys, sigFile, sums, version: '9.9.2' }], + ['tampered SHA256SUMS', { keys, sigFile, sums: tampered, version }], + ] as const) { + if (verifyReleaseSignature(attempt).ok) problems.push(`${dir} vector: ${label} verified`); + } + } + return problems; +} + +function main(): number { + const args = process.argv.slice(2); + let problems: string[]; + if (args.length === 1 && args[0] === '--vectors') { + problems = checkVectors(); + } else if (args.length === 2) { + problems = verifyDirectory(args[0].replace(/^v/, ''), args[1]); + } else { + console.error('usage: verify-release.ts --vectors | verify-release.ts '); + return 2; + } + for (const problem of problems) console.error(`✗ ${problem}`); + if (problems.length > 0) return 1; + console.log(`✓ all checks passed on ${runtimeName()}`); + return 0; +} + +process.exit(main()); diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.ts index a2b5e9f..251e288 100644 --- a/src/commands/upgrade.ts +++ b/src/commands/upgrade.ts @@ -3,9 +3,13 @@ * * Only meaningful for the bun-compiled binary install. npm-installed users * are redirected to `npm install -g`. Fetches the latest version from the - * release manifest, downloads the matching binary, verifies its SHA256 - * against the published SHA256SUMS, then atomically renames over the running - * executable (the old inode stays alive until the process exits). + * release manifest, then the release's SHA256SUMS and SHA256SUMS.sig, and + * checks the signature against the release keys built into this binary + * (src/config/release-keys.ts) before trusting any checksum in it. Only then + * does it download the matching binary, compare its SHA-256 with the signed + * list, and atomically rename it over the running executable (the old inode + * stays alive until the process exits). The download host is not trusted: a + * mirror set with DCD_DOWNLOAD_BASE works as long as it serves the same files. */ import { createHash } from 'node:crypto'; import { @@ -20,14 +24,23 @@ import { pipeline } from 'node:stream/promises'; import { defineCommand } from 'citty'; +import type { ReleaseKey, ReleaseSignatureAlg } from '../config/release-keys.js'; import { jsonFlag } from '../config/flags/output.flags.js'; -import { VersionService } from '../services/version.service.js'; +import { type ReleaseChannel, VersionService } from '../services/version.service.js'; import { CliError, getCliVersion, getInstallMethod, logger, } from '../utils/cli.js'; +import { + RELEASE_METADATA_MAX_BYTES, + RELEASE_VERSION_RE, + SIGNATURE_FILE_NAME, + isPrerelease, + parseSums, + verifyReleaseSignature, +} from '../utils/release-signature.js'; import { colors } from '../utils/styling.js'; import { ui } from '../utils/ui.js'; @@ -87,7 +100,7 @@ export const upgradeCommand = defineCommand({ return; } - const latest = result.version; + const latest = resolveUpgradeVersion(result.version, result.channel); if (!versionService.isOutdated(current, latest)) { if (json) { logger.json({ status: 'UP_TO_DATE', current, latest, channel: result.channel }); @@ -121,45 +134,146 @@ export const upgradeCommand = defineCommand({ } const base = process.env.DCD_DOWNLOAD_BASE ?? DEFAULT_DOWNLOAD_BASE; - const binaryUrl = `${base}/download/${latest}/${asset}`; - const sumsUrl = `${base}/download/${latest}/SHA256SUMS`; + const execPath = process.execPath; out(ui.info(`Upgrading ${colors.highlight(current)} → ${colors.highlight(latest)}`)); - out(ui.note(` ${binaryUrl}`)); - - const execPath = process.execPath; - const tmpPath = `${execPath}.new`; + out(ui.note(` ${base}/download/${latest}/${asset}`)); + let installed: InstallReleaseResult; try { - await downloadToFile(binaryUrl, tmpPath); - const expected = await fetchExpectedChecksum(sumsUrl, asset); - const actual = await sha256File(tmpPath); - if (expected !== actual) { - throw new Error( - `Checksum mismatch for ${asset}: expected ${expected}, got ${actual}`, - ); - } - chmodSync(tmpPath, 0o755); - // rename is atomic on the same filesystem; on POSIX the running process - // keeps the old inode open until exit, so this is safe to do mid-run. - renameSync(tmpPath, execPath); + installed = await installRelease({ asset, base, destination: execPath, version: latest }); } catch (e) { - safeUnlink(tmpPath); throw new CliError( `Upgrade failed: ${(e as Error).message}. The existing binary at ${execPath} was not modified.`, ); } if (json) { - logger.json({ status: 'UPGRADED', current, latest, channel: result.channel }); + logger.json({ + status: 'UPGRADED', + current, + latest, + channel: result.channel, + signature: { keyIds: installed.keyIds }, + }); return; } + out(ui.note(` Signature verified (${installed.keyIds.join(', ')})`)); logger.log(ui.success(`Upgraded to ${colors.highlight(latest)}`)); }, }); -async function downloadToFile(url: string, dest: string): Promise { - const res = await fetch(url, { redirect: 'follow' }); +/** + * Normalises the manifest's version (no leading `v`) and refuses anything that + * isn't a release version, or a prerelease offered on the stable channel. + */ +export function resolveUpgradeVersion(version: string, channel: ReleaseChannel): string { + const normalised = version.replace(/^v/, ''); + if (!RELEASE_VERSION_RE.test(normalised)) { + throw new CliError(`The update manifest returned an invalid version ('${version}').`); + } + if (channel === 'stable' && isPrerelease(normalised)) { + throw new CliError( + `The update manifest offered prerelease ${normalised} on the stable channel. Not upgrading.`, + ); + } + return normalised; +} + +export interface InstallReleaseOptions { + asset: string; + base: string; + /** The file to replace, normally process.execPath. */ + destination: string; + fetchImpl?: typeof fetch; + /** Overrides for tests; production uses the keys built into this binary. */ + keys?: Readonly>; + requiredAlgs?: readonly ReleaseSignatureAlg[]; + /** Without a leading `v`. */ + version: string; +} + +export interface InstallReleaseResult { + keyIds: string[]; +} + +/** + * Downloads `asset` of release `version` from `base` and replaces + * `destination` with it, only after the release signature and the binary's + * SHA-256 both check out. Throws with a user-facing message otherwise, and + * leaves `destination` untouched. + */ +export async function installRelease(options: InstallReleaseOptions): Promise { + const { asset, base, destination, version } = options; + const fetchImpl = options.fetchImpl ?? fetch; + const releaseUrl = `${base}/download/${version}`; + const notPublished = (file: string) => + new Error( + `release ${version} has no ${file} yet, so it may still be publishing. Try again in a few minutes`, + ); + + const sums = await fetchSmall(`${releaseUrl}/SHA256SUMS`, fetchImpl); + if (!sums) throw notPublished('SHA256SUMS'); + const sigFile = await fetchSmall(`${releaseUrl}/${SIGNATURE_FILE_NAME}`, fetchImpl); + if (!sigFile) throw notPublished(SIGNATURE_FILE_NAME); + + const verified = verifyReleaseSignature({ + keys: options.keys, + requiredAlgs: options.requiredAlgs, + sigFile, + sums, + version, + }); + if (!verified.ok) { + throw new Error(`release ${version} failed its signature check (${verified.reason}), so it was not installed`); + } + + const expected = parseSums(sums).find((entry) => entry.asset === asset)?.sha256; + if (!expected) throw new Error(`SHA256SUMS has no entry for ${asset}`); + + const tmpPath = `${destination}.new`; + try { + await downloadToFile(`${releaseUrl}/${asset}`, tmpPath, fetchImpl); + const actual = await sha256File(tmpPath); + if (expected !== actual) { + throw new Error(`Checksum mismatch for ${asset}: expected ${expected}, got ${actual}`); + } + chmodSync(tmpPath, 0o755); + // rename is atomic on the same filesystem; on POSIX the running process + // keeps the old inode open until exit, so this is safe to do mid-run. + renameSync(tmpPath, destination); + } catch (e) { + safeUnlink(tmpPath); + throw e; + } + return { keyIds: verified.keyIds }; +} + +/** Fetches a small release file. Returns null on 404; throws on anything else that isn't a 2xx. */ +async function fetchSmall(url: string, fetchImpl: typeof fetch): Promise { + const res = await fetchImpl(url, { redirect: 'follow' }); + if (res.status === 404) return null; + if (!res.ok || !res.body) throw new Error(`HTTP ${res.status} fetching ${url}`); + const tooBig = () => new Error(`${url} is larger than ${RELEASE_METADATA_MAX_BYTES} bytes`); + if (Number(res.headers.get('content-length') ?? 0) > RELEASE_METADATA_MAX_BYTES) throw tooBig(); + const chunks: Uint8Array[] = []; + let total = 0; + const reader = res.body.getReader(); + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + total += value.length; + if (total > RELEASE_METADATA_MAX_BYTES) { + await reader.cancel(); + throw tooBig(); + } + chunks.push(value); + } + return Buffer.concat(chunks); +} + +async function downloadToFile(url: string, dest: string, fetchImpl: typeof fetch): Promise { + const res = await fetchImpl(url, { redirect: 'follow' }); if (!res.ok || !res.body) { throw new Error(`HTTP ${res.status} fetching ${url}`); } @@ -170,20 +284,6 @@ async function downloadToFile(url: string, dest: string): Promise { ); } -async function fetchExpectedChecksum( - sumsUrl: string, - asset: string, -): Promise { - const res = await fetch(sumsUrl, { redirect: 'follow' }); - if (!res.ok) throw new Error(`HTTP ${res.status} fetching ${sumsUrl}`); - const body = await res.text(); - for (const line of body.split('\n')) { - const match = line.match(/^([a-f0-9]{64})\s+(.+)$/); - if (match && match[2].trim() === asset) return match[1]; - } - throw new Error(`SHA256SUMS has no entry for ${asset}`); -} - async function sha256File(path: string): Promise { const hash = createHash('sha256'); for await (const chunk of createReadStream(path)) { diff --git a/src/config/release-keys.ts b/src/config/release-keys.ts new file mode 100644 index 0000000..d25fc17 --- /dev/null +++ b/src/config/release-keys.ts @@ -0,0 +1,207 @@ +/** + * Public keys that sign the standalone release binaries. + * + * Every release carries `SHA256SUMS.sig` next to `SHA256SUMS`. `dcd upgrade` + * accepts a release only when it has a valid signature from one of these keys + * for every algorithm in REQUIRED_RELEASE_ALGS (see src/utils/release-signature.ts). + * The same keys are committed as PEM files in release-keys/, and install.sh and + * install.ps1 embed the P-256 ones; test/unit/release-signature.test.ts checks + * all three copies agree. + * + * Scope: a `stable` key may sign any version; a `beta` key may only sign a + * prerelease (a version with a `-`). Betas are signed in a different CI + * environment from stable releases, so a beta key can never ship a stable + * version. + * + * Rotation: the `-a` key of each pair signs and `-b` is a standby kept offline. + * A client only trusts the keys built into it, so a new key must ship in a + * release signed with a key the installed base already trusts. To rotate, sign + * with `-b`, then replace `-a` here and in release-keys/. + */ + +export type ReleaseSignatureAlg = 'ecdsa-p256-sha256' | 'ml-dsa-65'; +export type ReleaseKeyScope = 'beta' | 'stable'; + +export interface ReleaseKey { + alg: ReleaseSignatureAlg; + scope: ReleaseKeyScope; + /** SubjectPublicKeyInfo, DER, base64. */ + spki: string; +} + +/** One classical and one post-quantum signature, both required. */ +export const REQUIRED_RELEASE_ALGS: readonly ReleaseSignatureAlg[] = [ + 'ecdsa-p256-sha256', + 'ml-dsa-65', +]; + +export const RELEASE_SIGNING_KEYS: Readonly> = { + 'stable-p256-a': { + alg: 'ecdsa-p256-sha256', + scope: 'stable', + spki: [ + 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE7Iv4hlBLgONlWN0yT2EdgndGG/+U', + 'LTc9+6vTMugGeIFxCMzd4Da059Vu06I47NlruFeKaWAhj9R/66zVjs91Bg==', + ].join(''), + }, + 'stable-p256-b': { + alg: 'ecdsa-p256-sha256', + scope: 'stable', + spki: [ + 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV89JSdgJbq1LWLOpOA3p1whizFjd', + 'RPaTiHKLd1im7oW8CXLSYRle46Mi6IpSjVeXrflQeXJpswWUFV60+275lQ==', + ].join(''), + }, + 'stable-mldsa65-a': { + alg: 'ml-dsa-65', + scope: 'stable', + spki: [ + 'MIIHsjALBglghkgBZQMEAxIDggehADJlhCXmJVqiWsyma2Dkd+N9/r+Cs2oWdxef', + 'h4BZs1ZR2IeWkjCtx+k8p6S1iovDUDfiF0Iy+HH7o9TUi9Sk0Dflyi34FwHYiWzj', + 'hPXelx49+UY15Je1PEgNRDxvJByUjCvy5/pcKrGL8pK4szzE8vOu/yY5DYC2c3KS', + 'CClfLLgGt+RN9pDJvZLis5a6ezFnfwyHZmkiJflKTmezgjYxMhy2FQpvrl7NqgnM', + 'XOd84LB7DKrXepjlygjdhtSwVO0lKyoBCX+2wD0JjCIz51+PoKZC4a/T6CU2YUKf', + 'qoYbK0C/UtYi5wHdR2zGj54KtdLlp5qVLlp8dGSmi0Vulc+uRiXf/g83kpK5GXYb', + 'iPfAWu5ztvsB1m6iLHXpZvoAdQ+JmWh83w+h1smRur/n3lrEdKXILNlp9pQ+wxWE', + 'HqTvSy/JTkVwHs2EWcoGt9bvrM4Gt1XI/ANDTYVj5uQ9+w4K9MrT/FtwhPupI71G', + '22cCE4RQ67/dIImgoDwvHYa/2rWpaexAnUkIkRGol6959H/ImvT6i8/YhlcAl5pJ', + 'hbKlp+N69tX09R+WOcnhL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CCQ+bD1Tr6D83k9MH4VjDHXEk+dGoDAvhyP4oMX4e4rIXKQm6', + 'OTFfpL1SYj1fSfoFFjcyX06sKg1PFHVSf97p3S9mqTUNDm61Nd6u7axKACtxnERD', + '8B6jLVZzE09G+iGdDRSZARgbF+5fwbRQlaOfpJi37n0FxKxvgxt/1/0cWZoOT4RK', + '+6nA/K2JkWMIgAtrAbsylYK9OAT7U4gIGAsJ6qY9dUoce8ESPfC92XEue76Hasrd', + '3Q4lpUirXedGsvsrxulxAipeRQSS6Dz6JAooYJ+CtO8v30QmUtG9oa4yKhn0MaDd', + 'pPIYb9qYmlJZXWcdciK4UiThahd1TkjmRU5RGlynuR0qOeH0qogrJcEbe21sCeDw', + 'aOSnrDVQwv63FNLB2RaUwM46S90UC4Ud2l/4LxXa15OBlqi46d19ae9tDv/VIa/A', + 't2mWtYOmTYoQvk124x1n55+18CKl/XyJwCyOganefaJaive6mUVJ1T4hR5xyoPwn', + 'V2vO3we9Z+1RU+cOsK9T2GaFyE5ZsvCFK/BOpP89VpEKpIxQv5e3PRoTadXg2920', + 'Q6bl7mIOw9OAsMeX65evSM3rkUeMKRo27jgIYEO+vU+Kx/6AHu7ErdGZO4OL5nQx', + 'hplAGa4O/U8YT9EsXx39r3utW7h3Th9waAJTvWOYw9bbrGGc3Qc+afuMq6KG0iP1', + 'OyeI6D6/bwkTESzdsAUfQT1PHPz8FwD5zrn6pjTdWlT4D94ycg2iKeOPYVip8DXz', + 'LKelCU4zU8NtkCpuzpbu1F9jYA9xayeKndUB1JZpNL4nnX9bIavSaxKQTvOAegur', + 'NyvNQBXjpFg7T5oFAKDNVg2JphXdUDNG+BCfMN06RIpR1yyjoz2kEX3bilg9QGMy', + '+Yfp9Q5mWTE7+i6j5td2Y7urrQm8N1VSXZuwc4pIdH1LKufUkrw+u3a685eBbXz2', + 'fPiJ5esnE2qvNQxUHb/dfhQTeoE7y+aEZ8nNWht630SwdT6fhGVxFVj08mOxfIRA', + 'tikfDhwd', + ].join(''), + }, + 'stable-mldsa65-b': { + alg: 'ml-dsa-65', + scope: 'stable', + spki: [ + 'MIIHsjALBglghkgBZQMEAxIDggehACB6msp39uVdGBm20hXUUw73+0tnsoiaITNf', + '85z/4mjCNbnYFYp05gUImKH8ZxkxsqQgxqjs0EX7y+ia/YPDNO2zbB8cg/EDljT3', + 'xpQsTmW0dH3Yo4aZI3Mc/BbHl/715lgFLWv/m7Qx4+kQ4rz5yTFQVeAdUuNXaUDD', + 'UiiEl0IBnl+KvlPJTOaeNb2cUk6YS01ZEDFtiKl8NgnsHEwiozE/TJEituCnG5Gr', + '+Qaf+zPpV934dBfdU4dNQJIqLgU7rIwLCRy98REF30MIC6NtLViKWeQzIc1bXH/0', + 'q8GKCEXYvgqtSsaIsmGigDelzzASC15pkOfEYmJWf5yJgizPc/VIkEGdwIrB0wsY', + 'ZhZCjkykomo0v2mavjcj226y7USHy2UN8nZHqWBZJ7uXCJUunLzmK9JwNbRUWtkn', + 'Rixghf4q8Ct1fNr1+OpjPu86gpMdk1Fo/vYIRdkOQuTEXraP7rAdky7/icnEibHt', + '1/gdOqjmR293/5UK8FZiuyXZS7/98FTQGI3IrGwRcy33BjFz42tZzPUEueTvGTzp', + 'jzBpqIMgUGMaYm7dvn5RNtGZizSEQC0oCnKy1gNHm5yiP8T3Hjjm/omYWs9m9sm9', + '4HggbeRqjyNqH3UMBjf2zAzkd+YMcjo7t9gN5JwdWP93ynZFwUU1tCpjzq+mnxOC', + 'JKA/WuXSMhniuS7EkHtE0DS78NIl0ab7lIPGi5eiGuAaVG6BfHSQbbYm018Ibn85', + 'uRL1gE1d/QdneYw6REgkWs4MGT0KOz/1CoqrYfu8XwV0w55yflMa7F+NJ09CddIJ', + 'd0NzgJRRyti6a0wMxPMhiZnDXfr9e3S+zGXsjJuXavBYk9FWq7CJhMq/wx+zgjpa', + '0VhpojOQ8EeF7MfTtKII72b/BDelvBPG4Cj7NXFUYHyQxpZbfQbQu8PBXMk23CQG', + 'SNy3J7gdx55Z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 'hm5Mb4CPJFbjaJR/1z4Zqw2V8ppRiKr1GwRQ7nxrk0e4t44XjE8u9SJM1h+4SGo2', + '7avF69wGTvw23xi301Oe6O3IQG3AF/wN8sfuLfttHvbRVVloks8h8g8PYGmR/3vS', + 'jlUlHot+zL2xo21g7WHrYmxSGg71A+eO5en7hfDXUt6DAnQRKYkOg+iFE2wQArfs', + 'szZWnGERSe29Z9JGU3xOLyI0jCAsYBEg6aD0eunqz1hsOK8DYuq6josZV+iBM++t', + 'w9/bHsT7kfMXKVI6WiIwRrTF2kNUNBSTQi1Ulcyk8ULCqnDk9XC6283HG1F2zWnc', + 'krF36Fztt37QukhNAgoY4qb9lpKwvPze/zFlldOVBKlhfzI6F1HlofoHCmvQwu0e', + 'z2EmDPrEtQ7/Venurbp7NA/m1PF5YAaU2ER2RbE3XpudKM7mvrSorSvMFx8frloz', + 'Z17mXaRoDSLcRJ6nTe5WmXZypaRM1JwCSArEctxA7l8xatWahh/p7XSjsTfkcs/5', + 'KpWh4o8vh/sBTGioRbNHIObu74MQLS6qKpcQKoX+odIsGGpcwMA+2xmBPmgKBM4p', + 'ZoItSvhaMLCLjRh9ylD3Zcsve2rRxGkqggC6pJ++xPXIvXM/0ecsAbr6MFu31xST', + 'f+MhObaH', + ].join(''), + }, + 'beta-p256-a': { + alg: 'ecdsa-p256-sha256', + scope: 'beta', + spki: [ + 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE8O2oBUy5wLgDZCJvdH74Han/HE4N', + '5tWijNfL4kIoM3KEfpzGbcVo+i0/tdFF9Of7NdSzBKROdf1rBgAz8sB8UQ==', + ].join(''), + }, + 'beta-mldsa65-a': { + alg: 'ml-dsa-65', + scope: 'beta', + spki: [ + 'MIIHsjALBglghkgBZQMEAxIDggehANpvPsFuc3Ijsgjs3xFVCs9vQiLSC0WLA6nI', + '7B3WQhOtbWJUkwL1FUnXOxjENqTSKAAZ80Y+0e3MLr1Df8tGsWJzSe5NEAkmDyUi', + 'ZNAD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PTg7XNidc3O8Z6n6JNnrhj/K8J9Jm8DEnkCXZH+X/ECj68x4liw3SdZAceE', + 'JO4CsTWJ2iQzXVV5A6+1fFk/9gJUTeDIBwQVilGMFDK56d5jQUiNsk+ej7eX72q2', + 'DYXK/aHTs4kfoUeoU/ZsIacZO9Kppm3VFKrovVX0w/l0L22Swv/jZoncyRSoqqDk', + 'sIReFTJAY4zsrZsgmg5lSoqFk8ZsWSWv6uaxRdUw+07a8BlMtipIFfZfMlRNTxdf', + 'KE3UHPw+7eYcnJ/CpePt42X8gscC3gRNvCMaMk71Q9K2nlk3kigVKzvOBDIE/1/V', + 'K8HKtehAwa/l8FQ/PoLJNO6za2OUkwAe0OvxHPaAOgmU/JIOoB9Wscny3X+V1S3M', + 'FWFJSr2AlcGD8+gbN7XxpJlOUAxgW85hEVH4ayjhE3ws8Kvy+UEVVlaq9ZmWUIb0', + 'bwHlJJrd', + ].join(''), + }, +}; diff --git a/src/utils/release-signature.ts b/src/utils/release-signature.ts new file mode 100644 index 0000000..774ccd1 --- /dev/null +++ b/src/utils/release-signature.ts @@ -0,0 +1,235 @@ +/** + * Release signatures for the standalone binaries. + * + * A release publishes SHA256SUMS (one ` ` line per binary) and + * SHA256SUMS.sig. The signature covers this message, every line ending in LF: + * + * dcd-cli-release/v1 + * version= + * sha256sums= + * + * The verifier rebuilds the message from the version it asked for, so a valid + * signature for one release can't be replayed under another version. + * + * SHA256SUMS.sig is line-based so the install scripts can read it without jq: + * + * dcd-cli-release-signature/v1 + * + * ... + * + * `ecdsa-p256-sha256` is ECDSA over SHA-256 with a DER-encoded signature; + * `ml-dsa-65` is ML-DSA-65 (FIPS 204) over the message, empty context. + * + * scripts/sign-release.mjs writes this format and install.sh / install.ps1 + * read it; keep all of them in step. + */ +import { type KeyObject, createHash, createPublicKey, verify } from 'node:crypto'; + +import { + REQUIRED_RELEASE_ALGS, + RELEASE_SIGNING_KEYS, + type ReleaseKey, + type ReleaseSignatureAlg, +} from '../config/release-keys.js'; + +export const RELEASE_MESSAGE_HEADER = 'dcd-cli-release/v1'; +export const SIGNATURE_FILE_HEADER = 'dcd-cli-release-signature/v1'; +export const SIGNATURE_FILE_NAME = 'SHA256SUMS.sig'; +/** Upper bound for SHA256SUMS and SHA256SUMS.sig downloads. */ +export const RELEASE_METADATA_MAX_BYTES = 64 * 1024; + +const MAX_SIGNATURE_LINES = 16; +const ALG_RE = /^[a-z0-9-]{1,32}$/; +const KEY_ID_RE = /^[a-z0-9-]{1,64}$/; +const BASE64_RE = /^[A-Za-z0-9+/]+={0,2}$/; +/** A release version as it appears in the signed message: no leading `v`. */ +export const RELEASE_VERSION_RE = /^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$/; + +/** Decoded signature lengths each algorithm may have. */ +const SIGNATURE_BYTES: Record = { + 'ecdsa-p256-sha256': { min: 8, max: 72 }, + 'ml-dsa-65': { min: 3309, max: 3309 }, +}; + +export interface SignatureLine { + alg: string; + keyId: string; + signature: Buffer; +} + +export type ParseResult = + | { lines: SignatureLine[]; ok: true } + | { ok: false; reason: string }; + +export type VerifyResult = + | { keyIds: string[]; ok: true } + | { ok: false; reason: string }; + +export interface VerifyOptions { + keys?: Readonly>; + requiredAlgs?: readonly ReleaseSignatureAlg[]; + /** The exact SHA256SUMS bytes as downloaded. */ + sums: Uint8Array; + /** SHA256SUMS.sig as downloaded. */ + sigFile: Uint8Array; + /** The version that was asked for, without a leading `v`. */ + version: string; +} + +export function sha256Hex(data: Uint8Array): string { + return createHash('sha256').update(data).digest('hex'); +} + +export function releaseMessage(version: string, sumsSha256: string): Buffer { + return Buffer.from( + `${RELEASE_MESSAGE_HEADER}\nversion=${version}\nsha256sums=${sumsSha256}\n`, + 'utf8', + ); +} + +/** Whether a version is a prerelease, which is all a beta key may sign. */ +export function isPrerelease(version: string): boolean { + return version.includes('-'); +} + +export function parseSignatureFile(data: Uint8Array): ParseResult { + if (data.length > RELEASE_METADATA_MAX_BYTES) { + return { ok: false, reason: `${SIGNATURE_FILE_NAME} is larger than ${RELEASE_METADATA_MAX_BYTES} bytes` }; + } + const text = Buffer.from(data).toString('utf8'); + const rows = text.split('\n'); + // One LF after the last line is the normal ending; a missing one is fine too. + if (rows.length > 1 && rows.at(-1) === '') rows.pop(); + if (rows[0] !== SIGNATURE_FILE_HEADER) { + return { ok: false, reason: `${SIGNATURE_FILE_NAME} does not start with ${SIGNATURE_FILE_HEADER}` }; + } + const body = rows.slice(1); + if (body.length > MAX_SIGNATURE_LINES) { + return { ok: false, reason: `${SIGNATURE_FILE_NAME} has more than ${MAX_SIGNATURE_LINES} signatures` }; + } + const lines: SignatureLine[] = []; + for (const [index, row] of body.entries()) { + const fields = row.split(' '); + const [alg, keyId, b64] = fields; + const where = `${SIGNATURE_FILE_NAME} line ${index + 2}`; + if (fields.length !== 3) return { ok: false, reason: `${where} does not have 3 fields` }; + if (!ALG_RE.test(alg)) return { ok: false, reason: `${where} has an invalid algorithm` }; + if (!KEY_ID_RE.test(keyId)) return { ok: false, reason: `${where} has an invalid key id` }; + if (!BASE64_RE.test(b64)) return { ok: false, reason: `${where} has an invalid signature` }; + const signature = Buffer.from(b64, 'base64'); + // Node's decoder skips characters it can't use; insist on a canonical encoding. + if (signature.toString('base64') !== b64) { + return { ok: false, reason: `${where} has an invalid signature` }; + } + lines.push({ alg, keyId, signature }); + } + return { ok: true, lines }; +} + +function loadKey(key: ReleaseKey): KeyObject { + const keyObject = createPublicKey({ + key: Buffer.from(key.spki, 'base64'), + format: 'der', + type: 'spki', + }); + const type = keyObject.asymmetricKeyType; + const curve = keyObject.asymmetricKeyDetails?.namedCurve; + const fits = + key.alg === 'ecdsa-p256-sha256' + ? type === 'ec' && curve === 'prime256v1' + : type === key.alg; + if (!fits) { + throw new Error(`this runtime reads the ${key.alg} key as ${type ?? 'an unknown type'}`); + } + return keyObject; +} + +/** + * Loads every key with this runtime's crypto and returns what went wrong, if + * anything. A runtime that can't read an ML-DSA key would build a binary that + * can never upgrade, so the release workflows run this on the Bun they ship. + */ +export function checkReleaseKeys(keys: Readonly> = RELEASE_SIGNING_KEYS): string[] { + const problems: string[] = []; + for (const [keyId, key] of Object.entries(keys)) { + try { + loadKey(key); + } catch (error) { + problems.push(`${keyId}: ${(error as Error).message}`); + } + } + return problems; +} + +function verifyLine(alg: ReleaseSignatureAlg, keyObject: KeyObject, message: Buffer, signature: Buffer): boolean { + if (alg === 'ecdsa-p256-sha256') { + return verify('sha256', message, { key: keyObject, dsaEncoding: 'der' }, signature); + } + return verify(null, message, keyObject, signature); +} + +/** + * Checks SHA256SUMS.sig against SHA256SUMS for `version`. Never throws. + * + * Lines from keys this build doesn't know are skipped, so a later release can + * add signatures. Every line from a known key must verify: a known key that + * fails, signs with the wrong algorithm, or is a beta key on a stable version + * rejects the whole file. Each required algorithm needs at least one good line. + */ +export function verifyReleaseSignature(options: VerifyOptions): VerifyResult { + const keys = options.keys ?? RELEASE_SIGNING_KEYS; + const requiredAlgs = options.requiredAlgs ?? REQUIRED_RELEASE_ALGS; + const { version } = options; + try { + if (!RELEASE_VERSION_RE.test(version)) { + return { ok: false, reason: `'${version}' is not a release version` }; + } + const parsed = parseSignatureFile(options.sigFile); + if (!parsed.ok) return parsed; + + const message = releaseMessage(version, sha256Hex(options.sums)); + const verified = new Map(); + for (const line of parsed.lines) { + if (!Object.hasOwn(keys, line.keyId)) continue; + const key = keys[line.keyId]; + if (line.alg !== key.alg) { + return { ok: false, reason: `key ${line.keyId} is a ${key.alg} key, but its line says ${line.alg}` }; + } + if (key.scope === 'beta' && !isPrerelease(version)) { + return { ok: false, reason: `beta key ${line.keyId} can't sign stable version ${version}` }; + } + const { min, max } = SIGNATURE_BYTES[key.alg]; + if (line.signature.length < min || line.signature.length > max) { + return { ok: false, reason: `the ${key.alg} signature from ${line.keyId} has the wrong length` }; + } + if (!verifyLine(key.alg, loadKey(key), message, line.signature)) { + return { ok: false, reason: `the signature from ${line.keyId} does not match this release` }; + } + verified.set(key.alg, [...(verified.get(key.alg) ?? []), line.keyId]); + } + + for (const alg of requiredAlgs) { + if (!verified.has(alg)) { + return { ok: false, reason: `no ${alg} signature from a trusted key` }; + } + } + return { ok: true, keyIds: [...verified.values()].flat() }; + } catch (error) { + return { ok: false, reason: `could not check the signature: ${(error as Error).message}` }; + } +} + +export interface SumsEntry { + asset: string; + sha256: string; +} + +/** Parses SHA256SUMS (`<64 hex> ` per line). Unparseable lines are skipped. */ +export function parseSums(data: Uint8Array): SumsEntry[] { + const entries: SumsEntry[] = []; + for (const line of Buffer.from(data).toString('utf8').split('\n')) { + const match = line.match(/^([a-f0-9]{64}) {2}(\S+)$/); + if (match) entries.push({ sha256: match[1], asset: match[2] }); + } + return entries; +} diff --git a/test/fixtures/release-signature/beta/SHA256SUMS b/test/fixtures/release-signature/beta/SHA256SUMS new file mode 100644 index 0000000..675916f --- /dev/null +++ b/test/fixtures/release-signature/beta/SHA256SUMS @@ -0,0 +1,5 @@ +fee31d8718d28543025832cb842bb36f86e0fe1953f532dc030b1e3674d640f3 dcd-darwin-arm64 +ac9f7de405e519e075ee0736e26da5dcb511ea6cf6c5292ce9f4780ceeed3cf6 dcd-darwin-x64 +df42a6d831edf98098e53eb21f16dc5dfb68c2b1bd29bb6b9b40a0de9e84b567 dcd-linux-arm64 +250647a53bb8b4c08b1323c2f6ebf7aac34594f6708d0685072b6a3f7f92f643 dcd-linux-x64 +840b12f8bd03bbe6bb753ec2ca92a80c0d32ee47afa3b3a3e8c599ee8c80420f dcd-windows-x64.exe diff --git a/test/fixtures/release-signature/beta/SHA256SUMS.sig b/test/fixtures/release-signature/beta/SHA256SUMS.sig new file mode 100644 index 0000000..54f3996 --- /dev/null +++ b/test/fixtures/release-signature/beta/SHA256SUMS.sig @@ -0,0 +1,3 @@ +dcd-cli-release-signature/v1 +ecdsa-p256-sha256 test-beta-p256-a MEUCIAysTks/GceIrmKfqJ6VfoC40BeXTCln2HbuuCZ5E/NIAiEAjsBANlXatLCnFqPn7dEycpObzvKgKkKrjWud8mEC/dA= +ml-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9DdTYiZqMYdKzk/StptK9IMGCU2OlSAguXvAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwwSExUf diff --git a/test/fixtures/release-signature/beta/dcd-darwin-arm64 b/test/fixtures/release-signature/beta/dcd-darwin-arm64 new file mode 100755 index 0000000..33017c1 --- /dev/null +++ b/test/fixtures/release-signature/beta/dcd-darwin-arm64 @@ -0,0 +1,2 @@ +#!/bin/sh +echo "dcd 9.9.1-beta.1 (test fixture, dcd-darwin-arm64)" diff --git a/test/fixtures/release-signature/beta/dcd-darwin-x64 b/test/fixtures/release-signature/beta/dcd-darwin-x64 new file mode 100755 index 0000000..d151c1d --- /dev/null +++ b/test/fixtures/release-signature/beta/dcd-darwin-x64 @@ -0,0 +1,2 @@ +#!/bin/sh +echo "dcd 9.9.1-beta.1 (test fixture, dcd-darwin-x64)" diff --git a/test/fixtures/release-signature/beta/dcd-linux-arm64 b/test/fixtures/release-signature/beta/dcd-linux-arm64 new file mode 100755 index 0000000..e45cad8 --- /dev/null +++ b/test/fixtures/release-signature/beta/dcd-linux-arm64 @@ -0,0 +1,2 @@ +#!/bin/sh +echo "dcd 9.9.1-beta.1 (test fixture, dcd-linux-arm64)" diff --git a/test/fixtures/release-signature/beta/dcd-linux-x64 b/test/fixtures/release-signature/beta/dcd-linux-x64 new file mode 100755 index 0000000..4a452ba --- /dev/null +++ b/test/fixtures/release-signature/beta/dcd-linux-x64 @@ -0,0 +1,2 @@ +#!/bin/sh +echo "dcd 9.9.1-beta.1 (test fixture, dcd-linux-x64)" diff --git a/test/fixtures/release-signature/beta/dcd-windows-x64.exe b/test/fixtures/release-signature/beta/dcd-windows-x64.exe new file mode 100755 index 0000000..7ccb9b8 --- /dev/null +++ b/test/fixtures/release-signature/beta/dcd-windows-x64.exe @@ -0,0 +1,2 @@ +#!/bin/sh +echo "dcd 9.9.1-beta.1 (test fixture, dcd-windows-x64.exe)" diff --git a/test/fixtures/release-signature/generate.mjs b/test/fixtures/release-signature/generate.mjs new file mode 100644 index 0000000..d8df202 --- /dev/null +++ b/test/fixtures/release-signature/generate.mjs @@ -0,0 +1,69 @@ +#!/usr/bin/env node +/** + * Regenerates the release-signature test vectors in this directory: + * + * keys.json the four throwaway public keys, in the RELEASE_SIGNING_KEYS shape + * *.pem the two P-256 public keys, for the install script tests + * stable/ a signed fake release, version 9.9.0 + * beta/ a signed fake prerelease, version 9.9.1-beta.1 + * + * The private keys exist only in memory while this runs, so nothing here can + * sign anything else. Run it (Node 24 or later, for ML-DSA) only when the + * signature format changes: + * + * node test/fixtures/release-signature/generate.mjs + */ +import { createHash, generateKeyPairSync, sign } from 'node:crypto'; +import { mkdirSync, rmSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { SIGNATURE_FILE_HEADER, releaseMessage } from '../../../scripts/sign-release.mjs'; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const ASSETS = ['dcd-darwin-arm64', 'dcd-darwin-x64', 'dcd-linux-arm64', 'dcd-linux-x64', 'dcd-windows-x64.exe']; + +const keys = {}; +const privateKeys = {}; +for (const scope of ['stable', 'beta']) { + for (const [alg, idPart, make] of [ + ['ecdsa-p256-sha256', 'p256', () => generateKeyPairSync('ec', { namedCurve: 'prime256v1' })], + ['ml-dsa-65', 'mldsa65', () => generateKeyPairSync('ml-dsa-65')], + ]) { + const keyId = `test-${scope}-${idPart}-a`; + const { privateKey, publicKey } = make(); + keys[keyId] = { alg, scope, spki: publicKey.export({ type: 'spki', format: 'der' }).toString('base64') }; + privateKeys[keyId] = privateKey; + if (idPart === 'p256') { + writeFileSync(path.join(here, `${keyId}.pem`), publicKey.export({ type: 'spki', format: 'pem' })); + } + } +} +writeFileSync(path.join(here, 'keys.json'), `${JSON.stringify(keys, null, 2)}\n`); + +for (const [scope, version] of [['stable', '9.9.0'], ['beta', '9.9.1-beta.1']]) { + const dir = path.join(here, scope); + rmSync(dir, { recursive: true, force: true }); + mkdirSync(dir); + const sumsLines = []; + for (const asset of ASSETS) { + const body = Buffer.from(`#!/bin/sh\necho "dcd ${version} (test fixture, ${asset})"\n`); + writeFileSync(path.join(dir, asset), body, { mode: 0o755 }); + sumsLines.push(`${createHash('sha256').update(body).digest('hex')} ${asset}`); + } + const sums = Buffer.from(`${sumsLines.join('\n')}\n`); + writeFileSync(path.join(dir, 'SHA256SUMS'), sums); + + const message = releaseMessage(version, createHash('sha256').update(sums).digest('hex')); + const lines = [SIGNATURE_FILE_HEADER]; + for (const [keyId, key] of Object.entries(keys)) { + if (key.scope !== scope) continue; + const signature = + key.alg === 'ecdsa-p256-sha256' + ? sign('sha256', message, { key: privateKeys[keyId], dsaEncoding: 'der' }) + : sign(null, message, privateKeys[keyId]); + lines.push(`${key.alg} ${keyId} ${signature.toString('base64')}`); + } + writeFileSync(path.join(dir, 'SHA256SUMS.sig'), `${lines.join('\n')}\n`); +} +console.log('Wrote release-signature fixtures to', here); diff --git a/test/fixtures/release-signature/keys.json b/test/fixtures/release-signature/keys.json new file mode 100644 index 0000000..92a5f69 --- /dev/null +++ b/test/fixtures/release-signature/keys.json @@ -0,0 +1,22 @@ +{ + "test-stable-p256-a": { + "alg": "ecdsa-p256-sha256", + "scope": "stable", + "spki": "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEKArk2PSF3HODfXleD8/XHG0KWI+IAykSNydv1FSmbXWcQ/jU1cMgPZE0QzQXu8HSteF+vrgQmF/W+JqWG3oHoA==" + }, + "test-stable-mldsa65-a": { + "alg": "ml-dsa-65", + "scope": "stable", + "spki": "MIIHsjALBglghkgBZQMEAxIDggehAKxa1Y+AQTZwP6guxhXJ1apni2RD7fvP9yBmRlLbSWwmaOWWgPy9P/CeJ24ynfaUSC9E+k9wl5xIGoOj/6WKu+m1h/u9vMpYy1psIdNilu8WmKSRl0RM6mM7W5MxFijVzmy51P7gKpg7h70S0BnO+W4tcj9fdtWFQlMarDhWX1nSvMYFK8l9WrPvnlAkSEqQ0eKhVqWZiuYu+S14wVdj2DiLHcStWTA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ON3GRt76TSveBE13DnNBycXxQtiZggd4++ik6zdPhXexOeeXC+4h5M16zLAIdJt1rn4Z8fIifioiUar2mPqJPMXPu9LzaLiOnkvxmBVfsCuP1ZvAop+1Toyc/9wk0V8Hlq5gRMfGq4vqumyAcIxv66rpB1bz5DJDuz5ZAOtZArViGtAfeMQ4XTbHNXCuMFapXlTL9MCm0QAgZJ3vO+O5af03v+5" + }, + "test-beta-p256-a": { + "alg": "ecdsa-p256-sha256", + "scope": "beta", + "spki": "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEl/SJr58EzZSrkhem0jisG1OQnp98fOXcn89QnPMUngRrtYQmRZI/ME/ueYujVDzehjT7lR9iWX0jDux+1Cx4rw==" + }, + "test-beta-mldsa65-a": { + "alg": "ml-dsa-65", + "scope": "beta", + "spki": "MIIHsjALBglghkgBZQMEAxIDggehADsflDRN/DgoikN3wM+2/oIdLXESW/9ryKNjQazehXMzTM/+9Ybti/XCbV/jqR8SErf7lx0k6wrWAmKZoN//NTdf3gAbJBbfZzzlgm5H2t+gxQhmx4IE38Pzf7ao7DgMrQI7Z3ymxmBIx/UO8Ud7bk2r3JNKXWGJSZqxJdDzZeExKZfcqClLh0/zJ5Dv6pE7IvxsNTgjKC6hMHOZ2wRZX55VxwW/UUzqALq5xq1u4Qokz/hpwYVOMZpuP3QbiDQKUpf83RYeQsDsLS2Pu4R7MiZxgDyD9BNsyN642CaLE1EyPojQ9DH0TwqZ/T1BebO0yse/IVBQaibFNNUfYEuAjdTfZ2E1dYh9rbAoXWTHEMVbiCNv+LDbCZm6ET2/Q0OTSv3ilM0om+4o3tFjCavTFbNuJMBOSGugw+9VS3jeYm2xJcL58AbQ5G1lFKdB5xIKzKL0KzP/H3Lde3/CDxcxW1jaYKHGJmPSxLcam/0Xiwh4q6g0LbXseBPnPTo/0wgUGlHdUwjtZuEljir7vBXNnCbh1NHvSxp9s6A5eeK6lfrwsPEZu6zZoTtSkFn6klodVxBsp4ZnU9QlcshF+7ib9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4JRQJkn/56qGaMc5ZYFnKOeXF8gntVbcUeyWhNMqRpZEJVbqEvvDtteBibEX1P3EYFh5vz77k71wGQ7m7wHyL7771dvtcDnxcmCuNcGzMui45JkM2saG6DvXWgMkPiG5LSoF1jxhjL3RynY3dKMeyfhTXxcBrEcD7ZeOPeJWiOBJEDm8/UryaaNxY5eaIWBhuet1yEZW+coRenslg9/An5qXuI14ny98elUHSJzINfa3ij3HNZxmqlEBzIKvhD63XoZXSKXFxIBwW6SoiJkNbo5wMEBpJ+/mo1MZZAik9xZvYVS7IAgR1VA6jY956qOSMujy5iPBVIqGSgW3vVrdRCj7pXZgUF3/X37QZavns5mQnYaf7CGxCWgW9uG+ANiRO7S4ie1Tbe2R4GTe58/JNonez3stwxobUTHIY8kgaxKuK6Gm5+HljAP+yCF99XnyElZqfbh+C4zpAZrNO6q9HlI1ti1vth55VcDUzno3UitkZp5dlKEW9VUwWBXWmWxfJ+wUgD6AkdLRg9s4NTdy0s8BR0kb8lsTOUg+YMCGM6OXeLYslzvq5aSwzwT5++ZsJgNhghp/eeab7cupaMyT52HIx4DnLTPsZ3Xx10Z3q4uZINd12QcXOnEs1+0c2D7Mfkr90adJa7mKwCHpFjLDKM4it8NqO+Aod3ejmeXgUgQxDA/wwhkCO2MwAt13kdradfK1fM18Xaa+KPBw6EEzbiKhFRvu0XzeDM+ZptrxsJgB5NCJdazJepN/axdcZvcFEEEy8Bd58B3Mf5BWQO3tasXdRXoNcKEKPO1iW2RBb2unOqd3NjYO67xc45IRBmIifn66APMaH4+WpOe2hSeTs5Gblfl6XxyeM/r8VEzvfKDhcmh1Cv27HiKTOSNIv79CCsffqxa/g3dj3rSZT1K5L/r/a1gzbYtF6T3yjt" + } +} diff --git a/test/fixtures/release-signature/stable/SHA256SUMS b/test/fixtures/release-signature/stable/SHA256SUMS new file mode 100644 index 0000000..b2a2452 --- /dev/null +++ b/test/fixtures/release-signature/stable/SHA256SUMS @@ -0,0 +1,5 @@ +8846997dcb19488da2d1015f6d652566cb5d2063c953b71da0ded23930daa927 dcd-darwin-arm64 +be944431e37aa7dea101dc0d60bb34443561c6c98cf3f89e094635ef872019ce dcd-darwin-x64 +e28e60c47a35f2229a236fdf21675a53048c4fa35af43f8ed98ebcae15ab3c8a dcd-linux-arm64 +89c906cb920034cd6bfb4ca14fd0b53d30992c3c8a040591d2c526bd1033c26f dcd-linux-x64 +bbf4389f2a352a5211f5dc48aac936a1d2fbd8ebd763e57794d97b9eebd1bf58 dcd-windows-x64.exe diff --git a/test/fixtures/release-signature/stable/SHA256SUMS.sig b/test/fixtures/release-signature/stable/SHA256SUMS.sig new file mode 100644 index 0000000..4c61032 --- /dev/null +++ b/test/fixtures/release-signature/stable/SHA256SUMS.sig @@ -0,0 +1,3 @@ +dcd-cli-release-signature/v1 +ecdsa-p256-sha256 test-stable-p256-a MEUCIF0e1kDZO7yBnOPMjMJs/9mmyvLlCUGoy2cG9zhbsinEAiEA9aylVmXlJinhdMjAZBKEweXuhoIQWHahOXzvYEM2Ni0= +ml-dsa-65 test-stable-mldsa65-a YXc3C16bdSjpsZxOpxuDvNkLVBpjJYznO0RET7lFY1GXeGEmfL70Q0Ob5IE3d0nq28UNozqw4e8SK8u/1azZd3fQvuSZegs4vuPuzGGIpPcDj0q3eaDi7CT6N5UJ/yoyPMnPIuc3jwNKVy/RGZhDfX44Y5ojFG+h+L+k+K5CZdS5nB3coSp/BJOv2L4nmceY+pQjs76PLS+lZrV1KaCDGqbrBEoz6rRBZhwifFS2/0ebWpDzW9+pYHiL/FkBncZp2eJOnC+D7QE6ob6khK6utSSTqGsvTpEMAFABPKLpzZmx9olQsf3/FefUO0e0eEgRuP1GTKdJGDhvZ8WCG7ptM6B7c1jIxWJzpLkfRUJSL01dRogJ281l7zkQP9g+CUxVoA0qxe4MLKkhrP+jP9w5bNMGBgHhp9XOC3OnKuxMmSAJIWx4vivUPC7GMyPO/Gtp56Abh65tcrD7kAwnzzATS5GSvq0GtFVSw05k04ikb0HcYtwJtcE8NIuge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dP3SJi4ENov+PfMxVot+UglgXtR9nU4wOd2ifQgUaQ5EjPYs1FX3jJC39EoL/Yksxmfzf+aOd2kOazk1fp3AX52fHdAAm2wjjDAqwVGZYxJCjkv0XIDINHOOiLEPznXlgJyHVqoDyqjNsmDtnT2rxuMmmvsG6x/TsbIBDuZStmbaDilZ7hoPxRFXz3R4XrYiR3DavjU/GJpFkFEVRBELKlT8inXSuNl7jcET4uinZGsmV0o1O+MkEy8NsYav/Lbn0+cIKw0Xm7RNSLoe8uPhVb8mfLl1DHyEdz1hVOL+SsinGvfJj6O2khOaJFzzjzDmVkNst7pZ71/6b7l9MbOi+idb4lJnaqXFTJBkUiyux6IXTqbvCRR0nxk6gybthVr+LfH2hWr0gjB0mWIOM6HuclMTWsjiuBtqQB8wRAXnjRBiBMaBL1yEIZmkwuBlfei015kzqo/B/HKqUmqjGTwoo9VKRr2Jo9Pofas0XIZYxkqKcX2gHNVLRdKCIr4paq59F3OqlbhyYatDN+5wESCuN63AcX00D3vJFXpjrmystgmtxVGtNb2oKzCDnkFbtd8MAPqdcSsmro1Wu+UbtBE7KyagIVq/rXM3aAiM6SFxylpmarwc5YoGi+/47QZFHTnCIjpOUwAAAAAAAAAAAAAAAAAAAAAAAAAAABAcRGBsj diff --git a/test/fixtures/release-signature/stable/dcd-darwin-arm64 b/test/fixtures/release-signature/stable/dcd-darwin-arm64 new file mode 100755 index 0000000..6e859ee --- /dev/null +++ b/test/fixtures/release-signature/stable/dcd-darwin-arm64 @@ -0,0 +1,2 @@ +#!/bin/sh +echo "dcd 9.9.0 (test fixture, dcd-darwin-arm64)" diff --git a/test/fixtures/release-signature/stable/dcd-darwin-x64 b/test/fixtures/release-signature/stable/dcd-darwin-x64 new file mode 100755 index 0000000..28cbb9f --- /dev/null +++ b/test/fixtures/release-signature/stable/dcd-darwin-x64 @@ -0,0 +1,2 @@ +#!/bin/sh +echo "dcd 9.9.0 (test fixture, dcd-darwin-x64)" diff --git a/test/fixtures/release-signature/stable/dcd-linux-arm64 b/test/fixtures/release-signature/stable/dcd-linux-arm64 new file mode 100755 index 0000000..26f2451 --- /dev/null +++ b/test/fixtures/release-signature/stable/dcd-linux-arm64 @@ -0,0 +1,2 @@ +#!/bin/sh +echo "dcd 9.9.0 (test fixture, dcd-linux-arm64)" diff --git a/test/fixtures/release-signature/stable/dcd-linux-x64 b/test/fixtures/release-signature/stable/dcd-linux-x64 new file mode 100755 index 0000000..8e90471 --- /dev/null +++ b/test/fixtures/release-signature/stable/dcd-linux-x64 @@ -0,0 +1,2 @@ +#!/bin/sh +echo "dcd 9.9.0 (test fixture, dcd-linux-x64)" diff --git a/test/fixtures/release-signature/stable/dcd-windows-x64.exe b/test/fixtures/release-signature/stable/dcd-windows-x64.exe new file mode 100755 index 0000000..c01205a --- /dev/null +++ b/test/fixtures/release-signature/stable/dcd-windows-x64.exe @@ -0,0 +1,2 @@ +#!/bin/sh +echo "dcd 9.9.0 (test fixture, dcd-windows-x64.exe)" diff --git a/test/fixtures/release-signature/test-beta-p256-a.pem b/test/fixtures/release-signature/test-beta-p256-a.pem new file mode 100644 index 0000000..8d402ca --- /dev/null +++ b/test/fixtures/release-signature/test-beta-p256-a.pem @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEl/SJr58EzZSrkhem0jisG1OQnp98 +fOXcn89QnPMUngRrtYQmRZI/ME/ueYujVDzehjT7lR9iWX0jDux+1Cx4rw== +-----END PUBLIC KEY----- diff --git a/test/fixtures/release-signature/test-stable-p256-a.pem b/test/fixtures/release-signature/test-stable-p256-a.pem new file mode 100644 index 0000000..0de5a9e --- /dev/null +++ b/test/fixtures/release-signature/test-stable-p256-a.pem @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEKArk2PSF3HODfXleD8/XHG0KWI+I +AykSNydv1FSmbXWcQ/jU1cMgPZE0QzQXu8HSteF+vrgQmF/W+JqWG3oHoA== +-----END PUBLIC KEY----- diff --git a/test/helpers/release-fixture-server.ts b/test/helpers/release-fixture-server.ts new file mode 100644 index 0000000..28d9347 --- /dev/null +++ b/test/helpers/release-fixture-server.ts @@ -0,0 +1,94 @@ +import { readFileSync } from 'node:fs'; +import { type Server, createServer } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +/** + * A stand-in for get.devicecloud.dev that serves the signed test releases in + * test/fixtures/release-signature/ (see generate.mjs there): + * + * GET /latest.json[?channel=beta] { version } + * GET /download// a file of the release mapped to + * + * Each test maps versions to a fixture directory, and can drop, alter or + * replace any file of that release to play a tampered or half-published one. + */ +export const RELEASE_FIXTURES = fileURLToPath(new URL('../fixtures/release-signature/', import.meta.url)); + +export interface FixtureRelease { + /** Which signed fixture release to serve. */ + dir: 'beta' | 'stable'; + /** Files that answer 404. */ + omit?: string[]; + /** Replacement contents for a file. */ + replace?: Record; + /** Files served with their first byte flipped. */ + tamper?: string[]; +} + +export interface FixtureServer { + close(): Promise; + latest: { beta: null | string; stable: null | string }; + releases: Map; + /** Every path requested, in order. */ + requests: string[]; + url: string; +} + +export function readFixture(dir: 'beta' | 'stable', file: string): Buffer { + return readFileSync(path.join(RELEASE_FIXTURES, dir, file)); +} + +export async function startFixtureServer(): Promise { + const releases = new Map(); + const latest: FixtureServer['latest'] = { beta: null, stable: null }; + const requests: string[] = []; + + const server: Server = createServer((req, res) => { + const url = new URL(req.url ?? '/', 'http://fixture'); + requests.push(url.pathname); + if (url.pathname === '/latest.json') { + const channel = url.searchParams.get('channel') === 'beta' ? 'beta' : 'stable'; + res.setHeader('content-type', 'application/json'); + res.end(JSON.stringify({ channel, version: latest[channel] })); + return; + } + const match = url.pathname.match(/^\/download\/v?([^/]+)\/([^/]+)$/); + const release = match ? releases.get(match[1]) : undefined; + if (!match || !release || release.omit?.includes(match[2])) { + res.statusCode = 404; + res.end('Not Found'); + return; + } + const file = match[2]; + let body: Buffer; + if (release.replace && file in release.replace) { + body = Buffer.from(release.replace[file]); + } else { + try { + body = readFixture(release.dir, file); + } catch { + res.statusCode = 404; + res.end('Not Found'); + return; + } + } + if (release.tamper?.includes(file)) { + body = Buffer.from(body); + body[0] ^= 1; + } + res.setHeader('content-type', 'application/octet-stream'); + res.end(body); + }); + + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const { port } = server.address() as AddressInfo; + return { + close: () => new Promise((resolve) => server.close(() => resolve())), + latest, + releases, + requests, + url: `http://127.0.0.1:${port}`, + }; +} diff --git a/test/unit/install-ps1.test.ts b/test/unit/install-ps1.test.ts new file mode 100644 index 0000000..b5c02d9 --- /dev/null +++ b/test/unit/install-ps1.test.ts @@ -0,0 +1,178 @@ +import { expect } from 'chai'; +import { spawn, spawnSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { + type FixtureServer, + readFixture, + startFixtureServer, +} from '../helpers/release-fixture-server.js'; + +/** + * install.ps1's release-signature check, run by Windows PowerShell 5.1 and by + * PowerShell 7 against a stand-in download host, with the script's release + * keys swapped for the fixture keys and $FirstSigned for 9.0.0. + * + * Windows CI only: install.ps1 adds its install directory to the user's PATH + * in the registry, which a developer's machine should not collect from tests. + */ +const ROOT = fileURLToPath(new URL('../../', import.meta.url)); +const FIRST_SIGNED = '9.0.0'; +const ASSET = 'dcd-windows-x64.exe'; +const FIXTURE_KEYS = JSON.parse( + fs.readFileSync(path.join(ROOT, 'test/fixtures/release-signature/keys.json'), 'utf8'), +) as Record; + +/** install.ps1 with the fixture P-256 keys in place of the release keys. */ +function installerWithTestKeys(): string { + const script = fs.readFileSync(path.join(ROOT, 'install.ps1'), 'utf8'); + const entries = ['test-stable-p256-a', 'test-beta-p256-a'].map((keyId) => { + // A P-256 SPKI ends with the uncompressed point: 0x04, X, Y. + const point = Buffer.from(FIXTURE_KEYS[keyId].spki, 'base64').subarray(-64); + const x = point.subarray(0, 32).toString('base64'); + const y = point.subarray(32).toString('base64'); + return ` '${keyId}' = @{ Scope = '${FIXTURE_KEYS[keyId].scope}'; X = '${x}'; Y = '${y}' }`; + }); + const block = ['# >>> release keys >>>', '$ReleaseKeys = @{', ...entries, '}', '# <<< release keys <<<'].join('\n'); + const swapped = script + .replace(/# >>> release keys >>>[\s\S]*# <<< release keys << process.platform === 'win32' && spawnSync(shell, ['-NoProfile', '-Command', 'exit 0']).status === 0, +); + +interface Run { + installed: Buffer | null; + output: string; + status: null | number; +} + +describe('install.ps1 release signature check', function () { + if (process.platform !== 'win32' || !process.env.CI) return; + this.timeout(120_000); + + let server: FixtureServer; + let work: string; + let script: string; + + before(async () => { + server = await startFixtureServer(); + work = fs.mkdtempSync(path.join(os.tmpdir(), 'dcd-install-ps1-')); + script = path.join(work, 'install.ps1'); + fs.writeFileSync(script, installerWithTestKeys()); + }); + + after(async () => { + await server.close(); + fs.rmSync(work, { recursive: true, force: true }); + }); + + beforeEach(() => { + server.releases.clear(); + server.latest.stable = null; + server.latest.beta = null; + }); + + async function install(shell: string, env: Record = {}): Promise { + const installDir = fs.mkdtempSync(path.join(work, 'bin-')); + // Each shell builds its own PSModulePath, as in a fresh session. One + // inherited from a PowerShell 7 parent (the CI step) points Windows + // PowerShell 5.1 at PowerShell 7's modules, and Get-FileHash fails to load. + const inherited = Object.fromEntries( + Object.entries(process.env).filter(([name]) => name.toLowerCase() !== 'psmodulepath'), + ); + const child = spawn(shell, ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', script], { + env: { + ...inherited, + DCD_BETA: '', + DCD_DOWNLOAD_BASE: server.url, + DCD_INSTALL_DIR: installDir, + DCD_REQUIRE_SIGNATURE: '', + DCD_VERSION: '', + ...env, + }, + }); + let output = ''; + child.stdout.on('data', (chunk) => (output += chunk)); + child.stderr.on('data', (chunk) => (output += chunk)); + const status = await new Promise((resolve) => child.on('close', resolve)); + const target = path.join(installDir, 'dcd.exe'); + return { installed: fs.existsSync(target) ? fs.readFileSync(target) : null, output, status }; + } + + for (const shell of SHELLS) { + describe(shell, () => { + it('installs the latest stable release once its signature verifies', async () => { + server.latest.stable = '9.9.0'; + server.releases.set('9.9.0', { dir: 'stable' }); + const run = await install(shell); + expect(run.status, run.output).to.equal(0); + expect(run.output).to.include('Release signature verified (test-stable-p256-a)'); + expect(run.installed).to.deep.equal(readFixture('stable', ASSET)); + }); + + it('installs a beta signed with a beta key', async () => { + server.latest.beta = '9.9.1-beta.1'; + server.releases.set('9.9.1-beta.1', { dir: 'beta' }); + const run = await install(shell, { DCD_BETA: '1' }); + expect(run.status, run.output).to.equal(0); + expect(run.output).to.include('Release signature verified (test-beta-p256-a)'); + }); + + it('refuses an altered SHA256SUMS', async () => { + server.releases.set('9.9.0', { dir: 'stable', tamper: ['SHA256SUMS'] }); + const run = await install(shell, { DCD_VERSION: 'v9.9.0' }); + expect(run.status).to.not.equal(0); + expect(run.output).to.include('does not match release 9.9.0'); + expect(run.installed).to.equal(null); + }); + + it('refuses a binary that does not match the signed SHA256SUMS', async () => { + server.releases.set('9.9.0', { dir: 'stable', tamper: [ASSET] }); + const run = await install(shell, { DCD_VERSION: '9.9.0' }); + expect(run.status).to.not.equal(0); + expect(run.output).to.include('Checksum mismatch'); + expect(run.installed).to.equal(null); + }); + + it('refuses a beta key on a stable version', async () => { + server.releases.set('9.9.1', { dir: 'beta' }); + const run = await install(shell, { DCD_VERSION: '9.9.1' }); + expect(run.status).to.not.equal(0); + expect(run.output).to.include("which can't sign a stable release"); + }); + + it('refuses a missing signature on a version that should be signed', async () => { + server.releases.set('9.9.0', { dir: 'stable', omit: ['SHA256SUMS.sig'] }); + const run = await install(shell, { DCD_VERSION: '9.9.0' }); + expect(run.status).to.not.equal(0); + expect(run.output).to.include('has no SHA256SUMS.sig'); + }); + + it('warns for a release from before signing, and refuses it under DCD_REQUIRE_SIGNATURE', async () => { + server.releases.set('8.0.0', { dir: 'stable', omit: ['SHA256SUMS.sig'] }); + const relaxed = await install(shell, { DCD_VERSION: '8.0.0' }); + expect(relaxed.status, relaxed.output).to.equal(0); + expect(relaxed.output).to.include('Release signature not checked'); + const strict = await install(shell, { DCD_REQUIRE_SIGNATURE: '1', DCD_VERSION: '8.0.0' }); + expect(strict.status).to.not.equal(0); + expect(strict.output).to.include('DCD_REQUIRE_SIGNATURE is set'); + }); + + it('refuses a prerelease offered on the stable channel', async () => { + server.latest.stable = '9.9.1-beta.1'; + server.releases.set('9.9.1-beta.1', { dir: 'beta' }); + const run = await install(shell); + expect(run.status).to.not.equal(0); + expect(run.output).to.include('The stable channel returned prerelease 9.9.1-beta.1'); + }); + }); + } +}); diff --git a/test/unit/install-sh.test.ts b/test/unit/install-sh.test.ts new file mode 100644 index 0000000..8807226 --- /dev/null +++ b/test/unit/install-sh.test.ts @@ -0,0 +1,277 @@ +import { expect } from 'chai'; +import { spawn, spawnSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { + RELEASE_FIXTURES, + type FixtureServer, + readFixture, + startFixtureServer, +} from '../helpers/release-fixture-server.js'; + +/** + * install.sh's release-signature check, run as users run it: a real shell + * executing the script against a stand-in download host. The script's own + * release keys are swapped for the fixture keys, and FIRST_SIGNED for 9.0.0, + * so the fixture releases (9.9.0 stable, 9.9.1-beta.1 beta) count as signed. + */ +const ROOT = fileURLToPath(new URL('../../', import.meta.url)); +const FIRST_SIGNED = '9.0.0'; + +const ASSET = `dcd-${process.platform}-${process.arch}`; + +/** The absolute path of a command, or '' (spawn looks a bare name up in the child's PATH). */ +function which(name: string): string { + return spawnSync('sh', ['-c', `command -v ${name}`], { encoding: 'utf8' }).stdout.trim(); +} + +// `sh` is dash on Debian/Ubuntu and bash in POSIX mode on macOS. +const SHELLS: string[][] = [[which('sh')]]; +if (which('dash')) SHELLS.push([which('dash')]); +if (which('bash')) SHELLS.push([which('bash'), '--posix']); + +/** install.sh with the fixture P-256 keys in place of the release keys. */ +function installerWithTestKeys(): string { + const script = fs.readFileSync(path.join(ROOT, 'install.sh'), 'utf8'); + const pem = (keyId: string) => + fs + .readFileSync(path.join(RELEASE_FIXTURES, `${keyId}.pem`), 'utf8') + .trim() + .split('\n') + .map((line) => `'${line}'`) + .join(' '); + const block = [ + '# >>> release keys >>>', + 'release_key_pem() {', + ' case "$1" in', + ` test-stable-p256-a) printf '%s\\n' ${pem('test-stable-p256-a')} ;;`, + ` test-beta-p256-a) printf '%s\\n' ${pem('test-beta-p256-a')} ;;`, + ' *) return 1 ;;', + ' esac', + '}', + 'release_key_scope() {', + ' case "$1" in', + ' test-stable-p256-a) printf "stable\\n" ;;', + ' test-beta-p256-a) printf "beta\\n" ;;', + ' *) return 1 ;;', + ' esac', + '}', + '# <<< release keys <<<', + ].join('\n'); + const swapped = script + .replace(/# >>> release keys >>>[\s\S]*# <<< release keys << { + server = await startFixtureServer(); + work = fs.mkdtempSync(path.join(os.tmpdir(), 'dcd-install-sh-')); + script = path.join(work, 'install.sh'); + fs.writeFileSync(script, installerWithTestKeys()); + }); + + after(async () => { + await server.close(); + fs.rmSync(work, { recursive: true, force: true }); + }); + + beforeEach(() => { + server.releases.clear(); + server.latest.stable = null; + server.latest.beta = null; + }); + + async function install(shell: string[], env: Record = {}): Promise { + const home = fs.mkdtempSync(path.join(work, 'home-')); + const tmp = fs.mkdtempSync(path.join(work, 'tmp-')); + const installDir = path.join(home, 'bin'); + const child = spawn(shell[0], [...shell.slice(1), script], { + env: { + DCD_DOWNLOAD_BASE: server.url, + DCD_INSTALL_DIR: installDir, + HOME: home, + NO_COLOR: '1', + PATH: process.env.PATH ?? '', + SHELL: '/bin/sh', + TMPDIR: tmp, + ...env, + }, + }); + let stdout = ''; + let stderr = ''; + child.stdout.on('data', (chunk) => (stdout += chunk)); + child.stderr.on('data', (chunk) => (stderr += chunk)); + const status = await new Promise((resolve) => child.on('close', resolve)); + // Nothing is left behind in TMPDIR, whatever the outcome. + expect(fs.readdirSync(tmp), 'leftover temp files').to.deep.equal([]); + const target = path.join(installDir, 'dcd'); + return { installed: fs.existsSync(target) ? fs.readFileSync(target) : null, status, stderr, stdout }; + } + + for (const shell of SHELLS) { + describe(shell.map((part) => path.basename(part)).join(' '), () => { + it('installs the latest stable release once its signature verifies', async () => { + server.latest.stable = '9.9.0'; + server.releases.set('9.9.0', { dir: 'stable' }); + const run = await install(shell); + expect(run.status, run.stderr).to.equal(0); + expect(run.stdout).to.include('Release signature verified (test-stable-p256-a)'); + expect(run.installed).to.deep.equal(readFixture('stable', ASSET)); + }); + + it('installs a beta signed with a beta key', async () => { + server.latest.beta = '9.9.1-beta.1'; + server.releases.set('9.9.1-beta.1', { dir: 'beta' }); + const run = await install(shell, { DCD_BETA: '1' }); + expect(run.status, run.stderr).to.equal(0); + expect(run.stdout).to.include('Release signature verified (test-beta-p256-a)'); + expect(run.installed).to.deep.equal(readFixture('beta', ASSET)); + }); + + it('accepts a pinned version with a leading v', async () => { + server.releases.set('9.9.0', { dir: 'stable' }); + const run = await install(shell, { DCD_VERSION: 'v9.9.0' }); + expect(run.status, run.stderr).to.equal(0); + expect(run.stdout).to.include('Release signature verified'); + }); + + it('refuses an altered SHA256SUMS', async () => { + server.releases.set('9.9.0', { dir: 'stable', tamper: ['SHA256SUMS'] }); + const run = await install(shell, { DCD_VERSION: '9.9.0' }); + expect(run.status).to.equal(1); + expect(run.stderr).to.include('does not match release 9.9.0'); + expect(run.installed).to.equal(null); + }); + + it('refuses a binary that does not match the signed SHA256SUMS', async () => { + server.releases.set('9.9.0', { dir: 'stable', tamper: [ASSET] }); + const run = await install(shell, { DCD_VERSION: '9.9.0' }); + expect(run.status).to.equal(1); + expect(run.stderr).to.include('Checksum mismatch'); + expect(run.installed).to.equal(null); + }); + + it('refuses a signed release served under another version', async () => { + server.releases.set('9.9.2', { dir: 'stable' }); + const run = await install(shell, { DCD_VERSION: '9.9.2' }); + expect(run.status).to.equal(1); + expect(run.stderr).to.include('does not match release 9.9.2'); + expect(run.installed).to.equal(null); + }); + + it('refuses a beta key on a stable version', async () => { + server.releases.set('9.9.1', { dir: 'beta' }); + const run = await install(shell, { DCD_VERSION: '9.9.1' }); + expect(run.status).to.equal(1); + expect(run.stderr).to.include("beta key test-beta-p256-a, which can't sign a stable release"); + expect(run.installed).to.equal(null); + }); + + it('refuses a signature file with no trusted key', async () => { + server.releases.set('9.9.0', { + dir: 'stable', + replace: { 'SHA256SUMS.sig': 'dcd-cli-release-signature/v1\n' }, + }); + const run = await install(shell, { DCD_VERSION: '9.9.0' }); + expect(run.status).to.equal(1); + expect(run.stderr).to.include('no signature from a key this installer trusts'); + }); + + it('refuses a malformed signature line', async () => { + server.releases.set('9.9.0', { + dir: 'stable', + replace: { 'SHA256SUMS.sig': 'dcd-cli-release-signature/v1\necdsa-p256-sha256 test-stable-p256-a * x\n' }, + }); + const run = await install(shell, { DCD_VERSION: '9.9.0' }); + expect(run.status).to.equal(1); + expect(run.stderr).to.include('malformed line'); + }); + + it('refuses a missing signature on a version that should be signed', async () => { + server.releases.set('9.9.0', { dir: 'stable', omit: ['SHA256SUMS.sig'] }); + const run = await install(shell, { DCD_VERSION: '9.9.0' }); + expect(run.status).to.equal(1); + expect(run.stderr).to.include('has no SHA256SUMS.sig'); + expect(run.installed).to.equal(null); + }); + + it('warns, and still checks the checksum, for a release from before signing', async () => { + server.releases.set('8.0.0', { dir: 'stable', omit: ['SHA256SUMS.sig'] }); + const run = await install(shell, { DCD_VERSION: '8.0.0' }); + expect(run.status, run.stderr).to.equal(0); + expect(run.stderr).to.include('Release signature not checked: release 8.0.0 is older than signed releases'); + expect(run.stdout).to.include('Checksum verified'); + }); + + it('treats a prerelease of FIRST_SIGNED as older', async () => { + server.releases.set(`${FIRST_SIGNED}-beta.1`, { dir: 'beta', omit: ['SHA256SUMS.sig'] }); + const run = await install(shell, { DCD_VERSION: `${FIRST_SIGNED}-beta.1` }); + expect(run.status, run.stderr).to.equal(0); + expect(run.stderr).to.include('Release signature not checked'); + }); + + it('refuses an unsigned old release when DCD_REQUIRE_SIGNATURE is set', async () => { + server.releases.set('8.0.0', { dir: 'stable', omit: ['SHA256SUMS.sig'] }); + const run = await install(shell, { DCD_REQUIRE_SIGNATURE: '1', DCD_VERSION: '8.0.0' }); + expect(run.status).to.equal(1); + expect(run.stderr).to.include('DCD_REQUIRE_SIGNATURE is set'); + expect(run.installed).to.equal(null); + }); + + it('warns without openssl, and refuses when DCD_REQUIRE_SIGNATURE is set', async () => { + server.releases.set('9.9.0', { dir: 'stable' }); + const shim = fs.mkdtempSync(path.join(work, 'path-')); + const noOpenssl = pathWithoutOpenssl(shim); + + const relaxed = await install(shell, { DCD_VERSION: '9.9.0', PATH: noOpenssl }); + expect(relaxed.status, relaxed.stderr).to.equal(0); + expect(relaxed.stderr).to.include('Release signature not checked: openssl is not installed'); + + const strict = await install(shell, { DCD_REQUIRE_SIGNATURE: '1', DCD_VERSION: '9.9.0', PATH: noOpenssl }); + expect(strict.status).to.equal(1); + expect(strict.installed).to.equal(null); + }); + + it('refuses a prerelease offered on the stable channel', async () => { + server.latest.stable = '9.9.1-beta.1'; + server.releases.set('9.9.1-beta.1', { dir: 'beta' }); + const run = await install(shell); + expect(run.status).to.equal(1); + expect(run.stderr).to.include('The stable channel returned prerelease 9.9.1-beta.1'); + }); + }); + } +}); diff --git a/test/unit/release-signature.test.ts b/test/unit/release-signature.test.ts new file mode 100644 index 0000000..248ccbc --- /dev/null +++ b/test/unit/release-signature.test.ts @@ -0,0 +1,404 @@ +import { expect } from 'chai'; +import { execFileSync } from 'node:child_process'; +import { createHash, createPublicKey, generateKeyPairSync, sign } from 'node:crypto'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { + REQUIRED_RELEASE_ALGS, + RELEASE_SIGNING_KEYS, + type ReleaseKey, +} from '../../src/config/release-keys.js'; +import { + RELEASE_METADATA_MAX_BYTES, + SIGNATURE_FILE_HEADER, + checkReleaseKeys, + parseSignatureFile, + parseSums, + releaseMessage, + verifyReleaseSignature, +} from '../../src/utils/release-signature.js'; +import { RELEASE_FIXTURES, readFixture } from '../helpers/release-fixture-server.js'; + +const ROOT = fileURLToPath(new URL('../../', import.meta.url)); +const FIXTURE_KEYS = JSON.parse( + fs.readFileSync(path.join(RELEASE_FIXTURES, 'keys.json'), 'utf8'), +) as Record; +const P256_ONLY = ['ecdsa-p256-sha256'] as const; + +/** Node 22 has no ML-DSA; Node 24+ and the Bun the binaries ship with do. */ +const HAS_ML_DSA = (() => { + try { + generateKeyPairSync('ml-dsa-65' as Parameters[0]); + return true; + } catch { + return false; + } +})(); + +function needsMlDsa(this: Mocha.Context) { + if (!HAS_ML_DSA) this.skip(); +} + +const stable = { + sigFile: readFixture('stable', 'SHA256SUMS.sig'), + sums: readFixture('stable', 'SHA256SUMS'), + version: '9.9.0', +}; +const beta = { + sigFile: readFixture('beta', 'SHA256SUMS.sig'), + sums: readFixture('beta', 'SHA256SUMS'), + version: '9.9.1-beta.1', +}; + +function sigLines(file: Buffer): string[] { + return file.toString('utf8').trimEnd().split('\n').slice(1); +} + +function sigFileOf(...lines: string[]): Buffer { + return Buffer.from(`${[SIGNATURE_FILE_HEADER, ...lines].join('\n')}\n`); +} + +/** A P-256 key made for one test, with its ReleaseKey entry. */ +function freshP256(scope: ReleaseKey['scope'] = 'stable') { + const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'prime256v1' }); + const key: ReleaseKey = { + alg: 'ecdsa-p256-sha256', + scope, + spki: publicKey.export({ type: 'spki', format: 'der' }).toString('base64'), + }; + const signLine = (keyId: string, version: string, sums: Buffer) => { + const message = releaseMessage(version, createHash('sha256').update(sums).digest('hex')); + const signature = sign('sha256', message, { key: privateKey, dsaEncoding: 'der' }); + return `ecdsa-p256-sha256 ${keyId} ${signature.toString('base64')}`; + }; + return { key, signLine }; +} + +describe('release signatures', () => { + describe('message', () => { + it('is the documented three lines, each ending in LF', () => { + expect(releaseMessage('5.17.0', 'ab'.repeat(32)).toString('utf8')).to.equal( + `dcd-cli-release/v1\nversion=5.17.0\nsha256sums=${'ab'.repeat(32)}\n`, + ); + }); + + it('matches the one scripts/sign-release.mjs signs', async () => { + const signer = await import('../../scripts/sign-release.mjs'); + const digest = 'cd'.repeat(32); + expect(signer.releaseMessage('5.17.0-beta.2', digest)).to.deep.equal( + releaseMessage('5.17.0-beta.2', digest), + ); + expect(signer.SIGNATURE_FILE_HEADER).to.equal(SIGNATURE_FILE_HEADER); + }); + }); + + describe('golden vectors (test/fixtures/release-signature)', () => { + it('verifies the stable release with both algorithms', function () { + needsMlDsa.call(this); + expect(verifyReleaseSignature({ ...stable, keys: FIXTURE_KEYS })).to.deep.equal({ + ok: true, + keyIds: ['test-stable-p256-a', 'test-stable-mldsa65-a'], + }); + }); + + it('verifies the beta release with the beta keys', function () { + needsMlDsa.call(this); + expect(verifyReleaseSignature({ ...beta, keys: FIXTURE_KEYS })).to.deep.equal({ + ok: true, + keyIds: ['test-beta-p256-a', 'test-beta-mldsa65-a'], + }); + }); + + it('verifies the P-256 signature on any runtime', () => { + const p256Keys = { 'test-stable-p256-a': FIXTURE_KEYS['test-stable-p256-a'] }; + const result = verifyReleaseSignature({ ...stable, keys: p256Keys, requiredAlgs: P256_ONLY }); + expect(result).to.deep.equal({ ok: true, keyIds: ['test-stable-p256-a'] }); + }); + + it('lists the fixture assets in SHA256SUMS', () => { + expect(parseSums(stable.sums).map((entry) => entry.asset)).to.include.members([ + 'dcd-darwin-arm64', + 'dcd-linux-x64', + 'dcd-windows-x64.exe', + ]); + }); + }); + + describe('refuses', () => { + const p256Keys = { 'test-stable-p256-a': FIXTURE_KEYS['test-stable-p256-a'] }; + const check = (overrides: Partial[0]>) => + verifyReleaseSignature({ ...stable, keys: p256Keys, requiredAlgs: P256_ONLY, ...overrides }); + + it('an altered SHA256SUMS', () => { + const sums = Buffer.from(stable.sums); + sums[3] ^= 1; + expect(check({ sums })).to.deep.include({ ok: false }); + }); + + it('the same files under another version', () => { + const result = check({ version: '9.9.1' }); + expect(result.ok).to.equal(false); + expect(result).to.have.property('reason').that.includes('does not match'); + }); + + it('a version with a leading v', () => { + expect(check({ version: 'v9.9.0' })).to.deep.equal({ ok: false, reason: "'v9.9.0' is not a release version" }); + }); + + it('a file missing a required algorithm', function () { + needsMlDsa.call(this); + const sigFile = sigFileOf(sigLines(stable.sigFile)[0]); + expect(verifyReleaseSignature({ ...stable, keys: FIXTURE_KEYS, sigFile })).to.deep.equal({ + ok: false, + reason: 'no ml-dsa-65 signature from a trusted key', + }); + }); + + it('a beta key on a stable version', () => { + const keys = { 'test-beta-p256-a': FIXTURE_KEYS['test-beta-p256-a'] }; + const result = verifyReleaseSignature({ ...beta, keys, requiredAlgs: P256_ONLY, version: '9.9.1' }); + expect(result).to.deep.equal({ ok: false, reason: "beta key test-beta-p256-a can't sign stable version 9.9.1" }); + }); + + it('a line whose algorithm is not its key’s', () => { + const [line] = sigLines(stable.sigFile); + const sigFile = sigFileOf(line.replace('ecdsa-p256-sha256', 'ml-dsa-65')); + expect(check({ sigFile })).to.deep.equal({ + ok: false, + reason: 'key test-stable-p256-a is a ecdsa-p256-sha256 key, but its line says ml-dsa-65', + }); + }); + + it('any failing line from a trusted key, even next to a good one', () => { + const fresh = freshP256(); + const keys = { ...p256Keys, 'fresh-p256-a': fresh.key }; + const good = sigLines(stable.sigFile)[0]; + const wrong = fresh.signLine('fresh-p256-a', '9.9.9', stable.sums); + const result = check({ keys, sigFile: sigFileOf(good, wrong) }); + expect(result).to.deep.equal({ ok: false, reason: 'the signature from fresh-p256-a does not match this release' }); + }); + + it('a signature of the wrong length', () => { + const sigFile = sigFileOf(`ecdsa-p256-sha256 test-stable-p256-a ${Buffer.alloc(100).toString('base64')}`); + expect(check({ sigFile })).to.have.property('reason').that.includes('wrong length'); + }); + + for (const [label, file, reason] of [ + ['a wrong header', 'dcd-cli-release-signature/v2\n', 'does not start with'], + ['an extra field', `${SIGNATURE_FILE_HEADER}\necdsa-p256-sha256 test-stable-p256-a AAAA extra\n`, 'does not have 3 fields'], + ['a doubled space', `${SIGNATURE_FILE_HEADER}\necdsa-p256-sha256 test-stable-p256-a AAAA\n`, 'does not have 3 fields'], + ['a CRLF line ending', `${SIGNATURE_FILE_HEADER}\r\n`, 'does not start with'], + ['an invalid key id', `${SIGNATURE_FILE_HEADER}\necdsa-p256-sha256 Test_Key AAAA\n`, 'invalid key id'], + ['non-canonical base64', `${SIGNATURE_FILE_HEADER}\necdsa-p256-sha256 k AAB=\n`, 'invalid signature'], + ['a blank line', `${SIGNATURE_FILE_HEADER}\n\n`, 'does not have 3 fields'], + ['too many lines', `${SIGNATURE_FILE_HEADER}\n${'x k AAAA\n'.repeat(17)}`, 'more than 16'], + ['an oversize file', `${SIGNATURE_FILE_HEADER}\n${'A'.repeat(RELEASE_METADATA_MAX_BYTES)}`, 'larger than'], + ] as const) { + it(`a signature file with ${label}`, () => { + const result = check({ sigFile: Buffer.from(file) }); + expect(result.ok).to.equal(false); + expect(result).to.have.property('reason').that.includes(reason); + }); + } + }); + + describe('accepts', () => { + const p256Keys = { 'test-stable-p256-a': FIXTURE_KEYS['test-stable-p256-a'] }; + + it('a final line with no LF', () => { + const sigFile = Buffer.from(stable.sigFile.toString('utf8').trimEnd()); + expect(verifyReleaseSignature({ ...stable, keys: p256Keys, requiredAlgs: P256_ONLY, sigFile }).ok).to.equal(true); + }); + + it('lines for keys and algorithms it does not know', () => { + const sigFile = sigFileOf( + 'slh-dsa-shake-128s future-key-a AAAA', + ...sigLines(stable.sigFile), + 'ecdsa-p256-sha256 stable-p256-z AAAA', + ); + expect(verifyReleaseSignature({ ...stable, keys: p256Keys, requiredAlgs: P256_ONLY, sigFile }).ok).to.equal(true); + }); + + it('a stable key on a prerelease', () => { + const fresh = freshP256('stable'); + const sigFile = sigFileOf(fresh.signLine('fresh-p256-a', '1.0.0-beta.1', stable.sums)); + const result = verifyReleaseSignature({ + keys: { 'fresh-p256-a': fresh.key }, + requiredAlgs: P256_ONLY, + sigFile, + sums: stable.sums, + version: '1.0.0-beta.1', + }); + expect(result).to.deep.equal({ ok: true, keyIds: ['fresh-p256-a'] }); + }); + }); + + describe('parseSignatureFile', () => { + it('decodes each line', () => { + const parsed = parseSignatureFile(stable.sigFile); + expect(parsed.ok).to.equal(true); + if (!parsed.ok) return; + expect(parsed.lines.map((line) => [line.alg, line.keyId, line.signature.length > 0])).to.deep.equal([ + ['ecdsa-p256-sha256', 'test-stable-p256-a', true], + ['ml-dsa-65', 'test-stable-mldsa65-a', true], + ]); + }); + }); + + describe('built-in keys', () => { + const pemDir = path.join(ROOT, 'release-keys'); + const pemIds = fs.readdirSync(pemDir).map((file) => file.replace(/\.pem$/, '')).sort(); + + it('requires one classical and one post-quantum signature', () => { + expect([...REQUIRED_RELEASE_ALGS]).to.deep.equal(['ecdsa-p256-sha256', 'ml-dsa-65']); + }); + + it('has a PEM in release-keys/ for every key, and no other', () => { + expect(pemIds).to.deep.equal(Object.keys(RELEASE_SIGNING_KEYS).sort()); + for (const id of pemIds) { + const der = createPublicKey(fs.readFileSync(path.join(pemDir, `${id}.pem`))).export({ type: 'spki', format: 'der' }); + expect(der.toString('base64'), id).to.equal(RELEASE_SIGNING_KEYS[id].spki); + } + }); + + it('names each key --, matching its entry', () => { + for (const [id, key] of Object.entries(RELEASE_SIGNING_KEYS)) { + const match = id.match(/^(stable|beta)-(p256|mldsa65)-[a-z]$/); + expect(match, id).to.not.equal(null); + expect(key.scope, id).to.equal(match?.[1]); + expect(key.alg, id).to.equal(match?.[2] === 'p256' ? 'ecdsa-p256-sha256' : 'ml-dsa-65'); + } + }); + + it('has a stable and a beta key for each algorithm', () => { + for (const alg of REQUIRED_RELEASE_ALGS) { + for (const scope of ['stable', 'beta']) { + const found = Object.values(RELEASE_SIGNING_KEYS).some((key) => key.alg === alg && key.scope === scope); + expect(found, `${scope} ${alg}`).to.equal(true); + } + } + }); + + it('loads every P-256 key on this runtime', () => { + const p256 = Object.fromEntries( + Object.entries(RELEASE_SIGNING_KEYS).filter(([, key]) => key.alg === 'ecdsa-p256-sha256'), + ); + expect(checkReleaseKeys(p256)).to.deep.equal([]); + }); + + it('loads every ML-DSA key on a runtime that has ML-DSA', function () { + needsMlDsa.call(this); + expect(checkReleaseKeys()).to.deep.equal([]); + }); + + // From the keys in the source, not from file names: these ids are handed + // to a shell. The test above holds the release-keys/ file names to the same list. + const p256Ids = Object.keys(RELEASE_SIGNING_KEYS) + .filter((id) => RELEASE_SIGNING_KEYS[id].alg === 'ecdsa-p256-sha256') + .sort(); + + it('embeds the same P-256 keys and scopes in install.sh', function () { + if (process.platform === 'win32') this.skip(); + const script = fs.readFileSync(path.join(ROOT, 'install.sh'), 'utf8'); + const block = script.match(/# >>> release keys >>>[\s\S]*# <<< release keys << match[1]); + expect(ids.sort()).to.deep.equal(p256Ids); + }); + + it('embeds the same P-256 keys and scopes in install.ps1', () => { + const script = fs.readFileSync(path.join(ROOT, 'install.ps1'), 'utf8'); + const block = script.match(/# >>> release keys >>>[\s\S]*# <<< release keys << entry[1]).sort()).to.deep.equal(p256Ids); + for (const [, id, scope, x, y] of entries) { + const jwk = createPublicKey(fs.readFileSync(path.join(pemDir, `${id}.pem`))).export({ format: 'jwk' }); + expect(Buffer.from(x, 'base64').toString('base64url'), `${id} X`).to.equal(jwk.x); + expect(Buffer.from(y, 'base64').toString('base64url'), `${id} Y`).to.equal(jwk.y); + expect(scope, id).to.equal(RELEASE_SIGNING_KEYS[id].scope); + } + }); + }); + + describe('scripts/sign-release.mjs', () => { + type Signer = typeof import('../../scripts/sign-release.mjs'); + let signer: Signer; + before(async () => { + signer = await import('../../scripts/sign-release.mjs'); + }); + + function makeKeys(channel: 'beta' | 'stable') { + const ec = generateKeyPairSync('ec', { namedCurve: 'prime256v1' }); + const pq = generateKeyPairSync('ml-dsa-65' as Parameters[0]); + const pem = (key: typeof ec.privateKey, type: 'pkcs8' | 'spki') => + key.export({ type, format: 'pem' } as never) as unknown as string; + const ids = { ec: `${channel}-p256-a`, pq: `${channel}-mldsa65-a` }; + const publicPems: Record = { + [ids.ec]: pem(ec.publicKey, 'spki'), + [ids.pq]: pem(pq.publicKey, 'spki'), + }; + const keys: Record = { + [ids.ec]: { alg: 'ecdsa-p256-sha256', scope: channel, spki: ec.publicKey.export({ type: 'spki', format: 'der' }).toString('base64') }, + [ids.pq]: { alg: 'ml-dsa-65', scope: channel, spki: pq.publicKey.export({ type: 'spki', format: 'der' }).toString('base64') }, + }; + return { + keys, + publicKeyPem: (keyId: string) => publicPems[keyId], + signingKeys: [ + { keyId: ids.ec, privateKeyPem: pem(ec.privateKey, 'pkcs8') }, + { keyId: ids.pq, privateKeyPem: pem(pq.privateKey, 'pkcs8') }, + ], + }; + } + + it('writes a file the CLI accepts', function () { + needsMlDsa.call(this); + const made = makeKeys('stable'); + const sigFile = signer.signRelease({ + channel: 'stable', + keys: made.signingKeys, + publicKeyPem: made.publicKeyPem, + sums: stable.sums, + version: '5.17.0', + }); + expect(sigFile.startsWith(`${SIGNATURE_FILE_HEADER}\necdsa-p256-sha256 stable-p256-a `)).to.equal(true); + const result = verifyReleaseSignature({ + keys: made.keys, + sigFile: Buffer.from(sigFile), + sums: stable.sums, + version: '5.17.0', + }); + expect(result).to.deep.equal({ ok: true, keyIds: ['stable-p256-a', 'stable-mldsa65-a'] }); + }); + + it('refuses mistakes before signing', function () { + needsMlDsa.call(this); + const made = makeKeys('beta'); + const attempt = (overrides: Record) => () => + signer.signRelease({ + channel: 'beta', + keys: made.signingKeys, + publicKeyPem: made.publicKeyPem, + sums: stable.sums, + version: '5.17.0-beta.1', + ...overrides, + }); + expect(attempt({})).to.not.throw(); + expect(attempt({ version: '5.17.0' })).to.throw('beta releases must be prereleases'); + expect(attempt({ channel: 'stable' })).to.throw("stable releases can't be prereleases"); + expect(attempt({ version: 'v5.17.0-beta.1' })).to.throw('is not a release version'); + expect(attempt({ channel: 'stable', version: '5.17.0' })).to.throw("is not a stable ecdsa-p256-sha256 key id"); + const other = makeKeys('beta'); + expect(attempt({ publicKeyPem: other.publicKeyPem })).to.throw('does not match release-keys/beta-p256-a.pem'); + expect(attempt({ keys: [...made.signingKeys].reverse() })).to.throw('is not a beta ecdsa-p256-sha256 key id'); + }); + }); +}); diff --git a/test/unit/upgrade.test.ts b/test/unit/upgrade.test.ts new file mode 100644 index 0000000..08be0e8 --- /dev/null +++ b/test/unit/upgrade.test.ts @@ -0,0 +1,179 @@ +import { expect } from 'chai'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; + +import { installRelease, resolveUpgradeVersion } from '../../src/commands/upgrade.js'; +import type { ReleaseKey } from '../../src/config/release-keys.js'; +import { RELEASE_FIXTURES, readFixture } from '../helpers/release-fixture-server.js'; + +/** + * `dcd upgrade` replaces the running binary, so it must refuse anything whose + * signature or checksum doesn't hold up, and leave the old binary alone when + * it does. installRelease is driven here against the signed fixture releases + * in test/fixtures/release-signature/, served through a stubbed fetch. + */ +const FIXTURE_KEYS = JSON.parse( + fs.readFileSync(path.join(RELEASE_FIXTURES, 'keys.json'), 'utf8'), +) as Record; +const ASSET = 'dcd-linux-x64'; +const BASE = 'https://get.example.test'; +const OLD_BINARY = Buffer.from('the binary that is running now'); + +/** Serves fixture release `dir` for every version, with optional changes. */ +function fixtureFetch( + dir: 'beta' | 'stable', + change: { omit?: string[]; replace?: Record; status?: Record } = {}, +) { + const requested: string[] = []; + const impl = (async (input: unknown) => { + const url = String(input); + requested.push(url); + const file = url.split('/').pop() ?? ''; + if (change.status?.[file]) return new Response('error', { status: change.status[file] }); + if (change.omit?.includes(file)) return new Response('Not Found', { status: 404 }); + const body = change.replace?.[file] ?? readFixture(dir, file); + return new Response(Buffer.from(body), { status: 200 }); + }) as typeof fetch; + return { impl, requested }; +} + +describe('dcd upgrade', () => { + let work: string; + let destination: string; + + beforeEach(() => { + work = fs.mkdtempSync(path.join(os.tmpdir(), 'dcd-upgrade-')); + destination = path.join(work, 'dcd'); + fs.writeFileSync(destination, OLD_BINARY, { mode: 0o755 }); + }); + + afterEach(() => { + fs.rmSync(work, { recursive: true, force: true }); + }); + + // The P-256 key alone, so these run on Node 22 too; release-signature.test.ts + // covers both algorithms together. + const P256 = { + keys: { 'test-stable-p256-a': FIXTURE_KEYS['test-stable-p256-a'], 'test-beta-p256-a': FIXTURE_KEYS['test-beta-p256-a'] }, + requiredAlgs: ['ecdsa-p256-sha256'] as const, + }; + + async function upgrade(dir: 'beta' | 'stable', version: string, change = {}) { + const fetched = fixtureFetch(dir, change); + const attempt = installRelease({ asset: ASSET, base: BASE, destination, fetchImpl: fetched.impl, version, ...P256 }); + return { attempt, requested: fetched.requested }; + } + + async function refusal(promise: Promise): Promise { + try { + await promise; + } catch (error) { + // Whatever went wrong, the running binary is untouched and nothing is left beside it. + expect(fs.readFileSync(destination)).to.deep.equal(OLD_BINARY); + expect(fs.readdirSync(work)).to.deep.equal(['dcd']); + return (error as Error).message; + } + throw new Error('expected the upgrade to be refused'); + } + + it('installs a release whose signature and checksum verify', async () => { + const { attempt, requested } = await upgrade('stable', '9.9.0'); + expect(await attempt).to.deep.equal({ keyIds: ['test-stable-p256-a'] }); + expect(fs.readFileSync(destination)).to.deep.equal(readFixture('stable', ASSET)); + // The signature is checked before the binary is downloaded. + expect(requested).to.deep.equal([ + `${BASE}/download/9.9.0/SHA256SUMS`, + `${BASE}/download/9.9.0/SHA256SUMS.sig`, + `${BASE}/download/9.9.0/${ASSET}`, + ]); + expect(fs.statSync(destination).mode & 0o111).to.not.equal(0); + }); + + it('installs a beta signed with a beta key', async () => { + const { attempt } = await upgrade('beta', '9.9.1-beta.1'); + expect(await attempt).to.deep.equal({ keyIds: ['test-beta-p256-a'] }); + }); + + it('refuses an altered SHA256SUMS without downloading the binary', async () => { + const sums = Buffer.from(readFixture('stable', 'SHA256SUMS')); + sums[0] ^= 1; + const { attempt, requested } = await upgrade('stable', '9.9.0', { replace: { SHA256SUMS: sums } }); + expect(await refusal(attempt)).to.include('release 9.9.0 failed its signature check'); + expect(requested.some((url) => url.endsWith(ASSET))).to.equal(false); + }); + + it('refuses a binary that does not match the signed SHA256SUMS', async () => { + const { attempt } = await upgrade('stable', '9.9.0', { replace: { [ASSET]: 'something else' } }); + expect(await refusal(attempt)).to.include(`Checksum mismatch for ${ASSET}`); + }); + + it('refuses a signed release served under another version', async () => { + const { attempt } = await upgrade('stable', '9.9.5'); + expect(await refusal(attempt)).to.include('does not match this release'); + }); + + it('refuses a beta-signed release offered as a stable version', async () => { + const { attempt } = await upgrade('beta', '9.9.1'); + expect(await refusal(attempt)).to.include("beta key test-beta-p256-a can't sign stable version 9.9.1"); + }); + + it('refuses a release with no signature, saying it may still be publishing', async () => { + const { attempt } = await upgrade('stable', '9.9.0', { omit: ['SHA256SUMS.sig'] }); + expect(await refusal(attempt)).to.include('release 9.9.0 has no SHA256SUMS.sig yet'); + }); + + it('refuses a release with no SHA256SUMS', async () => { + const { attempt } = await upgrade('stable', '9.9.0', { omit: ['SHA256SUMS'] }); + expect(await refusal(attempt)).to.include('release 9.9.0 has no SHA256SUMS yet'); + }); + + it('reports a server error on the signature as an error, not as unpublished', async () => { + const { attempt } = await upgrade('stable', '9.9.0', { status: { 'SHA256SUMS.sig': 500 } }); + expect(await refusal(attempt)).to.include('HTTP 500'); + }); + + it('refuses an oversized signature file', async () => { + const { attempt } = await upgrade('stable', '9.9.0', { replace: { 'SHA256SUMS.sig': Buffer.alloc(70_000, 65) } }); + expect(await refusal(attempt)).to.include('is larger than'); + }); + + it('refuses an asset missing from SHA256SUMS', async () => { + const fetched = fixtureFetch('stable'); + const attempt = installRelease({ + asset: 'dcd-plan9-x64', + base: BASE, + destination, + fetchImpl: fetched.impl, + version: '9.9.0', + ...P256, + }); + expect(await refusal(attempt)).to.include('SHA256SUMS has no entry for dcd-plan9-x64'); + }); + + it('refuses everything against the built-in keys, which never signed the fixtures', async () => { + const fetched = fixtureFetch('stable'); + const attempt = installRelease({ asset: ASSET, base: BASE, destination, fetchImpl: fetched.impl, version: '9.9.0' }); + expect(await refusal(attempt)).to.include('failed its signature check'); + }); + + describe('resolveUpgradeVersion', () => { + it('drops a leading v', () => { + expect(resolveUpgradeVersion('v5.17.0', 'stable')).to.equal('5.17.0'); + }); + + it('takes a prerelease on the beta channel', () => { + expect(resolveUpgradeVersion('5.17.0-beta.2', 'beta')).to.equal('5.17.0-beta.2'); + }); + + it('refuses a prerelease on the stable channel', () => { + expect(() => resolveUpgradeVersion('5.17.0-beta.2', 'stable')).to.throw('prerelease 5.17.0-beta.2 on the stable channel'); + }); + + it('refuses anything that is not a release version', () => { + for (const bad of ['5.17', '5.17.0/../x', '5.17.0\n', 'latest']) { + expect(() => resolveUpgradeVersion(bad, 'beta'), JSON.stringify(bad)).to.throw('invalid version'); + } + }); + }); +}); From f3d68af55bd56f534b2abd74bd7f8cf11d3f7478 Mon Sep 17 00:00:00 2001 From: finalerock44 <77282157+finalerock44@users.noreply.github.com> Date: Fri, 4 Dec 2026 14:06:09 +0000 Subject: [PATCH 11/12] fix(release): publish the beta tarball by its ./ path (#385) --- .github/workflows/release-beta.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/release-beta.yml b/.github/workflows/release-beta.yml index afb17dc..71ee841 100644 --- a/.github/workflows/release-beta.yml +++ b/.github/workflows/release-beta.yml @@ -319,8 +319,11 @@ jobs: # `npm publish`, not `pnpm publish`: pnpm only learned the OIDC exchange in # v11 and this repo pins pnpm 10.17 in packageManager. No NODE_AUTH_TOKEN on # this step — its presence would take precedence over the OIDC token. + # + # The tarball path starts with ./ on purpose: npm reads `npm-pack/x.tgz` + # as the GitHub shorthand owner/repo and tries to clone it. - name: Publish to npm - run: npm publish npm-pack/*.tgz --tag beta + run: npm publish ./npm-pack/*.tgz --tag beta - name: Create the GitHub prerelease env: From 37a396d2a66914df308173e41d7e9b2ace545a70 Mon Sep 17 00:00:00 2001 From: "dcd-release-please[bot]" <296541543+dcd-release-please[bot]@users.noreply.github.com> Date: Fri, 4 Dec 2026 14:06:33 +0000 Subject: [PATCH 12/12] chore: release 5.17.0 --- CHANGELOG.md | 17 +++++++++++++++++ package.json | 2 +- server.json | 4 ++-- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c4033c..3f8d30b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,22 @@ # Changelog +## [5.17.0](https://github.com/devicecloud-dev/dcd-cli/compare/v5.16.0...v5.17.0) (2026-12-04) + + +### Features + +* sign release binaries ([#382](https://github.com/devicecloud-dev/dcd-cli/issues/382)) ([9da7637](https://github.com/devicecloud-dev/dcd-cli/commit/9da76376df9bd61bfc31fbea3b37ad51f9968ce5)) +* **api:** send the runtime (bun or node) with the CLI identity headers ([#377](https://github.com/devicecloud-dev/dcd-cli/issues/377)) ([ed3c255](https://github.com/devicecloud-dev/dcd-cli/commit/ed3c2554132c8e3e58865ecf1fa73bb54f8c3d71)) +* **device:** show the session's locale in dcd device status ([#374](https://github.com/devicecloud-dev/dcd-cli/issues/374)) ([ee995df](https://github.com/devicecloud-dev/dcd-cli/commit/ee995df83288a2309ebf1f721d09dd9d490eb6c9)) +* **retry:** add dcd retry to rerun failed tests ([#370](https://github.com/devicecloud-dev/dcd-cli/issues/370)) ([e0d5827](https://github.com/devicecloud-dev/dcd-cli/commit/e0d58278672cf381879641590f4da9429ecfd517)) +* **upload:** record iOS executable architectures in binary metadata ([#380](https://github.com/devicecloud-dev/dcd-cli/issues/380)) ([1d3f2b4](https://github.com/devicecloud-dev/dcd-cli/commit/1d3f2b4a525f6dc936d5f2deff40eb079593fa06)) + + +### Bug Fixes + +* **cloud:** mask -e values in the options summary and debug log ([#376](https://github.com/devicecloud-dev/dcd-cli/issues/376)) ([6776b6e](https://github.com/devicecloud-dev/dcd-cli/commit/6776b6e63265c25e2d514f9ef70d0751bf179754)) +* **release:** publish the beta tarball by its ./ path ([#385](https://github.com/devicecloud-dev/dcd-cli/issues/385)) ([f3d68af](https://github.com/devicecloud-dev/dcd-cli/commit/f3d68af55bd56f534b2abd74bd7f8cf11d3f7478)) + ## [5.16.0](https://github.com/devicecloud-dev/dcd-cli/compare/v5.15.0...v5.16.0) (2026-11-30) diff --git a/package.json b/package.json index ebb9f7f..2430235 100644 --- a/package.json +++ b/package.json @@ -63,7 +63,7 @@ "test:unit": "node scripts/test-runner.mjs --unit", "typecheck": "tsc --noEmit -p tsconfig.test.json" }, - "version": "5.16.0", + "version": "5.17.0", "bugs": { "url": "https://discord.gg/gm3mJwcNw8" }, diff --git a/server.json b/server.json index e150f71..4bcafdd 100644 --- a/server.json +++ b/server.json @@ -2,7 +2,7 @@ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json", "name": "dev.devicecloud/dcd", "description": "Run Maestro mobile app tests on devicecloud.dev: submit flows, check status, download artifacts.", - "version": "5.16.0", + "version": "5.17.0", "repository": { "url": "https://github.com/devicecloud-dev/dcd-cli", "source": "github" @@ -11,7 +11,7 @@ { "registryType": "npm", "identifier": "@devicecloud.dev/dcd", - "version": "5.16.0", + "version": "5.17.0", "runtimeHint": "npx", "runtimeArguments": [ {