diff --git a/.github/workflows/cli-checks.yml b/.github/workflows/cli-checks.yml new file mode 100644 index 000000000..ff67a8afb --- /dev/null +++ b/.github/workflows/cli-checks.yml @@ -0,0 +1,37 @@ +name: cli-checks + +on: + pull_request: + paths: + - 'cli/**' + - '.github/workflows/cli-checks.yml' + push: + branches: [main] + paths: + - 'cli/**' + - '.github/workflows/cli-checks.yml' + +permissions: + contents: read + +concurrency: + group: cli-checks-${{ github.ref }} + cancel-in-progress: true + +jobs: + onekey-release-sign: + runs-on: ubuntu-24.04 + defaults: + run: + working-directory: cli/onekey-release-sign + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 + with: + node-version: 24.21.0 + - name: Verify GnuPG is available + run: gpg --version + - name: Run CLI unit and end-to-end GPG multisig tests + run: npm run check diff --git a/README.md b/README.md index 4a3de9362..6aeb1f85d 100644 --- a/README.md +++ b/README.md @@ -131,6 +131,7 @@ app-modules/ ├── native-modules/ # 32 Nitro modules (headless native APIs) ├── native-views/ # 13 Fabric views (native UI) ├── chain-runtimes/ # Rust Zcash and Monero runtimes, built separately +├── cli/ # standalone Node.js release & security CLIs ├── example/react-native/ # example app consuming every package via workspace:* ├── docs/ # development requirements, release process, README guide ├── scripts/ # generators, versioning and publishing tooling diff --git a/cli/README.md b/cli/README.md new file mode 100644 index 000000000..e03db7703 --- /dev/null +++ b/cli/README.md @@ -0,0 +1,10 @@ +# CLI tools + +Standalone Node.js command-line packages for OneKey release engineering and +security tooling. These are not React Native packages and are not part of the +root Yarn workspaces or their synchronized RN version/publish commands. + +- [onekey-release-sign](./onekey-release-sign/README.md) — Multi-signature + OpenPGP/YubiKey release signing, RFC 4880 `.asc` merging, and verification + for OneKey OTA (`metadata.json.info`) and full-release (`SHA256SUMS.asc`) + artifacts. diff --git a/cli/onekey-release-sign/LICENSE b/cli/onekey-release-sign/LICENSE new file mode 100644 index 000000000..87bdf71d2 --- /dev/null +++ b/cli/onekey-release-sign/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) OneKeyHQ + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/cli/onekey-release-sign/README.md b/cli/onekey-release-sign/README.md new file mode 100644 index 000000000..00a18d694 --- /dev/null +++ b/cli/onekey-release-sign/README.md @@ -0,0 +1,104 @@ +# `@onekeyfe/onekey-release-sign` + +Multi-signature OpenPGP/YubiKey CLI and zero-dependency Node.js library for signing, merging, and verifying OneKey OTA (`metadata.json.info`) and full-release (`SHA256SUMS.asc`) artifacts. + +## Why single-file RFC 4880 multi-signature? + +Two or more release signers on separate machines sign the exact same canonical payload with their own YubiKey OpenPGP keys (`gpg --clearsign --digest-algo SHA256`). `onekey-release-sign merge` validates and packs their OpenPGP Signature Packets (`Tag 2`, type `0x01`, `SHA-256/384/512`) into **one standard RFC 4880 `.asc` file**: + +- Zero API/filename changes (`jsBundle.signature` stays one string; `.SHA256SUMS.asc` stays one file). +- 100% compatible with standard `gpg --verify` and `openpgp.js` multi-key verification. +- Verification deduplicates strictly by **Primary Key Fingerprint**, preventing duplicate-signature or primary+subkey bypasses. + +> **Compatibility note for shipped clients**: Currently shipped Android (`BundleCryptoCore.kt` `signatureList[0]`) and Desktop (`result[0]`) verifiers check only the **first** signature packet against the legacy embedded OneKey release key. Independently keyed multi-signature `.asc` files produced by this CLI are **release-gate / server-side verified** until client trust-store upgrades roll out to verify `>= 2` distinct embedded YubiKey public keys on-device. + +## Requirements + +- Node.js `>= 20` +- `gpg` (GnuPG 2.2+ with `pinentry-mac` on macOS or Gpg4win on Windows) +- Optional: `ykman` (YubiKey Manager CLI) for touch-policy diagnostics + +## Quick Start + +### 1. Check local GPG & YubiKey setup + +```sh +npx @onekeyfe/onekey-release-sign doctor +``` + +### 2. Sign independently (Signer A & Signer B on separate machines) + +```sh +# Signer A (validates payload & metadata.json SHA-256 on one immutable byte snapshot before invoking GPG pinentry + touch) +onekey-release-sign sign \ + --in electron.metadata.json.info \ + --artifact metadata.json \ + --key \ + --out sig-a.asc + +# Signer B (on another machine, exact same payload) +onekey-release-sign sign \ + --in electron.metadata.json.info \ + --artifact metadata.json \ + --key \ + --out sig-b.asc +``` + +### 3. Merge into one standard RFC 4880 `.asc` (Release Gate / Dashboard Backend) + +```sh +onekey-release-sign merge \ + --in sig-a.asc \ + --in sig-b.asc \ + --payload electron.metadata.json.info \ + --keyring trusted-yubikeys.asc \ + --threshold 2 \ + --artifact metadata.json \ + --out electron.metadata.json.info.asc +``` + +### 4. Verify multi-signature `.asc` + +```sh +onekey-release-sign verify \ + --in electron.metadata.json.info.asc \ + --keyring trusted-yubikeys.asc \ + --threshold 2 \ + --artifact metadata.json \ + --json +``` + +### 5. Full-release installer checksum helper + +```sh +onekey-release-sign checksum \ + --artifact OneKey-Wallet-6.8.0-mac-arm64.zip \ + --out OneKey-Wallet-6.8.0-mac-arm64.zip.SHA256SUMS +``` + +## Programmatic Usage (e.g. Dashboard Backend) + +```js +import { + mergeCleartextSignatures, + verifyMultisigCleartext, +} from '@onekeyfe/onekey-release-sign'; + +const merged = mergeCleartextSignatures([sigA, sigB]); + +const result = verifyMultisigCleartext({ + signedText: merged.armored, + keyringTexts: [trustedPublicKeysArmored], + threshold: 2, +}); +``` + +## Development + +```sh +cd cli/onekey-release-sign +npm test +npm run check +``` + +See [docs/SPEC.md](docs/SPEC.md) for the authoritative security contract. diff --git a/cli/onekey-release-sign/bin/onekey-release-sign.mjs b/cli/onekey-release-sign/bin/onekey-release-sign.mjs new file mode 100755 index 000000000..5b3ccf9b4 --- /dev/null +++ b/cli/onekey-release-sign/bin/onekey-release-sign.mjs @@ -0,0 +1,11 @@ +#!/usr/bin/env node +import { runCli } from '../src/cli.mjs'; + +const result = runCli(process.argv.slice(2)); +if (result.stdout) { + process.stdout.write(result.stdout); +} +if (result.stderr) { + process.stderr.write(result.stderr); +} +process.exitCode = result.exitCode; diff --git a/cli/onekey-release-sign/docs/SPEC.md b/cli/onekey-release-sign/docs/SPEC.md new file mode 100644 index 000000000..5090de455 --- /dev/null +++ b/cli/onekey-release-sign/docs/SPEC.md @@ -0,0 +1,79 @@ +# `@onekeyfe/onekey-release-sign` Specification + +## Purpose + +Provide a zero-dependency Node.js CLI and programmatic library for OneKey's +M-of-N (default 2-of-N) YubiKey/OpenPGP release-signing workflow covering: + +1. **OTA hot-update metadata** (`*.metadata.json.info` JSON referencing `metadata.json` SHA-256). +2. **Full-release installers/APKs** (`*.SHA256SUMS` / `*.SHA256SUMS.asc`). + +Multiple independent signers on separate machines sign the exact same canonical +payload with their own YubiKey OpenPGP keys. Their individual clear-signed +messages are merged into a **single RFC 4880 Cleartext Signed Message** (`.asc`) +whose signature armor block packs all `Signature Packet` (tag 2) binary packets +in sequence. + +> **Rollout compatibility boundary**: Shipped Android (`BundleCryptoCore.kt` +> `signatureList[0]`) and Desktop (`result[0]`) verifiers inspect only the first +> signature packet against the legacy embedded release key. Independently keyed +> multi-signature `.asc` output is **release-gate / server-side verified** until +> client binaries ship multi-key threshold verification. + +## Security Contract & Invariants + +1. **Single-message framing & mandatory CRC-24**: + - Inputs containing more than one `-----BEGIN PGP SIGNED MESSAGE-----` or + `-----BEGIN PGP SIGNATURE-----` block MUST be rejected. + - ASCII Armor blocks MUST include a valid RFC 4880 CRC-24 checksum line; + omitted or corrupted checksums MUST be rejected. +2. **Strict signature packet validation**: + - Every packet inside the signature armor block MUST be OpenPGP Packet Tag 2 (`Signature`). + - Signature type MUST be `0x01` (`CANONICAL_TEXT_DOCUMENT`). + - Hash algorithm MUST be one of `SHA-256` (`8`), `SHA-384` (`9`), or `SHA-512` (`10`). +3. **Clear-signed-only merge & canonical body identity**: + - `mergeCleartextSignatures` accepts only clear-signed `PGP SIGNED MESSAGE` + inputs (detached signatures without an embedded body are rejected) so every + input undergoes canonical body equality comparison. + - When `expectedBody` (`--payload`) is provided, it is canonicalized using + GnuPG clear-sign framing rules (stripping one framing-equivalent terminal + line ending and per-line trailing spaces/tabs, joining with CRLF). + - Exact duplicate signature packets are rejected. +4. **TOCTOU-safe signing & no CLI passphrases**: + - `sign` reads the payload file once into an immutable byte buffer, validates + it against every supplied `--artifact`, and pipes that exact snapshot to + `gpg --clearsign` via `stdin`. + - Protected keys obtain credentials strictly through GnuPG `pinentry` (never + via CLI argv or subprocess arguments). Subprocess error messages omit full + argument lists. +5. **Isolated verification keyring**: + - Verification MUST run `gpg` in a freshly created temporary `GNUPGHOME` + (`0700`) importing only explicitly provided `--keyring` public keys so the + caller's ambient `~/.gnupg` cannot inject trust. +6. **Primary-key fingerprint deduplication**: + - Valid signatures are counted strictly by distinct **Primary Key + Fingerprint** (normalized 40-hex uppercase from GnuPG `VALIDSIG` field 10). + - Signing twice with the same key, or signing with both a primary key and + its subkey, counts as **1** signer and MUST NOT satisfy `threshold >= 2`. +7. **Strict CLI option validation & complete artifact binding**: + - Every CLI subcommand validates option names and positional counts against + an explicit per-command allowlist and exits non-zero on unknown/misspelled + flags. + - Every repeated `--artifact` path is verified against the manifest (and + `metadata.json.info` rejects `> 1` `--artifact`). + - Release artifact basenames enforce one shared rule across `checksum` and + `inspectReleasePayload` (single-segment basename with no whitespace, path + separators, traversal, or control characters, matching shipped mobile and + desktop `SHA256SUMS` parsers). +8. **Safe subprocess execution**: + - All `gpg` / `ykman` invocations use `execFileSync` with argument arrays + (never shell interpolation). + +## CLI Subcommands + +- `doctor` — Check `gpg`, optional `ykman`, and plugged-in YubiKey OpenPGP card. +- `checksum` — Generate canonical ` ` payload for one or more artifacts. +- `inspect` — Parse and display a `metadata.json.info`, `SHA256SUMS`, or `.asc` file (verifying all supplied `--artifact` files). +- `sign` — Validate one immutable payload snapshot & all `--artifact` files locally, pipe that snapshot to `gpg --clearsign --digest-algo SHA256` via stdin, validate RFC 4880 output, and write `.asc`. +- `merge` — Merge 2+ clear-signed `.asc` files into one standard RFC 4880 multi-signature `.asc` (with optional `--payload`, isolated `--keyring`, `--threshold`, `--allow-fingerprint`, and `--artifact` checks). +- `verify` — Verify a multi-signature `.asc` against an explicit `--keyring`, `--threshold` (default `2`), optional `--allow-fingerprint`, and all supplied `--artifact` files (supports `--json`). diff --git a/cli/onekey-release-sign/package.json b/cli/onekey-release-sign/package.json new file mode 100644 index 000000000..b2a99a867 --- /dev/null +++ b/cli/onekey-release-sign/package.json @@ -0,0 +1,51 @@ +{ + "name": "@onekeyfe/onekey-release-sign", + "version": "0.1.0", + "description": "Multi-signature OpenPGP/YubiKey CLI and library for OneKey OTA and full-release artifact signing, RFC 4880 .asc merging, and threshold verification.", + "type": "module", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "bin": { + "onekey-release-sign": "./bin/onekey-release-sign.mjs" + }, + "main": "./src/index.mjs", + "exports": { + ".": "./src/index.mjs", + "./package.json": "./package.json" + }, + "files": [ + "bin", + "src", + "docs/SPEC.md", + "README.md", + "LICENSE" + ], + "scripts": { + "test": "node --test test/*.test.mjs", + "check": "node --test test/*.test.mjs && npm pack --dry-run" + }, + "keywords": [ + "onekey", + "yubikey", + "openpgp", + "gpg", + "multisig", + "release-signing", + "supply-chain" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/OneKeyHQ/app-modules.git", + "directory": "cli/onekey-release-sign" + }, + "bugs": { + "url": "https://github.com/OneKeyHQ/app-modules/issues" + }, + "homepage": "https://github.com/OneKeyHQ/app-modules/tree/main/cli/onekey-release-sign#readme", + "publishConfig": { + "registry": "https://registry.npmjs.org/", + "access": "public" + } +} diff --git a/cli/onekey-release-sign/src/cli.mjs b/cli/onekey-release-sign/src/cli.mjs new file mode 100644 index 000000000..24813c56b --- /dev/null +++ b/cli/onekey-release-sign/src/cli.mjs @@ -0,0 +1,414 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { + checkDoctor, + signCleartext, + verifyMultisigCleartext, +} from './gpg.mjs'; +import { + mergeCleartextSignatures, + parseCleartextSignedMessage, +} from './openpgp.mjs'; +import { + createSha256SumsPayload, + inspectReleasePayload, +} from './payload.mjs'; + +const pkgDir = path.dirname(path.dirname(fileURLToPath(import.meta.url))); +const pkgJson = JSON.parse(fs.readFileSync(path.join(pkgDir, 'package.json'), 'utf8')); + +export const USAGE = `onekey-release-sign v${pkgJson.version} +Multi-signature OpenPGP/YubiKey CLI for OneKey OTA and full-release signing. + +Usage: + onekey-release-sign [options] + +Commands: + doctor Check local gpg, ykman, and YubiKey OpenPGP card readiness + checksum Generate canonical SHA256SUMS payload + inspect Inspect metadata.json.info, SHA256SUMS, or signed .asc file + sign Verify payload/artifact locally and clearsign with GPG/YubiKey + merge Merge 2+ clear-signed .asc files into ONE RFC 4880 multi-sig .asc + verify Verify multi-sig .asc against explicit keyring & threshold + +Examples: + onekey-release-sign doctor + onekey-release-sign checksum --artifact OneKey-Wallet-6.8.0-mac-arm64.zip --out OneKey-Wallet-6.8.0-mac-arm64.zip.SHA256SUMS + onekey-release-sign inspect --in electron.metadata.json.info --artifact metadata.json + onekey-release-sign sign --in electron.metadata.json.info --artifact metadata.json --key --out sig-a.asc + onekey-release-sign merge --in sig-a.asc --in sig-b.asc --keyring pubkeys.asc --threshold 2 --out combined.asc + onekey-release-sign verify --in combined.asc --keyring pubkeys.asc --threshold 2 --artifact metadata.json --json +`; + +const REPEATABLE_FLAGS = new Set([ + 'in', + 'keyring', + 'allow-fingerprint', + 'artifact', +]); + +const BOOLEAN_FLAGS = new Set([ + 'json', + 'help', + 'version', + 'batch', +]); + +const ALLOWED_OPTIONS_BY_COMMAND = { + doctor: new Set(['gpg-home', 'json', 'help']), + checksum: new Set(['artifact', 'out', 'json', 'help']), + inspect: new Set(['in', 'artifact', 'json', 'help']), + sign: new Set([ + 'in', + 'artifact', + 'key', + 'digest-algo', + 'out', + 'gpg-home', + 'batch', + 'json', + 'help', + ]), + merge: new Set([ + 'in', + 'payload', + 'keyring', + 'threshold', + 'allow-fingerprint', + 'artifact', + 'out', + 'json', + 'help', + ]), + verify: new Set([ + 'in', + 'keyring', + 'threshold', + 'allow-fingerprint', + 'artifact', + 'json', + 'help', + ]), +}; + +/** + * Parse CLI arguments without external dependencies. + * Rejects malformed or duplicate non-repeatable flags. + * @param {string[]} argv + */ +export function parseArgs(argv) { + const positionals = []; + const options = {}; + + for (let i = 0; i < argv.length; i += 1) { + const token = argv[i]; + if (token === '-h') { + options.help = true; + continue; + } + if (token === '-v') { + options.version = true; + continue; + } + if (!token.startsWith('--')) { + positionals.push(token); + continue; + } + const eqIdx = token.indexOf('='); + const key = eqIdx >= 0 ? token.slice(2, eqIdx) : token.slice(2); + if (!key) { + throw new Error(`Invalid option token "${token}"`); + } + if (BOOLEAN_FLAGS.has(key)) { + options[key] = eqIdx >= 0 ? token.slice(eqIdx + 1) !== 'false' : true; + continue; + } + let value; + if (eqIdx >= 0) { + value = token.slice(eqIdx + 1); + } else { + if (i + 1 >= argv.length || argv[i + 1].startsWith('--')) { + throw new Error(`Missing value for option --${key}`); + } + value = argv[i + 1]; + i += 1; + } + if (REPEATABLE_FLAGS.has(key)) { + if (!Array.isArray(options[key])) { + options[key] = []; + } + options[key].push(value); + } else { + if (Object.prototype.hasOwnProperty.call(options, key)) { + throw new Error(`Option --${key} may only be specified once`); + } + options[key] = value; + } + } + + return { + command: positionals[0] ?? null, + restPositionals: positionals.slice(1), + options, + }; +} + +function validateCommandOptions(command, options, restPositionals, { maxPositionals = 0 } = {}) { + const allowed = ALLOWED_OPTIONS_BY_COMMAND[command]; + for (const key of Object.keys(options)) { + if (!allowed.has(key)) { + throw new Error(`Unknown option --${key} for command "${command}"`); + } + } + if (restPositionals.length > maxPositionals) { + throw new Error( + `Unexpected positional argument(s) for "${command}": ${restPositionals.slice(maxPositionals).join(' ')}`, + ); + } +} + +function resolveSingleInput(options, restPositionals, command) { + if (options.in && options.in.length > 1) { + throw new Error(`Command "${command}" accepts only one --in file, got ${options.in.length}`); + } + if (options.in && options.in.length === 1 && restPositionals.length > 0) { + throw new Error(`Command "${command}" received both --in and a positional input path`); + } + const inputPath = options.in?.[0] ?? restPositionals[0]; + return requireOption(inputPath, 'in'); +} + +function writeAtomic(filePath, content) { + const dir = path.dirname(path.resolve(filePath)); + fs.mkdirSync(dir, { recursive: true }); + const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}`; + fs.writeFileSync(tmpPath, content, 'utf8'); + fs.renameSync(tmpPath, filePath); +} + +function requireOption(value, name) { + if (!value || (Array.isArray(value) && value.length === 0)) { + throw new Error(`Missing required option --${name}`); + } + return value; +} + +function parseThreshold(raw, fallback = 2) { + if (raw === undefined) return fallback; + const parsed = Number(raw); + if (!Number.isInteger(parsed) || parsed < 1) { + throw new Error(`Invalid --threshold value "${raw}" (must be integer >= 1)`); + } + return parsed; +} + +/** + * Execute a CLI invocation and return `{ exitCode, stdout, stderr }`. + * @param {string[]} argv + */ +export function runCli(argv) { + try { + const { command, restPositionals, options } = parseArgs(argv); + + if (options.version) { + return { exitCode: 0, stdout: `${pkgJson.version}\n`, stderr: '' }; + } + if (options.help || !command || command === 'help') { + return { exitCode: 0, stdout: USAGE, stderr: '' }; + } + + if (!Object.prototype.hasOwnProperty.call(ALLOWED_OPTIONS_BY_COMMAND, command)) { + throw new Error(`Unknown command "${command}". Run "onekey-release-sign --help" for usage.`); + } + + const gpgHome = options['gpg-home']; + + if (command === 'doctor') { + validateCommandOptions(command, options, restPositionals, { maxPositionals: 0 }); + const report = checkDoctor({ gpgHome }); + const stdout = options.json + ? `${JSON.stringify(report, null, 2)}\n` + : [ + `GPG: ${report.gpgAvailable ? report.gpgVersion : 'NOT FOUND'}`, + `YubiKey: ${report.cardDetected ? `Detected (serial=${report.cardSerial ?? 'unknown'}, sigKey=${report.signatureKey ?? 'none'})` : 'Not detected'}`, + `ykman: ${report.ykmanAvailable ? report.ykmanVersion : 'Not installed (optional)'}`, + ].join('\n') + '\n'; + return { exitCode: report.gpgAvailable ? 0 : 1, stdout, stderr: '' }; + } + + if (command === 'checksum') { + validateCommandOptions(command, options, restPositionals, { maxPositionals: 0 }); + const artifacts = requireOption(options.artifact, 'artifact'); + const { content, entries } = createSha256SumsPayload(artifacts); + if (options.out) { + writeAtomic(options.out, content); + } + const stdout = options.json + ? `${JSON.stringify({ out: options.out ?? null, entries }, null, 2)}\n` + : options.out + ? `Wrote ${entries.length} checksum entry(ies) to ${options.out}\n` + : content; + return { exitCode: 0, stdout, stderr: '' }; + } + + if (command === 'inspect') { + validateCommandOptions(command, options, restPositionals, { maxPositionals: 1 }); + const inputPath = resolveSingleInput(options, restPositionals, command); + const raw = fs.readFileSync(inputPath, 'utf8'); + const artifactPaths = options.artifact ?? []; + + let isSigned = false; + let packetCount = 0; + let hashes = []; + let plainBody = raw; + if (raw.includes('-----BEGIN PGP SIGNED MESSAGE-----')) { + const parsed = parseCleartextSignedMessage(raw); + isSigned = true; + packetCount = parsed.packets.length; + hashes = parsed.hashes; + plainBody = parsed.plainBody; + } + + const payload = inspectReleasePayload(plainBody, { artifactPaths }); + const summary = { + file: inputPath, + signed: isSigned, + signaturePackets: packetCount, + hashes, + payload, + }; + return { exitCode: 0, stdout: `${JSON.stringify(summary, null, 2)}\n`, stderr: '' }; + } + + if (command === 'sign') { + validateCommandOptions(command, options, restPositionals, { maxPositionals: 1 }); + const inputPath = resolveSingleInput(options, restPositionals, command); + // Read ONE immutable byte snapshot, validate it against all supplied + // artifacts, then pipe those exact bytes to GnuPG via stdin (no TOCTOU). + const inputSnapshot = fs.readFileSync(inputPath); + const rawBody = inputSnapshot.toString('utf8'); + const artifactPaths = options.artifact ?? []; + const payload = inspectReleasePayload(rawBody, { artifactPaths }); + + const digestAlgo = (options['digest-algo'] ?? 'SHA256').toUpperCase(); + const signed = signCleartext({ + inputBytes: inputSnapshot, + keyId: options.key, + digestAlgo, + gpgHome, + batch: Boolean(options.batch), + }); + + if (options.out) { + writeAtomic(options.out, signed.armored); + } + + const stdout = options.json + ? `${JSON.stringify( + { + out: options.out ?? null, + digestAlgo, + packetCount: signed.parsed.packets.length, + payload, + }, + null, + 2, + )}\n` + : options.out + ? `Signed ${inputPath} (${payload.kind}) -> ${options.out}\n` + : signed.armored; + return { exitCode: 0, stdout, stderr: '' }; + } + + if (command === 'merge') { + validateCommandOptions(command, options, restPositionals, { maxPositionals: 0 }); + const inputs = requireOption(options.in, 'in'); + const threshold = parseThreshold(options.threshold, 2); + const signedTexts = inputs.map((filePath) => fs.readFileSync(filePath, 'utf8')); + const expectedBody = options.payload + ? fs.readFileSync(options.payload, 'utf8') + : undefined; + + const merged = mergeCleartextSignatures(signedTexts, { + expectedBody, + minSignatures: threshold, + }); + + const artifactPaths = options.artifact ?? []; + let verification = null; + if (options.keyring && options.keyring.length > 0) { + verification = verifyMultisigCleartext({ + signedText: merged.armored, + keyringFiles: options.keyring, + threshold, + allowedFingerprints: options['allow-fingerprint'] ?? [], + artifactPaths, + }); + } else { + if (options['allow-fingerprint'] && options['allow-fingerprint'].length > 0) { + throw new Error('--allow-fingerprint requires --keyring during merge'); + } + inspectReleasePayload(merged.plainBody, { artifactPaths }); + } + + if (options.out) { + writeAtomic(options.out, merged.armored); + } + + const stdout = options.json + ? `${JSON.stringify( + { + out: options.out ?? null, + packetCount: merged.packetCount, + hashes: merged.hashes, + verified: Boolean(verification), + primaryFingerprints: verification?.primaryFingerprints ?? null, + }, + null, + 2, + )}\n` + : options.out + ? `Merged ${merged.packetCount} signature(s) into ${options.out}${verification ? ` (verified ${verification.uniqueSignerCount}/${threshold} distinct signers)` : ''}\n` + : merged.armored; + return { exitCode: 0, stdout, stderr: '' }; + } + + if (command === 'verify') { + validateCommandOptions(command, options, restPositionals, { maxPositionals: 1 }); + const inputPath = resolveSingleInput(options, restPositionals, command); + const keyrings = requireOption(options.keyring, 'keyring'); + const threshold = parseThreshold(options.threshold, 2); + const signedText = fs.readFileSync(inputPath, 'utf8'); + const artifactPaths = options.artifact ?? []; + + const result = verifyMultisigCleartext({ + signedText, + keyringFiles: keyrings, + threshold, + allowedFingerprints: options['allow-fingerprint'] ?? [], + artifactPaths, + }); + + const stdout = options.json + ? `${JSON.stringify(result, null, 2)}\n` + : [ + `OK: Verified ${result.uniqueSignerCount} distinct trusted signer(s) (threshold=${result.threshold})`, + ...result.primaryFingerprints.map((fpr, idx) => ` Signer ${idx + 1}: ${fpr}`), + ...result.payload.artifactChecks.map( + (check) => ` Artifact: ${check.fileName} (sha256=${check.sha256})`, + ), + ].join('\n') + '\n'; + return { exitCode: 0, stdout, stderr: '' }; + } + + throw new Error(`Unknown command "${command}". Run "onekey-release-sign --help" for usage.`); + } catch (error) { + return { + exitCode: 1, + stdout: '', + stderr: `Error: ${error instanceof Error ? error.message : String(error)}\n`, + }; + } +} diff --git a/cli/onekey-release-sign/src/gpg.mjs b/cli/onekey-release-sign/src/gpg.mjs new file mode 100644 index 000000000..13fc8ee49 --- /dev/null +++ b/cli/onekey-release-sign/src/gpg.mjs @@ -0,0 +1,401 @@ +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +import { + ALLOWED_HASH_ALGORITHMS, + parseCleartextSignedMessage, +} from './openpgp.mjs'; +import { inspectReleasePayload } from './payload.mjs'; + +const FINGERPRINT_RE = /^[A-F0-9]{40}$/u; + +/** + * Normalize a 40-hex OpenPGP fingerprint (strips spaces/0x prefix, uppercases). + * @param {string} value + * @returns {string} + */ +export function normalizeFingerprint(value) { + const cleaned = String(value ?? '') + .replace(/^0x/iu, '') + .replace(/\s+/gu, '') + .toUpperCase(); + if (!FINGERPRINT_RE.test(cleaned)) { + throw new Error(`Invalid 40-character hex GPG fingerprint: "${value}"`); + } + return cleaned; +} + +function buildGpgEnv(gpgHome) { + const env = { ...process.env, LC_ALL: 'C' }; + if (gpgHome) { + env.GNUPGHOME = gpgHome; + } + return env; +} + +/** + * Run a GnuPG command via execFileSync (never via a shell). + * Error messages intentionally omit full subprocess argument lists to prevent + * accidental credential leakage in logs. + * @param {string[]} args + * @param {{ gpgHome?: string, input?: string | Buffer, gpgBin?: string, allowNonZero?: boolean, operation?: string }} [options] + */ +function runGpg( + args, + { gpgHome, input, gpgBin = 'gpg', allowNonZero = false, operation = 'command' } = {}, +) { + try { + const stdout = execFileSync(gpgBin, args, { + env: buildGpgEnv(gpgHome), + input, + encoding: 'utf8', + stdio: ['pipe', 'pipe', 'pipe'], + }); + return { exitCode: 0, stdout, stderr: '' }; + } catch (error) { + if (error?.code === 'ENOENT') { + throw new Error(`Required binary "${gpgBin}" not found in PATH. Install GnuPG first.`); + } + if (allowNonZero && typeof error?.status === 'number') { + return { + exitCode: error.status, + stdout: String(error.stdout ?? ''), + stderr: String(error.stderr ?? ''), + }; + } + const stderr = String(error?.stderr ?? '').trim(); + throw new Error( + `gpg ${operation} failed (exit ${error?.status ?? 'unknown'}): ${stderr || 'command exited with error'}`, + ); + } +} + +/** + * Inspect local GPG & YubiKey environment readiness. + * @param {{ gpgHome?: string, gpgBin?: string, ykmanBin?: string }} [options] + */ +export function checkDoctor({ gpgHome, gpgBin = 'gpg', ykmanBin = 'ykman' } = {}) { + const versionRes = runGpg(['--version'], { + gpgHome, + gpgBin, + allowNonZero: true, + operation: 'version', + }); + const gpgVersion = versionRes.stdout.split('\n')[0]?.trim() || null; + + const cardRes = runGpg(['--card-status'], { + gpgHome, + gpgBin, + allowNonZero: true, + operation: 'card-status', + }); + const cardDetected = cardRes.exitCode === 0 && cardRes.stdout.includes('Application ID'); + let signatureKey = null; + let cardSerial = null; + if (cardDetected) { + const sigMatch = /Signature key\s*\.+:\s*([A-F0-9 ]+)/iu.exec(cardRes.stdout); + if (sigMatch) { + signatureKey = sigMatch[1].replace(/\s+/gu, '').toUpperCase(); + } + const serialMatch = /Serial number\s*\.+:\s*(\S+)/iu.exec(cardRes.stdout); + if (serialMatch) { + cardSerial = serialMatch[1]; + } + } + + let ykmanVersion = null; + let openpgpInfo = null; + try { + ykmanVersion = execFileSync(ykmanBin, ['--version'], { + encoding: 'utf8', + stdio: ['pipe', 'pipe', 'pipe'], + }).trim(); + try { + openpgpInfo = execFileSync(ykmanBin, ['openpgp', 'info'], { + encoding: 'utf8', + stdio: ['pipe', 'pipe', 'pipe'], + }).trim(); + } catch { + openpgpInfo = null; + } + } catch { + ykmanVersion = null; + } + + return { + gpgAvailable: versionRes.exitCode === 0, + gpgVersion, + cardDetected, + cardSerial, + signatureKey, + ykmanAvailable: Boolean(ykmanVersion), + ykmanVersion, + openpgpInfo, + }; +} + +/** + * Sign an in-memory payload snapshot (or file read once) using + * `gpg --clearsign --digest-algo SHA256`, passing the exact validated bytes to + * GnuPG over stdin to eliminate TOCTOU races between validation and signing. + * + * Protected keys obtain their PIN/passphrase exclusively via GnuPG pinentry + * (never via CLI argv). + * + * @param {{ + * inputBytes?: Buffer | string, + * inputPath?: string, + * keyId?: string, + * digestAlgo?: 'SHA256' | 'SHA384' | 'SHA512', + * gpgHome?: string, + * gpgBin?: string, + * batch?: boolean, + * }} options + */ +export function signCleartext({ + inputBytes, + inputPath, + keyId, + digestAlgo = 'SHA256', + gpgHome, + gpgBin = 'gpg', + batch = false, +}) { + if (!['SHA256', 'SHA384', 'SHA512'].includes(digestAlgo)) { + throw new Error(`Unsupported digest algorithm: ${digestAlgo}`); + } + const snapshot = + inputBytes !== undefined + ? Buffer.isBuffer(inputBytes) + ? inputBytes + : Buffer.from(String(inputBytes), 'utf8') + : inputPath + ? fs.readFileSync(inputPath) + : null; + if (!snapshot || snapshot.length === 0) { + throw new Error('Cannot sign an empty payload'); + } + + const args = [ + '--clearsign', + '--armor', + '--digest-algo', + digestAlgo, + '--no-emit-version', + '--output', + '-', + ]; + if (keyId) { + args.push('--local-user', keyId); + } + if (batch) { + args.push('--batch', '--yes'); + } + + const res = runGpg(args, { + gpgHome, + gpgBin, + input: snapshot, + operation: 'clearsign', + }); + // Validate the generated signature strictly conforms to RFC 4880 Type 0x01. + const parsed = parseCleartextSignedMessage(res.stdout); + return { + armored: res.stdout, + parsed, + }; +} + +/** + * Parse GnuPG `--status-fd=1` output into verified and rejected signature records. + * @param {string} statusOutput + */ +export function parseGpgVerifyStatus(statusOutput) { + const validSignatures = []; + const invalidSignatures = []; + const lines = statusOutput.replace(/\r\n/g, '\n').split('\n'); + + for (const line of lines) { + if (!line.startsWith('[GNUPG:] ')) continue; + const rest = line.slice('[GNUPG:] '.length).trim(); + const parts = rest.split(/\s+/u); + const code = parts[0]; + + if (code === 'VALIDSIG') { + // VALIDSIG [] + const signingFingerprint = (parts[1] ?? '').toUpperCase(); + const timestamp = Number(parts[3] ?? 0); + const hashAlgo = Number(parts[8] ?? 0); + const sigClass = (parts[9] ?? '').toUpperCase(); + const primaryFingerprint = (parts[10] || parts[1] || '').toUpperCase(); + validSignatures.push({ + signingFingerprint, + primaryFingerprint, + timestamp, + hashAlgo, + hashName: ALLOWED_HASH_ALGORITHMS.get(hashAlgo) ?? `UNKNOWN_${hashAlgo}`, + sigClass, + }); + } else if ( + code === 'BADSIG' || + code === 'ERRSIG' || + code === 'EXPSIG' || + code === 'EXPKEYSIG' || + code === 'REVKEYSIG' + ) { + invalidSignatures.push({ code, detail: rest }); + } + } + + return { validSignatures, invalidSignatures }; +} + +function createIsolatedGpgHome() { + // GnuPG creates Unix domain sockets inside GNUPGHOME; macOS limits socket + // paths to 104 bytes, and os.tmpdir() (/var/folders/...) can exceed it. + const baseTmp = + process.platform !== 'win32' && fs.existsSync('/tmp') ? '/tmp' : os.tmpdir(); + const dir = fs.mkdtempSync(path.join(baseTmp, 'okgpg-')); + fs.chmodSync(dir, 0o700); + return dir; +} + +/** + * Cryptographically verify a single or multi-signature RFC 4880 `.asc` message + * inside a fresh isolated temporary `GNUPGHOME` containing ONLY the explicitly + * supplied trusted public keys, deduplicating signers strictly by Primary Key + * Fingerprint. + * + * @param {{ + * signedText: string, + * keyringFiles?: string[], + * keyringTexts?: string[], + * threshold?: number, + * allowedFingerprints?: string[], + * artifactPath?: string, + * artifactPaths?: string[], + * gpgBin?: string, + * }} options + */ +export function verifyMultisigCleartext({ + signedText, + keyringFiles = [], + keyringTexts = [], + threshold = 2, + allowedFingerprints = [], + artifactPath, + artifactPaths = [], + gpgBin = 'gpg', +}) { + if (!Number.isInteger(threshold) || threshold < 1) { + throw new Error(`Invalid signature threshold: ${threshold} (must be integer >= 1)`); + } + if (keyringFiles.length === 0 && keyringTexts.length === 0) { + throw new Error('At least one trusted public key (--keyring) is required for verification'); + } + + const allowlist = + allowedFingerprints.length > 0 + ? new Set(allowedFingerprints.map(normalizeFingerprint)) + : null; + + // 1. Strict RFC 4880 structural & packet validation before invoking gpg. + const parsed = parseCleartextSignedMessage(signedText); + + // 2. Inspect & bind payload against every supplied local artifact SHA-256. + const payloadInfo = inspectReleasePayload(parsed.plainBody, { + artifactPath, + artifactPaths, + }); + + // 3. Verify cryptographically in an isolated temporary GNUPGHOME (0700). + const tmpHome = createIsolatedGpgHome(); + try { + for (const file of keyringFiles) { + runGpg(['--batch', '--import', file], { + gpgHome: tmpHome, + gpgBin, + operation: 'import', + }); + } + for (let i = 0; i < keyringTexts.length; i += 1) { + const keyFile = path.join(tmpHome, `key-${i}.asc`); + fs.writeFileSync(keyFile, keyringTexts[i], { mode: 0o600 }); + runGpg(['--batch', '--import', keyFile], { + gpgHome: tmpHome, + gpgBin, + operation: 'import', + }); + } + + const msgFile = path.join(tmpHome, 'message.asc'); + fs.writeFileSync(msgFile, signedText, { mode: 0o600 }); + + const verifyRes = runGpg(['--batch', '--status-fd=1', '--verify', msgFile], { + gpgHome: tmpHome, + gpgBin, + allowNonZero: true, + operation: 'verify', + }); + const { validSignatures, invalidSignatures } = parseGpgVerifyStatus(verifyRes.stdout); + + // Reject if any cryptographic signature in the message was tampered/revoked/expired. + const hardErrors = invalidSignatures.filter( + (item) => + item.code === 'BADSIG' || + item.code === 'EXPSIG' || + item.code === 'EXPKEYSIG' || + item.code === 'REVKEYSIG', + ); + if (hardErrors.length > 0) { + throw new Error( + `Signature verification rejected due to invalid/expired/revoked signature: ${hardErrors.map((e) => e.detail).join('; ')}`, + ); + } + + // Deduplicate valid signatures strictly by PRIMARY key fingerprint and + // enforce SHA-256/384/512 + canonical text class 0x01 + optional allowlist. + const uniqueSigners = new Map(); + const skippedSigners = []; + + for (const sig of validSignatures) { + if (!ALLOWED_HASH_ALGORITHMS.has(sig.hashAlgo)) { + skippedSigners.push({ ...sig, reason: 'DISALLOWED_HASH_ALGO' }); + continue; + } + if (sig.sigClass !== '01') { + skippedSigners.push({ ...sig, reason: 'NOT_CANONICAL_TEXT_SIGNATURE' }); + continue; + } + if (allowlist && !allowlist.has(sig.primaryFingerprint)) { + skippedSigners.push({ ...sig, reason: 'NOT_IN_ALLOWLIST' }); + continue; + } + if (!uniqueSigners.has(sig.primaryFingerprint)) { + uniqueSigners.set(sig.primaryFingerprint, sig); + } + } + + const uniquePrimaryFingerprints = [...uniqueSigners.keys()]; + if (uniquePrimaryFingerprints.length < threshold) { + throw new Error( + `Insufficient distinct trusted signatures: got ${uniquePrimaryFingerprints.length}, required >= ${threshold}`, + ); + } + + return { + valid: true, + threshold, + uniqueSignerCount: uniquePrimaryFingerprints.length, + primaryFingerprints: uniquePrimaryFingerprints, + signatures: [...uniqueSigners.values()], + skippedSigners, + packetCount: parsed.packets.length, + payload: payloadInfo, + }; + } finally { + fs.rmSync(tmpHome, { recursive: true, force: true }); + } +} diff --git a/cli/onekey-release-sign/src/index.mjs b/cli/onekey-release-sign/src/index.mjs new file mode 100644 index 000000000..da9950789 --- /dev/null +++ b/cli/onekey-release-sign/src/index.mjs @@ -0,0 +1,31 @@ +export { + ALLOWED_HASH_ALGORITHMS, + ALLOWED_HASH_NAMES, + canonicalizeCleartextBody, + canonicalizePlaintextForClearsign, + crc24, + dashEscapeCleartextBody, + decodeArmor, + encodeArmor, + encodeCrc24, + mergeCleartextSignatures, + parseCleartextSignedMessage, + parseSignaturePackets, +} from './openpgp.mjs'; + +export { + assertSafeReleaseFileName, + createSha256SumsPayload, + inspectReleasePayload, + sha256File, +} from './payload.mjs'; + +export { + checkDoctor, + normalizeFingerprint, + parseGpgVerifyStatus, + signCleartext, + verifyMultisigCleartext, +} from './gpg.mjs'; + +export { parseArgs, runCli } from './cli.mjs'; diff --git a/cli/onekey-release-sign/src/openpgp.mjs b/cli/onekey-release-sign/src/openpgp.mjs new file mode 100644 index 000000000..fc96cc1c3 --- /dev/null +++ b/cli/onekey-release-sign/src/openpgp.mjs @@ -0,0 +1,554 @@ +import crypto from 'node:crypto'; + +const CRC24_INIT = 0xb704ce; +const CRC24_POLY = 0x1864cfb; + +const SIGNATURE_PACKET_TAG = 2; +const SIG_TYPE_CANONICAL_TEXT = 0x01; + +export const ALLOWED_HASH_ALGORITHMS = new Map([ + [8, 'SHA256'], + [9, 'SHA384'], + [10, 'SHA512'], +]); + +export const ALLOWED_HASH_NAMES = new Set(['SHA256', 'SHA384', 'SHA512']); + +const SIGNED_MSG_BEGIN = '-----BEGIN PGP SIGNED MESSAGE-----'; +const SIG_BEGIN = '-----BEGIN PGP SIGNATURE-----'; +const SIG_END = '-----END PGP SIGNATURE-----'; + +/** + * Compute RFC 4880 Section 6.1 CRC-24 checksum over raw bytes. + * @param {Uint8Array} bytes + * @returns {number} + */ +export function crc24(bytes) { + let crc = CRC24_INIT; + for (let i = 0; i < bytes.length; i += 1) { + crc ^= bytes[i] << 16; + for (let bit = 0; bit < 8; bit += 1) { + crc <<= 1; + if ((crc & 0x1000000) !== 0) { + crc ^= CRC24_POLY; + } + } + } + return crc & 0xffffff; +} + +/** + * Encode a 24-bit CRC value as a 4-character Base64 string (without leading '='). + * @param {number} value + * @returns {string} + */ +export function encodeCrc24(value) { + const buf = Buffer.from([ + (value >> 16) & 0xff, + (value >> 8) & 0xff, + value & 0xff, + ]); + return buf.toString('base64'); +} + +/** + * Encode raw binary data into RFC 4880 ASCII Armor. + * @param {string} label e.g. 'PGP SIGNATURE' + * @param {Uint8Array} bytes + * @param {Record} [headers] + * @returns {string} + */ +export function encodeArmor(label, bytes, headers = {}) { + const data = Buffer.from(bytes); + const b64 = data.toString('base64'); + const wrapped = []; + for (let i = 0; i < b64.length; i += 64) { + wrapped.push(b64.slice(i, i + 64)); + } + const headerLines = Object.entries(headers).map(([k, v]) => `${k}: ${v}`); + const checksum = encodeCrc24(crc24(data)); + return [ + `-----BEGIN ${label}-----`, + ...headerLines, + '', + ...wrapped, + `=${checksum}`, + `-----END ${label}-----`, + ].join('\n'); +} + +/** + * Decode an RFC 4880 ASCII Armor block and verify its mandatory CRC-24 checksum. + * @param {string} armoredText + * @param {string} [expectedLabel] + * @param {{ requireCrc?: boolean }} [options] + * @returns {{ label: string, headers: Record, bytes: Buffer }} + */ +export function decodeArmor(armoredText, expectedLabel, { requireCrc = true } = {}) { + const lines = armoredText.replace(/\r\n/g, '\n').replace(/\r/g, '\n').split('\n'); + const beginIndices = []; + const endIndices = []; + for (let i = 0; i < lines.length; i += 1) { + if (/^-----BEGIN [A-Z0-9 ]+-----$/u.test(lines[i])) { + beginIndices.push(i); + } else if (/^-----END [A-Z0-9 ]+-----$/u.test(lines[i])) { + endIndices.push(i); + } + } + if (beginIndices.length !== 1 || endIndices.length !== 1) { + throw new Error('ASCII armor must contain exactly one BEGIN and one END marker'); + } + const beginIdx = beginIndices[0]; + const endIdx = endIndices[0]; + if (endIdx <= beginIdx) { + throw new Error('Malformed ASCII armor marker order'); + } + const beginLabel = lines[beginIdx].slice('-----BEGIN '.length, -'-----'.length); + const endLabel = lines[endIdx].slice('-----END '.length, -'-----'.length); + if (beginLabel !== endLabel) { + throw new Error(`Mismatched armor labels: BEGIN ${beginLabel} vs END ${endLabel}`); + } + if (expectedLabel && beginLabel !== expectedLabel) { + throw new Error(`Expected armor label "${expectedLabel}", got "${beginLabel}"`); + } + + let blankIdx = -1; + const headers = {}; + for (let i = beginIdx + 1; i < endIdx; i += 1) { + const line = lines[i]; + if (line.trim() === '') { + blankIdx = i; + break; + } + const colon = line.indexOf(':'); + if (colon <= 0) { + throw new Error(`Malformed armor header line: ${line}`); + } + headers[line.slice(0, colon).trim()] = line.slice(colon + 1).trim(); + } + if (blankIdx < 0) { + throw new Error('Missing blank line separating armor headers and payload'); + } + + const bodyLines = lines + .slice(blankIdx + 1, endIdx) + .map((line) => line.trim()) + .filter(Boolean); + if (bodyLines.length === 0) { + throw new Error('Empty ASCII armor body'); + } + + let expectedCrc = null; + if (bodyLines[bodyLines.length - 1].startsWith('=')) { + const crcLine = bodyLines.pop(); + const crcB64 = crcLine.slice(1); + if (!/^[A-Za-z0-9+/]{4}$/u.test(crcB64)) { + throw new Error('Malformed CRC-24 checksum line in ASCII armor'); + } + const crcBytes = Buffer.from(crcB64, 'base64'); + if (crcBytes.length !== 3) { + throw new Error('Invalid CRC-24 length in ASCII armor'); + } + expectedCrc = (crcBytes[0] << 16) | (crcBytes[1] << 8) | crcBytes[2]; + } else if (requireCrc) { + throw new Error('Missing mandatory CRC-24 checksum line in ASCII armor'); + } + + const b64Payload = bodyLines.join(''); + if (!/^[A-Za-z0-9+/]+={0,2}$/u.test(b64Payload) || b64Payload.length % 4 !== 0) { + throw new Error('Invalid Base64 characters in ASCII armor body'); + } + const bytes = Buffer.from(b64Payload, 'base64'); + if (bytes.length === 0) { + throw new Error('Decoded ASCII armor body is empty'); + } + + if (expectedCrc !== null) { + const actualCrc = crc24(bytes); + if (actualCrc !== expectedCrc) { + throw new Error( + `ASCII armor CRC-24 mismatch: expected ${encodeCrc24(expectedCrc)}, got ${encodeCrc24(actualCrc)}`, + ); + } + } + + return { label: beginLabel, headers, bytes }; +} + +/** + * Canonicalize an already-armored cleartext body per RFC 4880 Section 7.1 + * (dash-unescape, strip trailing spaces/tabs per line, join with CRLF). + * @param {string} rawBody + * @returns {string} + */ +export function canonicalizeCleartextBody(rawBody) { + const lines = rawBody.replace(/\r\n/g, '\n').replace(/\r/g, '\n').split('\n'); + return lines + .map((line) => { + const unescaped = line.startsWith('- ') ? line.slice(2) : line; + return unescaped.replace(/[ \t]+$/u, ''); + }) + .join('\r\n'); +} + +/** + * Canonicalize an unarmored plaintext file into the exact RFC 4880 Section 7.1 + * cleartext form that `gpg --clearsign` signs: strip one framing-equivalent + * terminal line ending if present, strip trailing spaces/tabs per line, and + * join with CRLF (without dash-unescaping raw plaintext). + * @param {string} plainText + * @returns {string} + */ +export function canonicalizePlaintextForClearsign(plainText) { + let normalized = plainText.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); + if (normalized.endsWith('\n')) { + normalized = normalized.slice(0, -1); + } + return normalized + .split('\n') + .map((line) => line.replace(/[ \t]+$/u, '')) + .join('\r\n'); +} + +/** + * Dash-escape a cleartext payload per RFC 4880 Section 7.1 for output formatting. + * @param {string} plainBody + * @returns {string} + */ +export function dashEscapeCleartextBody(plainBody) { + const normalized = plainBody.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); + return normalized + .split('\n') + .map((line) => (line.startsWith('-') ? `- ${line}` : line)) + .join('\n'); +} + +/** + * Parse binary OpenPGP signature packet list and validate every packet is a + * strict canonical-text signature using SHA-256/384/512. + * @param {Uint8Array} binary + * @returns {Array<{ + * raw: Buffer, + * version: number, + * signatureType: number, + * pubKeyAlgo: number, + * hashAlgo: number, + * hashName: string, + * packetDigest: string, + * }>} + */ +export function parseSignaturePackets(binary) { + const buf = Buffer.from(binary); + if (buf.length === 0) { + throw new Error('Empty signature packet buffer'); + } + + const packets = []; + let offset = 0; + + while (offset < buf.length) { + const startOffset = offset; + const headerByte = buf[offset]; + if ((headerByte & 0x80) === 0) { + throw new Error(`Invalid OpenPGP packet header at offset ${startOffset}`); + } + + let tag; + let bodyLen; + let headerLen; + + if ((headerByte & 0x40) !== 0) { + // New packet format (RFC 4880 §4.2.2) + tag = headerByte & 0x3f; + if (offset + 1 >= buf.length) { + throw new Error('Truncated new-format OpenPGP packet length'); + } + const l0 = buf[offset + 1]; + if (l0 < 192) { + bodyLen = l0; + headerLen = 2; + } else if (l0 <= 223) { + if (offset + 2 >= buf.length) { + throw new Error('Truncated 2-octet OpenPGP packet length'); + } + bodyLen = ((l0 - 192) << 8) + buf[offset + 2] + 192; + headerLen = 3; + } else if (l0 === 255) { + if (offset + 5 >= buf.length) { + throw new Error('Truncated 5-octet OpenPGP packet length'); + } + bodyLen = buf.readUInt32BE(offset + 2); + headerLen = 6; + } else { + throw new Error('Partial body length packets are not supported for signatures'); + } + } else { + // Old packet format (RFC 4880 §4.2.1) + tag = (headerByte >> 2) & 0x0f; + const lenType = headerByte & 0x03; + if (lenType === 0) { + if (offset + 1 >= buf.length) { + throw new Error('Truncated 1-octet old-format OpenPGP packet length'); + } + bodyLen = buf[offset + 1]; + headerLen = 2; + } else if (lenType === 1) { + if (offset + 2 >= buf.length) { + throw new Error('Truncated 2-octet old-format OpenPGP packet length'); + } + bodyLen = buf.readUInt16BE(offset + 1); + headerLen = 3; + } else if (lenType === 2) { + if (offset + 4 >= buf.length) { + throw new Error('Truncated 4-octet old-format OpenPGP packet length'); + } + bodyLen = buf.readUInt32BE(offset + 1); + headerLen = 5; + } else { + throw new Error('Indeterminate-length OpenPGP packets are not supported'); + } + } + + const bodyStart = offset + headerLen; + const packetEnd = bodyStart + bodyLen; + if (packetEnd > buf.length) { + throw new Error(`Truncated OpenPGP packet body at offset ${startOffset}`); + } + + if (tag !== SIGNATURE_PACKET_TAG) { + throw new Error( + `Unexpected OpenPGP packet tag ${tag} at offset ${startOffset}; only Signature packets (tag 2) are allowed`, + ); + } + + if (bodyLen < 4) { + throw new Error('Truncated OpenPGP Signature packet body'); + } + + const version = buf[bodyStart]; + if (version !== 4 && version !== 6) { + throw new Error(`Unsupported OpenPGP Signature packet version: ${version}`); + } + const signatureType = buf[bodyStart + 1]; + if (signatureType !== SIG_TYPE_CANONICAL_TEXT) { + throw new Error( + `Expected canonical text signature (0x01), got 0x${signatureType.toString(16).padStart(2, '0')}. Sign with "gpg --clearsign".`, + ); + } + const pubKeyAlgo = buf[bodyStart + 2]; + const hashAlgo = buf[bodyStart + 3]; + const hashName = ALLOWED_HASH_ALGORITHMS.get(hashAlgo); + if (!hashName) { + throw new Error( + `Disallowed OpenPGP hash algorithm id ${hashAlgo}; only SHA-256, SHA-384, and SHA-512 are accepted`, + ); + } + + const raw = Buffer.from(buf.subarray(startOffset, packetEnd)); + const packetDigest = crypto.createHash('sha256').update(raw).digest('hex'); + + packets.push({ + raw, + version, + signatureType, + pubKeyAlgo, + hashAlgo, + hashName, + packetDigest, + }); + + offset = packetEnd; + } + + if (packets.length === 0) { + throw new Error('No OpenPGP signature packets found'); + } + + return packets; +} + +/** + * Strictly parse an RFC 4880 Cleartext Signed Message. + * Rejects multiple signed blocks, weak hash headers, missing CRC-24 checksum, + * and non-signature packets. + * @param {string} signedText + */ +export function parseCleartextSignedMessage(signedText) { + if (typeof signedText !== 'string' || !signedText.trim()) { + throw new Error('Signed message input is empty'); + } + const normalized = signedText.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); + const lines = normalized.split('\n'); + + const msgStarts = []; + const sigStarts = []; + const sigEnds = []; + for (let i = 0; i < lines.length; i += 1) { + if (lines[i] === SIGNED_MSG_BEGIN) msgStarts.push(i); + if (lines[i] === SIG_BEGIN) sigStarts.push(i); + if (lines[i] === SIG_END) sigEnds.push(i); + } + + if (msgStarts.length !== 1 || sigStarts.length !== 1 || sigEnds.length !== 1) { + throw new Error( + 'Cleartext signed message must contain exactly one PGP SIGNED MESSAGE block and one PGP SIGNATURE block', + ); + } + + const msgStartIdx = msgStarts[0]; + const sigStartIdx = sigStarts[0]; + const sigEndIdx = sigEnds[0]; + if (!(msgStartIdx < sigStartIdx && sigStartIdx < sigEndIdx)) { + throw new Error('Malformed PGP cleartext message framing order'); + } + + // Reject any non-whitespace content before BEGIN or after END to prevent smuggling. + const leading = lines.slice(0, msgStartIdx).join('').trim(); + const trailing = lines.slice(sigEndIdx + 1).join('').trim(); + if (leading.length > 0 || trailing.length > 0) { + throw new Error('Unexpected trailing or leading content outside PGP signed message'); + } + + let blankIdx = -1; + const hashes = new Set(); + for (let i = msgStartIdx + 1; i < sigStartIdx; i += 1) { + const line = lines[i]; + if (line === '') { + blankIdx = i; + break; + } + const colon = line.indexOf(':'); + if (colon <= 0) { + throw new Error(`Malformed cleartext armor header: ${line}`); + } + const key = line.slice(0, colon).trim(); + const value = line.slice(colon + 1).trim(); + if (key.toLowerCase() === 'hash') { + for (const token of value.split(',')) { + const hashName = token.trim().toUpperCase(); + if (!ALLOWED_HASH_NAMES.has(hashName)) { + throw new Error(`Disallowed cleartext Hash header: ${hashName}`); + } + hashes.add(hashName); + } + } + } + if (blankIdx < 0) { + throw new Error('Missing blank line after PGP SIGNED MESSAGE headers'); + } + + const rawBody = lines.slice(blankIdx + 1, sigStartIdx).join('\n'); + const canonicalBody = canonicalizeCleartextBody(rawBody); + const signatureBlock = lines.slice(sigStartIdx, sigEndIdx + 1).join('\n'); + const decodedSig = decodeArmor(signatureBlock, 'PGP SIGNATURE', { requireCrc: true }); + const packets = parseSignaturePackets(decodedSig.bytes); + + return { + hashes: [...hashes], + rawBody, + canonicalBody, + plainBody: canonicalBody.replace(/\r\n/g, '\n'), + signatureBlock, + packets, + }; +} + +/** + * Merge 2+ individually clear-signed PGP messages (`gpg --clearsign`) into ONE + * standard RFC 4880 Cleartext Signed Message containing all signature packets + * in a single armor block. + * + * Detached signature blocks without an embedded cleartext body are rejected so + * every merged input undergoes canonical body equality verification. + * + * @param {string[]} signedInputs + * @param {{ expectedBody?: string, minSignatures?: number }} [options] + * @returns {{ + * armored: string, + * canonicalBody: string, + * plainBody: string, + * hashes: string[], + * packetCount: number, + * }} + */ +export function mergeCleartextSignatures( + signedInputs, + { expectedBody, minSignatures = 2 } = {}, +) { + if (!Array.isArray(signedInputs) || signedInputs.length === 0) { + throw new Error('At least one clear-signed input is required'); + } + + let referenceCanonical = + expectedBody !== undefined ? canonicalizePlaintextForClearsign(expectedBody) : null; + let referencePlain = + referenceCanonical !== null ? referenceCanonical.replace(/\r\n/g, '\n') : null; + + const collectedPackets = []; + const seenDigests = new Set(); + const hashSet = new Set(); + + for (let idx = 0; idx < signedInputs.length; idx += 1) { + const input = signedInputs[idx]; + if (typeof input !== 'string' || !input.trim()) { + throw new Error(`Signed input #${idx + 1} is empty`); + } + if (!input.includes(SIGNED_MSG_BEGIN)) { + throw new Error( + `Signed input #${idx + 1} must be a clear-signed PGP SIGNED MESSAGE (detached signatures without an embedded body are not accepted for merge)`, + ); + } + + const parsed = parseCleartextSignedMessage(input); + if (referenceCanonical === null) { + referenceCanonical = parsed.canonicalBody; + referencePlain = parsed.plainBody; + } else if (parsed.canonicalBody !== referenceCanonical) { + throw new Error( + `Signed input #${idx + 1} has a different payload body; all signers must sign the exact same canonical payload`, + ); + } + + for (const pkt of parsed.packets) { + if (seenDigests.has(pkt.packetDigest)) { + throw new Error( + `Duplicate signature packet detected in input #${idx + 1}; each signer must provide a distinct signature`, + ); + } + seenDigests.add(pkt.packetDigest); + hashSet.add(pkt.hashName); + collectedPackets.push(pkt); + } + } + + if (collectedPackets.length < minSignatures) { + throw new Error( + `Expected at least ${minSignatures} signature packet(s), got ${collectedPackets.length}`, + ); + } + + const hashOrder = ['SHA256', 'SHA384', 'SHA512']; + const sortedHashes = [...hashSet].sort( + (a, b) => hashOrder.indexOf(a) - hashOrder.indexOf(b), + ); + const mergedBytes = Buffer.concat(collectedPackets.map((p) => p.raw)); + const mergedSigArmor = encodeArmor('PGP SIGNATURE', mergedBytes); + const escapedBody = dashEscapeCleartextBody(referencePlain ?? ''); + + const armored = [ + SIGNED_MSG_BEGIN, + `Hash: ${sortedHashes.join(', ')}`, + '', + escapedBody, + mergedSigArmor, + '', + ].join('\n'); + + return { + armored, + canonicalBody: referenceCanonical ?? '', + plainBody: referencePlain ?? '', + hashes: sortedHashes, + packetCount: collectedPackets.length, + }; +} diff --git a/cli/onekey-release-sign/src/payload.mjs b/cli/onekey-release-sign/src/payload.mjs new file mode 100644 index 000000000..8e870e6b6 --- /dev/null +++ b/cli/onekey-release-sign/src/payload.mjs @@ -0,0 +1,251 @@ +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; + +const HEX64_RE = /^[a-f0-9]{64}$/u; +const ALLOWED_APP_TYPES = new Set(['electron', 'ios', 'android']); + +/** + * Validate a release artifact basename against the shared rule supported by + * OneKey's downstream Desktop/iOS/Android SHA256SUMS verifiers (no path + * separators, no traversal, no whitespace, no control characters). + * @param {string} fileName + */ +export function assertSafeReleaseFileName(fileName) { + if ( + typeof fileName !== 'string' || + !fileName || + fileName === '.' || + fileName === '..' || + fileName.includes('..') || + fileName.includes('/') || + fileName.includes('\\') || + /\s/u.test(fileName) || + /[\x00-\x1f\x7f]/u.test(fileName) + ) { + throw new Error( + `Unsupported release artifact filename "${String(fileName)}": filenames must be single-segment basenames without spaces, path separators, or control characters`, + ); + } +} + +/** + * Compute lowercase hex SHA-256 digest of a file using streaming reads. + * @param {string} filePath + * @returns {string} + */ +export function sha256File(filePath) { + const stat = fs.statSync(filePath); + if (!stat.isFile()) { + throw new Error(`Artifact path is not a regular file: ${filePath}`); + } + if (stat.size === 0) { + throw new Error(`Artifact file is empty (0 bytes): ${filePath}`); + } + const hash = crypto.createHash('sha256'); + const fd = fs.openSync(filePath, 'r'); + try { + const chunk = Buffer.allocUnsafe(64 * 1024); + let bytesRead = 0; + do { + bytesRead = fs.readSync(fd, chunk, 0, chunk.length, null); + if (bytesRead > 0) { + hash.update(chunk.subarray(0, bytesRead)); + } + } while (bytesRead > 0); + } finally { + fs.closeSync(fd); + } + return hash.digest('hex'); +} + +/** + * Generate a canonical SHA256SUMS payload for one or more full-release artifacts. + * @param {string[]} artifactPaths + * @returns {{ content: string, entries: Array<{ fileName: string, sha256: string, path: string }> }} + */ +export function createSha256SumsPayload(artifactPaths) { + if (!Array.isArray(artifactPaths) || artifactPaths.length === 0) { + throw new Error('At least one artifact path is required'); + } + const entries = []; + const seenNames = new Set(); + for (const artifactPath of artifactPaths) { + const fileName = path.basename(artifactPath); + assertSafeReleaseFileName(fileName); + if (seenNames.has(fileName)) { + throw new Error(`Duplicate artifact filename in checksum list: ${fileName}`); + } + seenNames.add(fileName); + const sha256 = sha256File(artifactPath); + entries.push({ fileName, sha256, path: artifactPath }); + } + const content = `${entries.map((e) => `${e.sha256} ${e.fileName}`).join('\n')}\n`; + return { content, entries }; +} + +function normalizeArtifactPaths({ artifactPath, artifactPaths } = {}) { + const paths = []; + if (Array.isArray(artifactPaths)) { + paths.push(...artifactPaths); + } + if (artifactPath) { + paths.push(artifactPath); + } + return paths; +} + +/** + * Parse and validate an unsigned OneKey release payload (`metadata.json.info` + * JSON or `SHA256SUMS` text) and verify every supplied local artifact path. + * + * @param {string} plainBody + * @param {{ artifactPath?: string, artifactPaths?: string[] }} [options] + */ +export function inspectReleasePayload(plainBody, options = {}) { + const trimmed = plainBody.trim(); + if (!trimmed) { + throw new Error('Release payload body is empty'); + } + + const allArtifactPaths = normalizeArtifactPaths(options); + + if (trimmed.startsWith('{')) { + let parsed; + try { + parsed = JSON.parse(trimmed); + } catch (error) { + throw new Error(`Payload starts with '{' but is not valid JSON: ${error.message}`); + } + + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) { + throw new Error('metadata.json.info payload must be a JSON object'); + } + if (parsed.fileName !== 'metadata.json') { + throw new Error( + `Invalid metadata.json.info fileName: expected "metadata.json", got "${String(parsed.fileName)}"`, + ); + } + const sha256 = typeof parsed.sha256 === 'string' ? parsed.sha256.toLowerCase() : ''; + if (!HEX64_RE.test(sha256)) { + throw new Error('Invalid or missing 64-char hex sha256 in metadata.json.info'); + } + if (typeof parsed.appType !== 'string' || !ALLOWED_APP_TYPES.has(parsed.appType)) { + throw new Error( + `Invalid appType in metadata.json.info: expected electron|ios|android, got "${String(parsed.appType)}"`, + ); + } + if (typeof parsed.appVersion !== 'string' || !parsed.appVersion.trim()) { + throw new Error('Missing appVersion in metadata.json.info'); + } + if (typeof parsed.bundleVersion !== 'string' || !parsed.bundleVersion.trim()) { + throw new Error('Missing bundleVersion in metadata.json.info'); + } + + if (allArtifactPaths.length > 1) { + throw new Error( + `metadata.json.info binds a single metadata.json artifact, but ${allArtifactPaths.length} --artifact flags were provided`, + ); + } + + const artifactChecks = []; + if (allArtifactPaths.length === 1) { + const targetPath = allArtifactPaths[0]; + const actualSha256 = sha256File(targetPath); + if (actualSha256 !== sha256) { + throw new Error( + `Artifact SHA-256 mismatch for ${targetPath}: expected ${sha256}, actual ${actualSha256}`, + ); + } + artifactChecks.push({ + path: targetPath, + fileName: path.basename(targetPath), + sha256: actualSha256, + matched: true, + }); + } + + return { + kind: 'metadata-info', + fileName: parsed.fileName, + sha256, + appVersion: parsed.appVersion, + bundleVersion: parsed.bundleVersion, + buildNumber: parsed.buildNumber ?? null, + appType: parsed.appType, + size: parsed.size ?? null, + generatedAt: parsed.generatedAt ?? null, + artifactCheck: artifactChecks[0] ?? null, + artifactChecks, + }; + } + + // Otherwise parse as SHA256SUMS format: "<64-hex> [*]" + const lines = trimmed + .split(/\r?\n/u) + .map((line) => line.trim()) + .filter(Boolean); + const entries = []; + for (const line of lines) { + const digestField = line.slice(0, 64); + let filenameStart = 64; + while (line[filenameStart] === ' ' || line[filenameStart] === '\t') { + filenameStart += 1; + } + if (!/^[a-fA-F0-9]{64}$/u.test(digestField) || filenameStart === 64 || filenameStart === line.length) { + throw new Error(`Invalid SHA256SUMS line (expected "<64-hex-sha256> "): ${line}`); + } + if (line[filenameStart] === '*' && filenameStart + 1 < line.length) { + filenameStart += 1; + } + const digest = digestField.toLowerCase(); + const rawName = line.slice(filenameStart); + assertSafeReleaseFileName(rawName); + entries.push({ sha256: digest, fileName: rawName }); + } + if (entries.length === 0) { + throw new Error('No checksum entries found in SHA256SUMS payload'); + } + + const artifactChecks = []; + const seenTargets = new Set(); + for (const targetPath of allArtifactPaths) { + const targetName = path.basename(targetPath); + assertSafeReleaseFileName(targetName); + if (seenTargets.has(targetName)) { + throw new Error(`Duplicate --artifact filename provided: ${targetName}`); + } + seenTargets.add(targetName); + + const matching = entries.filter((entry) => entry.fileName === targetName); + if (matching.length === 0) { + throw new Error( + `Artifact "${targetName}" not found in SHA256SUMS entries (${entries.map((e) => e.fileName).join(', ')})`, + ); + } + const uniqueHashes = new Set(matching.map((entry) => entry.sha256)); + if (uniqueHashes.size !== 1) { + throw new Error(`Conflicting SHA-256 entries for "${targetName}" in SHA256SUMS`); + } + const expectedSha256 = matching[0].sha256; + const actualSha256 = sha256File(targetPath); + if (actualSha256 !== expectedSha256) { + throw new Error( + `Artifact SHA-256 mismatch for ${targetName}: expected ${expectedSha256}, actual ${actualSha256}`, + ); + } + artifactChecks.push({ + path: targetPath, + fileName: targetName, + sha256: actualSha256, + matched: true, + }); + } + + return { + kind: 'sha256sums', + entries, + artifactCheck: artifactChecks[0] ?? null, + artifactChecks, + }; +} diff --git a/cli/onekey-release-sign/test/cli.test.mjs b/cli/onekey-release-sign/test/cli.test.mjs new file mode 100644 index 000000000..da4ecd47c --- /dev/null +++ b/cli/onekey-release-sign/test/cli.test.mjs @@ -0,0 +1,272 @@ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import test from 'node:test'; +import { fileURLToPath } from 'node:url'; + +import { parseArgs, runCli } from '../src/cli.mjs'; + +const cliDir = path.dirname(path.dirname(fileURLToPath(import.meta.url))); +const binPath = path.join(cliDir, 'bin', 'onekey-release-sign.mjs'); + +function runGpgInHome(gpgHome, args, input) { + return execFileSync('gpg', args, { + env: { ...process.env, GNUPGHOME: gpgHome, LC_ALL: 'C' }, + input, + encoding: 'utf8', + stdio: ['pipe', 'pipe', 'pipe'], + }); +} + +function genKey(gpgHome, name, email) { + runGpgInHome(gpgHome, [ + '--batch', + '--pinentry-mode', + 'loopback', + '--passphrase', + '', + '--quick-generate-key', + `${name} <${email}>`, + 'ed25519', + 'sign', + 'never', + ]); + const fpr = runGpgInHome(gpgHome, ['--batch', '--with-colons', '--fingerprint', email]) + .split('\n') + .find((line) => line.startsWith('fpr:')) + .split(':')[9] + .toUpperCase(); + const pub = runGpgInHome(gpgHome, ['--batch', '--armor', '--export', fpr]); + return { fpr, pub }; +} + +test('parseArgs handles repeatable flags, equals syntax, and booleans', () => { + const parsed = parseArgs([ + 'merge', + '--in', + 'a.asc', + '--in=b.asc', + '--threshold', + '2', + '--json', + ]); + assert.equal(parsed.command, 'merge'); + assert.deepEqual(parsed.options.in, ['a.asc', 'b.asc']); + assert.equal(parsed.options.threshold, '2'); + assert.equal(parsed.options.json, true); +}); + +test('runCli rejects unknown/misspelled options, argv passphrases, and unknown commands', () => { + const helpRes = runCli(['--help']); + assert.equal(helpRes.exitCode, 0); + assert.match(helpRes.stdout, /onekey-release-sign/); + + const verRes = runCli(['--version']); + assert.equal(verRes.exitCode, 0); + assert.match(verRes.stdout, /^\d+\.\d+\.\d+\n$/); + + const badRes = runCli(['does-not-exist']); + assert.equal(badRes.exitCode, 1); + assert.match(badRes.stderr, /Unknown command/); + + // Misspelled check flags MUST fail instead of silently skipping verification! + const typoArtifact = runCli([ + 'verify', + '--in', + 'a.asc', + '--keyring', + 'k.asc', + '--artfact', + 'pkg.zip', + ]); + assert.equal(typoArtifact.exitCode, 1); + assert.match(typoArtifact.stderr, /Unknown option --artfact/); + + const typoAllow = runCli([ + 'verify', + '--in', + 'a.asc', + '--keyring', + 'k.asc', + '--allow-fingerprints', + 'AAAA', + ]); + assert.equal(typoAllow.exitCode, 1); + assert.match(typoAllow.stderr, /Unknown option --allow-fingerprints/); + + // Passphrase on CLI argv MUST be rejected + const passphraseRes = runCli([ + 'sign', + '--in', + 'payload.txt', + '--passphrase', + 'super-secret-do-not-leak', + ]); + assert.equal(passphraseRes.exitCode, 1); + assert.match(passphraseRes.stderr, /Unknown option --passphrase/); + assert.equal(passphraseRes.stderr.includes('super-secret-do-not-leak'), false); +}); + +test('CLI binary runs full multi-artifact checksum -> sign (x2) -> merge (--payload) -> inspect -> verify workflow', () => { + const baseTmp = fs.existsSync('/tmp') ? '/tmp' : os.tmpdir(); + const tmpRoot = fs.mkdtempSync(path.join(baseTmp, 'ok-cli-')); + const gpgHome = path.join(tmpRoot, 'g'); + fs.mkdirSync(gpgHome, { mode: 0o700 }); + + try { + const keyA = genKey(gpgHome, 'CLI Signer A', 'cli-a@onekey.test'); + const keyB = genKey(gpgHome, 'CLI Signer B', 'cli-b@onekey.test'); + const keyringPath = path.join(tmpRoot, 'keyring.asc'); + fs.writeFileSync(keyringPath, `${keyA.pub}\n${keyB.pub}\n`, 'utf8'); + + const artifact1 = path.join(tmpRoot, 'OneKey-Wallet-6.8.0-android.apk'); + const artifact2 = path.join(tmpRoot, 'OneKey-Wallet-6.8.0-mac-arm64.zip'); + fs.writeFileSync(artifact1, 'fake-apk-bytes-6.8.0', 'utf8'); + fs.writeFileSync(artifact2, 'fake-mac-bytes-6.8.0', 'utf8'); + const sumsPath = path.join(tmpRoot, 'SHA256SUMS'); + const sigAPath = path.join(tmpRoot, 'sig-a.asc'); + const sigBPath = path.join(tmpRoot, 'sig-b.asc'); + const mergedPath = path.join(tmpRoot, 'SHA256SUMS.asc'); + + const execCli = (args) => + execFileSync(process.execPath, [binPath, ...args], { + encoding: 'utf8', + stdio: ['pipe', 'pipe', 'pipe'], + }); + + // 1. checksum for 2 artifacts + execCli([ + 'checksum', + '--artifact', + artifact1, + '--artifact', + artifact2, + '--out', + sumsPath, + ]); + + // 2. sign by A and B (verifying BOTH artifacts before signing via stdin) + execCli([ + 'sign', + '--in', + sumsPath, + '--artifact', + artifact1, + '--artifact', + artifact2, + '--key', + keyA.fpr, + '--gpg-home', + gpgHome, + '--batch', + '--out', + sigAPath, + ]); + execCli([ + 'sign', + '--in', + sumsPath, + '--artifact', + artifact1, + '--artifact', + artifact2, + '--key', + keyB.fpr, + '--gpg-home', + gpgHome, + '--batch', + '--out', + sigBPath, + ]); + + // 3. merge + verify passing the original newline-terminated --payload AND both --artifact flags + const mergeOut = execCli([ + 'merge', + '--in', + sigAPath, + '--in', + sigBPath, + '--payload', + sumsPath, + '--keyring', + keyringPath, + '--threshold', + '2', + '--artifact', + artifact1, + '--artifact', + artifact2, + '--out', + mergedPath, + '--json', + ]); + const mergeJson = JSON.parse(mergeOut); + assert.equal(mergeJson.packetCount, 2); + assert.equal(mergeJson.verified, true); + assert.equal(mergeJson.primaryFingerprints.length, 2); + + // 4. inspect merged file with both artifacts + const inspectJson = JSON.parse( + execCli([ + 'inspect', + '--in', + mergedPath, + '--artifact', + artifact1, + '--artifact', + artifact2, + '--json', + ]), + ); + assert.equal(inspectJson.signed, true); + assert.equal(inspectJson.signaturePackets, 2); + assert.equal(inspectJson.payload.artifactChecks.length, 2); + + // 5. verify merged file with both artifacts + const verifyJson = JSON.parse( + execCli([ + 'verify', + '--in', + mergedPath, + '--keyring', + keyringPath, + '--threshold', + '2', + '--allow-fingerprint', + keyA.fpr, + '--allow-fingerprint', + keyB.fpr, + '--artifact', + artifact1, + '--artifact', + artifact2, + '--json', + ]), + ); + assert.equal(verifyJson.valid, true); + assert.equal(verifyJson.uniqueSignerCount, 2); + assert.equal(verifyJson.payload.artifactChecks.length, 2); + + // 6. Tamper the 2nd artifact while keeping the 1st valid -> verify MUST fail! + fs.writeFileSync(artifact2, 'tampered-mac-bytes-6.8.0', 'utf8'); + const tamperedVerify = runCli([ + 'verify', + '--in', + mergedPath, + '--keyring', + keyringPath, + '--threshold', + '2', + '--artifact', + artifact1, + '--artifact', + artifact2, + ]); + assert.equal(tamperedVerify.exitCode, 1); + assert.match(tamperedVerify.stderr, /Artifact SHA-256 mismatch for OneKey-Wallet-6.8.0-mac-arm64.zip/); + } finally { + fs.rmSync(tmpRoot, { recursive: true, force: true }); + } +}); diff --git a/cli/onekey-release-sign/test/multisig-e2e.test.mjs b/cli/onekey-release-sign/test/multisig-e2e.test.mjs new file mode 100644 index 000000000..a13c58941 --- /dev/null +++ b/cli/onekey-release-sign/test/multisig-e2e.test.mjs @@ -0,0 +1,311 @@ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import test from 'node:test'; + +import { + signCleartext, + verifyMultisigCleartext, +} from '../src/gpg.mjs'; +import { mergeCleartextSignatures } from '../src/openpgp.mjs'; +import { + createSha256SumsPayload, + inspectReleasePayload, + sha256File, +} from '../src/payload.mjs'; + +function runGpgInHome(gpgHome, args, input) { + return execFileSync('gpg', args, { + env: { ...process.env, GNUPGHOME: gpgHome, LC_ALL: 'C' }, + input, + encoding: 'utf8', + stdio: ['pipe', 'pipe', 'pipe'], + }); +} + +function generateTestKey(gpgHome, name, email) { + runGpgInHome(gpgHome, [ + '--batch', + '--pinentry-mode', + 'loopback', + '--passphrase', + '', + '--quick-generate-key', + `${name} <${email}>`, + 'ed25519', + 'sign', + 'never', + ]); + + const colonList = runGpgInHome(gpgHome, [ + '--batch', + '--with-colons', + '--fingerprint', + email, + ]); + const fprLine = colonList + .split('\n') + .find((line) => line.startsWith('fpr:')); + assert.ok(fprLine, `Failed to read fingerprint for ${email}`); + const fingerprint = fprLine.split(':')[9].toUpperCase(); + const publicKey = runGpgInHome(gpgHome, ['--batch', '--armor', '--export', fingerprint]); + return { fingerprint, publicKey }; +} + +function addSigningSubkey(gpgHome, primaryFingerprint) { + runGpgInHome(gpgHome, [ + '--batch', + '--pinentry-mode', + 'loopback', + '--passphrase', + '', + '--quick-add-key', + primaryFingerprint, + 'ed25519', + 'sign', + 'never', + ]); + const colonList = runGpgInHome(gpgHome, [ + '--batch', + '--with-colons', + '--fingerprint', + primaryFingerprint, + ]); + const fprs = colonList + .split('\n') + .filter((line) => line.startsWith('fpr:')) + .map((line) => line.split(':')[9].toUpperCase()); + assert.ok(fprs.length >= 2, 'Expected primary + subkey fingerprints'); + const subkeyFingerprint = fprs[fprs.length - 1]; + const publicKey = runGpgInHome(gpgHome, ['--batch', '--armor', '--export', primaryFingerprint]); + return { subkeyFingerprint, publicKey }; +} + +test('End-to-end 2-of-3 GPG multisig merge and verify for OTA metadata.json.info and SHA256SUMS', () => { + const baseTmp = fs.existsSync('/tmp') ? '/tmp' : os.tmpdir(); + const tmpRoot = fs.mkdtempSync(path.join(baseTmp, 'ok-e2e-')); + const gpgHome = path.join(tmpRoot, 'g'); + fs.mkdirSync(gpgHome, { mode: 0o700 }); + + try { + // 1. Create 3 distinct test signers (A with a signing subkey, B, and untrusted C) + const signerA = generateTestKey(gpgHome, 'OneKey Signer A', 'signer-a@onekey.test'); + const signerASub = addSigningSubkey(gpgHome, signerA.fingerprint); + const signerB = generateTestKey(gpgHome, 'OneKey Signer B', 'signer-b@onekey.test'); + const signerC = generateTestKey(gpgHome, 'OneKey Signer C', 'signer-c@onekey.test'); + + const trustedRingText = `${signerASub.publicKey}\n${signerB.publicKey}\n`; + const trustedRingFile = path.join(tmpRoot, 'trusted-pubkeys.asc'); + fs.writeFileSync(trustedRingFile, trustedRingText, 'utf8'); + + // 2. Prepare realistic OTA metadata.json + electron.metadata.json.info + const metadataJsonPath = path.join(tmpRoot, 'metadata.json'); + fs.writeFileSync( + metadataJsonPath, + JSON.stringify({ 'build/index.html': 'abc123', 'build/main.js': 'def456' }, null, 2), + 'utf8', + ); + const metadataSha256 = sha256File(metadataJsonPath); + const metadataInfoPath = path.join(tmpRoot, 'electron.metadata.json.info'); + const metadataInfoContent = + JSON.stringify( + { + fileName: 'metadata.json', + sha256: metadataSha256, + size: fs.statSync(metadataJsonPath).size, + generatedAt: '2026-11-23T12:00:00.000Z', + appVersion: '6.8.0', + buildNumber: '2026112301', + bundleVersion: '7800001', + appType: 'electron', + }, + null, + 2, + ) + '\n'; + fs.writeFileSync(metadataInfoPath, metadataInfoContent, 'utf8'); + + // 3. Signer A and Signer B sign independently + const sigA = signCleartext({ + inputPath: metadataInfoPath, + keyId: `${signerA.fingerprint}!`, + gpgHome, + batch: true, + }); + const sigB = signCleartext({ + inputPath: metadataInfoPath, + keyId: `${signerB.fingerprint}!`, + gpgHome, + batch: true, + }); + + // 4. Merge into ONE standard RFC 4880 .asc file, passing the original newline-terminated payload! + const merged = mergeCleartextSignatures([sigA.armored, sigB.armored], { + expectedBody: metadataInfoContent, + }); + assert.equal(merged.packetCount, 2); + + // 5. Verify with threshold=2 + artifact binding + const verified = verifyMultisigCleartext({ + signedText: merged.armored, + keyringFiles: [trustedRingFile], + threshold: 2, + allowedFingerprints: [signerA.fingerprint, signerB.fingerprint], + artifactPath: metadataJsonPath, + }); + assert.equal(verified.valid, true); + assert.equal(verified.uniqueSignerCount, 2); + assert.deepEqual( + new Set(verified.primaryFingerprints), + new Set([signerA.fingerprint, signerB.fingerprint]), + ); + assert.equal(verified.payload.kind, 'metadata-info'); + assert.equal(verified.payload.artifactCheck.matched, true); + + // 6. Verify native GnuPG CLI also recognizes BOTH signatures in the single merged file + const mergedPath = path.join(tmpRoot, 'electron.metadata.json.info.asc'); + fs.writeFileSync(mergedPath, merged.armored, 'utf8'); + const rawVerify = runGpgInHome(gpgHome, ['--batch', '--status-fd=1', '--verify', mergedPath]); + const validSigCount = rawVerify + .split('\n') + .filter((line) => line.startsWith('[GNUPG:] VALIDSIG ')).length; + assert.equal(validSigCount, 2); + + // 7. Security test: single signature alone must fail threshold=2 + assert.throws( + () => + verifyMultisigCleartext({ + signedText: sigA.armored, + keyringFiles: [trustedRingFile], + threshold: 2, + }), + /Insufficient distinct trusted signatures: got 1, required >= 2/, + ); + + // 8. Security test: primary key + signing subkey of the SAME master key must count as only 1 signer! + const sigASub = signCleartext({ + inputPath: metadataInfoPath, + keyId: `${signerASub.subkeyFingerprint}!`, + gpgHome, + batch: true, + }); + const sameMasterMerged = mergeCleartextSignatures([sigA.armored, sigASub.armored]); + assert.equal(sameMasterMerged.packetCount, 2); + assert.throws( + () => + verifyMultisigCleartext({ + signedText: sameMasterMerged.armored, + keyringFiles: [trustedRingFile], + threshold: 2, + }), + /Insufficient distinct trusted signatures: got 1, required >= 2/, + ); + + // 9. Security test: untrusted Signer C cannot satisfy threshold=2 alongside Signer A + const sigC = signCleartext({ + inputPath: metadataInfoPath, + keyId: `${signerC.fingerprint}!`, + gpgHome, + batch: true, + }); + const withUntrusted = mergeCleartextSignatures([sigA.armored, sigC.armored]); + assert.throws( + () => + verifyMultisigCleartext({ + signedText: withUntrusted.armored, + keyringFiles: [trustedRingFile], + threshold: 2, + }), + /Insufficient distinct trusted signatures: got 1, required >= 2/, + ); + + // 10. Security test: tampering 1 character in the cleartext body fails verification + const tamperedAsc = merged.armored.replace('7800001', '7800002'); + assert.throws( + () => + verifyMultisigCleartext({ + signedText: tamperedAsc, + keyringFiles: [trustedRingFile], + threshold: 2, + }), + /invalid\/expired\/revoked signature|BADSIG/i, + ); + + // 11. Security test: artifact SHA-256 mismatch is rejected + const wrongArtifact = path.join(tmpRoot, 'wrong-metadata.json'); + fs.writeFileSync(wrongArtifact, '{"tampered": true}', 'utf8'); + assert.throws( + () => + verifyMultisigCleartext({ + signedText: merged.armored, + keyringFiles: [trustedRingFile], + threshold: 2, + artifactPath: wrongArtifact, + }), + /Artifact SHA-256 mismatch/, + ); + + // 12. Full-release multi-artifact SHA256SUMS.asc end-to-end flow (including --payload round-trip) + const installerMac = path.join(tmpRoot, 'OneKey-Wallet-6.8.0-mac-arm64.zip'); + const installerApk = path.join(tmpRoot, 'OneKey-Wallet-6.8.0-android.apk'); + fs.writeFileSync(installerMac, 'fake-installer-mac-v6.8.0', 'utf8'); + fs.writeFileSync(installerApk, 'fake-installer-apk-v6.8.0', 'utf8'); + const sums = createSha256SumsPayload([installerMac, installerApk]); + const sumsPath = path.join(tmpRoot, 'SHA256SUMS'); + fs.writeFileSync(sumsPath, sums.content, 'utf8'); + + const sumSigA = signCleartext({ + inputPath: sumsPath, + keyId: `${signerA.fingerprint}!`, + gpgHome, + batch: true, + }); + const sumSigB = signCleartext({ + inputPath: sumsPath, + keyId: `${signerB.fingerprint}!`, + gpgHome, + batch: true, + }); + const sumMerged = mergeCleartextSignatures([sumSigA.armored, sumSigB.armored], { + expectedBody: sums.content, + }); + const sumVerified = verifyMultisigCleartext({ + signedText: sumMerged.armored, + keyringFiles: [trustedRingFile], + threshold: 2, + artifactPaths: [installerMac, installerApk], + }); + assert.equal(sumVerified.valid, true); + assert.equal(sumVerified.uniqueSignerCount, 2); + assert.equal(sumVerified.payload.kind, 'sha256sums'); + assert.equal(sumVerified.payload.artifactChecks.length, 2); + + // Tampering ONLY the 2nd artifact MUST fail verification when both are passed + fs.writeFileSync(installerApk, 'tampered-apk-v6.8.0', 'utf8'); + assert.throws( + () => + verifyMultisigCleartext({ + signedText: sumMerged.armored, + keyringFiles: [trustedRingFile], + threshold: 2, + artifactPaths: [installerMac, installerApk], + }), + /Artifact SHA-256 mismatch for OneKey-Wallet-6.8.0-android.apk/, + ); + + // 13. Filename rule consistency: spaces in artifact names rejected at both generation and parsing + const spaceFile = path.join(tmpRoot, 'OneKey Wallet 6.8.0.zip'); + fs.writeFileSync(spaceFile, 'binary-data', 'utf8'); + assert.throws( + () => createSha256SumsPayload([spaceFile]), + /Unsupported release artifact filename/, + ); + assert.throws( + () => inspectReleasePayload(`${'a'.repeat(64)} OneKey Wallet 6.8.0.zip\n`), + /Unsupported release artifact filename/, + ); + } finally { + fs.rmSync(tmpRoot, { recursive: true, force: true }); + } +}); diff --git a/cli/onekey-release-sign/test/openpgp.test.mjs b/cli/onekey-release-sign/test/openpgp.test.mjs new file mode 100644 index 000000000..e8b81ee6e --- /dev/null +++ b/cli/onekey-release-sign/test/openpgp.test.mjs @@ -0,0 +1,156 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { + canonicalizeCleartextBody, + canonicalizePlaintextForClearsign, + crc24, + dashEscapeCleartextBody, + decodeArmor, + encodeArmor, + encodeCrc24, + mergeCleartextSignatures, + parseCleartextSignedMessage, + parseSignaturePackets, +} from '../src/openpgp.mjs'; + +function makeFakeSigPacket({ + version = 4, + sigType = 0x01, + pubKeyAlgo = 1, + hashAlgo = 8, + payload = Buffer.from([0xaa, 0xbb, 0xcc, 0xdd]), + newFormat = true, +} = {}) { + const body = Buffer.concat([ + Buffer.from([version, sigType, pubKeyAlgo, hashAlgo]), + payload, + ]); + if (newFormat) { + return Buffer.concat([Buffer.from([0xc0 | 2, body.length]), body]); + } + return Buffer.concat([Buffer.from([0x80 | (2 << 2), body.length]), body]); +} + +test('crc24 matches RFC 4880 ASCII armor round-trip, rejects tampering, and requires checksum line', () => { + const sample = Buffer.from('OneKey multi-signature test payload', 'utf8'); + const armored = encodeArmor('PGP SIGNATURE', sample); + const decoded = decodeArmor(armored, 'PGP SIGNATURE'); + assert.deepEqual(decoded.bytes, sample); + assert.equal(encodeCrc24(crc24(sample)).length, 4); + + const tampered = armored.replace(/=[A-Za-z0-9+/]{4}\n-----END/, '=AAAA\n-----END'); + assert.throws(() => decodeArmor(tampered, 'PGP SIGNATURE'), /CRC-24 mismatch/); + + // Omitted CRC-24 line MUST be rejected + const missingCrc = armored.replace(/\n=[A-Za-z0-9+/]{4}\n-----END/, '\n-----END'); + assert.throws( + () => decodeArmor(missingCrc, 'PGP SIGNATURE'), + /Missing mandatory CRC-24 checksum/, + ); +}); + +test('canonicalizeCleartextBody and canonicalizePlaintextForClearsign align with GnuPG framing', () => { + const raw = '- --hello \nworld\t \n- line'; + assert.equal(canonicalizeCleartextBody(raw), '--hello\r\nworld\r\nline'); + assert.equal(dashEscapeCleartextBody('--hello\nworld'), '- --hello\nworld'); + + // Trailing single LF or CRLF is framing for clearsign; double LF preserves one blank line. + assert.equal(canonicalizePlaintextForClearsign('line1\nline2\n'), 'line1\r\nline2'); + assert.equal(canonicalizePlaintextForClearsign('line1\r\nline2\r\n'), 'line1\r\nline2'); + assert.equal(canonicalizePlaintextForClearsign('line1\nline2\n\n'), 'line1\r\nline2\r\n'); + // Plaintext starting with "- " is NOT dash-unescaped (only armored cleartext is). + assert.equal(canonicalizePlaintextForClearsign('- literal\n'), '- literal'); +}); + +test('parseSignaturePackets parses old and new packet formats and rejects unsafe packets', () => { + const pkt1 = makeFakeSigPacket({ newFormat: true, payload: Buffer.from([1, 2, 3, 4]) }); + const pkt2 = makeFakeSigPacket({ newFormat: false, payload: Buffer.from([5, 6, 7, 8]) }); + + const parsed = parseSignaturePackets(Buffer.concat([pkt1, pkt2])); + assert.equal(parsed.length, 2); + assert.equal(parsed[0].hashName, 'SHA256'); + assert.equal(parsed[1].hashName, 'SHA256'); + + // Reject binary signature type (0x00) + const binarySig = makeFakeSigPacket({ sigType: 0x00 }); + assert.throws(() => parseSignaturePackets(binarySig), /canonical text signature/i); + + // Reject weak SHA-1 hash algorithm (2) + const sha1Sig = makeFakeSigPacket({ hashAlgo: 2 }); + assert.throws(() => parseSignaturePackets(sha1Sig), /Disallowed OpenPGP hash/i); + + // Reject non-signature packet tag (e.g. Literal Data tag 11) + const literalPacket = Buffer.from([0xc0 | 11, 4, 1, 2, 3, 4]); + assert.throws(() => parseSignaturePackets(literalPacket), /Unexpected OpenPGP packet tag 11/); +}); + +test('parseCleartextSignedMessage rejects multiple blocks, weak headers, and omitted CRC-24', () => { + const pkt = makeFakeSigPacket(); + const sigArmor = encodeArmor('PGP SIGNATURE', pkt); + const valid = [ + '-----BEGIN PGP SIGNED MESSAGE-----', + 'Hash: SHA256', + '', + '{"hello":"world"}', + sigArmor, + ].join('\n'); + + const parsed = parseCleartextSignedMessage(valid); + assert.equal(parsed.plainBody, '{"hello":"world"}'); + assert.equal(parsed.packets.length, 1); + + const smuggled = `${valid}\n${valid}`; + assert.throws(() => parseCleartextSignedMessage(smuggled), /exactly one PGP SIGNED MESSAGE/); + + const weakHash = valid.replace('Hash: SHA256', 'Hash: SHA1'); + assert.throws(() => parseCleartextSignedMessage(weakHash), /Disallowed cleartext Hash header/); + + const missingCrcMsg = valid.replace(/\n=[A-Za-z0-9+/]{4}\n-----END/, '\n-----END'); + assert.throws( + () => parseCleartextSignedMessage(missingCrcMsg), + /Missing mandatory CRC-24 checksum/, + ); +}); + +test('mergeCleartextSignatures enforces clear-signed inputs, framing match, and uniqueness', () => { + const pktA = makeFakeSigPacket({ payload: Buffer.from([1, 1, 1, 1]) }); + const pktB = makeFakeSigPacket({ payload: Buffer.from([2, 2, 2, 2]) }); + const makeMsg = (body, pkt) => + [ + '-----BEGIN PGP SIGNED MESSAGE-----', + 'Hash: SHA256', + '', + body, + encodeArmor('PGP SIGNATURE', pkt), + ].join('\n'); + + const msgA = makeMsg('body-1', pktA); + const msgB = makeMsg('body-1', pktB); + // Matches expectedBody terminated with trailing LF or CRLF + const merged = mergeCleartextSignatures([msgA, msgB], { expectedBody: 'body-1\n' }); + assert.equal(merged.packetCount, 2); + const mergedCrlf = mergeCleartextSignatures([msgA, msgB], { expectedBody: 'body-1\r\n' }); + assert.equal(mergedCrlf.packetCount, 2); + + const reparsed = parseCleartextSignedMessage(merged.armored); + assert.equal(reparsed.packets.length, 2); + assert.equal(reparsed.plainBody, 'body-1'); + + // Detached signatures without embedded cleartext body MUST be rejected + const detachedB = encodeArmor('PGP SIGNATURE', pktB); + assert.throws( + () => mergeCleartextSignatures([msgA, detachedB]), + /must be a clear-signed PGP SIGNED MESSAGE/, + ); + + assert.throws( + () => mergeCleartextSignatures([msgA, makeMsg('body-tampered', pktB)]), + /different payload body/, + ); + + assert.throws( + () => mergeCleartextSignatures([msgA, msgA]), + /Duplicate signature packet/, + ); +});