diff --git a/README.md b/README.md index 2658970e..65a35563 100644 --- a/README.md +++ b/README.md @@ -401,6 +401,58 @@ EXAMPLES: genlayer account lock ``` +#### Ledger hardware wallets + +Connect one Ledger over USB, unlock it, and install the Ethereum app. Close other +applications using the device (such as Ledger Live), then import its public account: + +```sh +genlayer account import --name ledger --ledger +# Optional: choose another Ethereum derivation path (omit the m/ prefix) +genlayer account import --name ledger-2 --ledger --derivation-path "44'/60'/1'/0/0" +genlayer account use ledger +genlayer account show +genlayer account send 0x... 1gen --account ledger +``` + +Verify the address on the Ledger during import. The CLI stores only the address, +account type, and derivation path; the private key never leaves the device. The +default path is `44'/60'/0'/0/0`. Import selects the account unless `--no-set-active` +is given; replacing an existing account requires `--overwrite`. + +The active Ledger account can sign contract deployments/writes, transactions, +staking and vesting operations. Approve each signing request on the device; +account listing and balance queries do not need it connected. Exporting private +keys and caching/unlocking Ledger accounts are not supported. Removing the local +account only removes its public metadata. + +Validator registration and operator rotation also require an operator proof of +possession. The current SDK builds that proof from a software private key: use a +separate local keystore account as the operator, while the Ledger account signs +the owner transaction. A Ledger account cannot serve as that proof-signing +operator. + +Use Node.js 20 or newer. Install with npm optional dependencies enabled: Ledger +USB access uses native `node-hid` and `usb` modules. If their prebuilt binaries +cannot load, install your platform's native build prerequisites; Linux also needs +libudev and USB device permissions (Ledger udev rules). An unavailable USB driver +does not prevent using software accounts. + +This integration uses Ledger's Device Management Kit and supports Ethereum legacy, +EIP-2930 and EIP-1559 transactions plus personal-message signatures. Other hardware +wallet vendors, Bluetooth, and EIP-712 typed-data signing are not supported. +Signing uses a local-only context module: the CLI does not request Ledger-hosted +network/contract metadata, transaction checks, or signing telemetry. RPC requests +still go to the selected GenLayer endpoint. No remote clear-signing descriptors +are available, so GenLayer contract writes/deployments require blind signing in +the Ethereum app. The device cannot decode the contract calldata; review the +transaction and fees before approving. Device-provided transaction-check prompts +do not enable hosted checks in this CLI. See the +[pinned SDK audit](docs/ledger-validation.md) for the exact disabled calls. + +Discovery times out after 15 seconds, and each device operation after two minutes. +Rejected, disconnected, or mismatched devices do not broadcast a transaction. + #### Update Resources Manage and update models or configurations. diff --git a/docs/api-references/accounts/account/import.mdx b/docs/api-references/accounts/account/import.mdx index f0fbd34e..2595b791 100644 --- a/docs/api-references/accounts/account/import.mdx +++ b/docs/api-references/accounts/account/import.mdx @@ -2,7 +2,7 @@ title: account import --- -Import an account from a private key or keystore file +Import an account from a private key, keystore file, or Ledger ### Usage @@ -13,6 +13,8 @@ Import an account from a private key or keystore file | Short | Long | Description | Required | Default | | --- | --- | --- | :---: | --- | | | --name <name> | Name for the account | No | | +| | --ledger | Import an account from a Ledger connected via USB | No | | +| | --derivation-path <path> | Ledger Ethereum derivation path | No | `44'/60'/0'/0/0` | | | --private-key <key> | Private key to import | No | | | | --keystore <path> | Path to keystore file to import (geth, foundry, etc.) | No | | | | --password <password> | Password for the new keystore (skips confirmation prompt) | No | | diff --git a/docs/ledger-validation.md b/docs/ledger-validation.md new file mode 100644 index 00000000..e963879b --- /dev/null +++ b/docs/ledger-validation.md @@ -0,0 +1,159 @@ +# Ledger signing: SDK audit and release validation + +Physical-device validation is **pending**. Keep this PR in draft and do not ship +this signing path until a maintainer completes and records the checklist below. +Automated protocol tests and a no-device probe do not verify device displays, +firmware behavior, USB permissions on other hosts, or real signatures. +The maintainer must also confirm that CLI 0.40.0 has shipped and clear the +blocking review before taking this PR out of draft. + +## Pinned versions and context audit + +Reviewed the installed package source/source maps for: + +| Package | Exact version | +| --- | --- | +| `@ledgerhq/device-management-kit` | `1.12.0` | +| `@ledgerhq/device-signer-kit-ethereum` | `1.18.3` | +| `@ledgerhq/device-transport-kit-node-hid` | `1.0.1` | +| `@ledgerhq/context-module` | `2.9.0` | +| `@ledgerhq/signer-utils` | `1.3.0` | +| `@ledgerhq/device-contacts-kit` | `0.5.0` | +| `rxjs` | `7.8.2` | + +These versions are explicit optional dependencies, including the signer's context +peer. This pins the direct signing packages for global npm installs, which do not +use this repository's lockfile. Transitive dependencies still follow their +publishers' manifests; this is not a claim that the entire dependency tree is pinned. + +In Ethereum signer `api/SignerEthBuilder`, `build()` constructs a default +`ContextModuleBuilder` only when no custom module was supplied. The CLI always +supplies `offlineLedgerContext` through `withContextModule()`. + +In context module `src/ContextModuleBuilder`, `removeDefaultLoaders()` only flips +`defaultLoaders`. `src/DefaultContextModule` separately creates field loaders, +typed-data loaders, the blind-signing reporter and the signing reporter. Merely +calling `removeDefaultLoaders()` does **not** disable every hosted request. + +The default Ethereum signing path can make these requests (conditional on device +capabilities, transaction contents and context-loader eligibility): + +| Source under context-module `src/modules/` | Default request and disclosed data | +| --- | --- | +| `ethereum/dynamic-network/data/HttpDynamicNetworkDataSource` | GET `https://global.api.prd.ledger.com/cal/v1/networks`, `chain_id` query | +| `ethereum/calldata/data/HttpCalldataDescriptorDataSource`, token/external-plugin/gated-signing loaders | CAL GET metadata endpoints (`dapps`, `tokens`, `gated_dapps`, depending on loader), chain ID and contract address; calldata descriptors request `descriptors_calldata` | +| NFT, proxy and trusted-name HTTP data sources | `https://nft.api.live.ledger.com` routes containing chain/address/selector; proxy delegate POST also includes calldata and device challenge | +| `multichain/transaction-check/loaders/EthereumTransactionCheckLoader` and `data/HttpTransactionCheckDataSource` | POST `https://global.api.prd.ledger.com/transaction-checks/v3/ethereum/scan/tx`, body `{tx: {from, raw}, chain: chainId}` when device checks are enabled and loader requirements are met | +| `multichain/pki/data/HttpPkiCertificateDataSource` | CAL GET `certificates` with device/public-key metadata | +| `multichain/reporter/data/HttpBlindSigningReporterDatasource` | POST `https://blind-signing.api.ledger.com/ingest/v1/blind-signing-events`, including chain ID, target address, signing method and device/app details | +| `multichain/sign-reporter/data/HttpSignReporterDatasource` | POST `https://blind-signing.api.ledger.com/ingest/v2/blind-signing-events`, including chain ID, target address, selector, signing method and device/app details | + +The signer's `internal/app-binder/task/BuildBaseContexts` passes the transaction +subset to `getContexts()`, including raw transaction bytes when device checks are +enabled. `BuildSubcontextsTask` can request field context. After signing, +`BlindSigningDetectionTask` calls both `report()` and `signReport()`. + +Our replacement returns no contexts, returns a local error for field/typed-data +metadata, and makes both report methods no-ops. It instantiates none of the hosted +loaders/reporters. A device may still offer a transaction-check opt-in prompt; that +prompt does not enable any remote checks in this CLI. GenLayer contract writes and +deployments require blind signing, with no decoded calldata or hosted risk checks. +The selected GenLayer RPC remains necessary for transaction preparation/broadcast. + +Tests use the real pinned SDK's `BuildBaseContexts` and +`BlindSigningDetectionTask`, with network methods spied on and forbidden, for both +values of the device's transaction-check flag. Other tests exercise the SDK's real +`SendSignTransactionTask`, APDU command encoding and response parser with simulated +responses: both parities, legacy/EIP-2930/EIP-1559, chain IDs 4221/61127/61997/61999, +and 32 KiB deployment payloads. These are protocol tests, not physical-device tests. + +## Physical-device checklist — not yet run + +Record the CLI commit, OS/architecture, Node version, device model, firmware, +Ethereum app version and network/chain ID. Use a test-only wallet and test funds. +Do not record recovery phrases, private keys or PINs. + +- [ ] Install the packed CLI with optional dependencies on the target OS. Verify + native USB/HID loading and actionable permission failures. +- [ ] With no device connected, verify a roughly 15-second wait and readable + error. Connect during the wait and verify discovery succeeds. +- [ ] Check locked device, closed/wrong app, rejected import, rejected signing, + disconnected device and blind signing disabled. Verify errors are readable, + no rejected transaction is broadcast, and reconnect/retry works. +- [ ] Import and confirm the address on the physical display. Check default and + alternate derivation paths, plus wrong-device/passphrase rejection. Connect + only one Ledger: discovery selects the first accessible device. +- [ ] Sign a small transfer and recover/compare the sender from the raw signed + transaction. Record fee, amount, destination and chain display behavior. +- [ ] Sign contract writes and a large deployment with blind signing enabled. + Record exactly what the device displays (including what it cannot decode), + transaction size, chain ID, transaction type and confirmed receipt hash. +- [ ] Exercise the supported GenLayer chain IDs/transaction envelopes and both + signature parities; verify recovered sender and receipt for each test case. +- [ ] Sign UTF-8 and raw personal messages; verify with viem recovery. Try rejection. +- [ ] Run staking/vesting owner operations with a separate software operator + keystore. A Ledger selected as operator must give the explicit proof error. +- [ ] Observe network traffic during signing: no Ledger-hosted metadata/checks/ + telemetry requests, even if the device's transaction-check option is enabled. +- [ ] Confirm read-only/list commands work with the device disconnected. + +Attach results to the PR before removing the draft/release gate. No physical +hardware was available in the implementation environment. + +## Physical-device results record + +Status: **not run — awaiting a maintainer with a physical Ledger**. The fields +below are a reporting template, not validation evidence. Keep the checklist +unchecked until the corresponding result is observed on the device. + +Copy this record into the PR for each tested device/OS combination: + +| Environment | Recorded value | +| --- | --- | +| Tester and date | Pending | +| Tested CLI commit and package version | Pending | +| OS, version and architecture | Pending | +| Node and npm versions | Pending | +| Ledger model and firmware version | Pending | +| Ethereum app version | Pending | +| Network alias, chain ID and transaction envelope | Pending | +| Derivation path and public signer address | Pending | + +| Case | Result and device-screen observations | Public evidence | +| --- | --- | --- | +| Installation and USB/HID permissions | Not run | Pending | +| No device; connect during discovery | Not run | Pending | +| Locked/wrong app; rejection; disconnect/retry | Not run | Pending | +| Address confirmation; alternate path; wrong device/passphrase | Not run | Pending | +| Transfer | Not run | Receipt hash, chain ID, recovered sender | +| Contract write; blind signing disabled/enabled | Not run | Receipt hash, chain ID, recovered sender | +| Large deployment | Not run | Receipt hash, calldata size, envelope, chain ID, recovered sender | +| Both signature parities on supported chain IDs/envelopes | Not run | Per-case receipt hash and recovered sender | +| UTF-8/raw messages and rejection | Not run | Public test message and recovery result | +| Staking/vesting with separate software operator | Not run | Receipt hash, chain ID, operator address | +| Ledger selected as operator | Not run | Error text; confirmation no transaction was sent | +| Network traffic with device checks disabled/enabled | Not run | Sanitized capture showing no Ledger-hosted requests | +| Read-only commands with device disconnected | Not run | Command and observed result | + +Do not attach secrets, private RPC credentials, recovery phrases or PINs. For +rejected requests, record how absence of a broadcast was checked; no receipt is +expected. Record failures as failures and retain the draft gate while they are +investigated. A maintainer should remove draft status only after the required +hardware evidence is recorded and reviewed. Passing automated tests alone does +not clear this gate. + +## No-device host probe (2026-11-19) + +A standalone probe using the real pinned DMK and Node HID transport was run on +this Linux/Nix host, Node 20.20.1, without a connected Ledger. After supplying the +installed libudev/libusb runtime libraries, it exhausted the 15-second discovery +window and printed `No accessible Ledger found within 15 seconds ... Cause: No +selected device`, then exited with status 0 from the probe's error handler. Total +wall time was about 20 seconds including module initialization on the busy host. +A prior run missing libusb preserved `libusb-1.0.so.0` in the displayed cause. + +The probe exposed that DMK `CloseSessionsUseCase` closes sessions but does not +call Node HID `destroy()`. The CLI now explicitly destroys its transport as well +as closing sessions, so hotplug listeners do not keep a failed command alive. +No device signature or broadcast was requested. This is not physical-device +qualification and does not satisfy the release checklist above. diff --git a/esbuild.config.dev.js b/esbuild.config.dev.js index c0b98f8a..01f07b8c 100644 --- a/esbuild.config.dev.js +++ b/esbuild.config.dev.js @@ -11,7 +11,7 @@ export default { banner: { js: `const _importMetaUrl = new URL(import.meta.url).pathname;`, }, - external: ["commander", "dockerode", "dotenv", "ethers", "inquirer", "update-check", "ssh2", "fs-extra", "esbuild", "keytar"] + external: ["@ledgerhq/*", "rxjs", "commander", "dockerode", "dotenv", "ethers", "inquirer", "update-check", "ssh2", "fs-extra", "esbuild", "keytar"] }, watch: true, }; diff --git a/esbuild.config.prod.js b/esbuild.config.prod.js index 20e01180..448cd009 100644 --- a/esbuild.config.prod.js +++ b/esbuild.config.prod.js @@ -11,7 +11,7 @@ export default { banner: { js: `const _importMetaUrl = new URL(import.meta.url).pathname;`, }, - external: ["commander", "dockerode", "dotenv", "ethers", "inquirer", "update-check", "ssh2", "fs-extra", "esbuild", "keytar"] + external: ["@ledgerhq/*", "rxjs", "commander", "dockerode", "dotenv", "ethers", "inquirer", "update-check", "ssh2", "fs-extra", "esbuild", "keytar"] }, watch: false, }; diff --git a/package-lock.json b/package-lock.json index f4bf4542..ade0d141 100644 --- a/package-lock.json +++ b/package-lock.json @@ -54,7 +54,14 @@ "typescript": "^5.4.5" }, "optionalDependencies": { - "keytar": "^7.9.0" + "@ledgerhq/context-module": "2.9.0", + "@ledgerhq/device-contacts-kit": "0.5.0", + "@ledgerhq/device-management-kit": "1.12.0", + "@ledgerhq/device-signer-kit-ethereum": "1.18.3", + "@ledgerhq/device-transport-kit-node-hid": "1.0.1", + "@ledgerhq/signer-utils": "1.3.0", + "keytar": "^7.9.0", + "rxjs": "7.8.2" } }, "node_modules/@adraffy/ens-normalize": { @@ -327,7 +334,6 @@ } ], "license": "MIT", - "peer": true, "engines": { "node": ">=18" }, @@ -351,7 +357,6 @@ } ], "license": "MIT", - "peer": true, "engines": { "node": ">=18" } @@ -1424,6 +1429,60 @@ } } }, + "node_modules/@inversifyjs/common": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@inversifyjs/common/-/common-1.5.0.tgz", + "integrity": "sha512-Qj5BELk11AfI2rgZEAaLPmOftmQRLLmoCXgAjmaF0IngQN5vHomVT5ML7DZ3+CA5fgGcEVMcGbUDAun+Rz+oNg==", + "license": "MIT", + "optional": true + }, + "node_modules/@inversifyjs/container": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@inversifyjs/container/-/container-1.9.1.tgz", + "integrity": "sha512-8EhjFoAx1LoD7TpCuP9ptitwc+7kVXEpZB0IeoEsCQb9sWaNYYaBi+7Lommu3/1nYxdMbX2t7AJhQnryT1EEsg==", + "license": "MIT", + "optional": true, + "dependencies": { + "@inversifyjs/common": "1.5.0", + "@inversifyjs/core": "5.2.0", + "@inversifyjs/reflect-metadata-utils": "1.1.0" + }, + "peerDependencies": { + "reflect-metadata": "~0.2.2" + } + }, + "node_modules/@inversifyjs/core": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@inversifyjs/core/-/core-5.2.0.tgz", + "integrity": "sha512-MMaHGGRjQWT9uAof63sbZyEhRl4XptEAE17DJwrgUcN9LsdIEvecKP3r53pE9VF88PFR41knUKKzagUBvWLHmw==", + "license": "MIT", + "optional": true, + "dependencies": { + "@inversifyjs/common": "1.5.0", + "@inversifyjs/prototype-utils": "0.1.0", + "@inversifyjs/reflect-metadata-utils": "1.1.0" + } + }, + "node_modules/@inversifyjs/prototype-utils": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/@inversifyjs/prototype-utils/-/prototype-utils-0.1.0.tgz", + "integrity": "sha512-lNz1yyajMRDXBHLvJsYYX81FcmeD15e5Qz1zAZ/3zeYTl+u7ZF/GxNRKJzNOloeMPMtuR8BnvzHA1SZxjR+J9w==", + "license": "MIT", + "optional": true, + "dependencies": { + "@inversifyjs/common": "1.5.0" + } + }, + "node_modules/@inversifyjs/reflect-metadata-utils": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@inversifyjs/reflect-metadata-utils/-/reflect-metadata-utils-1.1.0.tgz", + "integrity": "sha512-jmuAuC3eL1GnFAYfJGJOMKRDL9q1mgzOyrban6zxfM8Yg1FUHsj25h27bW2G7p8X1Amvhg3MLkaOuogszkrofA==", + "license": "MIT", + "optional": true, + "peerDependencies": { + "reflect-metadata": "0.2.2" + } + }, "node_modules/@isaacs/cliui": { "version": "8.0.2", "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", @@ -1556,6 +1615,269 @@ "url": "https://opencollective.com/js-sdsl" } }, + "node_modules/@ledgerhq/context-module": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/@ledgerhq/context-module/-/context-module-2.9.0.tgz", + "integrity": "sha512-RogqzY2OErMxi+I1D9FtUeO0J0pLg8cI8nk2Omi2rsarM5U+tjmk4Ey7Gp3+N0s5T2nxswvlC0fy5paJCycaXA==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "bs58": "^6.0.0", + "crypto-js": "^4.2.0", + "ethers": "6.14.1", + "inversify": "7.5.1", + "purify-ts": "2.1.0", + "reflect-metadata": "0.2.2" + }, + "peerDependencies": { + "@ledgerhq/device-management-kit": "^1.12.0" + } + }, + "node_modules/@ledgerhq/context-module/node_modules/@types/node": { + "version": "22.7.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.7.5.tgz", + "integrity": "sha512-jML7s2NAzMWc//QSJ1a3prpk78cOPchGvXJsC3C6R6PSMoooztvRVQEz89gmBTBY1SPMaqo5teB4uNHPdetShQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "undici-types": "~6.19.2" + } + }, + "node_modules/@ledgerhq/context-module/node_modules/ethers": { + "version": "6.14.1", + "resolved": "https://registry.npmjs.org/ethers/-/ethers-6.14.1.tgz", + "integrity": "sha512-JnFiPFi3sK2Z6y7jZ3qrafDMwiXmU+6cNZ0M+kPq+mTy9skqEzwqAdFW3nb/em2xjlIVXX6Lz8ID6i3LmS4+fQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/ethers-io/" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "optional": true, + "dependencies": { + "@adraffy/ens-normalize": "1.10.1", + "@noble/curves": "1.2.0", + "@noble/hashes": "1.3.2", + "@types/node": "22.7.5", + "aes-js": "4.0.0-beta.5", + "tslib": "2.7.0", + "ws": "8.17.1" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@ledgerhq/context-module/node_modules/undici-types": { + "version": "6.19.8", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz", + "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==", + "license": "MIT", + "optional": true + }, + "node_modules/@ledgerhq/device-contacts-kit": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/@ledgerhq/device-contacts-kit/-/device-contacts-kit-0.5.0.tgz", + "integrity": "sha512-i8K0NSKalvIfg1mwrrOFEK00a5tPPFOqQBIHuSeTUUXWGH8VdnNulmTmAjNsw64Q+vskUs0+cd9DswAbtHHv9A==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@ledgerhq/signer-utils": "^1.3.0", + "inversify": "7.5.1", + "purify-ts": "2.1.0", + "reflect-metadata": "0.2.2", + "semver": "7.7.2", + "xstate": "5.19.2" + }, + "peerDependencies": { + "@ledgerhq/device-management-kit": "^1.9.1" + } + }, + "node_modules/@ledgerhq/device-management-kit": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/@ledgerhq/device-management-kit/-/device-management-kit-1.12.0.tgz", + "integrity": "sha512-lMdQi7whbBATHFUTHYN6Gv4E4UEc40q8KcffHZGiaPA0EvcJS0D1vSA6/HQjANsQryhQ7ZLgv3r2nFwmmL6ppA==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@noble/hashes": "^1.8.0", + "inversify": "7.5.1", + "isomorphic-ws": "^5.0.0", + "purify-ts": "2.1.0", + "reflect-metadata": "0.2.2", + "semver": "7.7.2", + "uuid": "11.0.3", + "ws": "^8.22.0", + "xstate": "5.19.2" + }, + "peerDependencies": { + "rxjs": "7.8.2" + } + }, + "node_modules/@ledgerhq/device-management-kit/node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "optional": true, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@ledgerhq/device-management-kit/node_modules/uuid": { + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.0.3.tgz", + "integrity": "sha512-d0z310fCWv5dJwnX1Y/MncBAqGMKEzlBb1AOf7z9K8ALnd0utBX/msg/fA0+sbyN1ihbMsLhrBlnl1ak7Wa0rg==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "optional": true, + "bin": { + "uuid": "dist/esm/bin/uuid" + } + }, + "node_modules/@ledgerhq/device-management-kit/node_modules/ws": { + "version": "8.23.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz", + "integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/@ledgerhq/device-signer-kit-ethereum": { + "version": "1.18.3", + "resolved": "https://registry.npmjs.org/@ledgerhq/device-signer-kit-ethereum/-/device-signer-kit-ethereum-1.18.3.tgz", + "integrity": "sha512-/Y6TLpfMD3oIt3MRhGHKMLA/13q7fJI+V/VXc0HmQ/X2H44zrkyxtpFnYsbKwTTR5E3ijGZUpbPt2I9gT2tNaA==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@ledgerhq/device-contacts-kit": "^0.5.0", + "@ledgerhq/signer-utils": "^1.3.0", + "ethers": "6.14.1", + "inversify": "7.5.1", + "purify-ts": "2.1.0", + "reflect-metadata": "0.2.2", + "semver": "7.7.2", + "xstate": "5.19.2" + }, + "peerDependencies": { + "@ledgerhq/context-module": "^2.9.0", + "@ledgerhq/device-management-kit": "^1.12.0" + } + }, + "node_modules/@ledgerhq/device-signer-kit-ethereum/node_modules/@types/node": { + "version": "22.7.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.7.5.tgz", + "integrity": "sha512-jML7s2NAzMWc//QSJ1a3prpk78cOPchGvXJsC3C6R6PSMoooztvRVQEz89gmBTBY1SPMaqo5teB4uNHPdetShQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "undici-types": "~6.19.2" + } + }, + "node_modules/@ledgerhq/device-signer-kit-ethereum/node_modules/ethers": { + "version": "6.14.1", + "resolved": "https://registry.npmjs.org/ethers/-/ethers-6.14.1.tgz", + "integrity": "sha512-JnFiPFi3sK2Z6y7jZ3qrafDMwiXmU+6cNZ0M+kPq+mTy9skqEzwqAdFW3nb/em2xjlIVXX6Lz8ID6i3LmS4+fQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/ethers-io/" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "optional": true, + "dependencies": { + "@adraffy/ens-normalize": "1.10.1", + "@noble/curves": "1.2.0", + "@noble/hashes": "1.3.2", + "@types/node": "22.7.5", + "aes-js": "4.0.0-beta.5", + "tslib": "2.7.0", + "ws": "8.17.1" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@ledgerhq/device-signer-kit-ethereum/node_modules/undici-types": { + "version": "6.19.8", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz", + "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==", + "license": "MIT", + "optional": true + }, + "node_modules/@ledgerhq/device-transport-kit-node-hid": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@ledgerhq/device-transport-kit-node-hid/-/device-transport-kit-node-hid-1.0.1.tgz", + "integrity": "sha512-OALVGVP9eOBaHMqUDlGOrbpsygYawF4Eh/qq8zSEhfeECsxWpmYmKjgm0nJzhiTSIEa/U2inQVbGk2oY5HSHdQ==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "node-hid": "^3.2.0", + "purify-ts": "2.1.0", + "usb": "^2.16.0", + "uuid": "11.0.3" + }, + "peerDependencies": { + "@ledgerhq/device-management-kit": "^1.2.0", + "rxjs": "7.8.2" + } + }, + "node_modules/@ledgerhq/device-transport-kit-node-hid/node_modules/uuid": { + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.0.3.tgz", + "integrity": "sha512-d0z310fCWv5dJwnX1Y/MncBAqGMKEzlBb1AOf7z9K8ALnd0utBX/msg/fA0+sbyN1ihbMsLhrBlnl1ak7Wa0rg==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "optional": true, + "bin": { + "uuid": "dist/esm/bin/uuid" + } + }, + "node_modules/@ledgerhq/signer-utils": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@ledgerhq/signer-utils/-/signer-utils-1.3.0.tgz", + "integrity": "sha512-qe+HQMgZxq6SPv8ghvlq4c33RchUwlf1qE/qp7MtUGPbKGAqD/0PKNyzx05sKLpmA8m6YZdtndHH4CEkikzqSQ==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "semver": "7.7.2" + }, + "peerDependencies": { + "@ledgerhq/device-management-kit": "^1.7.1" + } + }, "node_modules/@napi-rs/wasm-runtime": { "version": "0.2.12", "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-0.2.12.tgz", @@ -1669,7 +1991,6 @@ "integrity": "sha512-kIU8SLQkYWGp3pVKiYzA5OSaNF5EE03P/R8zEmmrG6XwOg5oBjXyQVVIauQ0dgau4zYhpZEhJrvIYt6oM+zZZA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@octokit/auth-token": "^5.0.0", "@octokit/graphql": "^8.2.2", @@ -2177,7 +2498,7 @@ "version": "7.0.15", "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", - "dev": true, + "devOptional": true, "license": "MIT" }, "node_modules/@types/json5": { @@ -2202,7 +2523,6 @@ "resolved": "https://registry.npmjs.org/@types/node/-/node-22.18.0.tgz", "integrity": "sha512-m5ObIqwsUp6BZzyiy4RdZpzWGub9bqLJMvZDD0QMXhxjqMHMENlj+SqF5QxoUwaQNFe+8kz8XM8ZQhqkQPTgMQ==", "license": "MIT", - "peer": true, "dependencies": { "undici-types": "~6.21.0" } @@ -2289,6 +2609,13 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/w3c-web-usb": { + "version": "1.0.14", + "resolved": "https://registry.npmjs.org/@types/w3c-web-usb/-/w3c-web-usb-1.0.14.tgz", + "integrity": "sha512-Qu3Nn6JFuF4+sHKYl+IcX9vYiI40ogleXzFFSxoE1W94rG98o/kXs8uJ0QSfFzuwBCZWlGfUGpPkgwuuX4PchA==", + "license": "MIT", + "optional": true + }, "node_modules/@typescript-eslint/eslint-plugin": { "version": "8.42.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.42.0.tgz", @@ -2325,7 +2652,6 @@ "integrity": "sha512-r1XG74QgShUgXph1BYseJ+KZd17bKQib/yF3SR+demvytiRXrwd12Blnz5eYGm8tXaeRdd4x88MlfwldHoudGg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.42.0", "@typescript-eslint/types": "8.42.0", @@ -2963,7 +3289,6 @@ "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "dev": true, "license": "MIT", - "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -3305,6 +3630,13 @@ "dev": true, "license": "MIT" }, + "node_modules/base-x": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/base-x/-/base-x-5.0.1.tgz", + "integrity": "sha512-M7uio8Zt++eg3jPj+rHMfCC+IuygQHHCOU+IYsVtik6FWjuYpVt/+MRKcgsAMHh8mMFAwnB+Bs+mTrFiXjMzKg==", + "license": "MIT", + "optional": true + }, "node_modules/base64-js": { "version": "1.5.1", "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", @@ -3385,6 +3717,16 @@ "node": ">=8" } }, + "node_modules/bs58": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/bs58/-/bs58-6.0.0.tgz", + "integrity": "sha512-PD0wEnEYg6ijszw/u8s+iI3H17cTymlrwkKhDhPZq+Sokl3AU4htyBFTjAeNAlCCmg0f53g6ih3jATyCKftTfw==", + "license": "MIT", + "optional": true, + "dependencies": { + "base-x": "^5.0.0" + } + }, "node_modules/buffer": { "version": "5.7.1", "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", @@ -4139,6 +4481,14 @@ "node": ">= 8" } }, + "node_modules/crypto-js": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.2.0.tgz", + "integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==", + "deprecated": "Active development of CryptoJS has been discontinued. This library is no longer maintained.", + "license": "MIT", + "optional": true + }, "node_modules/cssstyle": { "version": "4.6.0", "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz", @@ -4800,7 +5150,6 @@ "integrity": "sha512-RNCHRX5EwdrESy3Jc9o8ie8Bog+PeYvvSR8sDGoZxNFTvZ4dlxUB3WzQ3bQMztFrSRODGrLLj8g6OFuGY/aiQg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.12.1", @@ -4988,7 +5337,6 @@ "integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@rtsao/scc": "^1.1.0", "array-includes": "^3.1.9", @@ -6314,6 +6662,21 @@ "node": ">= 0.4" } }, + "node_modules/inversify": { + "version": "7.5.1", + "resolved": "https://registry.npmjs.org/inversify/-/inversify-7.5.1.tgz", + "integrity": "sha512-oWWFDU2BXiuqZynGcLDDD4tqiWAeaEUCALlCj0vk/QwHGgZY/tzDFPuTmWMY3jwRmDIHxVDkcj9SL3MFTlCEDw==", + "license": "MIT", + "optional": true, + "dependencies": { + "@inversifyjs/common": "1.5.0", + "@inversifyjs/container": "1.9.1", + "@inversifyjs/core": "5.2.0" + }, + "peerDependencies": { + "reflect-metadata": "~0.2.2" + } + }, "node_modules/ip-address": { "version": "10.0.1", "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.0.1.tgz", @@ -6860,6 +7223,16 @@ "dev": true, "license": "ISC" }, + "node_modules/isomorphic-ws": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/isomorphic-ws/-/isomorphic-ws-5.0.0.tgz", + "integrity": "sha512-muId7Zzn9ywDsyXgTIafTry2sV3nySZeUDe6YedVd1Hvuuep5AsIlqK+XefWpYTyJG5e503F2xIuT2lcU6rCSw==", + "license": "MIT", + "optional": true, + "peerDependencies": { + "ws": "*" + } + }, "node_modules/isows": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/isows/-/isows-1.0.7.tgz", @@ -6968,7 +7341,6 @@ "integrity": "sha512-twQoecYPiVA5K/h6SxtORw/Bs3ar+mLUtoPSc7iMXzQzK8d7eJ/R09wmTwAjiamETn1cXYPGfNnu7DMoHgu12w==", "devOptional": true, "license": "MIT", - "peer": true, "bin": { "jiti": "lib/jiti-cli.mjs" } @@ -6998,7 +7370,6 @@ "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==", "devOptional": true, "license": "MIT", - "peer": true, "dependencies": { "cssstyle": "^4.2.1", "data-urls": "^5.0.0", @@ -7649,6 +8020,46 @@ "dev": true, "license": "MIT" }, + "node_modules/node-gyp-build": { + "version": "4.8.4", + "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz", + "integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==", + "license": "MIT", + "optional": true, + "bin": { + "node-gyp-build": "bin.js", + "node-gyp-build-optional": "optional.js", + "node-gyp-build-test": "build-test.js" + } + }, + "node_modules/node-hid": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/node-hid/-/node-hid-3.4.0.tgz", + "integrity": "sha512-Br7EO3bJARAJBdtcsGzF/Vs5TjfbkaMdglqLQ+Rk9GOGgVqv5DxYUVH5znLerJU+OfBWw8sd552Ujcprz1bG9g==", + "hasInstallScript": true, + "license": "(MIT OR X11)", + "optional": true, + "dependencies": { + "node-addon-api": "^8.9.0", + "pkg-prebuilds": "^1.1.0" + }, + "bin": { + "hid-showdevices": "src/show-devices.js" + }, + "engines": { + "node": ">=10.16" + } + }, + "node_modules/node-hid/node_modules/node-addon-api": { + "version": "8.9.2", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.2.tgz", + "integrity": "sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==", + "license": "MIT", + "optional": true, + "engines": { + "node": "^18 || ^20 || >= 21" + } + }, "node_modules/normalize-package-data": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-6.0.2.tgz", @@ -8244,6 +8655,20 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/pkg-prebuilds": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/pkg-prebuilds/-/pkg-prebuilds-1.1.0.tgz", + "integrity": "sha512-jyai+KTQ2OwbN6iRYw88XbYOMgtpoSYJpjYebx7d9ihqz3txNi3ucsBt3va0iVWe6svSlaqpijMHFF/eJCMZzg==", + "license": "MIT", + "optional": true, + "bin": { + "pkg-prebuilds-copy": "bin/copy.mjs", + "pkg-prebuilds-verify": "bin/verify.mjs" + }, + "engines": { + "node": ">= 14.15.0" + } + }, "node_modules/pkg-types": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.3.0.tgz", @@ -8482,6 +8907,16 @@ "node": ">=6" } }, + "node_modules/purify-ts": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/purify-ts/-/purify-ts-2.1.0.tgz", + "integrity": "sha512-+KNUHV9FxB9BbjadFdvxa+LNJIaqZmSF7CQH5Rv6+f0rBzsxm9FEqrvkALQbWYJobAja2ZCbBDUY7O4fH2znMA==", + "license": "ISC", + "optional": true, + "dependencies": { + "@types/json-schema": "7.0.15" + } + }, "node_modules/queue-microtask": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", @@ -8630,6 +9065,13 @@ "url": "https://paulmillr.com/funding/" } }, + "node_modules/reflect-metadata": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz", + "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==", + "license": "Apache-2.0", + "optional": true + }, "node_modules/reflect.getprototypeof": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz", @@ -8712,7 +9154,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "@nodeutils/defaults-deep": "1.1.0", "@octokit/rest": "21.1.1", @@ -9772,7 +10213,6 @@ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "license": "MIT", - "peer": true, "engines": { "node": ">=12" }, @@ -10077,7 +10517,6 @@ "integrity": "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A==", "devOptional": true, "license": "Apache-2.0", - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -10178,7 +10617,6 @@ "dev": true, "hasInstallScript": true, "license": "MIT", - "peer": true, "dependencies": { "napi-postinstall": "^0.3.0" }, @@ -10237,6 +10675,32 @@ "node": "^12.20.0 || ^14.13.1 || >=16.0.0" } }, + "node_modules/usb": { + "version": "2.19.1", + "resolved": "https://registry.npmjs.org/usb/-/usb-2.19.1.tgz", + "integrity": "sha512-fjVddzu00GFc1Z5fd5+zuZrqylsfuBbmKKygx3rbIS9w5Nh3ddGVWDHkPBQ/BbB3PVEp6kdsZfX9WXhlsRdPDQ==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@types/w3c-web-usb": "^1.0.6", + "node-addon-api": "^8.0.0", + "node-gyp-build": "^4.5.0" + }, + "engines": { + "node": ">=12.22.0 <13.0 || >=14.17.0" + } + }, + "node_modules/usb/node_modules/node-addon-api": { + "version": "8.9.2", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.2.tgz", + "integrity": "sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==", + "license": "MIT", + "optional": true, + "engines": { + "node": "^18 || ^20 || >= 21" + } + }, "node_modules/util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", @@ -10357,7 +10821,6 @@ "resolved": "https://registry.npmjs.org/vite/-/vite-7.1.4.tgz", "integrity": "sha512-X5QFK4SGynAeeIt+A7ZWnApdUyHYm+pzv/8/A57LqSGcI88U6R6ipOs3uCesdc6yl7nl+zNO0t8LmqAdXcQihw==", "license": "MIT", - "peer": true, "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.5.0", @@ -10471,7 +10934,6 @@ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "license": "MIT", - "peer": true, "engines": { "node": ">=12" }, @@ -10929,7 +11391,6 @@ "resolved": "https://registry.npmjs.org/ws/-/ws-8.17.1.tgz", "integrity": "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==", "license": "MIT", - "peer": true, "engines": { "node": ">=10.0.0" }, @@ -10978,6 +11439,17 @@ "devOptional": true, "license": "MIT" }, + "node_modules/xstate": { + "version": "5.19.2", + "resolved": "https://registry.npmjs.org/xstate/-/xstate-5.19.2.tgz", + "integrity": "sha512-B8fL2aP0ogn5aviAXFzI5oZseAMqN00fg/TeDa3ZtatyDcViYLIfuQl4y8qmHCiKZgGEzmnTyNtNQL9oeJE2gw==", + "license": "MIT", + "optional": true, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/xstate" + } + }, "node_modules/y18n": { "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", diff --git a/package.json b/package.json index 5766ded7..57ae8004 100644 --- a/package.json +++ b/package.json @@ -82,7 +82,14 @@ "vitest": "^3.0.0" }, "optionalDependencies": { - "keytar": "^7.9.0" + "@ledgerhq/context-module": "2.9.0", + "@ledgerhq/device-contacts-kit": "0.5.0", + "@ledgerhq/device-management-kit": "1.12.0", + "@ledgerhq/device-signer-kit-ethereum": "1.18.3", + "@ledgerhq/device-transport-kit-node-hid": "1.0.1", + "@ledgerhq/signer-utils": "1.3.0", + "keytar": "^7.9.0", + "rxjs": "7.8.2" }, "overrides": { "vite": { diff --git a/src/commands/account/export.ts b/src/commands/account/export.ts index 38b59869..5fb1e2a4 100644 --- a/src/commands/account/export.ts +++ b/src/commands/account/export.ts @@ -29,6 +29,10 @@ export class ExportAccountAction extends BaseAction { this.failSpinner(`Account '${accountName}' not found.`); } + if (JSON.parse(readFileSync(keystorePath, "utf-8")).type === "ledger") { + throw new Error("Ledger private keys cannot be exported. Import the device on the destination machine instead."); + } + const outputPath = path.resolve(options.output); if (existsSync(outputPath) && !options.overwrite) { diff --git a/src/commands/account/import.ts b/src/commands/account/import.ts index 357751fa..fa3522e5 100644 --- a/src/commands/account/import.ts +++ b/src/commands/account/import.ts @@ -1,8 +1,11 @@ +import {importLedgerAccount} from "../../lib/accounts/ledger"; import {BaseAction} from "../../lib/actions/BaseAction"; import {ethers} from "ethers"; import {writeFileSync, existsSync, readFileSync} from "fs"; export interface ImportAccountOptions { + ledger?: boolean; + derivationPath?: string; privateKey?: string; keystore?: string; name: string; @@ -25,6 +28,22 @@ export class ImportAccountAction extends BaseAction { this.failSpinner(`Account '${options.name}' already exists. Use '--overwrite' to replace.`); } + if (options.derivationPath && !options.ledger) { + throw new Error("--derivation-path requires --ledger"); + } + if (options.ledger) { + if (options.privateKey || options.keystore || options.password || options.sourcePassword) { + throw new Error("--ledger cannot be combined with private-key, keystore, or password options"); + } + this.stopSpinner(); + const account = await importLedgerAccount(options.derivationPath); + await this.keychainManager.removePrivateKey(options.name); + writeFileSync(keystorePath, JSON.stringify(account, null, 2)); + if (options.setActive !== false) this.setActiveAccount(options.name); + this.logSuccess(`Ledger account '${options.name}' imported. Address: ${account.address}`); + return; + } + let privateKey: string; if (options.keystore) { diff --git a/src/commands/account/index.ts b/src/commands/account/index.ts index 219471ac..9b326a09 100644 --- a/src/commands/account/index.ts +++ b/src/commands/account/index.ts @@ -53,8 +53,10 @@ export function initializeAccountCommands(program: Command) { accountCommand .command("import") - .description("Import an account from a private key or keystore file") + .description("Import an account from a private key, keystore file, or Ledger") .requiredOption("--name ", "Name for the account") + .option("--ledger", "Import an account from a Ledger connected via USB") + .option("--derivation-path ", "Ledger Ethereum derivation path (default: 44'/60'/0'/0/0)") .option("--private-key ", "Private key to import") .option("--keystore ", "Path to keystore file to import (geth, foundry, etc.)") .option("--password ", "Password for the new keystore (skips confirmation prompt)") diff --git a/src/commands/account/send.ts b/src/commands/account/send.ts index e6905b46..910fae22 100644 --- a/src/commands/account/send.ts +++ b/src/commands/account/send.ts @@ -62,32 +62,36 @@ export class SendAction extends BaseAction { const keystoreJson = readFileSync(keystorePath, "utf-8"); const keystoreData = JSON.parse(keystoreJson); - if (!this.isValidKeystoreFormat(keystoreData)) { + const hardwareAccount = this.getLedgerAccount(); + if (!hardwareAccount && !this.isValidKeystoreFormat(keystoreData)) { this.failSpinner("Invalid keystore format."); return; } - // Get private key - const cachedKey = await this.keychainManager.getPrivateKey(accountName); - let privateKey: string; + // Hardware accounts sign on the device; software accounts decrypt as before. + let account = hardwareAccount; + if (!account) { + const cachedKey = await this.keychainManager.getPrivateKey(accountName); + let privateKey: string; - if (cachedKey) { - privateKey = cachedKey; - } else { - let password: string; - if (options.password) { - password = options.password; + if (cachedKey) { + privateKey = cachedKey; } else { - this.stopSpinner(); - password = await this.promptPassword(`Enter password to unlock account '${accountName}':`); - this.startSpinner("Preparing transfer..."); + let password: string; + if (options.password) { + password = options.password; + } else { + this.stopSpinner(); + password = await this.promptPassword(`Enter password to unlock account '${accountName}':`); + this.startSpinner("Preparing transfer..."); + } + const wallet = await ethers.Wallet.fromEncryptedJson(keystoreJson, password); + privateKey = wallet.privateKey; } - const wallet = await ethers.Wallet.fromEncryptedJson(keystoreJson, password); - privateKey = wallet.privateKey; - } + account = createAccount(privateKey as Hash); + } const network = this.getNetwork(options.network); - const account = createAccount(privateKey as Hash); const amount = this.parseAmount(options.amount); const client = createClient({ diff --git a/src/commands/account/show.ts b/src/commands/account/show.ts index 2c539f6b..b75e0ac8 100644 --- a/src/commands/account/show.ts +++ b/src/commands/account/show.ts @@ -43,7 +43,8 @@ export class ShowAccountAction extends BaseAction { const keystoreData = JSON.parse(readFileSync(keystorePath, "utf-8")); - if (!this.isValidKeystoreFormat(keystoreData)) { + const hardwareAccount = this.getLedgerAccount(); + if (!hardwareAccount && !this.isValidKeystoreFormat(keystoreData)) { this.failSpinner("Invalid keystore format."); return; } @@ -74,7 +75,7 @@ export class ShowAccountAction extends BaseAction { balance: `${formattedBalance} GEN`, network: networkAlias, chainId: network.id, - status: isUnlocked ? "unlocked" : "locked", + status: hardwareAccount ? "ledger" : isUnlocked ? "unlocked" : "locked", active: isActive, }; diff --git a/src/commands/account/unlock.ts b/src/commands/account/unlock.ts index 260b864f..d317505b 100644 --- a/src/commands/account/unlock.ts +++ b/src/commands/account/unlock.ts @@ -32,6 +32,10 @@ export class UnlockAccountAction extends BaseAction { const keystoreJson = readFileSync(keystorePath, "utf-8"); const keystoreData = JSON.parse(keystoreJson); + if (keystoreData.type === "ledger") { + this.failSpinner("Ledger accounts cannot be unlocked or cached. Approve each signing request on the device."); + return; + } if (!this.isValidKeystoreFormat(keystoreData)) { this.failSpinner("Invalid keystore format."); return; diff --git a/src/commands/staking/StakingAction.ts b/src/commands/staking/StakingAction.ts index 6d371097..e2e66ad6 100644 --- a/src/commands/staking/StakingAction.ts +++ b/src/commands/staking/StakingAction.ts @@ -155,9 +155,12 @@ export class StakingAction extends BaseAction { }; } - const privateKey = await this.getPrivateKeyForStaking(); - this._stakingPrivateKey = privateKey; - const account = createAccount(privateKey as `0x${string}`); + let account = this.getLedgerAccount(); + if (!account) { + const privateKey = await this.getPrivateKeyForStaking(); + this._stakingPrivateKey = privateKey; + account = createAccount(privateKey as `0x${string}`); + } this._stakingClient = createClient({ chain: network, @@ -222,6 +225,9 @@ export class StakingAction extends BaseAction { const keystoreJson = readFileSync(keystorePath, "utf-8"); const keystoreData = JSON.parse(keystoreJson); + if (keystoreData.type === "ledger") { + throw new Error("A Ledger account cannot sign the operator proof. Pass --operator
for a separate local software keystore account."); + } if (!this.isValidKeystoreFormat(keystoreData)) { throw new Error("Invalid keystore format."); } diff --git a/src/commands/staking/validatorJoin.ts b/src/commands/staking/validatorJoin.ts index 80219f13..9cade9db 100644 --- a/src/commands/staking/validatorJoin.ts +++ b/src/commands/staking/validatorJoin.ts @@ -69,7 +69,7 @@ export class ValidatorJoinAction extends StakingAction { ) { throw new Error( `Operator ${options.operator} must match a local CLI account so its proof of possession can be signed. ` + - "Import the operator keystore first or omit --operator to use the owner account.", + "Import a software operator keystore and pass its address with --operator. Omit --operator only when the owner is a software keystore account.", ); } diff --git a/src/commands/vesting/VestingAction.ts b/src/commands/vesting/VestingAction.ts index 4e359161..21ae00cc 100644 --- a/src/commands/vesting/VestingAction.ts +++ b/src/commands/vesting/VestingAction.ts @@ -49,9 +49,12 @@ export class VestingAction extends BaseAction { } const network = this.getNetwork(config); - const privateKey = await this.getPrivateKeyForVesting(); - this._vestingPrivateKey = privateKey; - const account = createAccount(privateKey as `0x${string}`); + let account = this.getLedgerAccount(); + if (!account) { + const privateKey = await this.getPrivateKeyForVesting(); + this._vestingPrivateKey = privateKey; + account = createAccount(privateKey as `0x${string}`); + } this._vestingClient = createClient({ chain: network, @@ -92,6 +95,9 @@ export class VestingAction extends BaseAction { const keystoreJson = readFileSync(keystorePath, "utf-8"); const keystoreData = JSON.parse(keystoreJson); + if (keystoreData.type === "ledger") { + throw new Error("A Ledger account cannot sign the operator proof. Pass --operator
for a separate local software keystore account."); + } if (!this.isValidKeystoreFormat(keystoreData)) { throw new Error("Invalid keystore format."); } diff --git a/src/lib/accounts/ledger.ts b/src/lib/accounts/ledger.ts new file mode 100644 index 00000000..fae3597a --- /dev/null +++ b/src/lib/accounts/ledger.ts @@ -0,0 +1,113 @@ +import { + getAddress, + isAddress, + recoverTransactionAddress, + recoverMessageAddress, + stringToBytes, + serializeTransaction, + serializeSignature, + hexToBytes, + type Address, + type TransactionSerializable, +} from "viem"; +import {toAccount} from "viem/accounts"; +import {deviceResult, withLedger} from "./ledgerDevice"; + +export const DEFAULT_LEDGER_PATH = "44'/60'/0'/0/0"; +export interface LedgerAccountData { + type: "ledger"; + address: Address; + derivationPath: string; +} + +export function validateLedgerPath(path: string): void { + if ( + !/^44'\/60'\/\d+'\/\d+\/\d+$/.test(path) || + path.split("/").some(part => Number(part.replace("'", "")) >= 0x80000000) + ) { + throw new Error( + "Invalid Ledger derivation path. Expected an Ethereum path such as 44'/60'/0'/0/0 (without m/).", + ); + } +} + +export function validateLedgerAccount(data: LedgerAccountData): void { + if (data.type !== "ledger" || !isAddress(data.address)) throw new Error("Invalid Ledger account address"); + validateLedgerPath(data.derivationPath); +} + +export async function importLedgerAccount(derivationPath = DEFAULT_LEDGER_PATH): Promise { + validateLedgerPath(derivationPath); + return withLedger(async signer => { + const {address} = await deviceResult(signer.getAddress(derivationPath, {checkOnDevice: true})); + return {type: "ledger", address: getAddress(address), derivationPath}; + }); +} + +export function ledgerAccount(data: LedgerAccountData) { + validateLedgerAccount(data); + const verified = (operation: Parameters>[0]) => + withLedger(async signer => { + const {address} = await deviceResult(signer.getAddress(data.derivationPath)); + if (address.toLowerCase() !== data.address.toLowerCase()) { + throw new Error( + "Connected Ledger does not match the imported account. Connect the correct device and passphrase.", + ); + } + return operation(signer); + }); + return toAccount({ + address: getAddress(data.address), + async signTransaction(transaction) { + // GenLayer uses standard Ethereum envelopes. Reject unsupported types before device interaction. + if (transaction.type && !["legacy", "eip2930", "eip1559"].includes(transaction.type)) { + throw new Error(`Ledger transaction type not supported: ${transaction.type}`); + } + const tx = transaction as TransactionSerializable; + const unsigned = serializeTransaction(tx); + return verified(async signer => { + console.error("Review and approve the transaction on your Ledger."); + const signature = await deviceResult( + signer.signTransaction(data.derivationPath, hexToBytes(unsigned)), + ); + const v = signature.v; + const yParity = (v < 2 ? v : v < 35 ? v - 27 : (v - 35) % 2) as 0 | 1; + const serialized = serializeTransaction(tx, { + r: signature.r, + s: signature.s, + v: BigInt(27 + yParity), + yParity, + }); + if ( + (await recoverTransactionAddress({serializedTransaction: serialized})).toLowerCase() !== + data.address.toLowerCase() + ) { + throw new Error("Ledger signature does not match the imported account"); + } + return serialized; + }); + }, + async signMessage({message}) { + return verified(async signer => { + const payload = + typeof message === "string" + ? stringToBytes(message) + : typeof message.raw === "string" + ? hexToBytes(message.raw) + : message.raw; + const signature = await deviceResult(signer.signMessage(data.derivationPath, payload)); + const serialized = serializeSignature({...signature, v: BigInt(signature.v)}); + if ( + (await recoverMessageAddress({message, signature: serialized})).toLowerCase() !== + data.address.toLowerCase() + ) { + throw new Error("Ledger message signature does not match the imported account"); + } + return serialized; + }); + }, + async signTypedData() { + throw new Error("Ledger typed-data signing is not supported by the CLI"); + }, + }); +} diff --git a/src/lib/accounts/ledgerContext.ts b/src/lib/accounts/ledgerContext.ts new file mode 100644 index 00000000..b52356f1 --- /dev/null +++ b/src/lib/accounts/ledgerContext.ts @@ -0,0 +1,23 @@ +import type {ContextModule, ClearSignContextType} from "@ledgerhq/context-module"; + +/** + * No remote loaders or reporting. Removing only the SDK's default loaders leaves + * field loaders and telemetry enabled in context-module 2.9.0; replace the whole + * interface instead. Contract calldata therefore requires on-device blind signing. + */ +export const offlineLedgerContext: ContextModule = { + async getContexts() { + return []; + }, + async getFieldContext() { + return { + type: "error" as ClearSignContextType.ERROR, + error: new Error("Remote Ledger field metadata is disabled"), + }; + }, + async getTypedDataFilters() { + return {type: "error", error: new Error("Ledger typed-data signing is not supported by the CLI")}; + }, + async report() {}, + async signReport() {}, +}; diff --git a/src/lib/accounts/ledgerDevice.ts b/src/lib/accounts/ledgerDevice.ts new file mode 100644 index 00000000..cceb3514 --- /dev/null +++ b/src/lib/accounts/ledgerDevice.ts @@ -0,0 +1,107 @@ +import {createRequire} from "node:module"; +import type {SignerEth} from "@ledgerhq/device-signer-kit-ethereum"; +import {offlineLedgerContext} from "./ledgerContext"; +import {isNoLedgerDevice, ledgerError} from "./ledgerErrors"; +import type {Observable} from "rxjs"; + +/** Wait for a terminal device state, releasing subscriptions on every outcome. */ +export async function deviceResult(action: { + observable: Observable<{status: string; output?: T; error?: unknown}>; + cancel: () => void; +}): Promise { + const {firstValueFrom, filter, timeout} = await import("rxjs"); + try { + const state = await firstValueFrom( + action.observable.pipe( + filter(state => ["completed", "error", "stopped"].includes(state.status)), + timeout(120_000), + ), + ); + if (state.status === "completed") return state.output as T; + throw state.error || new Error("Ledger operation cancelled"); + } catch (error) { + throw ledgerError(error); + } finally { + action.cancel(); + } +} + +export async function withLedger(operation: (signer: SignerEth) => Promise): Promise { + let modules; + try { + // Ledger's ESM distribution uses extensionless imports; use its Node CJS exports. + const require = createRequire(import.meta.url); + modules = [ + require("@ledgerhq/device-management-kit") as typeof import("@ledgerhq/device-management-kit"), + require("@ledgerhq/device-transport-kit-node-hid") as typeof import("@ledgerhq/device-transport-kit-node-hid"), + require("@ledgerhq/device-signer-kit-ethereum") as typeof import("@ledgerhq/device-signer-kit-ethereum"), + await import("rxjs"), + ] as const; + } catch (error) { + const cause = ledgerError(error); + throw Object.assign( + new Error( + `Ledger USB support is unavailable. Reinstall genlayer with optional dependencies enabled and the native USB/HID prerequisites for your OS. Cause: ${cause.message}`, + ), + {cause: error}, + ); + } + const [ + {DeviceManagementKitBuilder}, + {NodeHidTransport}, + {SignerEthBuilder}, + {firstValueFrom, timeout, defer, retry, timer, concatMap}, + ] = modules; + let transport: InstanceType | undefined; + const dmk = new DeviceManagementKitBuilder() + .addTransport(args => { + transport = new NodeHidTransport( + args.deviceModelDataSource, + args.loggerServiceFactory, + args.apduSenderServiceFactory, + args.apduReceiverServiceFactory, + ); + return transport; + }) + .build(); + let sessionId: string | undefined; + try { + console.error("Connect and unlock your Ledger. Follow the prompts on the device (Ethereum app)."); + let lastDiscoveryError: unknown; + const device = await firstValueFrom( + defer(() => dmk.startDiscovering({})).pipe( + retry({ + delay: error => { + if (!isNoLedgerDevice(error)) throw error; + lastDiscoveryError = error; + return defer(() => dmk.stopDiscovering()).pipe(concatMap(() => timer(500))); + }, + }), + timeout(15_000), + ), + ).catch(error => { + if (error?.name === "TimeoutError") { + throw ledgerError(lastDiscoveryError ?? {_tag: "NoAccessibleDeviceError"}); + } + throw error; + }); + await dmk.stopDiscovering(); + sessionId = await dmk.connect({device}); + return await operation( + new SignerEthBuilder({dmk, sessionId}).withContextModule(offlineLedgerContext).build(), + ); + } catch (error) { + throw ledgerError(error); + } finally { + try { + if (sessionId) await dmk.disconnect({sessionId}); + } finally { + try { + dmk.close(); + } finally { + // DMK 1.12.0 close() closes sessions, not the transport hotplug listeners. + transport?.destroy(); + } + } + } +} diff --git a/src/lib/accounts/ledgerErrors.ts b/src/lib/accounts/ledgerErrors.ts new file mode 100644 index 00000000..82287645 --- /dev/null +++ b/src/lib/accounts/ledgerErrors.ts @@ -0,0 +1,54 @@ +/** Ledger's errors are often tagged objects, not Error instances. */ +function errorDetails(error: unknown, depth = 0): {tag: string; code: string; message: string} { + if (depth > 5 || !error || typeof error !== "object") { + return {tag: "", code: "", message: typeof error === "string" ? error : ""}; + } + const value = error as Record; + const nested = errorDetails(value.originalError ?? value.cause ?? value.err, depth + 1); + return { + tag: [value._tag, value.name, nested.tag].filter(v => typeof v === "string").join(" "), + code: typeof value.errorCode === "string" ? value.errorCode.toLowerCase() : nested.code, + message: typeof value.message === "string" ? value.message : nested.message, + }; +} + +export function isNoLedgerDevice(error: unknown): boolean { + return errorDetails(error).tag.includes("NoAccessibleDeviceError"); +} + +export function ledgerError(error: unknown): Error { + if (error instanceof Error && error.name === "LedgerError") return error; + const {tag, code, message} = errorDetails(error); + let explanation: string; + if (tag.includes("DeviceLockedError") || code === "5515") { + explanation = "Ledger is locked. Unlock it with your PIN and retry."; + } else if (tag.includes("RefusedByUserDAError") || code === "6982") { + explanation = "Ledger request rejected on the device. Nothing was signed; retry when ready."; + } else if (code === "6985") { + // The Ethereum app uses this status for both refusal and unmet signing conditions. + explanation = + "Ledger status 6985 can mean either the request was rejected on the device or blind signing is disabled. For contract calls, enable blind signing in the Ethereum app, then review and approve on the device."; + } else if (code === "6a80") { + explanation = + "Ledger rejected the transaction data. For contract calls, check that blind signing is enabled in the Ethereum app; otherwise verify that the transaction is supported."; + } else if (tag.includes("UnsupportedApplicationDAError") || code === "6d00" || code === "6e00") { + explanation = + "Ledger Ethereum app is not open or is unsupported. Install/update and open the Ethereum app, then retry."; + } else if (tag.includes("NoAccessibleDeviceError")) { + explanation = + "No accessible Ledger found within 15 seconds. Connect and unlock one device; check USB/HID permissions and close Ledger Live."; + } else if (/DeviceDisconnected|ReconnectionFailed/.test(tag)) { + explanation = "Ledger disconnected. Reconnect and unlock it, then retry."; + } else if (/OpeningConnection|DeviceBusy/.test(tag)) { + explanation = + "Cannot open Ledger USB connection. Check USB/HID permissions and close other applications using the device."; + } else if (/Timeout/.test(tag)) { + explanation = "Ledger operation timed out. Unlock the device and follow its prompts, then retry."; + } else { + explanation = + message || + `Ledger operation failed (${tag.trim() || "unknown device error"}). Reconnect the device and retry.`; + } + const detail = message && explanation !== message ? ` Cause: ${message}` : ""; + return Object.assign(new Error(explanation + detail), {name: "LedgerError", cause: error}); +} diff --git a/src/lib/actions/BaseAction.ts b/src/lib/actions/BaseAction.ts index 55ebb5da..05c7c48b 100644 --- a/src/lib/actions/BaseAction.ts +++ b/src/lib/actions/BaseAction.ts @@ -1,3 +1,4 @@ +import {ledgerAccount, validateLedgerAccount} from "../accounts/ledger"; import {ConfigFileManager} from "../../lib/config/ConfigFileManager"; import {KeychainManager} from "../../lib/config/KeychainManager"; import ora, {Ora} from "ora"; @@ -406,6 +407,13 @@ export class BaseAction extends ConfigFileManager { } } + protected getLedgerAccount() { + const path = this.getKeystorePath(this.resolveAccountName()); + if (!existsSync(path)) return undefined; + const data = JSON.parse(readFileSync(path, "utf-8")); + return data.type === "ledger" ? ledgerAccount(data) : undefined; + } + private async getAccount(readOnly: boolean = false): Promise { const accountName = this.resolveAccountName(); const keystorePath = this.getKeystorePath(accountName); @@ -421,6 +429,11 @@ export class BaseAction extends ConfigFileManager { keystoreJson = readFileSync(keystorePath, "utf-8"); keystoreData = JSON.parse(keystoreJson); + if (keystoreData.type === "ledger") { + validateLedgerAccount(keystoreData); + return readOnly ? this.getAddress(keystoreData) : ledgerAccount(keystoreData); + } + if (!this.isValidKeystoreFormat(keystoreData)) { this.failSpinner("Invalid keystore format. Expected encrypted keystore file.", undefined, false); await this.confirmPrompt(`Would you like to recreate account '${accountName}'?`); diff --git a/tests/actions/ledger.test.ts b/tests/actions/ledger.test.ts new file mode 100644 index 00000000..5101de2f --- /dev/null +++ b/tests/actions/ledger.test.ts @@ -0,0 +1,254 @@ +// @vitest-environment node +import {beforeEach, afterEach, describe, it, expect, vi} from "vitest"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import {Command} from "commander"; +import {of} from "rxjs"; +import {Wallet, Transaction} from "ethers"; +import {recoverTransactionAddress, type TransactionSerialized} from "viem"; +import {initializeAccountCommands} from "../../src/commands/account"; +import {BaseAction} from "../../src/lib/actions/BaseAction"; +import {StakingAction} from "../../src/commands/staking/StakingAction"; +import {VestingAction} from "../../src/commands/vesting/VestingAction"; +import {SendAction} from "../../src/commands/account/send"; +import {ShowAccountAction} from "../../src/commands/account/show"; +import {ExportAccountAction} from "../../src/commands/account/export"; +import {UnlockAccountAction} from "../../src/commands/account/unlock"; +import {ImportAccountAction} from "../../src/commands/account/import"; +import {createClient} from "genlayer-js"; +import {ValidatorJoinAction} from "../../src/commands/staking/validatorJoin"; +import {ValidatorWizardAction} from "../../src/commands/staking/wizard"; + +const mocks = vi.hoisted(() => ({ + withLedger: vi.fn(), + getPrivateKey: vi.fn(), + removePrivateKey: vi.fn(), + storePrivateKey: vi.fn(), +})); +vi.mock("../../src/lib/accounts/ledgerDevice", async original => ({ + ...(await original()), + withLedger: mocks.withLedger, +})); +vi.mock("../../src/lib/config/KeychainManager", () => ({ + KeychainManager: class { + getPrivateKey = mocks.getPrivateKey; + removePrivateKey = mocks.removePrivateKey; + storePrivateKey = mocks.storePrivateKey; + isKeychainAvailable = async () => true; + isAccountUnlocked = async () => false; + }, +})); +vi.mock("genlayer-js", async original => ({...(await original()), createClient: vi.fn()})); +const wallet = new Wallet(`0x${"11".repeat(32)}`); +let home: string; +let signed: string; +let prompt: ReturnType; +const metadata = {type: "ledger", address: wallet.address, derivationPath: "44'/60'/0'/0/0"}; +const tx = { + type: "legacy" as const, + chainId: 4221, + gas: 21000n, + gasPrice: 10n, + nonce: 0, + value: 1n, + to: wallet.address as `0x${string}`, +}; +class ContractHarness extends BaseAction { + client(readOnly = false) { + return this.getClient(undefined, readOnly); + } +} +class StakingHarness extends StakingAction { + registration(client: any) { + return this.createValidatorRegistration(client); + } + client() { + return this.getStakingClient({account: "usb"}); + } +} +class VestingHarness extends VestingAction { + registration(client: any) { + return this.createVestingValidatorRegistration( + client, + wallet.address as `0x${string}`, + wallet.address as `0x${string}`, + ); + } + client() { + return this.getVestingClient({account: "usb"}); + } +} + +beforeEach(() => { + vi.clearAllMocks(); + home = fs.mkdtempSync(path.join(os.tmpdir(), "genlayer-ledger-test-")); + vi.spyOn(os, "homedir").mockReturnValue(home); + for (const method of [ + "startSpinner", + "stopSpinner", + "setSpinnerText", + "succeedSpinner", + "logSuccess", + "logInfo", + ] as const) { + vi.spyOn(BaseAction.prototype as any, method).mockImplementation(() => {}); + } + vi.spyOn(BaseAction.prototype as any, "failSpinner").mockImplementation((message, error) => { + throw error || new Error(String(message)); + }); + prompt = vi + .spyOn(BaseAction.prototype as any, "promptPassword") + .mockRejectedValue(new Error("Unexpected password prompt")); + mocks.withLedger.mockImplementation(async operation => + operation({ + getAddress: () => ({ + observable: of({status: "completed", output: {address: wallet.address}}), + cancel() {}, + }), + signTransaction: (_path: string, bytes: Uint8Array) => { + const request = Transaction.from(`0x${Buffer.from(bytes).toString("hex")}`); + const signature = wallet.signingKey.sign(request.unsignedHash); + return { + observable: of({status: "completed", output: {r: signature.r, s: signature.s, v: signature.v}}), + cancel() {}, + }; + }, + }), + ); + vi.mocked(createClient).mockImplementation( + ({account}: any) => + ({ + account, + getBalance: async () => 1n, + getCurrentNonce: async () => 0n, + prepareTransactionRequest: async (request: any) => ({...tx, ...request}), + sendRawTransaction: async ({serializedTransaction}: any) => { + signed = serializedTransaction; + return "0x123"; + }, + getTransactionReceipt: async () => ({status: "success", blockNumber: 1n, gasUsed: 21000n}), + }) as any, + ); +}); +afterEach(() => { + vi.restoreAllMocks(); + fs.rmSync(home, {recursive: true, force: true}); +}); + +async function importAccount() { + const program = new Command(); + initializeAccountCommands(program); + await program.parseAsync(["node", "genlayer", "account", "import", "--name", "usb", "--ledger"]); +} + +describe("Ledger command integration", () => { + it("imports via Commander, persists only metadata, and lists the account", async () => { + await importAccount(); + const action = new ContractHarness(); + expect(JSON.parse(fs.readFileSync(action.getKeystorePath("usb"), "utf8"))).toEqual(metadata); + expect(action.getActiveAccount()).toBe("usb"); + expect(action.listAccounts()[0].address).toBe(wallet.address); + expect(mocks.removePrivateKey).toHaveBeenCalledWith("usb"); + expect(prompt).not.toHaveBeenCalled(); + }); + it("passes a device signer to contract, staking and vesting clients", async () => { + await importAccount(); + const clients = [ + await new ContractHarness().client(), + await new StakingHarness().client(), + await new VestingHarness().client(), + ]; + for (const account of clients.map(client => client.account)) { + const serializedTransaction = await (account as any).signTransaction(tx); + expect(await recoverTransactionAddress({serializedTransaction})).toBe(wallet.address); + } + expect(mocks.getPrivateKey).not.toHaveBeenCalled(); + expect(prompt).not.toHaveBeenCalled(); + }); + it("sends a transfer signed by the device", async () => { + await importAccount(); + await new SendAction().execute({account: "usb", to: wallet.address, amount: "1"}); + expect(await recoverTransactionAddress({serializedTransaction: signed as TransactionSerialized})).toBe( + wallet.address, + ); + expect(mocks.getPrivateKey).not.toHaveBeenCalled(); + }); + it("reads balances and initializes a read-only client without connecting a device", async () => { + await importAccount(); + mocks.withLedger.mockClear(); + expect((await new ContractHarness().client(true)).account).toBe(wallet.address); + await new ShowAccountAction().execute({account: "usb"}); + expect(mocks.withLedger).not.toHaveBeenCalled(); + }); + it("refuses export and unlock without retrieving cached keys", async () => { + await importAccount(); + await expect( + new ExportAccountAction().execute({account: "usb", output: path.join(home, "export.json")}), + ).rejects.toThrow("cannot be exported"); + await expect(new UnlockAccountAction().execute({account: "usb"})).rejects.toThrow("cannot be unlocked"); + expect(mocks.getPrivateKey).not.toHaveBeenCalled(); + expect(mocks.storePrivateKey).not.toHaveBeenCalled(); + }); + it("preserves existing accounts unless overwrite is explicit", async () => { + await importAccount(); + mocks.withLedger.mockClear(); + await expect(importAccount()).rejects.toThrow("already exists"); + expect(mocks.withLedger).not.toHaveBeenCalled(); + }); + it("does not write metadata when device import fails", async () => { + mocks.withLedger.mockRejectedValue(new Error("User rejected")); + const action = new ImportAccountAction(); + await expect(action.execute({ledger: true, name: "usb", overwrite: false})).rejects.toThrow( + "User rejected", + ); + expect(action.accountExists("usb")).toBe(false); + }); + it.each([{ledger: true, privateKey: "unused"}, {derivationPath: "44'/60'/1'/0/0"}])( + "rejects conflicting options before accessing the device: %j", + async options => { + await expect( + new ImportAccountAction().execute({name: "usb", overwrite: false, ...options}), + ).rejects.toThrow(); + expect(mocks.withLedger).not.toHaveBeenCalled(); + }, + ); +}); + +describe("Ledger operator-proof errors", () => { + const context = {chainId: 4221n, registrar: wallet.address, owner: wallet.address}; + it.each([undefined, wallet.address])( + "validator join with Ledger operator %s fails before signing", + async operator => { + await importAccount(); + const client = {getValidatorRegistrationContext: async () => context, validatorJoin: vi.fn()}; + const action = new ValidatorJoinAction(); + vi.spyOn(action as any, "getStakingClient").mockResolvedValue(client); + await expect(action.execute({amount: "1gen", operator})).rejects.toThrow( + "Pass --operator
for a separate local software keystore", + ); + expect(client.validatorJoin).not.toHaveBeenCalled(); + expect(mocks.getPrivateKey).not.toHaveBeenCalled(); + expect(prompt).not.toHaveBeenCalled(); + }, + ); + it("rejects the Ledger operator on the shared wizard proof path", async () => { + await importAccount(); + const action = new ValidatorWizardAction(); + await expect( + (action as any).createValidatorRegistration( + {getValidatorRegistrationContext: async () => context}, + "usb", + ), + ).rejects.toThrow("A Ledger account cannot sign the operator proof"); + expect(mocks.getPrivateKey).not.toHaveBeenCalled(); + }); + it("rejects a Ledger operator in vesting validator registration", async () => { + await importAccount(); + await expect( + new VestingHarness().registration({getVestingValidatorRegistrationContext: async () => context}), + ).rejects.toThrow("Pass --operator
for a separate local software keystore"); + expect(mocks.getPrivateKey).not.toHaveBeenCalled(); + expect(prompt).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/libs/ledger.test.ts b/tests/libs/ledger.test.ts new file mode 100644 index 00000000..d37824c1 --- /dev/null +++ b/tests/libs/ledger.test.ts @@ -0,0 +1,259 @@ +// @vitest-environment node +import {createRequire} from "node:module"; +import {beforeEach, describe, expect, it, vi} from "vitest"; +import {Wallet, Transaction, Signature} from "ethers"; +import {recoverTransactionAddress, recoverMessageAddress, type TransactionSerializable} from "viem"; +import {of, defer, throwError, NEVER} from "rxjs"; +import {deviceResult} from "../../src/lib/accounts/ledgerDevice"; +import { + ledgerAccount, + importLedgerAccount, + validateLedgerPath, + DEFAULT_LEDGER_PATH, +} from "../../src/lib/accounts/ledger"; + +const mocks = vi.hoisted(() => ({ + getAddress: vi.fn(), + signTransaction: vi.fn(), + signMessage: vi.fn(), + withLedger: vi.fn(), +})); +vi.mock("../../src/lib/accounts/ledgerDevice", async importOriginal => ({ + ...(await importOriginal()), + withLedger: mocks.withLedger, +})); +// Fixed, public test key; never used on a network. +const wallet = new Wallet(`0x${"11".repeat(32)}`); +const data = { + type: "ledger" as const, + address: wallet.address as `0x${string}`, + derivationPath: DEFAULT_LEDGER_PATH, +}; +const action = (output: unknown) => ({observable: of({status: "completed", output}), cancel: vi.fn()}); + +beforeEach(() => { + vi.clearAllMocks(); + mocks.withLedger.mockImplementation(fn => fn(mocks)); + mocks.getAddress.mockReturnValue(action({address: wallet.address})); + mocks.signTransaction.mockImplementation((_path, bytes) => { + const tx = Transaction.from(`0x${Buffer.from(bytes).toString("hex")}`); + const sig = wallet.signingKey.sign(tx.unsignedHash); + return action({ + r: sig.r, + s: sig.s, + v: tx.type === 0 ? Number(tx.chainId * 2n + 35n) + sig.yParity : sig.yParity, + }); + }); +}); + +describe("Ledger account", () => { + it("imports only public metadata and verifies the address on-device", async () => { + expect(await importLedgerAccount()).toEqual(data); + expect(mocks.getAddress).toHaveBeenCalledWith(DEFAULT_LEDGER_PATH, {checkOnDevice: true}); + }); + it.each(["m/44'/60'/0'/0/0", "44'/0'/0'/0/0", "44'/60'/2147483648'/0/0", "", "../key"])( + "rejects invalid path %s", + path => { + expect(() => validateLedgerPath(path)).toThrow("Invalid Ledger derivation path"); + }, + ); + it("rejects malformed account metadata", () => { + expect(() => ledgerAccount({...data, address: "0x123"})).toThrow("Invalid Ledger account address"); + }); + it.each(["legacy", "eip2930", "eip1559"] as const)("signs and recovers a %s transaction", async type => { + const tx = { + type, + chainId: 4221, + nonce: 3, + gas: 70000n, + to: data.address, + value: 100n, + data: "0x1234" as const, + ...(type === "eip1559" ? {maxFeePerGas: 100n, maxPriorityFeePerGas: 1n} : {gasPrice: 10n}), + }; + const signed = await ledgerAccount(data).signTransaction(tx as TransactionSerializable); + expect(await recoverTransactionAddress({serializedTransaction: signed})).toBe(data.address); + const decoded = Transaction.from(signed); + expect(decoded.chainId).toBe(4221n); + expect(decoded.data).toBe("0x1234"); + expect(decoded.nonce).toBe(3); + expect(decoded.value).toBe(100n); + }); + it("rejects a different device before requesting a signature", async () => { + mocks.getAddress.mockReturnValue(action({address: `0x${"22".repeat(20)}`})); + await expect(ledgerAccount(data).signTransaction({chainId: 1, gasPrice: 1n})).rejects.toThrow( + "does not match", + ); + expect(mocks.signTransaction).not.toHaveBeenCalled(); + }); + it("propagates user rejection without producing a transaction", async () => { + mocks.signTransaction.mockReturnValue({ + observable: of({status: "error", error: new Error("User rejected")}), + cancel: vi.fn(), + }); + await expect(ledgerAccount(data).signTransaction({chainId: 1, gasPrice: 1n})).rejects.toThrow( + "User rejected", + ); + }); + it("rejects an invalid signature", async () => { + const sig = new Wallet(`0x${"22".repeat(32)}`).signingKey.sign(`0x${"00".repeat(32)}`); + mocks.signTransaction.mockReturnValue(action({r: sig.r, s: sig.s, v: sig.v})); + await expect(ledgerAccount(data).signTransaction({chainId: 1, gasPrice: 1n})).rejects.toThrow( + "signature does not match", + ); + }); + it("signs raw personal messages used by the SDK", async () => { + const message = {raw: "0x1234" as const}; + const signature = Signature.from(await wallet.signMessage(new Uint8Array([0x12, 0x34]))); + mocks.signMessage.mockReturnValue(action({r: signature.r, s: signature.s, v: signature.v})); + const signed = await ledgerAccount(data).signMessage({message}); + expect(await recoverMessageAddress({message, signature: signed})).toBe(data.address); + }); +}); + +describe("device result lifecycle", () => { + it.each(["error", "stopped"])("cancels subscription on %s", async status => { + const request = {observable: of({status}), cancel: vi.fn()}; + await expect(deviceResult(request)).rejects.toThrow(); + expect(request.cancel).toHaveBeenCalledOnce(); + }); + it("cleans up when the observable errors", async () => { + const request = {observable: throwError(() => new Error("Disconnected")), cancel: vi.fn()}; + await expect(deviceResult(request)).rejects.toThrow("Disconnected"); + expect(request.cancel).toHaveBeenCalledOnce(); + }); + it("cancels an unresponsive device after two minutes", async () => { + vi.useFakeTimers(); + try { + const request = {observable: NEVER, cancel: vi.fn()}; + const result = expect(deviceResult(request)).rejects.toThrow(); + await vi.waitFor(() => expect(vi.getTimerCount()).toBeGreaterThan(0)); + await vi.advanceTimersByTimeAsync(120_001); + await result; + expect(request.cancel).toHaveBeenCalledOnce(); + } finally { + vi.useRealTimers(); + } + }); +}); + +describe("personal-message bytes and recovery", () => { + it.each(["héllo 世界 🌍", "", {raw: "0x1234" as const}, {raw: new Uint8Array([0, 255])}])( + "signs the exact viem bytes for %j", + async message => { + const bytes = + typeof message === "string" + ? new TextEncoder().encode(message) + : typeof message.raw === "string" + ? new Uint8Array([0x12, 0x34]) + : message.raw; + const signature = Signature.from(await wallet.signMessage(bytes)); + mocks.signMessage.mockReturnValue(action({r: signature.r, s: signature.s, v: signature.v})); + const signed = await ledgerAccount(data).signMessage({message}); + expect(mocks.signMessage).toHaveBeenCalledWith(DEFAULT_LEDGER_PATH, bytes); + expect(await recoverMessageAddress({message, signature: signed})).toBe(data.address); + }, + ); + it("rejects a signature produced by a different key", async () => { + const signature = Signature.from(await new Wallet(`0x${"22".repeat(32)}`).signMessage("hello")); + mocks.signMessage.mockReturnValue(action({r: signature.r, s: signature.s, v: signature.v})); + await expect(ledgerAccount(data).signMessage({message: "hello"})).rejects.toThrow( + "message signature does not match", + ); + }); + it("rejects a signature over different message bytes", async () => { + const signature = Signature.from(await wallet.signMessage("different")); + mocks.signMessage.mockReturnValue(action({r: signature.r, s: signature.s, v: signature.v})); + await expect(ledgerAccount(data).signMessage({message: "héllo"})).rejects.toThrow( + "message signature does not match", + ); + }); +}); + +describe("pinned SDK transaction encoding", () => { + const require = createRequire(import.meta.url); + const { + SendSignTransactionTask, + } = require("@ledgerhq/device-signer-kit-ethereum/internal/app-binder/task/SendSignTransactionTask.js"); + const {noopLoggerFactory, APDU_MAX_PAYLOAD} = require("@ledgerhq/device-management-kit"); + const {ClearSigningType} = require("@ledgerhq/device-signer-kit-ethereum/api/model/ClearSigningType.js"); + const cases = [4221, 61127, 61997, 61999].flatMap(chainId => + (["legacy", "eip2930", "eip1559"] as const).map(type => ({chainId, type})), + ); + it.each(cases)( + "round-trips large deploy calldata through SDK chunks on $chainId/$type", + async ({chainId, type}) => { + const calldata = `0x${"ab".repeat(32 * 1024)}` as `0x${string}`; + let observedChunks = 0; + mocks.signTransaction.mockImplementation((_path, bytes: Uint8Array) => { + const tx = Transaction.from(`0x${Buffer.from(bytes).toString("hex")}`); + const signature = wallet.signingKey.sign(tx.unsignedHash); + const chunks: Uint8Array[] = []; + let length = 0; + const run = () => + new SendSignTransactionTask( + { + sendCommand: async (command: any) => { + const chunk = command.args.serializedTransaction; + expect(chunk.length).toBeLessThanOrEqual(APDU_MAX_PAYLOAD); + expect(command.args.isFirstChunk).toBe(chunks.length === 0); + command.getApdu(); // Exercise the real SDK's APDU encoder as well. + chunks.push(chunk); + length += chunk.length; + // 5 path components, each 4 bytes, plus the path length byte. + const last = length === bytes.length + 21; + const v = tx.type === 0 ? (chainId * 2 + 35 + signature.yParity) & 255 : signature.yParity; + return command.parseResponse({ + statusCode: new Uint8Array([0x90, 0x00]), + data: last + ? Buffer.concat([ + Buffer.from([v]), + Buffer.from(signature.r.slice(2), "hex"), + Buffer.from(signature.s.slice(2), "hex"), + ]) + : new Uint8Array(), + }); + }, + }, + { + derivationPath: DEFAULT_LEDGER_PATH, + serializedTransaction: bytes, + chainId, + transactionType: tx.type, + clearSigningType: ClearSigningType.BASIC, + loggerFactory: noopLoggerFactory, + }, + ) + .run() + .then((result: any) => { + expect(result.status).toBe("SUCCESS"); + expect(Buffer.concat(chunks).subarray(21)).toEqual(Buffer.from(bytes)); + observedChunks = chunks.length; + return {status: "completed", output: result.data}; + }); + return {observable: defer(run), cancel: vi.fn()}; + }); + // Exercise both parity values by selecting two public fixture nonces. + const parities = new Set(); + for (let nonce = 0; parities.size < 2 && nonce < 20; nonce++) { + const transaction = { + type, + chainId, + nonce, + gas: 1000000n, + data: calldata, + ...(type === "eip1559" ? {maxFeePerGas: 100n, maxPriorityFeePerGas: 1n} : {gasPrice: 10n}), + }; + const signed = await ledgerAccount(data).signTransaction(transaction as TransactionSerializable); + const decoded = Transaction.from(signed); + parities.add(decoded.signature!.yParity); + expect(decoded.data).toBe(calldata); + expect(decoded.chainId).toBe(BigInt(chainId)); + expect(decoded.to).toBeNull(); + expect(await recoverTransactionAddress({serializedTransaction: signed})).toBe(data.address); + } + expect(parities.size).toBe(2); + expect(observedChunks).toBeGreaterThan(1); + }, + ); +}); diff --git a/tests/libs/ledgerContext.test.ts b/tests/libs/ledgerContext.test.ts new file mode 100644 index 00000000..4459e860 --- /dev/null +++ b/tests/libs/ledgerContext.test.ts @@ -0,0 +1,79 @@ +// @vitest-environment node +import {createRequire} from "node:module"; +import {afterEach, expect, it, vi} from "vitest"; +import {offlineLedgerContext} from "../../src/lib/accounts/ledgerContext"; + +// Exercise the pinned SDK tasks, not mocks of the context module or device kit. +const require = createRequire(import.meta.url); +const { + BuildBaseContexts, +} = require("@ledgerhq/device-signer-kit-ethereum/internal/app-binder/task/BuildBaseContexts.js"); +const { + BlindSigningDetectionTask, +} = require("@ledgerhq/device-signer-kit-ethereum/internal/app-binder/task/BlindSigningDetectionTask.js"); +const { + DeviceModelId, + DeviceSessionStateType, + DmkNetworkClient, + noopLoggerFactory, +} = require("@ledgerhq/device-management-kit"); +const {ClearSigningType} = require("@ledgerhq/device-signer-kit-ethereum/api/model/ClearSigningType.js"); +const {ClearSignContextType} = require("@ledgerhq/context-module"); +afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); + +it.each([false, true])( + "builds contexts and handles reporting without network even when device checks are enabled=%s", + async web3ChecksEnabled => { + const network = vi.fn(() => { + throw new Error("Unexpected hosted service request"); + }); + vi.stubGlobal("fetch", network); + const get = vi.spyOn(DmkNetworkClient.prototype, "get").mockImplementation(network); + const post = vi.spyOn(DmkNetworkClient.prototype, "post").mockImplementation(network); + const api = { + getDeviceSessionState: () => ({ + deviceModelId: DeviceModelId.NANO_X, + sessionStateType: DeviceSessionStateType.Ready, + currentApp: {name: "Ethereum", version: "1.20.0"}, + }), + sendCommand: async () => ({status: "SUCCESS", data: {challenge: "1234"}}), + }; + const result = await new BuildBaseContexts(api, { + contextModule: offlineLedgerContext, + options: {}, + appConfig: {version: "1.20.0", web3ChecksEnabled}, + transaction: new Uint8Array([1, 2, 3]), + subset: {chainId: 4221, to: `0x${"11".repeat(20)}`, data: "0x12345678"}, + }).run(); + expect(result.clearSignContexts).toEqual([]); + expect(result.clearSigningType).toBe(ClearSigningType.BASIC); + expect((await offlineLedgerContext.getFieldContext({}, ClearSignContextType.ETHEREUM_TOKEN)).type).toBe( + "error", + ); + const reporting = await new BlindSigningDetectionTask({ + contextModule: offlineLedgerContext, + loggerFactory: noopLoggerFactory, + input: { + type: "transaction", + hasContext: false, + contextTypes: [], + usedFallback: false, + chainId: 4221, + targetAddress: `0x${"11".repeat(20)}`, + selectorId: "0x12345678", + deviceModelId: DeviceModelId.NANO_X, + signerAppVersion: "1.20.0", + deviceVersion: "test", + clearSigningType: ClearSigningType.BASIC, + partialContextErrors: 0, + }, + }).run(); + expect(reporting.isBlindSign).toBe(true); + expect(get).not.toHaveBeenCalled(); + expect(post).not.toHaveBeenCalled(); + expect(network).not.toHaveBeenCalled(); + }, +); diff --git a/tests/libs/ledgerDevice.test.ts b/tests/libs/ledgerDevice.test.ts new file mode 100644 index 00000000..b9b58d31 --- /dev/null +++ b/tests/libs/ledgerDevice.test.ts @@ -0,0 +1,156 @@ +// @vitest-environment node +import {beforeEach, afterEach, it, expect, vi} from "vitest"; +import {NEVER, of, throwError} from "rxjs"; +import {offlineLedgerContext} from "../../src/lib/accounts/ledgerContext"; +import {ledgerError} from "../../src/lib/accounts/ledgerErrors"; +import {withLedger} from "../../src/lib/accounts/ledgerDevice"; +const mocks = vi.hoisted(() => ({ + load: vi.fn(), + startDiscovering: vi.fn(), + stopDiscovering: vi.fn(), + connect: vi.fn(), + disconnect: vi.fn(), + close: vi.fn(), + destroy: vi.fn(), + signer: {}, + withContextModule: vi.fn(), +})); +vi.mock("node:module", () => ({createRequire: () => mocks.load})); +beforeEach(() => { + vi.clearAllMocks(); + mocks.startDiscovering.mockReturnValue(of({id: "usb"})); + mocks.connect.mockResolvedValue("session"); + mocks.stopDiscovering.mockResolvedValue(undefined); + mocks.load.mockImplementation(name => { + if (name === "@ledgerhq/device-management-kit") + return { + DeviceManagementKitBuilder: class { + addTransport(factory: (args: object) => unknown) { + factory({}); + return this; + } + build() { + return mocks; + } + }, + }; + if (name === "@ledgerhq/device-transport-kit-node-hid") + return { + NodeHidTransport: class { + destroy = mocks.destroy; + }, + }; + return { + SignerEthBuilder: class { + withContextModule(context: unknown) { + mocks.withContextModule(context); + return this; + } + build() { + return mocks.signer; + } + }, + }; + }); +}); +afterEach(() => vi.useRealTimers()); +it("disconnects and closes after successful signing", async () => { + expect( + await withLedger(async signer => { + expect(signer).toBe(mocks.signer); + return "signed"; + }), + ).toBe("signed"); + expect(mocks.withContextModule).toHaveBeenCalledWith(offlineLedgerContext); + expect(mocks.stopDiscovering).toHaveBeenCalledOnce(); + expect(mocks.disconnect).toHaveBeenCalledWith({sessionId: "session"}); + expect(mocks.close).toHaveBeenCalledOnce(); + expect(mocks.destroy).toHaveBeenCalledOnce(); +}); +it("releases USB after user rejection", async () => { + await expect( + withLedger(async () => { + throw new Error("Rejected"); + }), + ).rejects.toThrow("Rejected"); + expect(mocks.disconnect).toHaveBeenCalledOnce(); + expect(mocks.close).toHaveBeenCalledOnce(); +}); +it("closes discovery when no device can be accessed", async () => { + mocks.startDiscovering.mockReturnValue(throwError(() => new Error("USB denied"))); + await expect(withLedger(async () => {})).rejects.toThrow("USB denied"); + expect(mocks.disconnect).not.toHaveBeenCalled(); + expect(mocks.close).toHaveBeenCalledOnce(); +}); +it("times out discovery and releases resources", async () => { + vi.useFakeTimers(); + mocks.startDiscovering.mockReturnValue(NEVER); + const result = expect(withLedger(async () => {})).rejects.toThrow(); + await vi.waitFor(() => expect(vi.getTimerCount()).toBeGreaterThan(0)); + await vi.advanceTimersByTimeAsync(15_001); + await result; + expect(mocks.close).toHaveBeenCalledOnce(); +}); +it("explains missing optional native dependencies", async () => { + mocks.load.mockImplementation(() => { + throw new Error("Module not found"); + }); + await expect(withLedger(async () => {})).rejects.toThrow("Ledger USB support is unavailable"); +}); +it("polls the actual no-device error shape until a device appears", async () => { + vi.useFakeTimers(); + mocks.startDiscovering + .mockReturnValueOnce(throwError(() => ({_tag: "NoAccessibleDeviceError"}))) + .mockReturnValueOnce(throwError(() => ({_tag: "NoAccessibleDeviceError"}))) + .mockReturnValue(of({id: "usb"})); + const result = withLedger(async () => "connected"); + await vi.waitFor(() => expect(mocks.startDiscovering).toHaveBeenCalledOnce()); + await vi.advanceTimersByTimeAsync(1001); + expect(await result).toBe("connected"); + expect(mocks.startDiscovering).toHaveBeenCalledTimes(3); + expect(vi.getTimerCount()).toBe(0); +}); +it("waits 15 seconds on repeated no-device errors and stops polling", async () => { + vi.useFakeTimers(); + mocks.startDiscovering.mockReturnValue(throwError(() => ({_tag: "NoAccessibleDeviceError"}))); + const result = expect(withLedger(async () => {})).rejects.toThrow( + "No accessible Ledger found within 15 seconds", + ); + await vi.waitFor(() => expect(mocks.startDiscovering).toHaveBeenCalledOnce()); + await vi.advanceTimersByTimeAsync(14_000); + expect(mocks.close).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1001); + await result; + expect(mocks.close).toHaveBeenCalledOnce(); + expect(vi.getTimerCount()).toBe(0); +}); +it.each([ + [{_tag: "DeviceLockedError"}, "Unlock it with your PIN"], + [{_tag: "GlobalCommandError", errorCode: "5515"}, "Unlock it with your PIN"], + [{_tag: "UnsupportedApplicationDAError"}, "Ethereum app is not open"], + [{_tag: "EthAppCommandError", errorCode: "6d00"}, "Ethereum app is not open"], + [{_tag: "RefusedByUserDAError"}, "rejected on the device"], + [{_tag: "EthAppCommandError", errorCode: "6982"}, "rejected on the device"], + [{_tag: "EthAppCommandError", errorCode: "6985"}, "enable blind signing"], + [{_tag: "EthAppCommandError", errorCode: "6a80"}, "blind signing is enabled"], + [ + {_tag: "OpeningConnectionError", originalError: new Error("HID permission denied")}, + "HID permission denied", + ], + [{_tag: "DeviceDisconnectedWhileSendingError"}, "Ledger disconnected"], +])("maps SDK error %j to readable guidance", (error, expected) => { + expect(ledgerError(error)).toBeInstanceOf(Error); + expect(ledgerError(error).message).toContain(expected); + expect(ledgerError(error).cause).toBe(error); +}); +it("retains native dependency load diagnostics", async () => { + const error = new Error("libudev.so.1: cannot open shared object file"); + mocks.load.mockImplementation(() => { + throw error; + }); + await expect(withLedger(async () => {})).rejects.toThrow("Cause: libudev.so.1"); +}); +it("explains both possible causes of status 6985", () => { + const message = ledgerError({_tag: "EthAppCommandError", errorCode: "6985"}).message; + expect(message).toContain("either the request was rejected on the device or blind signing is disabled"); +});