Skip to content

feat(cli): add @onekeyfe/onekey-release-sign multisig CLI package - #295

Open
huhuanming wants to merge 3 commits into
mainfrom
feat/onekey-release-sign-cli
Open

huhuanming wants to merge 3 commits into
mainfrom
feat/onekey-release-sign-cli

Conversation

@huhuanming

@huhuanming huhuanming commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Creates a top-level cli/ directory (outside root Yarn workspaces, mirroring chain-runtimes/, so synchronized RN package versioning and yarn.lock --immutable stay untouched).
  • Adds @onekeyfe/onekey-release-sign (cli/onekey-release-sign), a zero-dependency Node.js (>= 20) CLI and programmatic library for M-of-N (default 2-of-N) YubiKey/OpenPGP signing, RFC 4880 single-file .asc merging, and threshold verification for OneKey OTA (metadata.json.info) and full-release (SHA256SUMS.asc) artifacts.
  • Adds .github/workflows/cli-checks.yml to run unit tests, end-to-end GnuPG multisig tests, and npm pack --dry-run on cli/** changes.

Package Capabilities

  • onekey-release-sign doctor — inspects gpg, optional ykman, and plugged-in YubiKey OpenPGP card status.
  • onekey-release-sign checksum — generates canonical <sha256> <filename> payloads for full-release installers/APKs.
  • onekey-release-sign inspect — parses metadata.json.info, SHA256SUMS, or signed .asc files with optional --artifact SHA-256 verification.
  • onekey-release-sign sign — verifies payload & optional --artifact hash locally before invoking gpg --clearsign --digest-algo SHA256 (YubiKey PIN + touch).
  • onekey-release-sign merge — validates and combines 2+ signed .asc inputs over the exact same canonical payload into one standard RFC 4880 .asc file, with optional isolated --keyring + --threshold + --artifact verification.
  • onekey-release-sign verify — cryptographically verifies a multi-signature .asc in a freshly created isolated GNUPGHOME (0700), deduplicating valid signers strictly by Primary Key Fingerprint (blocking duplicate signatures and primary+subkey bypasses) and supporting --json output.

Security Invariants Verified

  • Rejects multiple PGP SIGNED MESSAGE blocks, non-signature packet smuggling, binary (0x00) signatures, weak hashes (SHA-1/MD5), CRC-24 corruption, mismatched payloads during merge, tampered cleartext bytes, untrusted keys, artifact SHA-256 mismatches, and primary+subkey duplicate signing by the same master key.

Verification

  • cd cli/onekey-release-sign && npm run check: 9/9 tests passed (unit + real GnuPG 2-of-3 end-to-end OTA & SHA256SUMS multisig + CLI binary tests) and npm pack --dry-run verified (16.2 kB, 0 runtime deps).
  • Verified cross-library interoperability of merged RFC 4880 .asc output with openpgp@5.11.3 (RSA-2048 2-of-2 verified).
  • Root repository gates: node --test scripts/*.test.mjs (90/90 passed), node scripts/validate-npm-dist-tag.mjs (45 workspaces validated), development/lint/test-integrity.js (89 test files passed).

Devin Review

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 7 potential issues.

2 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)

Devin Review

const sortedHashes = [...hashSet].sort(
(a, b) => hashOrder.indexOf(a) - hashOrder.indexOf(b),
);
const mergedBytes = Buffer.concat(collectedPackets.map((p) => p.raw));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Android updates reject signer order

When the embedded release key signs second, mergeCleartextSignatures puts its signature where Android cannot use it. Both Android verifiers check only the first signature, even when the CLI verifies both.

Learn more

The CLI checks the threshold across all signature packets, but the Android bundle verifier and the APK verifier only look up and verify the first packet against the embedded OneKey keyring. The CLI merge path passes files in command-line order, so a gate can approve an artifact current Android apps reject.

Example: Merge the new YubiKey signer's file first and the existing OneKey release signer's file second. A keyring containing both can pass --threshold 2, while current Android builds reject the first signature because its key is not embedded.

Recommended fix: Define a legacy-compatible merge mode that requires a signature verifiable by the existing Android keyring and places it first. Test the emitted messages with the Android OTA and APK verifiers. For releases that do not include the legacy key, require a client trust-store rollout before using the merged output.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread cli/onekey-release-sign/src/cli.mjs Outdated
const keyrings = requireOption(options.keyring, 'keyring');
const threshold = parseThreshold(options.threshold, 2);
const signedText = fs.readFileSync(inputPath, 'utf8');
const artifactPath = options.artifact?.[0];

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Extra release artifacts go unchecked

With repeated --artifact flags, verify checks only the first file and succeeds even when a later file fails its checksum. sign, inspect, and merge also discard every artifact after the first.

Learn more

The checksum command accepts repeated artifact flags and writes all the requested checksums. The sign path, inspect path, and merge path independently select the first artifact, like verification. The underlying payload checker matches and hashes one path per call.

Example: Generate a manifest for desktop.zip and mobile.apk. Verify the signed manifest with both artifact flags after mobile.apk changes. Verification reports success if desktop.zip still matches.

Recommended fix: Verify all supplied paths against the signed manifest and report each binding, or reject multiple artifact flags on commands that accept only one. Add a CLI test with a correct first file and an incorrect second file.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread cli/onekey-release-sign/src/payload.mjs Outdated
Comment on lines +147 to +159
const tokens = line.split(/\s+/u);
if (tokens.length < 2) {
throw new Error(`Invalid SHA256SUMS line (expected "<sha256> <filename>"): ${line}`);
}
const digest = tokens[0].toLowerCase();
if (!HEX64_RE.test(digest)) {
throw new Error(`Invalid SHA-256 hex digest in SHA256SUMS line: ${line}`);
}
const rawName = tokens[1].replace(/^\*/u, '');
if (rawName.includes('..') || rawName.includes('/') || rawName.includes('\\')) {
throw new Error(`Unsafe path in SHA256SUMS filename: ${rawName}`);
}
entries.push({ sha256: digest, fileName: rawName });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Checksum filenames truncate at spaces

For an installer named OneKey Wallet.zip, inspectReleasePayload reads only OneKey from the checksum line. Signing with --artifact then rejects the installer even though the CLI generated its checksum.

Learn more

createSha256SumsPayload writes the entire basename after the digest. Signing calls inspectReleasePayload before invoking GPG, and artifact matching compares against the actual basename.

Example: checksum --artifact "OneKey Wallet.zip" emits the full name, but signing that manifest with the same artifact fails because the parsed name is OneKey.

Recommended fix: Parse the checksum separator and mode marker explicitly, preserving the remaining filename. If downstream release consumers require a narrower filename format, reject those names at generation instead of emitting a manifest this workflow cannot use. Test generation and artifact verification together.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread cli/onekey-release-sign/src/openpgp.mjs Outdated
Comment on lines +479 to +482
} 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`,
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Merge rejects the original payload

When --payload points to the newline-terminated file both signers used, mergeCleartextSignatures rejects it as different. GnuPG uses the final newline as framing, but merge still counts it in the expected payload.

Learn more

The checksum generator terminates its output with a newline. The merge command forwards the original file verbatim as expectedBody. GnuPG's clearsigned representation uses the last line ending before signature armor as framing, which cleartext parsing excludes. Comparing the original file's canonical form with that parsed form therefore rejects exact matches when the file ends in a newline.

Example: Generate SHA256SUMS with checksum, sign it twice, then pass that same SHA256SUMS as merge --payload. The first signature fails the body comparison.

Recommended fix: Compare both sides in GnuPG's clearsign form, removing one framing-equivalent terminal line ending from the expected plaintext and applying dash unescaping only to armor text. Keep detached text-mode handling separate, because its signature can cover the final newline. Test with real GnuPG and LF, CRLF, and multiple terminal line endings.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +97 to +104
if (REPEATABLE_FLAGS.has(key)) {
if (!Array.isArray(options[key])) {
options[key] = [];
}
options[key].push(value);
} else {
options[key] = value;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Verification ignores misspelled check flags

When an operator mistypes --artifact, parseArgs accepts it, but verify skips the artifact check. Signature verification still returns success even if the artifact does not match.

Learn more

Validate option names against each subcommand's supported options before doing any work, and return a nonzero exit for unknown options. Cover misspellings of --artifact and --allow-fingerprint in the CLI tests.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +63 to +66
const stderr = String(error?.stderr ?? '').trim();
throw new Error(
`gpg ${args.join(' ')} failed (exit ${error?.status ?? 'unknown'}): ${stderr || error.message}`,
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟥 Signing failures expose key passphrases

When batch signing fails, runGpg includes the supplied passphrase in its error. The CLI writes that error to stderr, exposing the passphrase to anyone who can read the captured job logs.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +140 to +152
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];
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟨 Missing armor checksum passes verification

When a signed artifact omits its CRC-24 checksum, decodeArmor accepts the block without checking it. The release verifier can accept that input despite the mandatory armor checksum.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

@sidmorizon

Copy link
Copy Markdown
Contributor

@codex review

@sidmorizon

Copy link
Copy Markdown
Contributor

@codex security review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-23T16:04:49.603192Z 1a0f8bd Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@sidmorizon

Copy link
Copy Markdown
Contributor

Cursor review failed.

Remote error: cursor_permission_denied: HTTP 403 Forbidden: Cloud Agent is not available for free users. Please upgrade to Pro.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

Unknown error
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@cursor

cursor Bot commented Nov 23, 2026

Copy link
Copy Markdown

Skipping Bugbot: Bugbot is disabled for this repository. Visit the Bugbot dashboard to update your settings.

@sidmorizon

Copy link
Copy Markdown
Contributor

Devin Cloud review ↗

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: 1a0f8bd524

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread cli/onekey-release-sign/src/gpg.mjs Resolved
Comment thread cli/onekey-release-sign/src/cli.mjs Resolved
Comment thread cli/onekey-release-sign/README.md Resolved
positionals.push(token);
continue;
}
const eqIdx = token.indexOf('=');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: [Reject malformed signer and artifact options]

A misspelled --allow-fingerprint is accepted as an unknown option, then verify uses an empty allowlist. A misspelled --artifact likewise drops the digest check. Repeating --artifact also succeeds on commands that read only the first value, leaving the remaining files unchecked.

Please validate option names, values, and counts per command before running the operation.

Comment thread cli/onekey-release-sign/src/payload.mjs Outdated
.filter(Boolean);
const entries = [];
for (const line of lines) {
const tokens = line.split(/\s+/u);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: [Use a filename rule that checksum and verification share]

checksum writes Installer Preview.apk verbatim. This parser splits on whitespace and keeps only Installer, so sign --artifact or verify --artifact cannot find the original file in a manifest the CLI generated.

Please enforce the same release-manifest filename rule when generating and reading entries, rejecting basenames the release consumers cannot represent.

Comment thread cli/onekey-release-sign/src/openpgp.mjs Resolved
Comment thread cli/onekey-release-sign/src/openpgp.mjs Resolved
Comment thread cli/onekey-release-sign/src/openpgp.mjs Resolved
@sidmorizon

Copy link
Copy Markdown
Contributor

Comment thread cli/onekey-release-sign/src/gpg.mjs Outdated
Comment on lines +163 to +167
if (batch) {
args.push('--batch', '--yes', '--pinentry-mode', 'loopback');
if (passphrase !== undefined) {
args.push('--passphrase', passphrase);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 P0: 批量签名泄露密钥口令

Type: Security

Severity: critical

批量签名时,signCleartext 把密钥口令放进本机可查看的进程参数。runGpg 在 GPG 失败时将口令写入异常,CLI 随后输出到标准错误。

Recommendation

使用 --passphrase-fd 0 通过子进程标准输入传入口令,并向 CLI 提供从标准输入或专用文件描述符读取口令的方式。不要在异常中打印未经脱敏的子进程参数。用模拟 GPG 失败的测试断言输出不含口令。

const sortedHashes = [...hashSet].sort(
(a, b) => hashOrder.indexOf(a) - hashOrder.indexOf(b),
);
const mergedBytes = Buffer.concat(collectedPackets.map((p) => p.raw));

@sidmorizon sidmorizon Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 P1: 签名顺序导致 Android 拒绝更新

Severity: severe

现有发布密钥的签名排在第二位时,mergeCleartextSignatures 仍按输入顺序输出。Android 的 OTA 验证和 APK 验证只检查首个签名。若首个签名的密钥不在设备内置密钥环中,即使 CLI 验证通过,设备也会拒绝更新。

Originally reported at cli/onekey-release-sign/src/openpgp.mjs:521-521 on commit 1a0f8bd524e3cbfa0b0036b4b65dc518eb8f0219. The finding's code and surrounding context were verified unchanged at commit 25fa06700fee2ecd665c81fbd277929ce6c06cd2; other code may have changed since the review.

Comment thread cli/onekey-release-sign/src/openpgp.mjs Outdated
Comment on lines +456 to +461
let referenceCanonical =
expectedBody !== undefined ? canonicalizeCleartextBody(expectedBody) : null;
let referencePlain =
expectedBody !== undefined
? expectedBody.replace(/\r\n/g, '\n').replace(/\r/g, '\n')
: null;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 P2: 合并拒绝原始校验文件

Severity: non-severe

将生成签名的同一份 checksum 文件传给 merge --payload 时,mergeCleartextSignatures 会误报正文不同。校验文件生成器写入末尾换行,而 签名解析器不将签名分隔符前的换行计入正文。

Comment thread cli/onekey-release-sign/src/payload.mjs Outdated
Comment on lines +147 to +155
const tokens = line.split(/\s+/u);
if (tokens.length < 2) {
throw new Error(`Invalid SHA256SUMS line (expected "<sha256> <filename>"): ${line}`);
}
const digest = tokens[0].toLowerCase();
if (!HEX64_RE.test(digest)) {
throw new Error(`Invalid SHA-256 hex digest in SHA256SUMS line: ${line}`);
}
const rawName = tokens[1].replace(/^\*/u, '');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 P2: 安装包名称在空格处截断

Severity: non-severe

安装包名称包含空格时,inspectReleasePayload 只读取名称的第一段。checksum写入的是完整名称,因此发布人员无法用生成的清单核对同一个安装包。

Comment thread cli/onekey-release-sign/src/cli.mjs Outdated
const keyrings = requireOption(options.keyring, 'keyring');
const threshold = parseThreshold(options.threshold, 2);
const signedText = fs.readFileSync(inputPath, 'utf8');
const artifactPath = options.artifact?.[0];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 P2: 重复参数指定的安装包漏检

Severity: non-severe

对多文件清单重复传入 --artifact 时,runCli 只检查第一个安装包。即使后续安装包的摘要不匹配,命令仍会返回成功。

Comment thread cli/onekey-release-sign/src/openpgp.mjs Outdated
Comment on lines +485 to +490
} else if (input.includes(SIG_BEGIN)) {
if (referenceCanonical === null) {
throw new Error(
`Signed input #${idx + 1} is a detached signature; provide expectedBody or at least one cleartext-signed input`,
);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 P2: 分离签名排在首位时无法合并

Severity: non-severe

未传 --payload 时,mergeCleartextSignatures 会拒绝排在首位的分离签名,即使后续输入已提供所需正文。


function normalizeArtifactPaths({ artifactPath, artifactPaths } = {}) {
const paths = [];
if (Array.isArray(artifactPaths)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: [Reject malformed artifact lists before verification]

If a JavaScript caller supplies a single path string as artifactPaths, this branch drops it. verifyMultisigCleartext can then return valid: true once enough signatures pass, even if the supplied artifact is missing or its digest differs from the signed manifest.

Please reject any supplied artifactPaths value that is not an array of non-empty path strings before verifying signatures.

@sidmorizon

Copy link
Copy Markdown
Contributor

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants