diff --git a/.depcheckrc.yml b/.depcheckrc.yml index 277d274ef..ab62c86dc 100644 --- a/.depcheckrc.yml +++ b/.depcheckrc.yml @@ -2,6 +2,8 @@ ignore-patterns: - '.yarn' - 'dist/' + # Python virtualenv created by scripts/setup-python.sh + - '.venv/' ignores: # Ignore depcheck itself (seems to be required for monorepos) - 'depcheck' @@ -31,3 +33,7 @@ ignores: # Ignore dependency that is used with jest "directives" (thus, they cannot be detected # by depcheck properly) - 'jest-environment-jsdom' + # @metamask/hw-emulator: imported via a relative source path (documented + # workaround in src/qr/emulator.test.ts — the sibling package's name does + # not match its directory and its v2 build is broken) + - '@metamask/eth-qr-keyring' diff --git a/.github/workflows/build-speculos.yml b/.github/workflows/build-speculos.yml new file mode 100644 index 000000000..27b170b39 --- /dev/null +++ b/.github/workflows/build-speculos.yml @@ -0,0 +1,134 @@ +name: Build Speculos Binary + +on: + workflow_dispatch: + inputs: + version: + description: 'Speculos version to build' + required: true + default: '0.27.8' + push: + tags: + - 'speculos-v*' + +jobs: + build: + runs-on: ubuntu-latest + permissions: + contents: read + + outputs: + version: ${{ steps.version.outputs.version }} + + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + + - name: Resolve and validate version + id: version + env: + INPUT_VERSION: ${{ github.event.inputs.version }} + TAG_VERSION: ${{ github.ref_name }} + run: | + # Precedence: dispatch input → pushed tag name → default. + if [ -n "${INPUT_VERSION}" ]; then + VERSION="${INPUT_VERSION}" + elif [[ "${TAG_VERSION}" == speculos-v* ]]; then + VERSION="${TAG_VERSION#speculos-v}" + else + VERSION="0.27.8" + fi + if ! printf '%s' "$VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$'; then + echo "::error::Invalid Speculos version '${VERSION}': expected MAJOR.MINOR.PATCH (e.g. 0.27.8)" + exit 1 + fi + printf 'version=%s\n' "$VERSION" >> "$GITHUB_OUTPUT" + + - name: Set up Python + uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + with: + python-version: '3.11' + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + # Pinned for reproducible builds; keep in sync with + # packages/speculos-up/scripts/build-speculos*.sh. + pip install pyinstaller==6.14.1 + + - name: Install speculos + env: + SPECULOS_VERSION: ${{ steps.version.outputs.version }} + run: | + pip install "speculos==${SPECULOS_VERSION}" + # pkg_resources (bundled by PyInstaller) imports backports.tarfile at runtime. + pip install backports.tarfile + + - name: Build standalone binary + run: | + mkdir -p dist + # 0.27 moved imports into speculos/__init__.py, so it cannot be the entry script. + printf 'from speculos.main import main\nmain()\n' > speculos-entry.py + pyinstaller \ + --onefile \ + --name speculos \ + --distpath dist \ + --workpath build \ + --noupx \ + --collect-all speculos \ + speculos-entry.py + + - name: Smoke test binary + run: ./dist/speculos --help > /dev/null + + - name: Verify binary architecture + run: | + file dist/speculos | tee /tmp/speculos-file.txt + grep -Fq 'ELF' /tmp/speculos-file.txt + grep -Fq 'x86-64' /tmp/speculos-file.txt + + - name: Package archive + env: + SPECULOS_VERSION: ${{ steps.version.outputs.version }} + run: | + cd dist + tar -czf "speculos-v${SPECULOS_VERSION}-linux-amd64.tar.gz" speculos + + - name: Upload build artifact + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: speculos-linux-amd64 + path: dist/speculos-v*-linux-amd64.tar.gz + if-no-files-found: error + + release: + needs: build + runs-on: ubuntu-latest + permissions: + contents: write + + steps: + - name: Download build artifacts + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + pattern: speculos-linux-* + path: dist + merge-multiple: true + + - name: Create or update GitHub release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + SPECULOS_VERSION: ${{ needs.build.outputs.version }} + RELEASE_TAG: speculos-v${{ needs.build.outputs.version }} + run: | + gh release view "${RELEASE_TAG}" \ + || gh release create "${RELEASE_TAG}" \ + --title "Speculos ${SPECULOS_VERSION}" \ + --notes "Speculos binary release ${SPECULOS_VERSION}." + + - name: Upload release assets + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + RELEASE_TAG: speculos-v${{ needs.build.outputs.version }} + run: gh release upload "${RELEASE_TAG}" dist/*.tar.gz --clobber diff --git a/.gitignore b/.gitignore index 8d474d7d9..3c91e498b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ .DS_Store dist/ +dist-build/ coverage/ # Logs @@ -77,4 +78,7 @@ node_modules/ !.yarn/versions # Cursor rules -.cursorrules \ No newline at end of file +.cursorrules + +# Git worktrees +.worktrees/ \ No newline at end of file diff --git a/README.md b/README.md index a0e8c2b26..596ab627d 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,7 @@ This repository contains the following packages [^fn1]: - [`@metamask/eth-simple-keyring`](packages/keyring-eth-simple) - [`@metamask/eth-snap-keyring`](packages/keyring-snap-bridge) - [`@metamask/eth-trezor-keyring`](packages/keyring-eth-trezor) +- [`@metamask/hw-emulator`](packages/hw-emulator) - [`@metamask/hw-wallet-sdk`](packages/hw-wallet-sdk) - [`@metamask/key-derivation-purposes`](packages/key-derivation-purposes) - [`@metamask/keyring-api`](packages/keyring-api) @@ -36,6 +37,7 @@ This repository contains the following packages [^fn1]: - [`@metamask/keyring-snap-client`](packages/keyring-snap-client) - [`@metamask/keyring-snap-sdk`](packages/keyring-snap-sdk) - [`@metamask/keyring-utils`](packages/keyring-utils) +- [`@metamask/speculos-up`](packages/speculos-up) - [`@metamask/watch-only-keyring`](packages/keyring-watch-only) @@ -49,6 +51,7 @@ Or, in graph form [^fn1]: graph LR; linkStyle default opacity:0.5 account_api(["@metamask/account-api"]); + hw_emulator(["@metamask/hw-emulator"]); hw_wallet_sdk(["@metamask/hw-wallet-sdk"]); key_derivation_purposes(["@metamask/key-derivation-purposes"]); keyring_api(["@metamask/keyring-api"]); @@ -67,8 +70,10 @@ linkStyle default opacity:0.5 keyring_snap_sdk(["@metamask/keyring-snap-sdk"]); keyring_utils(["@metamask/keyring-utils"]); watch_only_keyring(["@metamask/watch-only-keyring"]); + speculos_up(["@metamask/speculos-up"]); account_api --> keyring_api; account_api --> keyring_utils; + hw_emulator --> keyring_eth_qr; keyring_api --> keyring_utils; eth_hd_keyring --> keyring_api; eth_hd_keyring --> keyring_sdk; diff --git a/eslint.config.mjs b/eslint.config.mjs index ae517fb95..08eca361f 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -16,6 +16,10 @@ const config = createConfig([ '**/dist/**', '**/docs/**', '**/coverage/**', + // Archived research spikes — not part of any published package. + '**/spike/**', + // Python virtualenv created by scripts/setup-python.sh. + '**/.venv/**', ], }, diff --git a/package.json b/package.json index 8d855e632..44bf322e4 100644 --- a/package.json +++ b/package.json @@ -79,7 +79,6 @@ "typescript-eslint": "^8.48.0" }, "resolutions": { - "@types/node": "^20.19.0", "@types/web": "^0.0.69", "@typescript/lib-dom": "npm:@types/web@^0.0.69", "axios@1.7.7": "^1.20.0", @@ -87,10 +86,13 @@ "eslint-plugin-import-x": "<=4.6.1", "napi-postinstall": "npm:npm-empty-package@^1.0.0", "protobufjs@7.4.0": "^7.6.5", - "tar": "^7.5.16", + "tar@^6.1.11": "^7.5.16", + "tar@^6.1.2": "^7.5.16", + "tar@^7.5.4": "^7.5.16", "tinypool@2.1.0": "^2.2.0", "uuid@11.0.3": "^11.1.1", - "ws@8.17.1": "^8.22.0" + "ws@8.17.1": "^8.22.0", + "yargs@17.7.2": "^17.7.3" }, "engines": { "node": ">=22" diff --git a/packages/hw-emulator/.gitignore b/packages/hw-emulator/.gitignore new file mode 100644 index 000000000..a8fc3283d --- /dev/null +++ b/packages/hw-emulator/.gitignore @@ -0,0 +1,10 @@ +__pycache__/ +*.pyc +*.pyo +.venv/ +*.egg-info/ +dist/ +build/ +.pytest_cache/ +# Archived research spikes — kept locally, not tracked +spike/ diff --git a/packages/hw-emulator/.yarnignore b/packages/hw-emulator/.yarnignore new file mode 100644 index 000000000..1523440d5 --- /dev/null +++ b/packages/hw-emulator/.yarnignore @@ -0,0 +1,10 @@ +# Prevent yarn `file:` packing from copying non-portable / heavy local state +# into consumers' node_modules. The venv is created per-host via +# scripts/setup-python.sh and located at runtime via SPECULOS_BLE_VENV_DIR. +.venv/ +coverage/ +node_modules/ +*.egg-info/ +__pycache__/ +.tsbuildinfo +*.tsbuildinfo diff --git a/packages/hw-emulator/CHANGELOG.md b/packages/hw-emulator/CHANGELOG.md new file mode 100644 index 000000000..381acf2dd --- /dev/null +++ b/packages/hw-emulator/CHANGELOG.md @@ -0,0 +1,73 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +### Added + +- Added QR hardware wallet emulator (`EmulatorType.Qr`) with UR synthesis, ECDSA signer, BC-UR fountain codec, QR rendering (PNG and Y4M), and QR screenshot decoding ([#560](https://github.com/MetaMask/accounts/pull/560)) +- Initial release of `@metamask/hw-emulator` ([#560](https://github.com/MetaMask/accounts/pull/560)) + - Hardware wallet emulator lifecycle, transport, and device interaction for E2E testing + - Ledger emulator via Speculos with support for Nano S+, Nano X, Stax, and Flex devices + - Docker and native run modes + - `SpeculosClient` for APDU exchange and screen events + - `ApduBridge` for WebSocket-to-APDU bridge (WebHID mocking) + - `DockerManager` for Docker Compose lifecycle management + - `ProcessManager` for native Speculos process spawning + - Device interaction automation (button presses, touch gestures) + - Resilience utilities (`withRetry`, `ExponentialBackoff`) + - Ledger HID framing session utilities + - WebHID mock script generation for E2E tests + - Deterministic accounts with pre-configured seed + - Bundled ELF app binaries for all supported devices + - Docker Compose configuration for Speculos + - JSDoc documentation on all public types, classes, methods, and constants + - `getElfFilePath` utility for resolving ELF binary paths (native mode) + - `startNative()` defaults to `@metamask/speculos-up` managed binary when no `binary` option is provided + - Fix Docker mode ignoring custom `apduPort` / `apiPort` by passing host ports to `docker-compose` + - Fix Docker mode ignoring the `seed` option by wiring `SPECULOS_SEED` through `docker-compose.yml` + - Fix Docker mode ignoring the `display` option by wiring `SPECULOS_DISPLAY` through `docker-compose.yml` +- Added `@metamask/speculos-up` as peer dependency ([#560](https://github.com/MetaMask/accounts/pull/560)) + +### Changed + +- `SpeculosBleRunner` now honors `SPECULOS_BLE_PACKAGE_DIR` and `SPECULOS_BLE_VENV_DIR` environment variables (mirroring `scripts/setup-python.sh`) so it can locate `python/` and the virtualenv at a stable path even when the package is copied into a consumer's `node_modules` via a Yarn `file:` resolution ([#560](https://github.com/MetaMask/accounts/pull/560)) +- `SpeculosBleRunner.start()` now accepts an optional `onLog(line, stream)` callback that receives BLE process stdout/stderr/exit/error output (previously silently discarded) ([#560](https://github.com/MetaMask/accounts/pull/560)) +- Merged `@metamask/speculos-ble` package into `@metamask/hw-emulator`. The BLE bridge (Python source, TypeScript `SpeculosBleRunner` wrapper, Docker config) now lives in this package under `python/`, `src/ble/`, and `scripts/` ([#560](https://github.com/MetaMask/accounts/pull/560)) + +### Fixed + +- Native mode now spawns Speculos from the bundled `nvram/` directory so `--load-nvram` finds `main_nvram.bin`, which Speculos resolves relative to the process working directory ([#560](https://github.com/MetaMask/accounts/pull/560)) + - Previously the flag was passed with no reachable NVRAM file, which could abort startup under the default `loadNvram: true`. Docker mode is unchanged. +- Pinned `protobuf>=5.26,<7` in the Python BLE bridge dependencies — bumble's `android_netsim` transport imports `google.protobuf` at runtime and `grpcio` does not pull it in transitively, so fresh virtualenvs were missing it at import time ([#560](https://github.com/MetaMask/accounts/pull/560)) +- Ledger `Speculos.start()` no longer leaks the process/container when the APDU client fails to connect after startup; `stop()` now cleans up all created resources regardless of the started flag ([#560](https://github.com/MetaMask/accounts/pull/560)) + - `ApduBridge` server errors after startup no longer trigger unhandled promise rejections. + - `SpeculosClient.connect()` now enforces a configurable connect timeout instead of hanging indefinitely, and a timed-out exchange can no longer consume a stale late response as its own. + - `DockerManager` tears the container down when the health check fails, uses a per-instance container name so multiple emulators can run concurrently, and honors `stopTimeout` in `docker compose down`. + - `ProcessManager.stop()` is idempotent under concurrent calls (no listener/timer accumulation). + - The WebHID mock script rejects pending exchanges on WebSocket close/error and tolerates non-JSON frames. + - Transaction-signing chunk tracking moved from bridge-global state to per-connection state, fixing corrupted counters with concurrent connections. + - `parseTxPayloadLength` now handles single-byte RLP values correctly. + - Touch-device interactions throw a descriptive error when the device model lacks the required button coordinates, instead of silently doing nothing. + - `SpeculosBleRunner.setupVenv()` uses `execFileSync` (no shell), `stop()` tolerates an already-exited process, and the control-API readiness probe no longer leaks its abort timer. +- Trezor sidecar now tracks and stops the secondary CORS proxy on port 21325 (previously leaked), enforces a 10 MB request-body cap on the proxy (413 beyond), and the asset server rejects path traversal via resolved-path checks ([#560](https://github.com/MetaMask/accounts/pull/560)) + - `ControllerClient` no longer leaks pending-request entries on synchronous send failures and routes post-connect socket errors to pending rejections instead of settled promises. + - `TrezorEmulator.start()` stops the Docker container when the controller never becomes available. + - Speculos Docker image pinned to `0.25.13` (was mutable `latest`), and host-side port defaults aligned across `docker-compose.yml` and `scripts/start-android.sh`. + - `scripts/start-android.sh` cleanup now stops and removes the container instead of only killing the Docker CLI process. +- QR screenshot decoding now validates PNG chunk lengths and CRCs and rejects truncated IDAT streams instead of decoding garbage pixels ([#560](https://github.com/MetaMask/accounts/pull/560)) + - Y4M rendering survives early ffmpeg exit (EPIPE) without crashing, and failed renders clean up their partial output file. + - `parseXfp` rejects fingerprints that are not exactly 8 hex characters. + - Transaction rejection can target a specific request id so armed rejections cannot be consumed by unrelated requests. + - `renderToPng` throws for multi-fragment URs (use `renderToY4m`), missing derivation paths produce a clear error, and decoding distinguishes completion from success. +- Python BLE bridge hardening ([#560](https://github.com/MetaMask/accounts/pull/560)) + - Speculos TCP client enforces a 64 KB max response size; APDU fragmentation rejects payloads over the 16-bit length limit and reassembly detects declared-length overflow. + - Control API validates inputs (`/button/press`, `/error/inject`) and returns 504 instead of an opaque 500 when signing auto-approval times out. + - Error injection is applied atomically under a lock; GATT send failures propagate and reset cancels in-flight exchanges; `device.stop()` is idempotent; dependencies pinned (`bumble==0.0.233`, `aiohttp==3.14.3`, `click==8.4.2`). +- The Trezor sidecar CORS proxy now only accepts origin-form request targets and builds the upstream URL from the configured bridge origin, so a caller-supplied path can no longer redirect the proxy at another host ([#560](https://github.com/MetaMask/accounts/pull/560)) + +[Unreleased]: https://github.com/MetaMask/accounts/ diff --git a/packages/hw-emulator/Dockerfile b/packages/hw-emulator/Dockerfile new file mode 100644 index 000000000..8bd94bed4 --- /dev/null +++ b/packages/hw-emulator/Dockerfile @@ -0,0 +1,16 @@ +FROM python:3.11-slim + +RUN apt-get update && apt-get install -y --no-install-recommends \ + libusb-1.0-0 \ + libbluetooth3 \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /app +COPY pyproject.toml ./ +COPY python/ python/ + +RUN pip install --no-cache-dir ".[test]" + +EXPOSE 9999 5000 5002 + +CMD ["speculos-ble", "--transport", "vhci", "--verbose"] diff --git a/packages/hw-emulator/LICENSE b/packages/hw-emulator/LICENSE new file mode 100644 index 000000000..fe29e78e0 --- /dev/null +++ b/packages/hw-emulator/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 MetaMask + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/hw-emulator/README.md b/packages/hw-emulator/README.md new file mode 100644 index 000000000..0ccc110c2 --- /dev/null +++ b/packages/hw-emulator/README.md @@ -0,0 +1,206 @@ +# `@metamask/hw-emulator` + +Hardware wallet emulator lifecycle, transport, and device interaction for E2E testing. + +Provides a programmatic interface for launching and controlling hardware wallet emulators (Ledger via [Speculos](https://github.com/LedgerHQ/speculos)), sending APDU commands, and automating device screen interactions (button presses, touch gestures) — all without physical hardware. + +## Installation + +`yarn add @metamask/hw-emulator` + +or + +`npm install @metamask/hw-emulator` + +## Supported Devices + +| Device | Model ID | Interaction Type | +| ------- | -------- | ---------------- | +| Nano S+ | `nanosp` | Button | +| Nano X | `nanox` | Button | +| Stax | `stax` | Touch | +| Flex | `flex` | Touch | + +## Quick Start + +### Docker Mode (recommended for macOS / CI) + +```typescript +import { createEmulator, EmulatorType } from '@metamask/hw-emulator'; + +const emulator = createEmulator(EmulatorType.Ledger, { + device: 'flex', + mode: 'docker', +}); + +await emulator.start(); +await emulator.approveTransaction(); +await emulator.stop(); +``` + +### Native Mode (Linux only) + +Requires the Speculos binary to be installed and available on `PATH`, or passed via the `binary` option. + +```typescript +import { createEmulator, EmulatorType } from '@metamask/hw-emulator'; + +const emulator = createEmulator(EmulatorType.Ledger, { + device: 'nanosp', + mode: 'native', + binary: '/usr/local/bin/speculos', +}); + +await emulator.start(); +await emulator.approveSigning(); +await emulator.stop(); +``` + +## API + +### `createEmulator(type, options?)` + +Factory function that creates a `HardwareWalletEmulator` instance. + +- **`type`** — `'ledger'` (via `EmulatorType.Ledger`). Trezor support is not yet implemented. +- **`options`** — See [`SpeculosOptions`](#speculosoptions). + +### `HardwareWalletEmulator` + +| Method | Description | +| ---------------------- | ------------------------------------------ | +| `start()` | Start the emulator (Docker or native). | +| `stop()` | Stop the emulator and clean up resources. | +| `isRunning()` | Returns whether the emulator is active. | +| `approveTransaction()` | Approve the current transaction on screen. | +| `approveSigning()` | Approve the current signing request. | +| `rejectTransaction()` | Reject the current transaction on screen. | +| `navigateToMainMenu()` | Navigate back to the device main menu. | +| `getInteraction()` | Get the low-level device interaction API. | + +### `SpeculosOptions` + +| Option | Type | Default | Description | +| -------------- | --------- | ------------ | ---------------------------------------------------- | +| `device` | `string` | `'flex'` | Device model ID (`nanosp`, `nanox`, `stax`, `flex`). | +| `seed` | `string` | Built-in | Mnemonic seed for deterministic accounts. | +| `apduPort` | `number` | `9998` | APDU communication port. | +| `apiPort` | `number` | `5001` | Speculos REST API port. | +| `wsBridgePort` | `number` | `9876` | WebSocket bridge port for WebHID mock. | +| `mode` | `string` | Auto | Run mode: `'docker'` or `'native'`. Auto-detected. | +| `binary` | `string` | — | Path to Speculos binary (native mode only). | +| `display` | `string` | `'headless'` | Display mode. | +| `loadNvram` | `boolean` | `true` | Load persisted NVRAM state. | +| `startTimeout` | `number` | `60000` | Startup timeout in ms. | + +### Low-Level APIs + +The package also exports granular components for advanced use cases: + +- **`SpeculosClient`** — HTTP client for the Speculos REST API (APDU exchange, screen events). +- **`ApduBridge`** — WebSocket-to-APDU bridge for browser-based WebHID mocking. +- **`DockerManager`** — Direct Docker Compose lifecycle management. +- **`createProcessManager()`** — Native Speculos process spawning and monitoring. +- **`createDeviceInteraction()`** — Screen automation (button presses, touch coordinates). +- **`withRetry()` / `ExponentialBackoff`** — Resilience utilities for flaky device communication. +- **`createLedgerHidFramingSession()`** — Low-level Ledger HID frame encoding/decoding. +- **`getWebHidMockScript()`** — Generates a browser script to mock WebHID for E2E tests. +- **`SpeculosBleRunner`** — Manages the lifecycle of the BLE bridge Python service (see [BLE Bridge](#ble-bridge)). + +## BLE Bridge + +The package includes a Python BLE bridge that wraps the Speculos APDU stream into a Bluetooth Low Energy GATT server, enabling Bluetooth-based Ledger device testing on Android emulators and physical devices. It emulates a Bluetooth Ledger device (advertised as a Nano X) using [Speculos](https://github.com/LedgerHQ/speculos) + [Bumble](https://github.com/nickoala/pygatt). + +It bridges three surfaces: + +1. **BLE GATT server** — advertises as a Ledger Nano X, accepts BLE connections +2. **APDU bridge** — forwards BLE APDU packets to/from the Speculos emulator +3. **Control API** — HTTP endpoint for test automation (button presses, screenshots, BLE disconnect) + +The Python source lives in `python/speculos_ble/`, and the `SpeculosBleRunner` TypeScript class (in `src/ble/`) provides a programmatic API for starting, monitoring, and stopping the bridge process. + +### Setup + +```bash +# Create the Python virtualenv (first time only) +./scripts/setup-python.sh +``` + +### Programmatic Usage + +```typescript +import { SpeculosBleRunner } from '@metamask/hw-emulator'; + +// One-time venv setup +if (!SpeculosBleRunner.isVenvReady()) { + SpeculosBleRunner.setupVenv(); +} + +const runner = new SpeculosBleRunner({ + controlApiPort: 5002, + deviceName: 'Ledger Nano X', + transport: 'android-netsim', +}); + +runner.start(); +await runner.waitForControlApi(); + +// ... run tests ... + +await runner.disconnectBle(); +await runner.stop(); +``` + +### Transport Modes + +| Transport | Description | +| ---------------- | --------------------------------------------------------- | +| `android-netsim` | Android emulator with Bluetooth netsim support (default). | +| `vhci` | Linux VHCI kernel module (for other Bluetooth stacks). | + +### Python Tests + +```bash +yarn test:python +# or: cd tests/python && python -m pytest -v +``` + +### Requirements + +- Python 3.10–3.13 (for the BLE bridge) +- Docker (for the Speculos emulator) +- Android emulator with Bluetooth netsim support (for `android-netsim` transport) +- VHCI kernel module (for `vhci` transport on Linux) + +## Docker Setup + +The package includes a `docker-compose.yml` for running Speculos via Docker: + +```bash +# Start with default device (Flex) +docker compose up -d + +# Start with a specific device +SPECULOS_DEVICE=nanosp docker compose up -d + +# Start with custom host ports (must match apduPort / apiPort in createEmulator options) +SPECULOS_APDU_PORT=9997 SPECULOS_API_PORT=5002 docker compose up -d +``` + +The ELF app binaries for all supported devices are bundled in the `apps/` directory. + +## Deterministic Accounts + +The default seed produces these pre-funded Ethereum accounts: + +| Index | Address | +| ----- | -------------------------------------------- | +| 0 | `0x24fC293546A31F5Ce73bAfecE37969A95CCd1aBf` | +| 1 | `0x730A5c73bC3ACcf56daba2D5D897bEb10F852865` | +| 2 | `0x805c2797CCBa57887F5fA0DD95C017145d67604a` | +| 3 | `0x2Bf9972F600D8C3B3f0AEe8f1e17Fc4631242fF4` | +| 4 | `0xDc660e6D52F6f774d0879f99929711155Bc03902` | + +## Contributing + +This package is part of a monorepo. Instructions for contributing can be found in the [monorepo README](https://github.com/MetaMask/accounts#readme). diff --git a/packages/hw-emulator/apps/ethereum-apex_p.elf b/packages/hw-emulator/apps/ethereum-apex_p.elf new file mode 100644 index 000000000..85725752c Binary files /dev/null and b/packages/hw-emulator/apps/ethereum-apex_p.elf differ diff --git a/packages/hw-emulator/apps/ethereum-flex.elf b/packages/hw-emulator/apps/ethereum-flex.elf new file mode 100644 index 000000000..c84dd4a41 Binary files /dev/null and b/packages/hw-emulator/apps/ethereum-flex.elf differ diff --git a/packages/hw-emulator/apps/ethereum-nanosp.elf b/packages/hw-emulator/apps/ethereum-nanosp.elf new file mode 100755 index 000000000..52e33f1f1 Binary files /dev/null and b/packages/hw-emulator/apps/ethereum-nanosp.elf differ diff --git a/packages/hw-emulator/apps/ethereum-nanox.elf b/packages/hw-emulator/apps/ethereum-nanox.elf new file mode 100644 index 000000000..673e22816 Binary files /dev/null and b/packages/hw-emulator/apps/ethereum-nanox.elf differ diff --git a/packages/hw-emulator/apps/ethereum-stax.elf b/packages/hw-emulator/apps/ethereum-stax.elf new file mode 100644 index 000000000..1ca95769d Binary files /dev/null and b/packages/hw-emulator/apps/ethereum-stax.elf differ diff --git a/packages/hw-emulator/docker-compose.yml b/packages/hw-emulator/docker-compose.yml new file mode 100644 index 000000000..afa4ef154 --- /dev/null +++ b/packages/hw-emulator/docker-compose.yml @@ -0,0 +1,42 @@ +version: '3.8' +services: + speculos: + image: ghcr.io/ledgerhq/speculos:0.25.13 + container_name: metamask-speculos + ports: + - '${SPECULOS_APDU_PORT:-9998}:9999' + - '${SPECULOS_API_PORT:-5001}:5000' + volumes: + - ./apps:/speculos/apps + - ./nvram/main_nvram.bin:/speculos/main_nvram.bin + environment: + - DISPLAY=:99 + command: > + --model ${SPECULOS_DEVICE:-nanosp} + /speculos/apps/${SPECULOS_ELF_FILENAME:-ethereum-nanosp.elf} + --seed "${SPECULOS_SEED:-grit essence story volume tip entry situate found february olympic monitor hybrid}" + --display ${SPECULOS_DISPLAY:-headless} + --apdu-port 9999 + --api-port 5000 + --load-nvram + healthcheck: + test: + - CMD-SHELL + - python3 -c "import urllib.request; urllib.request.urlopen('http://localhost:5000/')" + interval: 2s + timeout: 3s + retries: 10 + +--- +# Note: +# - Image is pinned to 0.25.13, the newest tag published at ghcr.io/ledgerhq/speculos +# (native mode bundles Speculos 0.27.8) +# - SPECULOS_APDU_PORT / SPECULOS_API_PORT are host-side ports (defaults 9998 / 5001) +# - Container listens on 9999 (APDU) and 5000 (API) internally +# - Host-side defaults match src/ledger/constants.ts (DEFAULT_DEVICE) and +# scripts/start-android.sh (APDU 9998, API 5001) +# - SPECULOS_DEVICE selects the device model (nanosp, nanox, stax, flex) +# - SPECULOS_ELF_FILENAME is the ELF filename inside /speculos/apps/ (NOT the host path) +# - SPECULOS_SEED sets the mnemonic for deterministic accounts (DockerManager / Speculos seed option) +# - SPECULOS_DISPLAY sets the Speculos display backend (DockerManager display option, default headless) +# - Defaults to Nano S+ (nanosp) for local development without SPECULOS_DEVICE set diff --git a/packages/hw-emulator/jest.config.js b/packages/hw-emulator/jest.config.js new file mode 100644 index 000000000..a852d54fd --- /dev/null +++ b/packages/hw-emulator/jest.config.js @@ -0,0 +1,13 @@ +const merge = require('deepmerge'); +const path = require('path'); +const baseConfig = require('../../jest.config.packages'); + +module.exports = merge(baseConfig, { + displayName: path.basename(__dirname), + // Spike directories contain browser-context scripts named `test.js` that + // Jest's default testMatch would otherwise pick up as test suites. + testPathIgnorePatterns: ['/node_modules/', '/spike/'], + coverageThreshold: { + global: { branches: 10, functions: 20, lines: 20, statements: 20 }, + }, +}); diff --git a/packages/hw-emulator/nvram/main_nvram.bin b/packages/hw-emulator/nvram/main_nvram.bin new file mode 100644 index 000000000..51460ef08 Binary files /dev/null and b/packages/hw-emulator/nvram/main_nvram.bin differ diff --git a/packages/hw-emulator/package.json b/packages/hw-emulator/package.json new file mode 100644 index 000000000..8d2ddd6b3 --- /dev/null +++ b/packages/hw-emulator/package.json @@ -0,0 +1,131 @@ +{ + "name": "@metamask/hw-emulator", + "version": "0.2.0", + "description": "Hardware wallet emulator lifecycle, transport, BLE bridge, and device interaction for E2E testing", + "keywords": [ + "ble", + "bluetooth", + "e2e", + "emulator", + "hardware-wallet", + "ledger", + "metamask", + "testing", + "trezor" + ], + "homepage": "https://github.com/MetaMask/accounts/tree/main/packages/hw-emulator#readme", + "bugs": { + "url": "https://github.com/MetaMask/accounts/issues" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/MetaMask/accounts.git" + }, + "files": [ + "dist/", + "apps/", + "nvram/", + "docker-compose.yml", + "python/", + "tests/python/", + "scripts/", + "Dockerfile", + "pyproject.toml" + ], + "sideEffects": false, + "main": "./dist/index.cjs", + "browser": { + "./dist/ledger/docker-manager.cjs": false, + "./dist/ledger/process-manager.cjs": false + }, + "types": "./dist/index.d.cts", + "exports": { + ".": { + "import": { + "types": "./dist/index.d.mts", + "default": "./dist/index.mjs" + }, + "require": { + "types": "./dist/index.d.cts", + "default": "./dist/index.cjs" + } + }, + "./package.json": "./package.json" + }, + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + }, + "scripts": { + "build": "ts-bridge --project tsconfig.build.json --verbose --clean --no-references", + "build:all": "ts-bridge --project tsconfig.build.json --verbose --clean", + "build:clean": "yarn build --clean", + "build:docs": "typedoc", + "changelog:update": "../../scripts/update-changelog.sh @metamask/hw-emulator", + "changelog:validate": "../../scripts/validate-changelog.sh @metamask/hw-emulator", + "publish:preview": "yarn npm publish --tag preview", + "since-latest-release": "../../scripts/since-latest-release.sh", + "test": "yarn test:source && yarn test:types", + "test:clean": "jest --clearCache", + "test:source": "jest --reporters=jest-silent-reporter", + "test:types": "../../scripts/tsd-test.sh ./src", + "test:verbose": "jest --verbose", + "test:watch": "jest --watch", + "test:python": "cd tests/python && python -m pytest -v" + }, + "dependencies": { + "@ethereumjs/rlp": "^10.1.3", + "@ethereumjs/tx": "^10.1.3", + "@ethereumjs/util": "^10.1.3", + "@keystonehq/bc-ur-registry-eth": "^0.23.2", + "@metamask/eth-sig-util": "^10.0.1", + "@metamask/utils": "^11.11.0", + "@ngraveio/bc-ur": "^1.1.13", + "@zxing/library": "^0.23.0", + "ethereum-cryptography": "^3.2.0", + "hdkey": "^2.1.0", + "qrcode-generator": "^2.0.4", + "secp256k1": "^5.0.2", + "ws": "^8.23.1" + }, + "devDependencies": { + "@ethereumjs/common": "^10.1.3", + "@lavamoat/allow-scripts": "^5.1.1", + "@lavamoat/preinstall-always-fail": "^3.0.2", + "@metamask/auto-changelog": "^7.1.0", + "@metamask/eth-qr-keyring": "^3.0.2", + "@ts-bridge/cli": "^0.6.4", + "@types/jest": "^30.0.0", + "@types/node": "^26.6.11", + "@types/secp256k1": "^4.0.7", + "@types/ws": "^8.18.2", + "deepmerge": "^4.3.1", + "depcheck": "^1.4.7", + "jest": "^30.5.2", + "jest-it-up": "^5.0.1", + "rimraf": "^6.1.4", + "ts-jest": "^29.4.15", + "ts-node": "^10.9.2", + "tsd": "^0.33.0", + "typedoc": "^0.28.20", + "typescript": "~5.9.3", + "uuid": "^11.1.1" + }, + "peerDependencies": { + "@metamask/speculos-up": "^0.1.0" + }, + "peerDependenciesMeta": { + "@metamask/speculos-up": { + "optional": true + } + }, + "engines": { + "node": ">=22" + }, + "lavamoat": { + "allowScripts": { + "@lavamoat/preinstall-always-fail": false + } + } +} diff --git a/packages/hw-emulator/pyproject.toml b/packages/hw-emulator/pyproject.toml new file mode 100644 index 000000000..99e57f438 --- /dev/null +++ b/packages/hw-emulator/pyproject.toml @@ -0,0 +1,33 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "speculos-ble" +version = "0.1.0" +description = "Virtual BLE Ledger device for E2E testing with Speculos" +requires-python = ">=3.10,<3.14" +dependencies = [ + # Pinned exactly on purpose: the emulator must behave identically on CI + # and dev machines, and BLE-stack behavior (bumble) should not drift + # between installs. Bump pins deliberately, then re-run tests/python. + "bumble==0.0.233", + "grpcio>=1.62.0,<2", + # bumble's android_netsim transport imports google.protobuf at runtime; + # grpcio does not pull it in transitively. + "protobuf>=5.26,<7", + "aiohttp==3.14.3", + "click==8.4.2", +] + +[project.optional-dependencies] +test = ["pytest>=8.0", "pytest-asyncio>=0.23", "aiohttp[speedups]>=3.9"] + +[project.scripts] +speculos-ble = "speculos_ble.__main__:main" + +[tool.hatch.build.targets.wheel] +packages = ["python/speculos_ble"] + +[tool.pytest.ini_options] +testpaths = ["tests/python"] diff --git a/packages/hw-emulator/python/speculos_ble/__init__.py b/packages/hw-emulator/python/speculos_ble/__init__.py new file mode 100644 index 000000000..1629be4ad --- /dev/null +++ b/packages/hw-emulator/python/speculos_ble/__init__.py @@ -0,0 +1,3 @@ +"""Virtual BLE Ledger device for E2E testing with Speculos.""" + +__version__ = "0.1.0" diff --git a/packages/hw-emulator/python/speculos_ble/__main__.py b/packages/hw-emulator/python/speculos_ble/__main__.py new file mode 100644 index 000000000..660341d45 --- /dev/null +++ b/packages/hw-emulator/python/speculos_ble/__main__.py @@ -0,0 +1,154 @@ +"""CLI entry point for speculos-ble.""" + +from __future__ import annotations + +import asyncio +import logging +import os +import signal +import sys + +import click + +from .device import VirtualLedgerDevice +from .types import ( + DEFAULT_CONTROL_API_PORT, + DEFAULT_DEVICE_NAME, + DEFAULT_SPECULOS_APDU_PORT, + DEFAULT_SPECULOS_API_PORT, + DEFAULT_SPECULOS_HOST, + VirtualLedgerConfig, +) + +logger = logging.getLogger(__name__) + + +def _netsim_ini_path() -> str | None: + from bumble.transport.android_netsim import get_ini_dir, ini_file_name + + ini_dir = get_ini_dir() + if ini_dir is None: + return None + return str(ini_dir / ini_file_name(0)) + + +async def _wait_for_netsim(timeout: float = 30.0) -> None: + import time + + ini_path = _netsim_ini_path() + if ini_path is None: + raise RuntimeError( + "Cannot determine netsim ini directory for this platform" + ) + + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if os.path.exists(ini_path): + logger.info("Found netsim config at %s", ini_path) + return + await asyncio.sleep(0.5) + raise FileNotFoundError( + f"netsim.ini not found after {timeout}s. Expected at: {ini_path}" + ) + + +@click.command() +@click.option( + "--transport", + type=click.Choice(["vhci", "usb", "hci-socket", "android-netsim"]), + default="vhci", + help="BLE transport backend", +) +@click.option( + "--device-name", + default=DEFAULT_DEVICE_NAME, + help="BLE advertising name", +) +@click.option( + "--speculos-host", + default=DEFAULT_SPECULOS_HOST, + help="Speculos host", +) +@click.option( + "--speculos-apdu-port", + default=DEFAULT_SPECULOS_APDU_PORT, + type=int, + help="Speculos TCP APDU port", +) +@click.option( + "--speculos-api-port", + default=DEFAULT_SPECULOS_API_PORT, + type=int, + help="Speculos REST API port", +) +@click.option( + "--control-api-port", + default=DEFAULT_CONTROL_API_PORT, + type=int, + help="Control REST API port", +) +@click.option( + "--verbose", "-v", + is_flag=True, + help="Enable debug logging", +) +def main( + transport: str, + device_name: str, + speculos_host: str, + speculos_apdu_port: int, + speculos_api_port: int, + control_api_port: int, + verbose: bool, +) -> None: + logging.basicConfig( + level=logging.DEBUG if verbose else logging.INFO, + format="%(asctime)s %(name)s %(levelname)s %(message)s", + ) + + transport_map = { + "vhci": "vhci", + "usb": "usb:0", + "hci-socket": "hci-socket:0", + "android-netsim": "android-netsim", + } + + config = VirtualLedgerConfig( + transport=transport_map.get(transport, transport), + device_name=device_name, + speculos_host=speculos_host, + speculos_apdu_port=speculos_apdu_port, + speculos_api_port=speculos_api_port, + control_api_port=control_api_port, + ) + + device = VirtualLedgerDevice(config) + + loop = asyncio.new_event_loop() + + def _shutdown(signum, frame): + logger.info("Received signal %s, shutting down", signum) + loop.call_soon_threadsafe( + lambda: asyncio.ensure_future(device.stop()), + ) + + signal.signal(signal.SIGINT, _shutdown) + signal.signal(signal.SIGTERM, _shutdown) + + try: + if transport == "android-netsim": + logger.info("Waiting for android-netsim readiness...") + loop.run_until_complete(_wait_for_netsim()) + + loop.run_until_complete(device.start()) + logger.info("Virtual Ledger device running. Press Ctrl+C to stop.") + loop.run_forever() + except KeyboardInterrupt: + pass + finally: + loop.run_until_complete(device.stop()) + loop.close() + + +if __name__ == "__main__": + main() diff --git a/packages/hw-emulator/python/speculos_ble/apdu_bridge.py b/packages/hw-emulator/python/speculos_ble/apdu_bridge.py new file mode 100644 index 000000000..d37502bc9 --- /dev/null +++ b/packages/hw-emulator/python/speculos_ble/apdu_bridge.py @@ -0,0 +1,96 @@ +"""APDU bridge between GATT writes and Speculos TCP. + +Handles: + - Forwarding reassembled APDUs to Speculos + - Returning responses via GATT notifications + - Signing APDU detection for test orchestration + - Error injection for negative tests +""" + +from __future__ import annotations + +import asyncio +import logging +import time + +from .speculos_client import SpeculosTcpClient +from .types import SIGNING_INS_BYTES + +logger = logging.getLogger(__name__) + + +class ApduBridge: + def __init__( + self, + speculos_host: str = "127.0.0.1", + speculos_apdu_port: int = 9999, + ) -> None: + self._speculos = SpeculosTcpClient(speculos_host, speculos_apdu_port) + self._signing_detected = asyncio.Event() + self._error_injection: bytes | None = None + self._connected = False + # Serializes APDU handling so that the error-injection check and + # consumption are atomic with respect to concurrent GATT writes; + # without this, an injected error could be applied to the wrong APDU. + self._apdu_lock = asyncio.Lock() + + async def start(self) -> None: + await self._speculos.connect() + self._connected = True + + async def stop(self) -> None: + await self._speculos.disconnect() + self._connected = False + + async def handle_apdu(self, apdu: bytes) -> bytes: + """Handle one reassembled APDU and return the response bytes. + + Auto-connects to Speculos on the first APDU if the bridge is not + yet connected. As a side effect, when the APDU looks like a + signing request (INS in SIGNING_INS_BYTES), the + ``signing_detected`` event is set for test orchestration. An + injected error response (see ``inject_error``) takes precedence + over forwarding the APDU to Speculos and is consumed by exactly + one exchange. + """ + async with self._apdu_lock: + if not self._connected: + await self.start() + + is_signing = self._is_signing_apdu(apdu) + if is_signing: + logger.info( + "Signing APDU detected (INS=0x%02X)", + apdu[1] if len(apdu) > 1 else 0, + ) + self._signing_detected.set() + + if self._error_injection is not None: + response = self._error_injection + self._error_injection = None + logger.info("Error injection active, returning injected response") + return response + + response = await self._speculos.exchange(apdu) + return response + + def inject_error(self, response: bytes) -> None: + self._error_injection = response + + @property + def signing_detected(self) -> asyncio.Event: + return self._signing_detected + + def clear_signing_flag(self) -> None: + self._signing_detected.clear() + + @property + def is_connected(self) -> bool: + return self._connected + + @staticmethod + def _is_signing_apdu(apdu: bytes) -> bool: + if len(apdu) < 2: + return False + ins = apdu[1] + return ins in SIGNING_INS_BYTES diff --git a/packages/hw-emulator/python/speculos_ble/apdu_framing.py b/packages/hw-emulator/python/speculos_ble/apdu_framing.py new file mode 100644 index 000000000..a16e7928f --- /dev/null +++ b/packages/hw-emulator/python/speculos_ble/apdu_framing.py @@ -0,0 +1,122 @@ +"""APDU fragmentation and reassembly for Ledger BLE protocol. + +Protocol: + Write (phone → device): transport library chunks with headers + Notify (device → phone): we chunk responses with headers + + Header format: + Chunk 0: [TagId=0x05][chunk_idx:2B BE][total_len:2B BE][data...] + Chunk N: [TagId=0x05][chunk_idx:2B BE][data...] +""" + +from __future__ import annotations + +import struct +from collections.abc import Iterator + +from .types import BLE_TAG_ID, MIN_MTU + +# The chunk-0 header encodes the total APDU length as a 16-bit BE field, +# so a framed APDU can never exceed 65535 bytes. +MAX_APDU_SIZE = 0xFFFF + + +def _chunk_overhead(index: int) -> int: + return 5 if index == 0 else 3 + + +def fragment_apdu(apdu: bytes, mtu: int) -> list[bytes]: + if mtu < MIN_MTU: + raise ValueError(f"MTU too small for Ledger framing: {mtu}") + if len(apdu) > MAX_APDU_SIZE: + raise ValueError( + f"APDU too large for Ledger BLE framing: {len(apdu)} bytes " + f"(max {MAX_APDU_SIZE})" + ) + if not apdu: + return [] + + chunks: list[bytes] = [] + offset = 0 + index = 0 + + while offset < len(apdu): + overhead = _chunk_overhead(index) + payload_size = min(mtu - overhead, len(apdu) - offset) + payload = apdu[offset : offset + payload_size] + + if index == 0: + header = struct.pack(">BHH", BLE_TAG_ID, index, len(apdu)) + else: + header = struct.pack(">BH", BLE_TAG_ID, index) + + chunks.append(header + payload) + offset += payload_size + index += 1 + + return chunks + + +class ApduReassembler: + def __init__(self) -> None: + self._buffer = bytearray() + self._expected_total: int | None = None + self._next_index: int = 0 + + def reset(self) -> None: + self._buffer.clear() + self._expected_total = None + self._next_index = 0 + + def feed(self, frame: bytes) -> bytes | None: + if len(frame) < 3: + return None + + tag = frame[0] + if tag != BLE_TAG_ID: + return None + + chunk_index = struct.unpack_from(">H", frame, 1)[0] + + if chunk_index == 0: + if len(frame) < 5: + return None + self._buffer.clear() + self._expected_total = struct.unpack_from(">H", frame, 3)[0] + if self._expected_total == 0: + # A zero-length APDU is invalid; fragment_apdu() never + # emits an empty sequence. + self.reset() + return None + self._next_index = 0 + data_offset = 5 + else: + if chunk_index != self._next_index: + self.reset() + return None + data_offset = 3 + + data = frame[data_offset:] + self._buffer.extend(data) + self._next_index = chunk_index + 1 + + if self._expected_total is None: + return None + + if len(self._buffer) > self._expected_total: + # More data arrived than the chunk-0 header declared. Reject + # explicitly instead of silently truncating. + received = len(self._buffer) + declared = self._expected_total + self.reset() + raise ValueError( + f"APDU reassembly overflow: received {received} bytes but " + f"chunk-0 header declared a total of {declared} bytes" + ) + + if len(self._buffer) == self._expected_total: + result = bytes(self._buffer) + self.reset() + return result + + return None diff --git a/packages/hw-emulator/python/speculos_ble/control_api.py b/packages/hw-emulator/python/speculos_ble/control_api.py new file mode 100644 index 000000000..90ab49479 --- /dev/null +++ b/packages/hw-emulator/python/speculos_ble/control_api.py @@ -0,0 +1,237 @@ +"""REST control API for test orchestration. + +Endpoints for button presses, screenshots, BLE control, error injection, +and signing automation. Runs alongside the virtual BLE device. +""" + +from __future__ import annotations + +import asyncio +import logging +from typing import TYPE_CHECKING + +import aiohttp +from aiohttp import web + +from .types import ( + ConnectionState, + validate_button_press, +) + +if TYPE_CHECKING: + from .device import VirtualLedgerDevice + +logger = logging.getLogger(__name__) + +# Largest accepted error-injection payload (typical injections are a +# 2-byte status word). +MAX_INJECTED_ERROR_SIZE = 64 + +DEFAULT_AUTO_APPROVE_TIMEOUT = 60.0 +MAX_AUTO_APPROVE_TIMEOUT = 300.0 + +# The blind-signing toggle sits several screens deep in the Speculos +# settings menu: each "right" press advances one screen, so the full +# sequence of presses (with a delay for Speculos to render each +# transition) is required to reach the toggle, which "both" then enables. +BLIND_SIGNING_RIGHT_PRESSES = 5 +BLIND_SIGNING_STEP_DELAY_S = 0.3 + +# Default auto-approve sequence: advance through the review screens with +# "right" presses, then confirm with a single "both" press. +DEFAULT_AUTO_APPROVE_RIGHT_PRESSES = 4 +DEFAULT_AUTO_APPROVE_CONFIRM_PRESSES = 1 + + +class ControlApiServer: + def __init__( + self, + device: "VirtualLedgerDevice", + host: str = "127.0.0.1", + port: int = 5002, + ) -> None: + self._device = device + self._host = host + self._port = port + self._app = web.Application() + self._runner: web.AppRunner | None = None + self._add_routes() + + def _add_routes(self) -> None: + self._app.add_routes([ + web.get("/health", self._health), + web.post("/button/press", self._button_press), + web.get("/screenshot", self._screenshot), + web.post("/blind-signing/enable", self._blind_signing_enable), + web.post("/ble/advertise/start", self._advertise_start), + web.post("/ble/advertise/stop", self._advertise_stop), + web.get("/ble/connection", self._ble_connection), + web.post("/ble/disconnect", self._ble_disconnect), + web.post("/error/inject", self._error_inject), + web.get("/debug/apdu-log", self._apdu_log), + web.post("/signing/auto-approve", self._signing_auto_approve), + ]) + + async def start(self) -> None: + self._runner = web.AppRunner(self._app) + await self._runner.setup() + site = web.TCPSite(self._runner, self._host, self._port) + await site.start() + logger.info("Control API listening on %s:%d", self._host, self._port) + + async def stop(self) -> None: + if self._runner: + await self._runner.cleanup() + + async def _health(self, request: web.Request) -> web.Response: + return web.json_response({ + "status": "ready", + "ble_state": self._device.state.value, + "speculos_connected": self._device.apdu_bridge.is_connected, + }) + + @staticmethod + def _bad_request(message: str) -> web.Response: + return web.json_response({"ok": False, "error": message}, status=400) + + async def _button_press(self, request: web.Request) -> web.Response: + try: + body = await request.json() + except ValueError: + return self._bad_request("request body must be valid JSON") + + button = body.get("button", "right") + count = body.get("count", 1) + + try: + validate_button_press(button, count) + except ValueError as e: + return self._bad_request(str(e)) + + try: + await self._device.press_button(button, count) + except ValueError as e: + return self._bad_request(str(e)) + except Exception as e: + return web.json_response( + {"ok": False, "error": str(e)}, status=502 + ) + return web.json_response({"ok": True}) + + async def _screenshot(self, request: web.Request) -> web.Response: + screenshot = await self._device.take_screenshot() + return web.Response( + body=screenshot, + content_type="image/png", + ) + + async def _blind_signing_enable(self, request: web.Request) -> web.Response: + for _ in range(BLIND_SIGNING_RIGHT_PRESSES): + await self._device.press_button("right", 1) + await asyncio.sleep(BLIND_SIGNING_STEP_DELAY_S) + await self._device.press_button("both", 1) + return web.json_response({"ok": True}) + + async def _advertise_start(self, request: web.Request) -> web.Response: + await self._device.start_advertising() + return web.json_response({"ok": True}) + + async def _advertise_stop(self, request: web.Request) -> web.Response: + await self._device.stop_advertising() + return web.json_response({"ok": True}) + + async def _ble_connection(self, request: web.Request) -> web.Response: + return web.json_response({ + "state": self._device.state.value, + "has_connection": self._device.gatt_server.connection is not None, + }) + + async def _ble_disconnect(self, request: web.Request) -> web.Response: + await self._device.disconnect_peer() + return web.json_response({"ok": True}) + + async def _error_inject(self, request: web.Request) -> web.Response: + try: + body = await request.json() + except ValueError: + return self._bad_request("request body must be valid JSON") + + error_hex = body.get("response", "6D00") + if not isinstance(error_hex, str): + return self._bad_request("'response' must be a hex string") + try: + error_bytes = bytes.fromhex(error_hex) + except ValueError: + return self._bad_request( + f"'response' is not a valid hex string: {error_hex!r}" + ) + if not error_bytes: + return self._bad_request("'response' must not be empty") + if len(error_bytes) > MAX_INJECTED_ERROR_SIZE: + return self._bad_request( + f"'response' too large: {len(error_bytes)} bytes " + f"(max {MAX_INJECTED_ERROR_SIZE})" + ) + self._device.apdu_bridge.inject_error(error_bytes) + return web.json_response({"ok": True}) + + async def _apdu_log(self, request: web.Request) -> web.Response: + entries = self._device.gatt_server.apdu_log + return web.json_response([ + { + "timestamp": e.timestamp, + "direction": e.direction, + "data_hex": e.data.hex(), + "tag": e.tag, + } + for e in entries + ]) + + async def _signing_auto_approve(self, request: web.Request) -> web.Response: + try: + body = await request.json() + except ValueError: + return self._bad_request("request body must be valid JSON") + + sequence = body.get("presses", [ + {"button": "right", "count": DEFAULT_AUTO_APPROVE_RIGHT_PRESSES}, + {"button": "both", "count": DEFAULT_AUTO_APPROVE_CONFIRM_PRESSES}, + ]) + timeout = body.get("timeout", DEFAULT_AUTO_APPROVE_TIMEOUT) + + if not isinstance(sequence, list): + return self._bad_request("'presses' must be a list") + try: + for step in sequence: + if not isinstance(step, dict): + raise ValueError("each press in 'presses' must be an object") + validate_button_press( + step.get("button", "right"), step.get("count", 1) + ) + except ValueError as e: + return self._bad_request(str(e)) + + if ( + not isinstance(timeout, (int, float)) + or isinstance(timeout, bool) + or not 0 < timeout <= MAX_AUTO_APPROVE_TIMEOUT + ): + return self._bad_request( + f"'timeout' must be a number in (0, {MAX_AUTO_APPROVE_TIMEOUT}]" + ) + + try: + await self._device.wait_for_signing_and_approve( + sequence, timeout=timeout + ) + except asyncio.TimeoutError: + return web.json_response( + { + "ok": False, + "error": ( + f"signing request not detected within {timeout}s" + ), + }, + status=504, + ) + return web.json_response({"ok": True}) diff --git a/packages/hw-emulator/python/speculos_ble/device.py b/packages/hw-emulator/python/speculos_ble/device.py new file mode 100644 index 000000000..9b69c7ada --- /dev/null +++ b/packages/hw-emulator/python/speculos_ble/device.py @@ -0,0 +1,250 @@ +"""Virtual Ledger device — main orchestrator. + +Wires together: + - Bumble Device (advertising, connections) + - LedgerGattServer (GATT service with APDU characteristics) + - ApduBridge (GATT ↔ Speculos TCP relay) + - ControlApiServer (REST API for test orchestration) + - Connection lifecycle state machine +""" + +from __future__ import annotations + +import asyncio +import logging +import os +from typing import Any + +import aiohttp + +from bumble import data_types +from bumble.core import AdvertisingData, UUID +from bumble.device import Device, Connection +from bumble.hci import Address +from bumble.pairing import PairingConfig, PairingDelegate +from bumble.transport import open_transport + +from .apdu_bridge import ApduBridge +from .control_api import ControlApiServer +from .gatt_server import LedgerGattServer +from .types import ( + ConnectionState, + DEFAULT_DEVICE_NAME, + LEDGER_SERVICE_UUID, + MTU_PROBE_BYTE, + VirtualLedgerConfig, + validate_button_press, +) + +logger = logging.getLogger(__name__) + +# BLE static random addresses have the two most-significant bits set. +STATIC_RANDOM_ADDRESS_MSB_MASK = 0xC0 + +# Delay between consecutive Speculos button presses, so each screen +# transition settles before the next press. +BUTTON_PRESS_INTERVAL_S = 0.1 + + +class VirtualLedgerDevice(Device.Listener, Connection.Listener): + def __init__(self, config: VirtualLedgerConfig) -> None: + self._config = config + self._state = ConnectionState.IDLE + + self.apdu_bridge = ApduBridge( + speculos_host=config.speculos_host, + speculos_apdu_port=config.speculos_apdu_port, + ) + + self.gatt_server = LedgerGattServer( + on_apdu=self.apdu_bridge.handle_apdu, + on_mtu_probe=self._handle_mtu_probe, + apdu_log_size=config.apdu_log_size, + ) + + self._control_api = ControlApiServer( + device=self, + port=config.control_api_port, + ) + + self._device: Device | None = None + self._transport: Any = None + self._connection: Connection | None = None + self._http_session: aiohttp.ClientSession | None = None + self._stopped = False + + @property + def state(self) -> ConnectionState: + return self._state + + def _set_state(self, state: ConnectionState) -> None: + logger.info("State: %s → %s", self._state.value, state.value) + self._state = state + + async def start(self) -> None: + self._set_state(ConnectionState.ADVERTISING) + + self._transport = await open_transport(self._config.transport) + + random_address = self._generate_random_address() + + self._device = Device.with_hci( + name=self._config.device_name, + address=random_address, + hci_source=self._transport.source, + hci_sink=self._transport.sink, + ) + + self._device.listener = self + self._device.pairing_config_factory = lambda connection: PairingConfig( + sc=True, + mitm=False, + bonding=False, + delegate=PairingDelegate( + io_capability=PairingDelegate.IoCapability.NO_OUTPUT_NO_INPUT, + ), + ) + + self.gatt_server.bind(self._device) + self._device.add_services([self.gatt_server.service]) + + self._device.advertising_data = bytes( + AdvertisingData([ + data_types.CompleteListOf128BitServiceUUIDs([UUID(LEDGER_SERVICE_UUID)]), + data_types.ShortenedLocalName(self._config.device_name[:8]), + ]) + ) + self._device.scan_response_data = bytes( + AdvertisingData([ + data_types.CompleteLocalName(self._config.device_name), + ]) + ) + + await self._device.power_on() + await self._device.start_advertising( + auto_restart=self._config.auto_restart_advertising, + ) + + await self.apdu_bridge.start() + await self._control_api.start() + + logger.info( + "Virtual Ledger device '%s' ready (address: %s)", + self._config.device_name, + random_address, + ) + + async def stop(self) -> None: + # Idempotency guard: stop() may be invoked both from the signal + # handler and from the CLI's finally block (and re-entrantly from + # concurrent shutdown paths); only the first call runs teardown. + if self._stopped: + return + self._stopped = True + + self._set_state(ConnectionState.DISCONNECTING) + + await self._control_api.stop() + await self.apdu_bridge.stop() + + if self._http_session and not self._http_session.closed: + await self._http_session.close() + + if self._device: + await self._device.stop_advertising() + await self._device.power_off() + + if self._transport: + await self._transport.close() + + self._set_state(ConnectionState.IDLE) + + async def start_advertising(self) -> None: + if self._device: + await self._device.start_advertising( + auto_restart=self._config.auto_restart_advertising, + ) + + async def stop_advertising(self) -> None: + if self._device: + await self._device.stop_advertising() + + async def disconnect_peer(self) -> None: + if self._connection: + await self._connection.disconnect() + + @staticmethod + def _generate_random_address() -> Address: + random_bytes = bytearray(os.urandom(6)) + random_bytes[0] |= STATIC_RANDOM_ADDRESS_MSB_MASK + addr_str = ":".join(f"{b:02X}" for b in random_bytes) + return Address(addr_str) + + async def _handle_mtu_probe(self, connection: Connection, value: bytes) -> None: + negotiated_mtu = connection.att_mtu + self.gatt_server.set_mtu(negotiated_mtu) + logger.info("MTU probe handled, negotiated MTU: %d", negotiated_mtu) + + mtu_value = max(negotiated_mtu, 23) + probe_response = bytes([ + MTU_PROBE_BYTE, # probe marker echo + 0x00, 0x00, 0x00, 0x00, # reserved padding + mtu_value & 0xFF, (mtu_value >> 8) & 0xFF, # MTU, little-endian + ]) + await self.gatt_server.send_raw_notification(connection, probe_response) + + def _get_http_session(self) -> aiohttp.ClientSession: + if self._http_session is None or self._http_session.closed: + self._http_session = aiohttp.ClientSession() + return self._http_session + + async def press_button(self, button: str, count: int = 1) -> None: + validate_button_press(button, count) + session = self._get_http_session() + url = ( + f"http://{self._config.speculos_host}:{self._config.speculos_api_port}" + f"/button/{button}" + ) + for _ in range(count): + async with session.post(url, json={"action": "press-and-release"}) as resp: + resp.raise_for_status() + await asyncio.sleep(BUTTON_PRESS_INTERVAL_S) + + async def take_screenshot(self) -> bytes: + session = self._get_http_session() + url = ( + f"http://{self._config.speculos_host}:{self._config.speculos_api_port}" + f"/screenshot" + ) + async with session.get(url) as resp: + resp.raise_for_status() + return await resp.read() + + async def wait_for_signing_and_approve( + self, + sequence: list[dict[str, Any]], + timeout: float = 60.0, + ) -> None: + self.apdu_bridge.clear_signing_flag() + await asyncio.wait_for( + self.apdu_bridge.signing_detected.wait(), + timeout=timeout, + ) + for step in sequence: + await self.press_button(step["button"], step.get("count", 1)) + + def on_connection(self, connection: Connection) -> None: + logger.info("BLE connected: %s", connection) + self._connection = connection + connection.listener = self + self._set_state(ConnectionState.CONNECTED) + + def on_disconnection(self, reason: int) -> None: + logger.info("BLE disconnected: reason=%s", reason) + self._connection = None + self.gatt_server.reset() + if self._state != ConnectionState.DISCONNECTING: + self._set_state(ConnectionState.IDLE) + + def on_connection_att_mtu_update(self) -> None: + pass diff --git a/packages/hw-emulator/python/speculos_ble/gatt_server.py b/packages/hw-emulator/python/speculos_ble/gatt_server.py new file mode 100644 index 000000000..dec0d6b6d --- /dev/null +++ b/packages/hw-emulator/python/speculos_ble/gatt_server.py @@ -0,0 +1,268 @@ +"""GATT server exposing the Ledger Nano X BLE service. + +Characteristics: + - Write (UUID ...0002): receives chunked APDU frames from phone + - Notify (UUID ...0001): sends chunked APDU responses to phone + - WriteCmd (UUID ...0003): receives APDU frames without response + +Uses the actual Bumble API: Characteristic + CharacteristicValue callbacks. +""" + +from __future__ import annotations + +import asyncio +import logging +import struct +import time +from typing import TYPE_CHECKING + +from bumble.gatt import Characteristic, CharacteristicValue, Service + +from .apdu_framing import ApduReassembler, fragment_apdu +from .types import ( + LEDGER_SERVICE_UUID, + LEDGER_NOTIFY_CHAR_UUID, + LEDGER_WRITE_CHAR_UUID, + LEDGER_WRITE_CMD_CHAR_UUID, + MTU_PROBE_BYTE, + DEFAULT_MTU, + MIN_MTU, + ApduLogEntry, +) + +if TYPE_CHECKING: + from bumble.device import Device, Connection + +logger = logging.getLogger(__name__) + +# Status word 0x6D00 ("instruction not supported"), notified to the peer +# when an APDU exchange fails. +DEFAULT_APDU_ERROR_RESPONSE = bytes([0x6D, 0x00]) + + +class LedgerGattServer: + def __init__( + self, + on_apdu: "asyncio.coroutine", + on_mtu_probe: "asyncio.coroutine | None" = None, + apdu_log_size: int = 100, + ) -> None: + self._on_apdu = on_apdu + self._on_mtu_probe = on_mtu_probe + self._reassembler = ApduReassembler() + self._connection: Connection | None = None + self._device: Device | None = None + self._mtu: int = DEFAULT_MTU + # Single lock for the server lifetime; reset() never replaces it + # (a coroutine holding the old lock would be orphaned). In-flight + # exchanges are cancelled in reset() instead, via _exchange_task. + self._exchange_lock = asyncio.Lock() + self._exchange_task: "asyncio.Task[None] | None" = None + self._apdu_log: list[ApduLogEntry] = [] + self._apdu_log_size = apdu_log_size + self._subscribed_connections: set[Connection] = set() + + self.write_char = Characteristic( + LEDGER_WRITE_CHAR_UUID, + Characteristic.Properties.WRITE, + Characteristic.WRITEABLE, + CharacteristicValue(write=self._on_write), + ) + + self.write_cmd_char = Characteristic( + LEDGER_WRITE_CMD_CHAR_UUID, + Characteristic.Properties.WRITE_WITHOUT_RESPONSE, + Characteristic.WRITEABLE, + CharacteristicValue(write=self._on_write), + ) + + self.notify_char = Characteristic( + LEDGER_NOTIFY_CHAR_UUID, + Characteristic.Properties.READ | Characteristic.Properties.NOTIFY, + Characteristic.READABLE, + bytes([0x00]), + ) + + self.service = Service( + LEDGER_SERVICE_UUID, + [self.write_char, self.write_cmd_char, self.notify_char], + ) + + self.notify_char.on("subscription", self._on_subscription) + + def bind(self, device: "Device") -> None: + self._device = device + + def set_mtu(self, mtu: int) -> None: + self._mtu = max(mtu, MIN_MTU) + + def _log_apdu(self, direction: str, data: bytes, tag: str = "") -> None: + entry = ApduLogEntry( + timestamp=time.monotonic(), + direction=direction, + data=data, + tag=tag, + ) + self._apdu_log.append(entry) + if len(self._apdu_log) > self._apdu_log_size: + self._apdu_log.pop(0) + + @property + def apdu_log(self) -> list[ApduLogEntry]: + return list(self._apdu_log) + + @property + def connection(self) -> Connection | None: + return self._connection + + def _on_subscription( + self, + connection: "Connection", + notify_enabled: bool, + indicate_enabled: bool, + ) -> None: + logger.info( + "Subscription changed: notify=%s indicate=%s conn=%s", + notify_enabled, + indicate_enabled, + connection, + ) + if notify_enabled: + self._subscribed_connections.add(connection) + else: + self._subscribed_connections.discard(connection) + + async def _on_write(self, connection: "Connection", value: bytes) -> None: + self._connection = connection + + try: + if len(value) >= 1 and value[0] == MTU_PROBE_BYTE: + logger.debug("MTU probe received: %s", value.hex()) + self._log_apdu("in", value, "mtu_probe") + if self._on_mtu_probe: + await self._on_mtu_probe(connection, value) + return + + self._log_apdu("in", value, "chunk") + + complete_apdu = self._reassembler.feed(value) + if complete_apdu is None: + return + + self._log_apdu("in", complete_apdu, "apdu_complete") + logger.info("Complete APDU received (%d bytes)", len(complete_apdu)) + + async with self._exchange_lock: + # Track the in-flight exchange so reset() can cancel it + # instead of orphaning the coroutine on a replaced lock. + self._exchange_task = asyncio.current_task() + try: + await self._run_apdu_exchange(connection, complete_apdu) + finally: + self._exchange_task = None + except asyncio.CancelledError: + logger.info("In-flight APDU exchange cancelled (connection reset)") + raise + except Exception: + logger.exception("GATT write handler error") + + async def _run_apdu_exchange( + self, connection: "Connection", apdu: bytes, + ) -> None: + """Run one complete-APDU exchange and notify the response. + + On failure the reassembler is reset and the standard 0x6D00 error + status word is notified to the peer instead of a real response. + """ + try: + response = await self._on_apdu(apdu) + except asyncio.CancelledError: + raise + except Exception: + logger.exception("APDU exchange failed") + self._reassembler.reset() + await self._send_response(connection, DEFAULT_APDU_ERROR_RESPONSE) + return + + if response: + self._log_apdu("out", response, "apdu_response") + await self._send_response(connection, response) + + async def _send_response( + self, connection: "Connection", response: bytes, + ) -> None: + if self._device is None: + raise RuntimeError( + "No device bound to GATT server, cannot send notification" + ) + + chunks = fragment_apdu(response, self._mtu) + logger.debug( + "Sending response (%d bytes) in %d chunk(s)", + len(response), + len(chunks), + ) + + send_error: Exception | None = None + for i, chunk in enumerate(chunks): + self.notify_char.value = chunk + try: + await self._device.notify_subscriber(connection, self.notify_char) + except Exception as e: + logger.error( + "Failed to send notification chunk %d/%d: %s", + i + 1, + len(chunks), + e, + ) + send_error = e + break + + if send_error is not None: + # The response was NOT delivered (or only partially); record + # the failure and propagate so the caller doesn't treat the + # exchange as successful. + self._log_apdu("out", response, "apdu_response_failed") + raise send_error + + self._log_apdu("out", response, "apdu_response_sent") + + async def send_notification(self, data: bytes) -> None: + if self._device is None or not self._subscribed_connections: + return + chunks = fragment_apdu(data, self._mtu) + for chunk in chunks: + self.notify_char.value = chunk + await self._device.notify_subscribers(self.notify_char) + + async def send_notification_to(self, connection: Connection, data: bytes) -> None: + if self._device is None: + return + chunks = fragment_apdu(data, self._mtu) + for chunk in chunks: + self.notify_char.value = chunk + await self._device.notify_subscriber(connection, self.notify_char) + + async def send_raw_notification( + self, connection: Connection, data: bytes, + ) -> None: + if self._device is None: + return + self.notify_char.value = data + await self._device.notify_subscriber(connection, self.notify_char) + + def reset(self) -> None: + """Reset per-connection state. + + The exchange lock is intentionally NOT replaced: a coroutine + holding it during an in-flight exchange would be orphaned by a + swap. Instead, the in-flight exchange task (if any) is cancelled, + which releases the single lock and lets queued writers proceed. + """ + self._reassembler.reset() + self._connection = None + self._subscribed_connections.clear() + task = self._exchange_task + if task is not None and not task.done(): + logger.info("Cancelling in-flight APDU exchange on reset") + task.cancel() diff --git a/packages/hw-emulator/python/speculos_ble/speculos_client.py b/packages/hw-emulator/python/speculos_ble/speculos_client.py new file mode 100644 index 000000000..7c7170348 --- /dev/null +++ b/packages/hw-emulator/python/speculos_ble/speculos_client.py @@ -0,0 +1,138 @@ +"""TCP client for Speculos APDU exchange. + +Protocol: + Request: [4-byte BE length] [raw APDU] + Response: [4-byte BE length] [response data] [2-byte SW] + +The 4-byte length prefix covers the data only; the 2-byte SW follows. +""" + +from __future__ import annotations + +import asyncio +import os +import struct +import logging + +logger = logging.getLogger(__name__) + +# Standard maximum APDU response size (64 KiB). Applies to the declared +# data length; the 2-byte status word is extra. +MAX_RESPONSE_SIZE = 64 * 1024 + + +class SpeculosTimeoutError(Exception): + """Raised when a Speculos TCP operation times out.""" + + +class SpeculosProtocolError(Exception): + """Raised when Speculos sends a malformed or oversized response.""" + + +class SpeculosTcpClient: + def __init__( + self, + host: str = "127.0.0.1", + port: int = 9999, + # E2E approval automation presses device buttons while an APDU is + # pending; a 30s fuse races the adaptive approval loop's worst case + # (~50s). Env-overridable, default raised to 120s. + timeout: float = float(os.environ.get("SPECULOS_APDU_TIMEOUT", "120.0")), + ) -> None: + self._host = host + self._port = port + self._timeout = timeout + self._reader: asyncio.StreamReader | None = None + self._writer: asyncio.StreamWriter | None = None + self._lock = asyncio.Lock() + + async def connect(self) -> None: + if self._writer is not None and not self._writer.is_closing(): + return + logger.info("Connecting to Speculos at %s:%d", self._host, self._port) + self._reader, self._writer = await asyncio.open_connection( + self._host, self._port, + ) + logger.info("Connected to Speculos") + + async def disconnect(self) -> None: + if self._writer is not None: + self._writer.close() + try: + await self._writer.wait_closed() + except Exception: + pass + self._writer = None + self._reader = None + logger.info("Disconnected from Speculos") + + async def exchange(self, apdu: bytes) -> bytes: + """Exchange one APDU with Speculos and return data + status word. + + Auto-connects if the client is not yet connected. On + ConnectionError, OSError, or IncompleteReadError the client + disconnects, reconnects, and retries the exchange exactly once. + Send/receive timeouts are wrapped in SpeculosTimeoutError (after + tearing down the connection); a malformed or oversized response + raises SpeculosProtocolError and also disconnects. + """ + async with self._lock: + try: + if self._writer is None or self._reader is None: + await self.connect() + + await self._send(apdu) + return await self._recv() + except SpeculosProtocolError: + logger.error( + "Speculos protocol error (oversized or malformed response), " + "disconnecting" + ) + await self.disconnect() + raise + except asyncio.TimeoutError: + msg = ( + f"Speculos operation timed out after {self._timeout}s " + f"(APDU: {apdu.hex()})" + ) + logger.error(msg) + await self.disconnect() + raise SpeculosTimeoutError(msg) from None + except (ConnectionError, OSError, asyncio.IncompleteReadError): + logger.warning("Speculos connection lost, reconnecting") + await self.disconnect() + await self.connect() + await self._send(apdu) + return await self._recv() + + async def _send(self, apdu: bytes) -> None: + assert self._writer is not None + length_prefix = struct.pack(">I", len(apdu)) + self._writer.write(length_prefix + apdu) + await asyncio.wait_for(self._writer.drain(), timeout=self._timeout) + logger.debug("Sent APDU (%d bytes): %s", len(apdu), apdu.hex()) + + async def _recv(self) -> bytes: + assert self._reader is not None + length_data = await asyncio.wait_for( + self._reader.readexactly(4), timeout=self._timeout, + ) + raw_length = struct.unpack(">I", length_data)[0] + if raw_length > MAX_RESPONSE_SIZE: + raise SpeculosProtocolError( + f"Speculos declared a response length of {raw_length} bytes, " + f"which exceeds the maximum allowed {MAX_RESPONSE_SIZE} bytes" + ) + response = await asyncio.wait_for( + self._reader.readexactly(raw_length), timeout=self._timeout, + ) + sw = await asyncio.wait_for( + self._reader.readexactly(2), timeout=self._timeout, + ) + full_response = response + sw + logger.debug("Recv APDU (%d bytes): %s", len(full_response), full_response.hex()) + return full_response + + @property + def is_connected(self) -> bool: + return self._writer is not None and not self._writer.is_closing() diff --git a/packages/hw-emulator/python/speculos_ble/types.py b/packages/hw-emulator/python/speculos_ble/types.py new file mode 100644 index 000000000..496652ac1 --- /dev/null +++ b/packages/hw-emulator/python/speculos_ble/types.py @@ -0,0 +1,89 @@ +from __future__ import annotations + +import enum +from dataclasses import dataclass, field + + +LEDGER_SERVICE_UUID = "13d63400-2c97-0004-0000-4c6564676572" +LEDGER_WRITE_CHAR_UUID = "13d63400-2c97-0004-0002-4c6564676572" +LEDGER_NOTIFY_CHAR_UUID = "13d63400-2c97-0004-0001-4c6564676572" +LEDGER_WRITE_CMD_CHAR_UUID = "13d63400-2c97-0004-0003-4c6564676572" + +DEFAULT_DEVICE_NAME = "Ledger Nano X" +DEFAULT_SPECULOS_HOST = "127.0.0.1" +DEFAULT_SPECULOS_APDU_PORT = 9999 +DEFAULT_SPECULOS_API_PORT = 5000 +DEFAULT_CONTROL_API_PORT = 5002 + +BLE_TAG_ID = 0x05 +MTU_PROBE_BYTE = 0x08 +DEFAULT_MTU = 23 +LEDGER_REQUESTED_MTU = 156 +# Smallest MTU the Ledger BLE framing can carry: chunk-0 overhead +# (5 header bytes) + non-zero payload. +MIN_MTU = 7 + +VALID_BUTTONS = frozenset({"left", "right", "both"}) +MAX_BUTTON_PRESS_COUNT = 20 + +SIGNING_INS_BYTES = frozenset({ + 0x02, # GET_PUBLIC_KEY (used for derivation verification) + 0x04, # SIGN (legacy) + 0x08, # SIGN_PERSONAL_MESSAGE + 0x0C, # SIGN_TYPED_DATA (EIP-712) + 0x1A, # SIGN_EIP_712 (alternate) + 0x20, # SIGN_EIP_1559 (type 2 tx) + 0x22, # SIGN_EIP_2930 (type 1 tx) +}) + + +class ConnectionState(enum.Enum): + IDLE = "idle" + ADVERTISING = "advertising" + CONNECTING = "connecting" + CONNECTED = "connected" + EXCHANGING = "exchanging" + DISCONNECTING = "disconnecting" + + +@dataclass +class ApduLogEntry: + timestamp: float + direction: str + data: bytes + tag: str = "" + + +@dataclass +class VirtualLedgerConfig: + transport: str = "vhci" + device_name: str = DEFAULT_DEVICE_NAME + speculos_host: str = DEFAULT_SPECULOS_HOST + speculos_apdu_port: int = DEFAULT_SPECULOS_APDU_PORT + speculos_api_port: int = DEFAULT_SPECULOS_API_PORT + control_api_port: int = DEFAULT_CONTROL_API_PORT + auto_restart_advertising: bool = True + apdu_log_size: int = 100 + + +def validate_button_press(button: str, count: int) -> None: + """Validate button press arguments. + + @param button - Button name, must be one of VALID_BUTTONS. + @param count - Number of presses, an integer in [1, MAX_BUTTON_PRESS_COUNT]. + @raises ValueError if either argument is invalid. + """ + if not isinstance(button, str) or button not in VALID_BUTTONS: + raise ValueError( + f"Invalid button {button!r}: must be one of " + f"{', '.join(sorted(VALID_BUTTONS))}" + ) + if ( + not isinstance(count, int) + or isinstance(count, bool) + or not 1 <= count <= MAX_BUTTON_PRESS_COUNT + ): + raise ValueError( + f"Invalid count {count!r}: must be an integer between 1 and " + f"{MAX_BUTTON_PRESS_COUNT}" + ) diff --git a/packages/hw-emulator/scripts/setup-python.sh b/packages/hw-emulator/scripts/setup-python.sh new file mode 100755 index 000000000..e18215446 --- /dev/null +++ b/packages/hw-emulator/scripts/setup-python.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PKG_DIR="$(dirname "$SCRIPT_DIR")" +VENV_DIR="${SPECULOS_BLE_VENV_DIR:-$PKG_DIR/.venv}" + +PYTHON="" +for py in python3.13 python3.12 python3.11 python3.10 python3; do + if command -v "$py" &>/dev/null; then + PYTHON="$py" + break + fi +done + +if [ -z "$PYTHON" ]; then + echo "ERROR: No suitable Python found. Need Python 3.10-3.13." + exit 1 +fi + +echo "Using $PYTHON ($($PYTHON --version))" + +if [ -d "$VENV_DIR" ]; then + echo "Removing existing venv at $VENV_DIR" + rm -rf "$VENV_DIR" +fi + +$PYTHON -m venv "$VENV_DIR" +source "$VENV_DIR/bin/activate" +pip install --upgrade pip +pip install -e "$PKG_DIR[test]" +echo "speculos-ble installed. Activate with: source $VENV_DIR/bin/activate" diff --git a/packages/hw-emulator/scripts/start-android.sh b/packages/hw-emulator/scripts/start-android.sh new file mode 100755 index 000000000..82d13c0a6 --- /dev/null +++ b/packages/hw-emulator/scripts/start-android.sh @@ -0,0 +1,156 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PKG_DIR="$(dirname "$SCRIPT_DIR")" + +# Host-side port defaults are aligned with docker-compose.yml and the +# DEFAULT_DEVICE defaults in src/ledger/constants.ts (APDU 9998, API 5001), +# so all entry points expose Speculos on the same host ports. +SPECULOS_HOST="${SPECULOS_HOST:-127.0.0.1}" +SPECULOS_APDU_PORT="${SPECULOS_APDU_PORT:-9998}" +SPECULOS_API_PORT="${SPECULOS_API_PORT:-5001}" +CONTROL_API_PORT="${CONTROL_API_PORT:-5002}" +DEVICE_NAME="${DEVICE_NAME:-Ledger Nano X}" +TRANSPORT="${TRANSPORT:-android-netsim}" +VERBOSE="${VERBOSE:-}" + +SPECULOS_APP="${SPECULOS_APP:-ethereum}" +SPECULOS_MODEL="${SPECULOS_MODEL:-nanox}" + +# Look for ELF in hw-emulator package (via node_modules or sibling package dir) +ELF_PATH="" +HW_EMULATOR_DIRS=( + "${HW_EMULATOR_DIR:-}" + "${PKG_DIR}/../../node_modules/@metamask-previews/hw-emulator/apps" + "${PKG_DIR}/../../node_modules/@metamask/hw-emulator/apps" + "${PKG_DIR}/../hw-emulator/apps" +) +for dir in "${HW_EMULATOR_DIRS[@]}"; do + [ -z "$dir" ] && continue + if [ -d "$dir" ]; then + ELF_PATH="$(find "$dir" -name "${SPECULOS_APP}*.elf" 2>/dev/null | head -1)" + [ -n "$ELF_PATH" ] && break + fi +done + +if [ -z "$ELF_PATH" ]; then + echo "WARNING: Could not find $SPECULOS_APP ELF binary." + echo "Set HW_EMULATOR_DIR or install @metamask/hw-emulator." + echo "Will attempt to use Docker image's built-in app." +fi + +cleanup() { + echo "" + echo "Stopping processes..." + if [ -n "${SPECULOS_PID:-}" ]; then + # `docker run -d` was detached: killing the CLI PID does not stop the + # container. Stop and remove it so interrupted runs don't leak it. + docker stop speculos-ledger >/dev/null 2>&1 || true + docker rm speculos-ledger >/dev/null 2>&1 || true + fi + [ -n "${BLE_PID:-}" ] && kill "$BLE_PID" 2>/dev/null || true + wait 2>/dev/null +} +trap cleanup EXIT INT TERM + +if ! curl -sf "http://${SPECULOS_HOST}:${SPECULOS_API_PORT}/ping" >/dev/null 2>&1; then + echo "Starting Speculos..." + + if docker ps --format '{{.Names}}' | grep -q '^speculos-ledger$'; then + echo "Stopping existing speculos-ledger container..." + docker stop speculos-ledger >/dev/null 2>&1 || true + docker rm speculos-ledger >/dev/null 2>&1 || true + fi + + if [ -n "$ELF_PATH" ]; then + ELF_DIR="$(dirname "$ELF_PATH")" + ELF_NAME="$(basename "$ELF_PATH")" + docker run -d \ + --name speculos-ledger \ + -p "${SPECULOS_APDU_PORT}:9998" \ + -p "${SPECULOS_API_PORT}:5000" \ + -v "${ELF_DIR}:/apps:ro" \ + ghcr.io/ledgerhq/speculos \ + --model "$SPECULOS_MODEL" \ + --display headless \ + --apdu-port 9998 \ + --api-port 5000 \ + "/apps/${ELF_NAME}" \ + & + else + docker run -d \ + --name speculos-ledger \ + -p "${SPECULOS_APDU_PORT}:9998" \ + -p "${SPECULOS_API_PORT}:5000" \ + ghcr.io/ledgerhq/speculos \ + --model "$SPECULOS_MODEL" \ + --display headless \ + --apdu-port 9998 \ + --api-port 5000 \ + "apps/${SPECULOS_MODEL}/${SPECULOS_APP}.elf" \ + & + fi + SPECULOS_PID=$! + + echo "Waiting for Speculos API on :${SPECULOS_API_PORT}..." + for i in $(seq 1 30); do + if curl -sf "http://${SPECULOS_HOST}:${SPECULOS_API_PORT}/ping" >/dev/null 2>&1; then + break + fi + sleep 1 + done + + if ! curl -sf "http://${SPECULOS_HOST}:${SPECULOS_API_PORT}/ping" >/dev/null 2>&1; then + echo "ERROR: Speculos failed to start" + exit 1 + fi +fi + +echo "Speculos ready." + +VENV="${SPECULOS_BLE_VENV_DIR:-$PKG_DIR/.venv}" +if [ ! -d "$VENV" ]; then + echo "ERROR: Python venv not found at $VENV. Run scripts/setup-python.sh first." + exit 1 +fi +source "$VENV/bin/activate" + +echo "Starting speculos-ble (transport: $TRANSPORT)..." +VERBOSE_FLAG="" +[ -n "$VERBOSE" ] && VERBOSE_FLAG="-v" + +speculos-ble \ + --transport "$TRANSPORT" \ + --device-name "$DEVICE_NAME" \ + --speculos-host "$SPECULOS_HOST" \ + --speculos-apdu-port "$SPECULOS_APDU_PORT" \ + --speculos-api-port "$SPECULOS_API_PORT" \ + --control-api-port "$CONTROL_API_PORT" \ + $VERBOSE_FLAG \ + & +BLE_PID=$! + +echo "Waiting for Control API on :${CONTROL_API_PORT}..." +for i in $(seq 1 30); do + if curl -sf "http://${SPECULOS_HOST}:${CONTROL_API_PORT}/health" >/dev/null 2>&1; then + echo "speculos-ble ready." + break + fi + sleep 1 +done + +if ! curl -sf "http://${SPECULOS_HOST}:${CONTROL_API_PORT}/health" >/dev/null 2>&1; then + echo "ERROR: speculos-ble Control API failed to start" + exit 1 +fi + +echo "" +echo "=== Stack Running ===" +echo "Speculos API: http://${SPECULOS_HOST}:${SPECULOS_API_PORT}" +echo "Control API: http://${SPECULOS_HOST}:${CONTROL_API_PORT}" +echo "APDU TCP: ${SPECULOS_HOST}:${SPECULOS_APDU_PORT}" +echo "" +echo "Press Ctrl+C to stop." + +wait diff --git a/packages/hw-emulator/src/ble/index.ts b/packages/hw-emulator/src/ble/index.ts new file mode 100644 index 000000000..c70a67277 --- /dev/null +++ b/packages/hw-emulator/src/ble/index.ts @@ -0,0 +1,2 @@ +export { SpeculosBleRunner } from './speculos-ble-runner'; +export type { SpeculosBleConfig, SpeculosBleRunnerOptions } from './types'; diff --git a/packages/hw-emulator/src/ble/speculos-ble-runner.test.ts b/packages/hw-emulator/src/ble/speculos-ble-runner.test.ts new file mode 100644 index 000000000..5ad1d5acf --- /dev/null +++ b/packages/hw-emulator/src/ble/speculos-ble-runner.test.ts @@ -0,0 +1,286 @@ +/* eslint-disable n/no-sync -- synchronous fs is acceptable for temp-file test fixtures. */ +/* eslint-disable n/no-process-env -- tests read/write relocation env vars. */ +/* eslint-disable require-unicode-regexp -- pre-existing path regexes. */ +/* eslint-disable jest/no-restricted-matchers -- `.resolves`/`.rejects` are used for clarity. */ +import childProcess from 'child_process'; +import type { ChildProcess } from 'node:child_process'; +import { EventEmitter } from 'node:events'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; + +import { SpeculosBleRunner } from './speculos-ble-runner'; + +describe('SpeculosBleRunner', () => { + describe('static methods', () => { + it('resolves pythonDir to a path containing speculos_ble source', () => { + const dir = SpeculosBleRunner.pythonDir; + expect(dir).toContain('python'); + }); + + it('resolves packageDir to the package root', () => { + const dir = SpeculosBleRunner.packageDir; + expect(dir).not.toContain('dist'); + }); + + it('resolves venvPython to a .venv/bin/python path', () => { + const py = SpeculosBleRunner.venvPython; + expect(py).toMatch(/\.venv[\\/]bin[\\/]python$/); + }); + + it('isVenvReady returns a boolean', () => { + expect(typeof SpeculosBleRunner.isVenvReady()).toBe('boolean'); + }); + + it('honors SPECULOS_BLE_PACKAGE_DIR to relocate packageDir/pythonDir', () => { + const origPkg = process.env.SPECULOS_BLE_PACKAGE_DIR; + const origVenv = process.env.SPECULOS_BLE_VENV_DIR; + try { + process.env.SPECULOS_BLE_PACKAGE_DIR = '/tmp/fake-pkg'; + expect(SpeculosBleRunner.packageDir).toBe('/tmp/fake-pkg'); + expect(SpeculosBleRunner.pythonDir).toBe('/tmp/fake-pkg/python'); + // venv follows packageDir by default + expect(SpeculosBleRunner.venvPython).toBe( + '/tmp/fake-pkg/.venv/bin/python', + ); + } finally { + if (origPkg === undefined) { + delete process.env.SPECULOS_BLE_PACKAGE_DIR; + } else { + process.env.SPECULOS_BLE_PACKAGE_DIR = origPkg; + } + if (origVenv === undefined) { + delete process.env.SPECULOS_BLE_VENV_DIR; + } else { + process.env.SPECULOS_BLE_VENV_DIR = origVenv; + } + } + }); + + it('honors SPECULOS_BLE_VENV_DIR to relocate the venv independently', () => { + const origPkg = process.env.SPECULOS_BLE_PACKAGE_DIR; + const origVenv = process.env.SPECULOS_BLE_VENV_DIR; + try { + process.env.SPECULOS_BLE_PACKAGE_DIR = '/tmp/fake-pkg'; + process.env.SPECULOS_BLE_VENV_DIR = '/tmp/fake-venv'; + expect(SpeculosBleRunner.venvDir).toBe('/tmp/fake-venv'); + expect(SpeculosBleRunner.venvPython).toBe('/tmp/fake-venv/bin/python'); + } finally { + if (origPkg === undefined) { + delete process.env.SPECULOS_BLE_PACKAGE_DIR; + } else { + process.env.SPECULOS_BLE_PACKAGE_DIR = origPkg; + } + if (origVenv === undefined) { + delete process.env.SPECULOS_BLE_VENV_DIR; + } else { + process.env.SPECULOS_BLE_VENV_DIR = origVenv; + } + } + }); + }); + + describe('constructor', () => { + it('applies default configuration', () => { + const runner = new SpeculosBleRunner(); + expect(runner.host).toBe('127.0.0.1'); + expect(runner.controlApiPort).toBe(5002); + }); + + it('overrides defaults with provided options', () => { + const runner = new SpeculosBleRunner({ + speculosHost: '10.0.0.1', + controlApiPort: 9999, + }); + expect(runner.host).toBe('10.0.0.1'); + expect(runner.controlApiPort).toBe(9999); + }); + + it('accepts an onLog callback without error', () => { + const runner = new SpeculosBleRunner({ onLog: (): void => undefined }); + expect(runner).toBeInstanceOf(SpeculosBleRunner); + }); + }); + + describe('isRunning', () => { + it('returns false before start() is called', () => { + const runner = new SpeculosBleRunner(); + expect(runner.isRunning).toBe(false); + }); + }); + + describe('disconnectBle', () => { + it('does not throw when the control API is unreachable', async () => { + const runner = new SpeculosBleRunner({ controlApiPort: 1 }); + await expect(runner.disconnectBle()).resolves.not.toThrow(); + }); + }); + + describe('setupVenv', () => { + it('runs setup-python.sh via execFileSync without a shell', () => { + const fixtureDir = mkdtempSync(path.join(tmpdir(), 'ble-venv-')); + const scriptsDir = path.join(fixtureDir, 'scripts'); + mkdirSync(scriptsDir); + writeFileSync(path.join(scriptsDir, 'setup-python.sh'), '#!/bin/sh\n', { + mode: 0o755, + }); + + const execFileSyncSpy = jest + .spyOn(childProcess, 'execFileSync') + .mockReturnValue(''); + + const origDir = process.env.SPECULOS_BLE_PACKAGE_DIR; + try { + process.env.SPECULOS_BLE_PACKAGE_DIR = fixtureDir; + SpeculosBleRunner.setupVenv(); + + expect(execFileSyncSpy).toHaveBeenCalledTimes(1); + expect(execFileSyncSpy).toHaveBeenCalledWith( + 'bash', + [path.join(fixtureDir, 'scripts', 'setup-python.sh')], + { stdio: 'inherit' }, + ); + } finally { + if (origDir === undefined) { + delete process.env.SPECULOS_BLE_PACKAGE_DIR; + } else { + process.env.SPECULOS_BLE_PACKAGE_DIR = origDir; + } + execFileSyncSpy.mockRestore(); + rmSync(fixtureDir, { recursive: true, force: true }); + } + }); + }); + + describe('isControlApiReady', () => { + const originalFetch = global.fetch; + + afterEach(() => { + global.fetch = originalFetch; + jest.useRealTimers(); + }); + + it('clears the abort timer when the fetch rejects', async () => { + jest.useFakeTimers(); + global.fetch = jest + .fn() + .mockRejectedValue( + new Error('network down'), + ) as unknown as typeof fetch; + + const runner = new SpeculosBleRunner(); + await expect(runner.isControlApiReady()).resolves.toBe(false); + + expect(jest.getTimerCount()).toBe(0); + }); + + it('clears the abort timer when the API reports ready', async () => { + jest.useFakeTimers(); + global.fetch = jest.fn().mockResolvedValue({ + ok: true, + json: async () => ({ status: 'ready' }), + }) as unknown as typeof fetch; + + const runner = new SpeculosBleRunner(); + await expect(runner.isControlApiReady()).resolves.toBe(true); + + expect(jest.getTimerCount()).toBe(0); + }); + }); + + describe('stop', () => { + function createFakeChildProcess(): ChildProcess & { + emitExit: () => void; + } { + const emitter = new EventEmitter(); + const fake = emitter as unknown as ChildProcess & { + emitExit: () => void; + }; + // eslint-disable-next-line jest/prefer-spy-on -- kill does not exist on the EventEmitter. + fake.kill = jest.fn(); + // Mark the process as still running (exitCode/signalCode are null until + // the process exits) so stop() actually attempts to signal it. + Object.assign(fake, { exitCode: null, signalCode: null }); + fake.emitExit = (): void => { + emitter.emit('exit', 0, 'SIGTERM'); + }; + return fake; + } + + function createVenv(): string { + const dir = mkdtempSync(path.join(tmpdir(), 'ble-run-')); + const bin = path.join(dir, 'bin'); + mkdirSync(bin); + writeFileSync(path.join(bin, 'python'), '#!/bin/sh\n', { mode: 0o755 }); + return dir; + } + + afterEach(() => { + jest.restoreAllMocks(); + jest.useRealTimers(); + }); + + it('resolves without throwing when the child process already exited', async () => { + const venvDir = createVenv(); + const origVenv = process.env.SPECULOS_BLE_VENV_DIR; + try { + process.env.SPECULOS_BLE_VENV_DIR = venvDir; + const fake = createFakeChildProcess(); + // kill() throws, simulating an already-exited process. + (fake.kill as jest.Mock).mockImplementation(() => { + throw new Error('process already exited'); + }); + jest + .spyOn(childProcess, 'spawn') + .mockReturnValue(fake as unknown as ChildProcess); + + const runner = new SpeculosBleRunner(); + runner.start(); + + await expect(runner.stop()).resolves.not.toThrow(); + expect(runner.isRunning).toBe(false); + } finally { + if (origVenv === undefined) { + delete process.env.SPECULOS_BLE_VENV_DIR; + } else { + // eslint-disable-next-line require-atomic-updates -- env save/restore test fixture. + process.env.SPECULOS_BLE_VENV_DIR = origVenv; + } + rmSync(venvDir, { recursive: true, force: true }); + } + }); + + it('clears the SIGKILL timer when the process exits gracefully', async () => { + jest.useFakeTimers(); + const venvDir = createVenv(); + const origVenv = process.env.SPECULOS_BLE_VENV_DIR; + try { + process.env.SPECULOS_BLE_VENV_DIR = venvDir; + const fake = createFakeChildProcess(); + jest + .spyOn(childProcess, 'spawn') + .mockReturnValue(fake as unknown as ChildProcess); + + const runner = new SpeculosBleRunner(); + runner.start(); + + const stopPromise = runner.stop(); + // The process exits before the 5s SIGKILL fallback fires. + fake.emitExit(); + await stopPromise; + + expect(fake.kill).toHaveBeenCalledWith('SIGTERM'); + // No dangling SIGKILL timer remains. + expect(jest.getTimerCount()).toBe(0); + } finally { + if (origVenv === undefined) { + delete process.env.SPECULOS_BLE_VENV_DIR; + } else { + // eslint-disable-next-line require-atomic-updates -- env save/restore test fixture. + process.env.SPECULOS_BLE_VENV_DIR = origVenv; + } + rmSync(venvDir, { recursive: true, force: true }); + } + }); + }); +}); diff --git a/packages/hw-emulator/src/ble/speculos-ble-runner.ts b/packages/hw-emulator/src/ble/speculos-ble-runner.ts new file mode 100644 index 000000000..f5bdf15bc --- /dev/null +++ b/packages/hw-emulator/src/ble/speculos-ble-runner.ts @@ -0,0 +1,332 @@ +// eslint-disable-next-line import-x/no-nodejs-modules +import { execFileSync, spawn } from 'node:child_process'; +// eslint-disable-next-line import-x/no-nodejs-modules +import type { ChildProcess } from 'node:child_process'; +// eslint-disable-next-line import-x/no-nodejs-modules +import { existsSync } from 'node:fs'; +// eslint-disable-next-line import-x/no-nodejs-modules +import { dirname, join, resolve } from 'node:path'; + +import type { + SpeculosBleConfig, + SpeculosBleLogStream, + SpeculosBleRunnerOptions, +} from './types'; + +const DEFAULT_CONFIG: SpeculosBleConfig = { + speculosHost: '127.0.0.1', + speculosApduPort: 9998, + speculosApiPort: 5001, + controlApiPort: 5002, + deviceName: 'Ledger Nano X', + transport: 'android-netsim', + verbose: false, +}; + +/** + * Manages the lifecycle of the speculos-ble Python service. + * + * This TypeScript wrapper provides a programmatic API for starting, + * monitoring, and stopping the BLE bridge process that emulates a + * Bluetooth Ledger device using Speculos. + * + * The Python source lives under `python/` in this package. The + * virtual environment is created at `.venv/` by running + * `scripts/setup-python.sh`. + */ +export class SpeculosBleRunner { + readonly #config: SpeculosBleConfig; + + readonly #onLog: + | ((line: string, stream: SpeculosBleLogStream) => void) + | undefined; + + #childProcess: ChildProcess | undefined; + + /** + * Resolve the package root directory. + * + * Defaults to the directory two levels above the compiled output + * (`dist/ble/` → package root). Override with the `SPECULOS_BLE_PACKAGE_DIR` + * environment variable so the runner can locate `python/`, `scripts/`, + * and the venv even when the package has been copied into a consumer's + * `node_modules` (e.g. via a Yarn `file:` resolution), where the relative + * resolution would point at the copy rather than the source of truth. + * + * @returns The resolved package root directory. + */ + static get packageDir(): string { + // eslint-disable-next-line no-restricted-globals + const envDir = process.env.SPECULOS_BLE_PACKAGE_DIR; + return envDir + ? resolve(envDir) + : // eslint-disable-next-line no-restricted-globals + dirname(dirname(__dirname)); + } + + /** + * Resolve the Python source directory (`/python`). + * + * @returns The resolved Python source directory. + */ + static get pythonDir(): string { + return join(SpeculosBleRunner.packageDir, 'python'); + } + + /** + * Resolve the virtualenv directory. + * + * Defaults to `/.venv`. Override with the + * `SPECULOS_BLE_VENV_DIR` environment variable (mirrors + * `scripts/setup-python.sh`) to keep the venv at a stable location + * independent of where the package is resolved. + * + * @returns The resolved virtualenv directory. + */ + static get venvDir(): string { + // eslint-disable-next-line no-restricted-globals + const envVenv = process.env.SPECULOS_BLE_VENV_DIR; + return envVenv + ? resolve(envVenv) + : join(SpeculosBleRunner.packageDir, '.venv'); + } + + /** + * Path to the Python venv interpreter. + * + * @returns The path to the venv's Python interpreter. + */ + static get venvPython(): string { + return join(SpeculosBleRunner.venvDir, 'bin', 'python'); + } + + /** + * Check whether the Python venv has been created. + * + * @returns True if the venv interpreter exists. + */ + static isVenvReady(): boolean { + return existsSync(SpeculosBleRunner.venvPython); + } + + /** + * Run `scripts/setup-python.sh` to create the venv. + * + * The script path is passed as a dedicated argument to `bash` via + * `execFileSync` (no shell) so it is never subject to shell interpolation. + */ + static setupVenv(): void { + const script = join( + SpeculosBleRunner.packageDir, + 'scripts', + 'setup-python.sh', + ); + execFileSync('bash', [script], { stdio: 'inherit' }); + } + + constructor(options: SpeculosBleRunnerOptions = {}) { + this.#config = { ...DEFAULT_CONFIG, ...options }; + this.#onLog = options.onLog; + } + + /** + * Speculos host. + * + * @returns The configured Speculos host. + */ + get host(): string { + return this.#config.speculosHost; + } + + /** + * Control API port. + * + * @returns The configured Control API port. + */ + get controlApiPort(): number { + return this.#config.controlApiPort; + } + + /** + * Whether the child process is still running. + * + * @returns True if the child process has not exited. + */ + get isRunning(): boolean { + return this.#childProcess?.exitCode === null; + } + + /** + * Start the BLE bridge Python service. + * + * @returns The spawned child process. + * @throws If the venv is not ready. + */ + start(): ChildProcess { + if (!SpeculosBleRunner.isVenvReady()) { + throw new Error( + 'Python venv not found. Run `SpeculosBleRunner.setupVenv()` or `scripts/setup-python.sh` first.', + ); + } + + const args = [ + '-m', + 'speculos_ble', + '--transport', + this.#config.transport, + '--device-name', + this.#config.deviceName, + '--speculos-host', + this.#config.speculosHost, + '--speculos-apdu-port', + String(this.#config.speculosApduPort), + '--speculos-api-port', + String(this.#config.speculosApiPort), + '--control-api-port', + String(this.#config.controlApiPort), + ]; + + if (this.#config.verbose) { + args.push('-v'); + } + + this.#childProcess = spawn(SpeculosBleRunner.venvPython, args, { + cwd: SpeculosBleRunner.pythonDir, + stdio: ['ignore', 'pipe', 'pipe'], + env: { + // eslint-disable-next-line no-restricted-globals + ...process.env, + VIRTUAL_ENV: SpeculosBleRunner.venvDir, + }, + }); + + const proc = this.#childProcess; + const onLog = this.#onLog; + if (onLog) { + proc.stdout?.on('data', (data: Buffer) => { + const line = data.toString().trim(); + if (line) { + onLog(line, 'stdout'); + } + }); + proc.stderr?.on('data', (data: Buffer) => { + const line = data.toString().trim(); + if (line) { + onLog(line, 'stderr'); + } + }); + proc.on('error', (error: Error) => { + onLog(error.message, 'error'); + }); + proc.on('exit', (code: number | null, signal: string | null) => { + onLog(`exited code=${code} signal=${signal}`, 'exit'); + }); + } + + return this.#childProcess; + } + + /** + * Stop the BLE bridge service gracefully (SIGTERM, then SIGKILL after 5s). + * + * Killing a process that already exited throws, so both signals are + * best-effort and an already-exited process is a no-op. + */ + async stop(): Promise { + const proc = this.#childProcess; + if (!proc) { + return; + } + this.#childProcess = undefined; + + // Already exited — nothing to terminate or wait for. + if (proc.exitCode !== null || proc.signalCode !== null) { + return; + } + + try { + proc.kill('SIGTERM'); + } catch { + // Already exited. + return; + } + + await new Promise((resolveExit) => { + const killTimer = setTimeout(() => { + try { + proc.kill('SIGKILL'); + } catch { + // Already exited. + } + resolveExit(); + }, 5_000); + proc.once('exit', () => { + clearTimeout(killTimer); + resolveExit(); + }); + }); + } + + /** + * Check whether the Control API is responding and reports `ready`. + * + * The abort timer is always cleared, including when the fetch rejects, so + * no timer is leaked. + * + * @returns True if the Control API reports `ready`. + */ + async isControlApiReady(): Promise { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 2_000); + try { + const resp = await fetch( + `http://${this.#config.speculosHost}:${this.#config.controlApiPort}/health`, + { signal: controller.signal }, + ); + if (!resp.ok) { + return false; + } + const json = (await resp.json()) as { status: string }; + return json.status === 'ready'; + } catch { + return false; + } finally { + clearTimeout(timeout); + } + } + + /** + * Poll the Control API until it is ready or the retry budget is exhausted. + * + * @param maxRetries - Maximum number of polling attempts. + * @param delayMs - Delay between attempts in milliseconds. + * @throws If the Control API does not become ready in time. + */ + async waitForControlApi(maxRetries = 30, delayMs = 2_000): Promise { + for (let i = 0; i < maxRetries; i++) { + if (await this.isControlApiReady()) { + return; + } + await new Promise((resolveDelay) => { + setTimeout(resolveDelay, delayMs); + }); + } + throw new Error( + `Control API not ready at ${this.#config.speculosHost}:${this.#config.controlApiPort} after ${maxRetries} retries`, + ); + } + + /** + * Disconnect any active BLE connections via the Control API. + */ + async disconnectBle(): Promise { + try { + await fetch( + `http://${this.#config.speculosHost}:${this.#config.controlApiPort}/ble/disconnect`, + { method: 'POST' }, + ); + } catch { + // Best effort + } + } +} diff --git a/packages/hw-emulator/src/ble/types.ts b/packages/hw-emulator/src/ble/types.ts new file mode 100644 index 000000000..0afb6c454 --- /dev/null +++ b/packages/hw-emulator/src/ble/types.ts @@ -0,0 +1,37 @@ +/** + * Configuration options for the Speculos BLE bridge service. + */ +export type SpeculosBleConfig = { + /** Host where Speculos is running. */ + speculosHost: string; + /** Speculos APDU TCP port. */ + speculosApduPort: number; + /** Speculos HTTP API port. */ + speculosApiPort: number; + /** Control API port for the BLE bridge. */ + controlApiPort: number; + /** BLE device name advertised to the scanner. */ + deviceName: string; + /** Transport mode (e.g. `android-netsim`, `vhci`). */ + transport: string; + /** Enable verbose logging. */ + verbose: boolean; +}; + +/** + * The BLE process stream (or lifecycle event) that produced a log line. + */ +export type SpeculosBleLogStream = 'stdout' | 'stderr' | 'exit' | 'error'; + +/** + * Options for constructing a {@link SpeculosBleRunner}. + * All fields are optional; defaults are applied. + */ +export type SpeculosBleRunnerOptions = Partial & { + /** + * Optional sink for BLE process output and lifecycle events. + * When omitted, stdout/stderr/exit/error are silently dropped. + * Useful for wiring the runner into a host logger (e.g. Detox test logger). + */ + onLog?: (line: string, stream: SpeculosBleLogStream) => void; +}; diff --git a/packages/hw-emulator/src/factory.test.ts b/packages/hw-emulator/src/factory.test.ts new file mode 100644 index 000000000..88c014cd7 --- /dev/null +++ b/packages/hw-emulator/src/factory.test.ts @@ -0,0 +1,111 @@ +import { createEmulator } from './factory'; +import type { TrezorEmulatorOptions } from './trezor'; +import type { TrezorDockerManager } from './trezor'; +import type { TrezorControllerClient } from './trezor'; +import type { TrezorSidecarManager } from './trezor'; +import { EmulatorType } from './types'; +import type { EmulatorType as EmulatorTypeValue } from './types'; + +describe('createEmulator', () => { + it('creates a Ledger emulator', () => { + const emu = createEmulator(EmulatorType.Ledger); + expect(emu).toBeDefined(); + expect(emu.isRunning()).toBe(false); + }); + + it('creates a Ledger emulator with options', () => { + const emu = createEmulator(EmulatorType.Ledger, { device: 'nanosp' }); + expect(emu).toBeDefined(); + expect(emu.isRunning()).toBe(false); + }); + + it('creates a Ledger emulator from an EmulatorType value', () => { + const type: EmulatorTypeValue = EmulatorType.Ledger; + + const emu = createEmulator(type); + + expect(emu).toBeDefined(); + expect(emu.isRunning()).toBe(false); + }); + + it('creates a Trezor emulator with mock injections', () => { + const emu = createEmulator(EmulatorType.Trezor, { + docker: { start: jest.fn(), stop: jest.fn() }, + controller: { + connect: jest.fn(), + disconnect: jest.fn(), + ping: jest.fn(), + emulatorStart: jest.fn(), + emulatorSetup: jest.fn(), + bridgeStart: jest.fn(), + pressYes: jest.fn(), + pressNo: jest.fn(), + click: jest.fn(), + swipe: jest.fn(), + input: jest.fn(), + getScreenshot: jest.fn(), + }, + sidecarManager: { + start: jest.fn(), + stop: jest.fn(), + isRunning: () => false, + }, + } as Record); + expect(emu).toBeDefined(); + expect(emu.isRunning()).toBe(false); + }); + + it('creates a Trezor emulator from typed TrezorEmulatorOptions', () => { + const options: TrezorEmulatorOptions = { + model: 'T2T1', + seed: 'test seed words', + label: 'test trezor', + docker: { + start: jest.fn(), + stop: jest.fn(), + } as unknown as TrezorDockerManager, + controller: { + connect: jest.fn(), + disconnect: jest.fn(), + ping: jest.fn(), + emulatorStart: jest.fn(), + emulatorSetup: jest.fn(), + bridgeStart: jest.fn(), + pressYes: jest.fn(), + pressNo: jest.fn(), + click: jest.fn(), + swipe: jest.fn(), + input: jest.fn(), + getScreenshot: jest.fn(), + } as unknown as TrezorControllerClient, + sidecarManager: { + start: jest.fn(), + stop: jest.fn(), + isRunning: () => false, + } as TrezorSidecarManager, + }; + + // This resolves through the Trezor-specific overload (no `unknown` cast). + const emu = createEmulator(EmulatorType.Trezor, options); + expect(emu).toBeDefined(); + expect(emu.isRunning()).toBe(false); + }); + + it('throws for unknown emulator type', () => { + expect(() => + createEmulator('unknown' as typeof EmulatorType.Ledger), + ).toThrow('Unknown emulator type'); + }); + + it('returns an emulator with the HardwareWalletEmulator interface', () => { + const emu = createEmulator(EmulatorType.Ledger); + expect(typeof emu.start).toBe('function'); + expect(typeof emu.stop).toBe('function'); + expect(typeof emu.isRunning).toBe('function'); + expect(typeof emu.getInteraction).toBe('function'); + expect(typeof emu.approveTransaction).toBe('function'); + expect(typeof emu.approveSigning).toBe('function'); + expect(typeof emu.rejectTransaction).toBe('function'); + expect(typeof emu.navigateToMainMenu).toBe('function'); + }); +}); diff --git a/packages/hw-emulator/src/factory.ts b/packages/hw-emulator/src/factory.ts new file mode 100644 index 000000000..838330635 --- /dev/null +++ b/packages/hw-emulator/src/factory.ts @@ -0,0 +1,53 @@ +import type { SpeculosOptions } from './ledger/speculos'; +import { Speculos } from './ledger/speculos'; +import type { QrEmulatorOptions } from './qr'; +import { QrEmulator } from './qr'; +import type { TrezorEmulatorOptions } from './trezor'; +import { TrezorEmulator } from './trezor'; +import { EmulatorType } from './types'; +import type { + EmulatorType as EmulatorTypeValue, + HardwareWalletEmulator, +} from './types'; + +export type { HardwareWalletEmulator, DeviceInteraction } from './types'; + +/** + * Create a hardware wallet emulator instance. + * + * @param type - The emulator type to create. + * @param options - Emulator-specific configuration options. + * @returns A HardwareWalletEmulator instance. + * @throws If the emulator type is not supported. + */ +export function createEmulator( + type: typeof EmulatorType.Ledger, + options?: SpeculosOptions, +): HardwareWalletEmulator; +export function createEmulator( + type: typeof EmulatorType.Qr, + options?: QrEmulatorOptions, +): HardwareWalletEmulator; +export function createEmulator( + type: typeof EmulatorType.Trezor, + options?: TrezorEmulatorOptions, +): HardwareWalletEmulator; +export function createEmulator( + type: EmulatorTypeValue, + options?: Record, +): HardwareWalletEmulator; +export function createEmulator( + type: EmulatorTypeValue, + options?: Record, +): HardwareWalletEmulator { + switch (type) { + case EmulatorType.Ledger: + return new Speculos(options as SpeculosOptions); + case EmulatorType.Qr: + return new QrEmulator(options as QrEmulatorOptions); + case EmulatorType.Trezor: + return new TrezorEmulator(options as TrezorEmulatorOptions); + default: + throw new Error(`Unknown emulator type: ${String(type)}`); + } +} diff --git a/packages/hw-emulator/src/index.ts b/packages/hw-emulator/src/index.ts new file mode 100644 index 000000000..418606287 --- /dev/null +++ b/packages/hw-emulator/src/index.ts @@ -0,0 +1,129 @@ +export { + EmulatorType, + type HardwareWalletEmulator, + type DeviceInteraction, +} from './types'; + +export { createEmulator } from './factory'; + +export { + Speculos, + type SpeculosOptions, + SpeculosClient, + type SpeculosClientOptions, + type APDUResponse, + ApduBridge, + createDeviceInteraction, + NanoInteraction, + TouchInteraction, + type DeviceInteraction as LedgerDeviceInteraction, + createProcessManager, + type ProcessManager, + type ProcessManagerOptions, + type ProcessManagerStatus, + DockerManager, + type DockerManagerOptions, + type DockerManagerStatus, + getWebHidMockScript, + DEVICE_MODELS, + DEFAULT_DEVICE_MODEL, + DEFAULT_DEVICE, + DEVICE_PRESETS, + SPECULOS_APDU_PORT, + SPECULOS_API_PORT, + SPECULOS_WS_BRIDGE_PORT, + SPECULOS_LEDGER_ADDRESSES, + SPECULOS_LEDGER_ADDRESS, + SPECULOS_SEED, + getDeviceModel, + detectRunMode, + type DeviceModel, + type DeviceConfig, + type InteractionType, + type RunMode, + withRetry, + ExponentialBackoff, + isRetryableError, + createLedgerHidFramingSession, + pushLedgerHidFrame, + encodeLedgerHidResponse, + type LedgerHidFramingSession, +} from './ledger'; + +export { + SpeculosBleRunner, + type SpeculosBleConfig, + type SpeculosBleRunnerOptions, +} from './ble'; + +export { + QrEmulator, + type QrEmulatorOptions, + type QrKeyringBridge, + type QrScanRequest, + type QrSignatureRequest, + QrScanRequestType, + type QrPairMode, + type SerializedUR, + synthesizeAccountUR, + buildCryptoAccountUR, + buildCryptoHDKeyUR, + deriveAccountAddress, + deriveKey, + signRequest, + decodeSignRequest, + derivePrivateKey, + parseXfp, + pathToComponents, + createKeypath, + createCryptoHDKey, + createCryptoOutput, + createCryptoAccount, + encodeToFragments, + createEncoder, + FragmentDecoder, + decodeFragments, + renderQrPng, + renderUrToY4m, + ensureFfmpegAvailable, + isFfmpegAvailable, + FfmpegUnavailableError, + decodeQrImage, + decodeQrScreenshots, + QR_EMULATOR_SEED, + QR_EMULATOR_ROOT_DERIVATION_PATH, + QR_EMULATOR_ACCOUNT_PATH, + QR_EMULATOR_CHILDREN_PATH, + QR_EMULATOR_ACCOUNT_DERIVATION_PATH, + QR_EMULATOR_DEFAULT_XFP, + QR_EMULATOR_ADDRESS, + QR_FRAGMENT_SIZE, + QR_REFRESH_MS, + QR_CODE_SIZE_PX, + QR_UPPERCASE, +} from './qr'; + +export { + TrezorEmulator, + type TrezorEmulatorOptions, + TrezorControllerClient, + type ControllerClientOptions, + type SetupParams, + createSidecarManager, + type TrezorSidecarManager, + type SidecarManagerOptions, + getTrezorConnectSrcInjectionScript, + TrezorDockerManager, + TrezorDeviceInteraction, + type DeviceInteraction as TrezorDeviceInteractionType, + MODEL_PROFILES, + type TrezorModel, + type ModelProfile, + TREZOR_EMULATOR_SEED, + TREZOR_DEFAULT_MODEL, + TREZOR_CONNECT_SRC, + TREZOR_TRANSPORT_BRIDGE_PORT, + TREZOR_CONTROLLER_PORT, + TREZOR_EMULATOR_PORT, + TREZOR_MSG, +} from './trezor'; diff --git a/packages/hw-emulator/src/ledger/apdu-bridge.test.ts b/packages/hw-emulator/src/ledger/apdu-bridge.test.ts new file mode 100644 index 000000000..ef7002782 --- /dev/null +++ b/packages/hw-emulator/src/ledger/apdu-bridge.test.ts @@ -0,0 +1,478 @@ +import type { WebSocket as WsWebSocket } from 'ws'; +import { WebSocket as WsWebSocketClass } from 'ws'; + +import { ApduBridge } from './apdu-bridge'; +import { SpeculosClient } from './client'; +import * as ledgerHidFraming from './ledger-hid-framing'; +import type { LedgerHidFramingSession } from './ledger-hid-framing'; + +// Capture every WebSocketServer instance created by the module under test so +// tests can emit server events directly. The real implementation is preserved. +jest.mock('ws', () => { + const actual = jest.requireActual('ws'); + const instances: unknown[] = []; + class CapturingWebSocketServer extends actual.WebSocketServer { + constructor(...args: ConstructorParameters) { + super(...args); + instances.push(this); + } + } + return { + ...actual, + WebSocketServer: CapturingWebSocketServer, + __testInstances: instances, + }; +}); + +/** The subset of a WebSocketServer used by the tests. */ +type CapturedWsServer = { + address: () => { port: number } | string | null; + emit: (event: string | symbol, ...args: unknown[]) => boolean; +}; + +/** + * Create a mock WebSocket connection. + * + * @returns The mock WebSocket. + */ +function createMockWebSocket(): WsWebSocket { + return { send: jest.fn() } as unknown as WsWebSocket; +} + +describe('ApduBridge', () => { + describe('constructor', () => { + it('creates an instance with client and port', () => { + const client = new SpeculosClient(); + const bridge = new ApduBridge(client, 9876); + expect(bridge.getPort()).toBe(9876); + }); + + it('returns the client', () => { + const client = new SpeculosClient(); + const bridge = new ApduBridge(client, 9876); + expect(bridge.getClient()).toBe(client); + }); + }); + + describe('start and stop', () => { + it('starts and stops the WebSocket server', async () => { + const client = new SpeculosClient(); + const bridge = new ApduBridge(client, 0); + await bridge.start(); + expect(bridge.getPort()).toBe(0); + await bridge.stop(); + }); + + it('stop resolves when not started', async () => { + const client = new SpeculosClient(); + const bridge = new ApduBridge(client, 9877); + await bridge.stop(); + expect(true).toBe(true); + }); + + it('rejects start when the port is already in use', async () => { + const firstBridge = new ApduBridge(new SpeculosClient(), 0); + await firstBridge.start(); + + const firstAddress = getCapturedServers().at(-1)?.address(); + const port = + firstAddress && typeof firstAddress === 'object' + ? firstAddress.port + : 0; + + const secondBridge = new ApduBridge(new SpeculosClient(), port); + await expect(secondBridge.start()).rejects.toThrow('EADDRINUSE'); + + await firstBridge.stop(); + // The failed bridge cleaned up its reference, so stop is a no-op. + await secondBridge.stop(); + }); + + it('routes post-listening server errors to console.error instead of the settled start promise', async () => { + const bridge = new ApduBridge(new SpeculosClient(), 0); + const logSpy = jest + .spyOn(console, 'log') + .mockImplementation(() => undefined); + await bridge.start(); + const server = getCapturedServers().at(-1); + expect(server).toBeDefined(); + + const errorSpy = jest + .spyOn(console, 'error') + .mockImplementation(() => undefined); + try { + server?.emit('error', new Error('late server failure')); + expect(errorSpy).toHaveBeenCalledWith( + expect.stringContaining('late server failure'), + ); + } finally { + errorSpy.mockRestore(); + logSpy.mockRestore(); + await bridge.stop(); + } + }); + + it('replies with an error for non-JSON messages', async () => { + const bridge = new ApduBridge(new SpeculosClient(), 0); + await bridge.start(); + const address = getCapturedServers().at(-1)?.address(); + const port = address && typeof address === 'object' ? address.port : 0; + expect(port).not.toBe(0); + + const ws = new WsWebSocketClass(`ws://127.0.0.1:${port}`); + const received = new Promise((resolve) => { + ws.on('message', (data: Buffer) => { + resolve(data.toString()); + }); + }); + ws.on('open', () => { + ws.send('this is not json'); + }); + + const message = await received; + expect(message).toContain('APDU_ERROR'); + expect(message).toContain('Invalid JSON message'); + + ws.close(); + await bridge.stop(); + }); + }); + + describe('injectNextErrorResponse', () => { + afterEach(() => { + jest.restoreAllMocks(); + }); + + it('does not throw', () => { + const client = new SpeculosClient(); + const bridge = new ApduBridge(client, 9878); + expect(() => bridge.injectNextErrorResponse(0x6d00)).not.toThrow(); + }); + + it('applies the injected error to the next exchange by default', async () => { + const { bridge, exchangeMock, encodeMock } = setupHandleHidSendTest([ + Buffer.from([0xe0, 0x02, 0x00, 0x00, 0x00]), + ]); + + bridge.injectNextErrorResponse(0x6982); + await bridge.handleHidSend(createMockWebSocket(), { id: 1, data: [] }); + + expect(exchangeMock).toHaveBeenCalledTimes(1); + expect(encodeMock.mock.calls[0]?.[1]).toStrictEqual( + Buffer.from([0x69, 0x82]), + ); + }); + + it('keeps the injection queued until an APDU matches the matcher', async () => { + const { bridge, exchangeMock, encodeMock } = setupHandleHidSendTest([ + Buffer.from([0xe0, 0x02, 0x00, 0x00, 0x00]), + Buffer.from([0xe0, 0x08, 0x00, 0x00, 0x00]), + ]); + + bridge.injectNextErrorResponse(0x6d00, (apdu) => apdu[1] === 0x08); + + // Non-matching exchange: real response passes through. + await bridge.handleHidSend(createMockWebSocket(), { id: 1, data: [] }); + expect(encodeMock.mock.calls[0]?.[1]).toStrictEqual( + Buffer.from([0x41, 0x42, 0x90, 0x00]), + ); + + // Matching exchange: injected error replaces the response. + await bridge.handleHidSend(createMockWebSocket(), { id: 2, data: [] }); + expect(exchangeMock).toHaveBeenCalledTimes(2); + expect(encodeMock.mock.calls[1]?.[1]).toStrictEqual( + Buffer.from([0x6d, 0x00]), + ); + }); + }); + + describe('parseTxPayloadLength RLP prefix ranges', () => { + const bridge = new ApduBridge(new SpeculosClient(), 0); + + /** + * Build a first sign-transaction chunk payload with one derivation path. + * + * @param rlp - The RLP-encoded transaction bytes. + * @returns The chunk payload (path count + path + RLP data). + */ + const makeFirstChunk = (rlp: number[]): Buffer => + Buffer.from([1, 0xde, 0xad, 0xbe, 0xef, ...rlp]); + + it('treats a single-byte RLP value (0x00) as a 1-byte payload', () => { + expect(bridge.parseTxPayloadLength(makeFirstChunk([0x00]))).toBe(6); + }); + + it('treats a single-byte RLP value (0x7f) as a 1-byte payload', () => { + expect(bridge.parseTxPayloadLength(makeFirstChunk([0x7f]))).toBe(6); + }); + + it('does not skip into the next byte for single-byte values', () => { + // With the old bug, 0x7f skipped the prefix and decoded the following + // 0x01 as another single-byte value, overcounting by one. + expect(bridge.parseTxPayloadLength(makeFirstChunk([0x7f, 0x01]))).toBe(6); + }); + + it('parses short string prefixes (0x80–0xb7)', () => { + // Empty string: header 0x80, length 0 → 4 (path) + 1 + 1 + 0. + expect(bridge.parseTxPayloadLength(makeFirstChunk([0x80]))).toBe(6); + // 0xb7: header 1 byte, payload 55 bytes. + expect( + bridge.parseTxPayloadLength(makeFirstChunk([0xb7, ...filler(55)])), + ).toBe(61); + }); + + it('parses long string prefixes (0xb8+)', () => { + // 0xb8 with 1-byte length: header 2 bytes, payload 1 byte. + expect( + bridge.parseTxPayloadLength(makeFirstChunk([0xb8, 0x01, 0xaa])), + ).toBe(8); + // 0xb8 with 1-byte length 0xff: header 2 bytes, payload 255 bytes. + expect( + bridge.parseTxPayloadLength( + makeFirstChunk([0xb8, 0xff, ...filler(255)]), + ), + ).toBe(262); + }); + + it('parses short list prefixes (0xc0–0xf7)', () => { + // Empty list: header 0xc0, length 0. + expect(bridge.parseTxPayloadLength(makeFirstChunk([0xc0]))).toBe(6); + // 0xf7: header 1 byte, payload 55 bytes (0xf7 - 0xc0). + expect( + bridge.parseTxPayloadLength(makeFirstChunk([0xf7, ...filler(55)])), + ).toBe(61); + }); + + it('parses long list prefixes (0xf8+)', () => { + // 0xf8 with 1-byte length 0x64: header 2 bytes, payload 100 bytes. + expect( + bridge.parseTxPayloadLength( + makeFirstChunk([0xf8, 0x64, ...filler(100)]), + ), + ).toBe(107); + }); + + it('returns null for incomplete length-of-length data', () => { + // 0xf8 requires a length byte that is missing here. + expect(bridge.parseTxPayloadLength(makeFirstChunk([0xf8]))).toBeNull(); + }); + }); + + describe('handleHidSend per-connection sign-tx progress', () => { + afterEach(() => { + jest.restoreAllMocks(); + }); + + it('tracks sign-transaction progress per WebSocket connection', async () => { + const { bridge, exchangeMock } = setupHandleHidSendTest( + [ + // ws1: first chunk with a 103-byte payload total (0xf8 0x64), 50 sent. + makeSignTxChunk(0x00, 50, [0x00, 0xf8, 0x64]), + // ws2: first chunk with a 203-byte payload total (0xf8 0xc8), 60 sent. + makeSignTxChunk(0x00, 60, [0x00, 0xf8, 0xc8]), + // ws1: continuation of 30 bytes (sent becomes 80). + makeSignTxChunk(0x80, 30, []), + // ws1: continuation of 25 bytes (sent becomes 105 >= 103 → last chunk). + makeSignTxChunk(0x80, 25, []), + ], + + Buffer.from([0x90, 0x00]), + ); + + const ws1 = createMockWebSocket(); + const ws2 = createMockWebSocket(); + + await bridge.handleHidSend(ws1, { id: 1, data: [] }); + await bridge.handleHidSend(ws2, { id: 2, data: [] }); + await bridge.handleHidSend(ws1, { id: 3, data: [] }); + await bridge.handleHidSend(ws1, { id: 4, data: [] }); + + // With per-connection state, ws1's last chunk completes its own 103-byte + // payload and triggers the final empty-chunk acknowledgement exchange. + expect(exchangeMock).toHaveBeenCalledTimes(5); + + expect(exchangeMock).toHaveBeenLastCalledWith( + Buffer.from([0xe0, 0x04, 0x80, 0x00, 0x00]), + ); + }); + }); + + describe('handleHidSend signing-ready timer', () => { + const signTxContinuation = Buffer.from([ + 0xe0, 0x04, 0x80, 0x00, 0x01, 0x00, + ]); + const personalSignApdu = Buffer.from([0xe0, 0x08, 0x00, 0x00, 0x00]); + + beforeEach(() => { + jest.useFakeTimers(); + jest + .spyOn(ledgerHidFraming, 'createLedgerHidFramingSession') + .mockReturnValue({ + channel: 0, + framing: {} as never, + acc: null, + }); + jest + .spyOn(ledgerHidFraming, 'encodeLedgerHidResponse') + .mockReturnValue([Buffer.alloc(1)]); + }); + + afterEach(() => { + jest.restoreAllMocks(); + jest.useRealTimers(); + }); + + it('does not emit signing-ready from a fallback timer on queued signing APDUs', async () => { + const client = new SpeculosClient(); + const bridge = new ApduBridge(client, 9879); + const ws = createMockWebSocket(); + + const blockedExchange = new Promise(() => undefined); + jest.spyOn(client, 'exchange').mockReturnValue(blockedExchange); + + jest + .spyOn(ledgerHidFraming, 'pushLedgerHidFrame') + .mockReturnValueOnce(signTxContinuation) + .mockReturnValueOnce(personalSignApdu); + + let readyResolved = false; + // eslint-disable-next-line no-void, promise/always-return + void bridge.waitForSigningReady(10_000).then(() => { + readyResolved = true; + }); + + // eslint-disable-next-line no-void + void bridge.handleHidSend(ws, { id: 1, data: [] }); + // eslint-disable-next-line no-void + void bridge.handleHidSend(ws, { id: 2, data: [] }); + + await jest.advanceTimersByTimeAsync(500); + await Promise.resolve(); + + expect(readyResolved).toBe(false); + }); + + it('exchanges each queued signing APDU with Speculos individually', async () => { + const client = new SpeculosClient(); + const bridge = new ApduBridge(client, 9880); + const ws = createMockWebSocket(); + + const firstResponse = Buffer.from([0x90, 0x00]); + const secondResponse = Buffer.from([0x41, 0x42, 0x90, 0x00]); + + let resolveFirst!: (response: Buffer) => void; + const blockedFirst = new Promise((resolve) => { + resolveFirst = resolve; + }); + + const exchangeMock = jest + .spyOn(client, 'exchange') + .mockReturnValueOnce(blockedFirst) + .mockResolvedValueOnce(secondResponse); + + jest + .spyOn(ledgerHidFraming, 'pushLedgerHidFrame') + .mockReturnValueOnce(signTxContinuation) + .mockReturnValueOnce(personalSignApdu); + + const firstSend = bridge.handleHidSend(ws, { id: 1, data: [] }); + const secondSend = bridge.handleHidSend(ws, { id: 2, data: [] }); + + resolveFirst(firstResponse); + + await Promise.all([firstSend, secondSend]); + + expect(exchangeMock).toHaveBeenCalledTimes(2); + expect(exchangeMock).toHaveBeenNthCalledWith(1, signTxContinuation); + expect(exchangeMock).toHaveBeenNthCalledWith(2, personalSignApdu); + }); + }); +}); + +/** + * Get the WebSocketServer instances captured by the ws module mock. + * + * @returns The captured server instances. + */ +function getCapturedServers(): CapturedWsServer[] { + return jest.requireMock('ws').__testInstances; +} + +/** + * Produce a filler byte array. + * + * @param length - Number of bytes. + * @returns An array of filler bytes. + */ +function filler(length: number): number[] { + return Array.from({ length }, () => 0xab); +} + +/** + * Build a sign-transaction APDU chunk. + * + * @param p2 - 0x00 for a first chunk, 0x80 for a continuation. + * @param dataLen - Payload length in bytes. + * @param prefix - Leading payload bytes (path count + RLP prefix). + * @returns The APDU buffer. + */ +function makeSignTxChunk( + p2: number, + dataLen: number, + prefix: number[], +): Buffer { + const payload = Buffer.concat([ + Buffer.from(prefix), + Buffer.from(filler(Math.max(0, dataLen - prefix.length))), + ]); + if (payload.length !== dataLen) { + throw new Error('invalid test chunk construction'); + } + return Buffer.from([ + 0xe0, + 0x04, + p2, + Math.floor(dataLen / 256), + dataLen % 256, + ...payload, + ]); +} + +/** + * Set up a handleHidSend test with mocked framing and client exchange. + * + * @param apdus - The APDUs returned by pushLedgerHidFrame, in order. + * @param exchangeResponse - The response returned by the client exchange mock. + * @returns The bridge, the exchange mock, and the encode mock. + */ +function setupHandleHidSendTest( + apdus: Buffer[], + exchangeResponse: Buffer = Buffer.from([0x41, 0x42, 0x90, 0x00]), +): { + bridge: ApduBridge; + exchangeMock: jest.SpyInstance, [Buffer]>; + encodeMock: jest.SpyInstance; +} { + const client = new SpeculosClient(); + const bridge = new ApduBridge(client, 0); + + const pushMock = jest.spyOn(ledgerHidFraming, 'pushLedgerHidFrame'); + for (const apdu of apdus) { + pushMock.mockReturnValueOnce(apdu); + } + jest + .spyOn(ledgerHidFraming, 'createLedgerHidFramingSession') + .mockReturnValue({ + channel: 0, + framing: {} as never, + acc: null, + }); + const encodeMock = jest + .spyOn(ledgerHidFraming, 'encodeLedgerHidResponse') + .mockReturnValue([Buffer.alloc(1)]); + const exchangeMock = jest + .spyOn(client, 'exchange') + .mockResolvedValue(exchangeResponse); + + return { bridge, exchangeMock, encodeMock }; +} diff --git a/packages/hw-emulator/src/ledger/apdu-bridge.ts b/packages/hw-emulator/src/ledger/apdu-bridge.ts new file mode 100644 index 000000000..ae0ce30df --- /dev/null +++ b/packages/hw-emulator/src/ledger/apdu-bridge.ts @@ -0,0 +1,827 @@ +// eslint-disable-next-line import-x/no-nodejs-modules +import { EventEmitter } from 'node:events'; +import { WebSocketServer } from 'ws'; +import type { WebSocket as WsWebSocket } from 'ws'; + +import { SpeculosClient } from './client'; +import type { DeviceInteraction } from './device-interaction'; +import { + createLedgerHidFramingSession, + encodeLedgerHidResponse, + pushLedgerHidFrame, +} from './ledger-hid-framing'; +import type { LedgerHidFramingSession } from './ledger-hid-framing'; + +/** Ledger application class byte shared by all Ethereum app APDUs. */ +const LEDGER_CLA = 0xe0; + +/** Ethereum app instruction byte for GET_APP_CONFIGURATION. */ +const INS_GET_APP_CONFIGURATION = 0x06; + +/** Ethereum app instruction byte for signing a transaction. */ +const INS_SIGN_TRANSACTION = 0x04; + +/** Ethereum app instruction byte for signing a personal message. */ +const INS_SIGN_PERSONAL_MESSAGE = 0x08; + +/** Ethereum app instruction byte for the v2 message-signing flow. */ +const INS_SIGN_MESSAGE_V2 = 0x1a; + +/** Ethereum app instruction byte for typed-data (EIP-712) signing. */ +const INS_SIGN_TYPED_DATA = 0x20; + +/** Ethereum app instruction byte for the v2 typed-data signing flow. */ +const INS_SIGN_TYPED_DATA_V2 = 0x22; + +/** P1 byte marking the first chunk of a multi-chunk signing APDU. */ +const P1_FIRST_CHUNK = 0x00; + +/** P1 byte marking a continuation chunk of a multi-chunk signing APDU. */ +const P1_CONTINUATION_CHUNK = 0x80; + +/** APDU header size in bytes: CLA, INS, P1, P2 and the payload length. */ +const APDU_HEADER_LENGTH = 5; + +/** SW1/SW2 byte pair spelling the APDU success status word 0x9000. */ +const STATUS_WORD_OK_SW1 = 0x90; +/** Second status word byte of the 0x9000 success pair. */ +const STATUS_WORD_OK_SW2 = 0x00; + +/** + * Empty continuation APDU sent after the final sign-transaction chunk to + * collect the signing acknowledgement from the device. + */ +// eslint-disable-next-line no-restricted-globals +const EMPTY_SIGN_TX_CONTINUATION_APDU = Buffer.from([ + LEDGER_CLA, + INS_SIGN_TRANSACTION, + P1_CONTINUATION_CHUNK, + 0x00, + 0x00, +]); + +/** + * App-configuration flags byte value with the blind-signing bit (bit 0) set, + * i.e. the value that marks data (blind) signing as enabled. + */ +const BLIND_SIGNING_FLAGS_ENABLED = 0x01; + +/** Delay before signalling that the device is ready for signing input, in milliseconds. */ +const SIGNING_READY_DELAY_MS = 500; + +/** Delay between observing a signing APDU and approving it on the device screen, in milliseconds. */ +const SIGNING_APPROVAL_DELAY_MS = 1500; + +/** Grace period before force-closing the WebSocket server, in milliseconds. */ +const FORCE_CLOSE_TIMEOUT_MS = 1000; + +/** + * Minimum sign-transaction first-chunk payload: the path-count byte, one + * 4-byte derivation path component, and at least one RLP byte + * (1 + (1 × 4) + 1). + */ +const MIN_SIGN_TX_FIRST_CHUNK_DATA_LENGTH = 6; + +/** + * Per-connection state tracking the HID framing session and the + * sign-transaction upload progress. Progress lives here — not on the bridge + * instance — so concurrent WebSocket connections cannot corrupt each other's + * counters. + */ +type WsConnectionState = { + framingSession: LedgerHidFramingSession | null; + /** Total RLP payload length expected for the sign-transaction in flight, or null. */ + signTxTotalDataLen: number | null; + /** Number of payload bytes sent so far for the sign-transaction in flight. */ + signTxDataSent: number; +}; + +/** + * Result of decoding an RLP length prefix. + */ +type RlpDecodeResult = { + /** Number of bytes in the RLP header. */ + headerSize: number; + /** Decoded payload length. */ + length: number; +}; + +/** + * A parsed bridge protocol message. All fields are optional; malformed + * messages are treated according to which fields are present. + */ +type BridgeMessage = { + id?: number | undefined; + type?: string | undefined; + data?: unknown; +}; + +/** + * Predicate constraining which APDU an injected error response applies to. + */ +export type InjectedErrorMatcher = (apdu: Buffer) => boolean; + +/** + * Check whether a value is an array of numbers (APDU/HID frame payloads). + * + * @param value - The value to check. + * @returns True if the value is a number array. + */ +function isNumberArray(value: unknown): value is number[] { + return ( + Array.isArray(value) && value.every((item) => typeof item === 'number') + ); +} + +/** + * Parse a raw WebSocket message into a bridge protocol message. + * + * @param raw - The raw message string. + * @returns The parsed message, or null if it is not valid JSON. + */ +function parseBridgeMessage(raw: string): BridgeMessage | null { + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + return null; + } + if (typeof parsed !== 'object' || parsed === null) { + return null; + } + const record = parsed as Record; + return { + id: typeof record.id === 'number' ? record.id : undefined, + type: typeof record.type === 'string' ? record.type : undefined, + data: record.data, + }; +} + +/** + * WebSocket bridge that relays HID-framed APDUs between browser WebHID mock and Speculos. + */ +export class ApduBridge { + #wss: WebSocketServer | null = null; + + readonly #client: SpeculosClient; + + readonly #port: number; + + readonly #emitter = new EventEmitter(); + + readonly #signingReadyEmitter = new EventEmitter(); + + readonly #connectionState = new WeakMap(); + + #injectedErrorStatusCode: number | null = null; + + #injectedErrorMatcher: InjectedErrorMatcher | null = null; + + #signingLockChain: Promise = Promise.resolve(); + + #signingLockDepth = 0; + + /** + * @param client - The Speculos client for APDU communication. + * @param port - The port to listen on for WebSocket connections. + */ + constructor(client: SpeculosClient, port: number) { + this.#client = client; + this.#port = port; + this.#emitter.setMaxListeners(20); + } + + /** + * Wait for a signing APDU to be sent to Speculos. + * + * @param timeout - Maximum wait time in milliseconds. + * @returns The signing APDU buffer. + */ + async waitForSigningApdu(timeout = 30000): Promise { + let timer: ReturnType; + return new Promise((resolve, reject) => { + const handler = (apdu: Buffer): void => { + clearTimeout(timer); + resolve(apdu); + }; + timer = setTimeout(() => { + this.#emitter.removeListener('signing-apdu', handler); + reject(new Error('Timeout waiting for signing APDU')); + }, timeout); + this.#emitter.once('signing-apdu', handler); + }); + } + + /** + * Wait for a signing APDU and then approve the transaction via device interaction. + * + * @param interaction - The device interaction handler. + * @param timeout - Maximum wait time in milliseconds. + * @returns The signing APDU buffer. + */ + async waitForSigningApduAndApprove( + interaction: DeviceInteraction, + timeout = 30000, + ): Promise { + const apdu = await this.waitForSigningApdu(timeout); + await new Promise((resolve) => + setTimeout(resolve, SIGNING_APPROVAL_DELAY_MS), + ); + await interaction.approveTransaction(); + return apdu; + } + + /** + * Wait for a signing APDU and then approve personal signing. + * + * @param interaction - The device interaction handler. + * @param timeout - Maximum wait time in milliseconds. + * @returns The signing APDU buffer. + */ + async waitForSigningApduAndApproveSigning( + interaction: DeviceInteraction, + timeout = 30000, + ): Promise { + const apdu = await this.waitForSigningApdu(timeout); + await new Promise((resolve) => + setTimeout(resolve, SIGNING_APPROVAL_DELAY_MS), + ); + await interaction.approveSigning(); + return apdu; + } + + /** + * Wait for a signing APDU and then approve blind signing. + * + * @param interaction - The device interaction handler. + * @param timeout - Maximum wait time in milliseconds. + * @param scrollCount - Number of review screens to scroll through. + * @returns The signing APDU buffer. + */ + async waitForSigningApduAndApproveBlindSigning( + interaction: DeviceInteraction, + timeout = 30000, + scrollCount?: number, + ): Promise { + const apdu = await this.waitForSigningApdu(timeout); + await this.waitForSigningReady(timeout); + await interaction.approveBlindSigning(scrollCount); + return apdu; + } + + /** + * Wait for the Ledger to show the signing review UI. + * + * @param timeout - Maximum wait time in milliseconds. + * @returns A promise that resolves when signing is ready. + */ + async waitForSigningReady(timeout = 30000): Promise { + let timer: ReturnType; + return new Promise((resolve, reject) => { + const handler = (): void => { + clearTimeout(timer); + resolve(); + }; + timer = setTimeout(() => { + this.#signingReadyEmitter.removeListener('signing-ready', handler); + reject(new Error('Timeout waiting for signing ready')); + }, timeout); + this.#signingReadyEmitter.once('signing-ready', handler); + }); + } + + /** + * Get the underlying SpeculosClient. + * + * @returns The client instance. + */ + getClient(): SpeculosClient { + return this.#client; + } + + /** + * Inject an error status code to return instead of the real response for an + * upcoming APDU exchange. + * + * IMPORTANT: by default the injection is NOT tied to a specific request — + * it applies to whatever APDU exchange completes next on any WebSocket + * connection. Pass a `matcher` to constrain which APDU the error applies + * to; the injection then stays queued until an exchange satisfies the + * matcher (and is simply never consumed if none ever does). + * + * @param statusCode - 16-bit APDU status word to return (e.g. 0x6982). + * @param matcher - Optional predicate over the APDU buffer; when provided, + * only an APDU satisfying it consumes the injection. + */ + injectNextErrorResponse( + statusCode: number, + matcher?: InjectedErrorMatcher, + ): void { + this.#injectedErrorStatusCode = statusCode; + this.#injectedErrorMatcher = matcher ?? null; + } + + /** + * Create a fresh per-connection state object. + * + * @returns The new connection state. + */ + #createConnectionState(): WsConnectionState { + return { + framingSession: null, + signTxTotalDataLen: null, + signTxDataSent: 0, + }; + } + + /** + * Get (or lazily create) the per-connection state for a WebSocket. + * + * @param ws - The WebSocket connection. + * @returns The connection state. + */ + #getConnectionState(ws: WsWebSocket): WsConnectionState { + let state = this.#connectionState.get(ws); + if (!state) { + state = this.#createConnectionState(); + this.#connectionState.set(ws, state); + } + return state; + } + + /** + * Acquire the signing lock so concurrent signing APDUs are serialized. + * + * @returns A release function and whether this caller waited behind another signing flow. + */ + async #acquireSigningLock(): Promise<{ + release: () => void; + wasQueued: boolean; + }> { + const wasQueued = this.#signingLockDepth > 0; + this.#signingLockDepth += 1; + + let releaseLock!: () => void; + const previousLock = this.#signingLockChain; + this.#signingLockChain = new Promise((resolve) => { + releaseLock = resolve; + }); + + await previousLock; + + return { + wasQueued, + release: (): void => { + this.#signingLockDepth -= 1; + releaseLock(); + }, + }; + } + + /** + * Start the WebSocket server. + * + * @returns A promise that resolves when listening. + */ + async start(): Promise { + return new Promise((resolve, reject) => { + const wss = new WebSocketServer({ port: this.#port }); + this.#wss = wss; + + wss.on('connection', (ws: WsWebSocket) => { + this.#connectionState.set(ws, this.#createConnectionState()); + + ws.on('message', (data: Buffer): void => { + this.#handleMessage(ws, data).catch((caughtError: unknown) => { + const errorMessage = + caughtError instanceof Error + ? caughtError.message + : String(caughtError); + ws.send( + JSON.stringify({ type: 'APDU_ERROR', error: errorMessage }), + ); + }); + }); + + ws.on('close', () => { + this.#connectionState.delete(ws); + }); + }); + + // Startup-only error listener: removed once 'listening' fires. Calling + // reject() on the already-settled promise afterwards would be a silent + // no-op and swallow the error, so a persistent handler below logs + // instead. + const onStartupError = (serverError: Error): void => { + wss.removeListener('error', onStartupError); + this.#wss = null; + reject(serverError); + }; + wss.on('error', onStartupError); + + wss.on('listening', () => { + wss.removeListener('error', onStartupError); + // Persistent handler for post-startup server errors. + wss.on('error', (serverError: Error) => { + console.error( + `[ApduBridge] Server error on port ${this.#port}: ${serverError.message}`, + ); + }); + console.log(`[ApduBridge] Server listening on port ${this.#port}`); + resolve(); + }); + }); + } + + /** + * Handle a single raw WebSocket message, parsing it exactly once. + * + * @param ws - The WebSocket connection the message arrived on. + * @param data - The raw message payload. + */ + async #handleMessage(ws: WsWebSocket, data: Buffer): Promise { + const message = parseBridgeMessage(data.toString()); + if (!message) { + ws.send( + JSON.stringify({ + type: 'APDU_ERROR', + error: 'Invalid JSON message', + }), + ); + return; + } + + if (message.type === 'DEBUG') { + return; + } + + try { + if (message.type === 'HID_SEND') { + if (!isNumberArray(message.data)) { + throw new Error('HID_SEND message requires a numeric data array'); + } + await this.handleHidSend(ws, { id: message.id, data: message.data }); + return; + } + + // APDU_REQUEST is a direct, unframed APDU pipe: the payload is a whole + // APDU forwarded straight to Speculos, bypassing the HID framing + // reassembly and the signing lock used by the HID_SEND path below. + if (message.type === 'APDU_REQUEST') { + if (!isNumberArray(message.data)) { + throw new Error('APDU_REQUEST message requires a numeric data array'); + } + // eslint-disable-next-line no-restricted-globals + const apduData = Buffer.from(message.data); + const response = await this.#client.exchange(apduData); + + ws.send( + JSON.stringify({ + type: 'APDU_RESPONSE', + id: message.id, + data: Array.from(response), + }), + ); + } + } catch (bridgeError: unknown) { + const errorMessage = + bridgeError instanceof Error + ? bridgeError.message + : String(bridgeError); + ws.send( + JSON.stringify({ + type: 'APDU_ERROR', + id: message.id, + error: errorMessage, + }), + ); + } + } + + /** + * Handle an incoming HID_SEND WebSocket message, reassembling HID frames into + * APDUs, forwarding them to Speculos, and sending the HID-framed response back. + * + * @param ws - The WebSocket connection. + * @param message - The parsed message with raw frame data. + * @param message.id - Optional message identifier for response correlation. + * @param message.data - Raw HID frame bytes as a number array. + */ + async handleHidSend( + ws: WsWebSocket, + message: { id?: number | undefined; data: number[] }, + ): Promise { + // eslint-disable-next-line no-restricted-globals + const frame = Buffer.from(message.data); + const state = this.#getConnectionState(ws); + + state.framingSession ??= createLedgerHidFramingSession(frame); + + const apdu = pushLedgerHidFrame(state.framingSession, frame); + if (!apdu) { + ws.send( + JSON.stringify({ + type: 'HID_FRAME_ACK', + id: message.id, + }), + ); + return; + } + + const isSignTx = + apdu.length >= 2 && + apdu[0] === LEDGER_CLA && + apdu[1] === INS_SIGN_TRANSACTION; + const isSigningIns = + apdu.length >= 2 && + apdu[0] === LEDGER_CLA && + (apdu[1] === INS_SIGN_TRANSACTION || + apdu[1] === INS_SIGN_PERSONAL_MESSAGE || + apdu[1] === INS_SIGN_MESSAGE_V2 || + apdu[1] === INS_SIGN_TYPED_DATA || + apdu[1] === INS_SIGN_TYPED_DATA_V2); + + const isSignTxFirst = isSignTx && apdu[2] === P1_FIRST_CHUNK; + const isSignTxContinuation = isSignTx && apdu[2] === P1_CONTINUATION_CHUNK; + const dataLen = + apdu.length > APDU_HEADER_LENGTH ? apdu.length - APDU_HEADER_LENGTH : 0; + + // Sign-transaction upload progress is tracked per connection so concurrent + // WebSocket connections cannot corrupt each other's counters. + if (isSignTxFirst && apdu.length > APDU_HEADER_LENGTH) { + const totalPayloadLen = this.parseTxPayloadLength( + apdu.subarray(APDU_HEADER_LENGTH), + ); + if (totalPayloadLen !== null) { + state.signTxTotalDataLen = totalPayloadLen; + state.signTxDataSent = dataLen; + } + } else if (isSignTxContinuation) { + state.signTxDataSent += dataLen; + } + + const isSigningFirstChunk = isSigningIns && apdu[2] === P1_FIRST_CHUNK; + const isOtherSigning = isSigningIns && apdu[1] !== INS_SIGN_TRANSACTION; + + if (isSigningFirstChunk || isOtherSigning) { + this.#emitter.emit('signing-apdu', apdu); + } + + const isLastSignTxChunk = + isSignTxContinuation && + state.signTxTotalDataLen !== null && + state.signTxDataSent >= state.signTxTotalDataLen; + const isSingleChunkSignTx = + isSignTxFirst && + state.signTxTotalDataLen !== null && + state.signTxDataSent >= state.signTxTotalDataLen; + const shouldStartSigningTimer = + isSigningIns && (!isSignTx || isLastSignTxChunk || isSingleChunkSignTx); + + const signingLock = isSigningIns ? await this.#acquireSigningLock() : null; + const wasQueuedSigning = signingLock?.wasQueued ?? false; + + let signingReadyFired = false; + const signingReadyTimer = + shouldStartSigningTimer && !wasQueuedSigning + ? setTimeout(() => { + signingReadyFired = true; + this.#signingReadyEmitter.emit('signing-ready'); + }, SIGNING_READY_DELAY_MS) + : null; + const shouldEmitSigningReadyOnLastChunk = + (isLastSignTxChunk || isSingleChunkSignTx) && !signingReadyFired; + + let response: Buffer; + + try { + response = await this.#client.exchange(apdu); + + if (signingReadyTimer) { + clearTimeout(signingReadyTimer); + } + + if (shouldEmitSigningReadyOnLastChunk && !signingReadyFired) { + signingReadyFired = true; + this.#signingReadyEmitter.emit('signing-ready'); + } + + const isLastChunkWithAck = + (isSignTxContinuation || isSingleChunkSignTx) && + state.signTxTotalDataLen !== null && + state.signTxDataSent >= state.signTxTotalDataLen && + response.length === 2 && + response[0] === STATUS_WORD_OK_SW1 && + response[1] === STATUS_WORD_OK_SW2; + + if (isLastChunkWithAck) { + const readyTimer = setTimeout(() => { + signingReadyFired = true; + this.#signingReadyEmitter.emit('signing-ready'); + }, SIGNING_READY_DELAY_MS); + response = await this.#client.exchange(EMPTY_SIGN_TX_CONTINUATION_APDU); + clearTimeout(readyTimer); + state.signTxTotalDataLen = null; + state.signTxDataSent = 0; + } else if (!isSignTx || (isSingleChunkSignTx && response.length > 2)) { + state.signTxTotalDataLen = null; + state.signTxDataSent = 0; + } + + const injectedCode = this.#injectedErrorStatusCode; + const injectedMatcher = this.#injectedErrorMatcher; + const injectionMatches = + injectedCode !== null && + (injectedMatcher === null || injectedMatcher(apdu)); + if (injectionMatches) { + this.#injectedErrorStatusCode = null; + this.#injectedErrorMatcher = null; + const sw1 = Math.floor(injectedCode / 256); + const sw2 = injectedCode % 256; + // eslint-disable-next-line no-restricted-globals + response = Buffer.from([sw1, sw2]); + } + + // GET_APP_CONFIGURATION (INS_GET_APP_CONFIGURATION) response byte 0 + // is the flags byte, where bit 0 reports whether data (blind) signing + // is enabled (see SpeculosClient#getAppConfiguration, which decodes the + // same byte). Speculos' canned app-config response can report 0 here, + // which makes browser clients (e.g. @ledgerhq/hw-app-eth) treat the + // device as incapable of data signing and abort signing flows. Force + // the byte to BLIND_SIGNING_FLAGS_ENABLED so WebHID clients routed + // through this bridge keep working. + if ( + apdu.length >= 2 && + apdu[0] === LEDGER_CLA && + apdu[1] === INS_GET_APP_CONFIGURATION && + response.length >= 3 + ) { + const responseSw1 = response[response.length - 2]; + const responseSw2 = response[response.length - 1]; + if ( + responseSw1 === STATUS_WORD_OK_SW1 && + responseSw2 === STATUS_WORD_OK_SW2 && + response[0] !== BLIND_SIGNING_FLAGS_ENABLED + ) { + // eslint-disable-next-line no-restricted-globals + response = Buffer.from([ + BLIND_SIGNING_FLAGS_ENABLED, + ...response.subarray(1), + ]); + } + } + + const responseFrames = encodeLedgerHidResponse( + state.framingSession, + response, + ); + + for (const responseFrame of responseFrames) { + ws.send( + JSON.stringify({ + type: 'HID_RECV', + id: message.id, + data: Array.from(responseFrame), + }), + ); + } + + ws.send( + JSON.stringify({ + type: 'HID_EXCHANGE_COMPLETE', + id: message.id, + }), + ); + + state.framingSession = null; + } finally { + signingLock?.release(); + } + } + + /** + * Stop the WebSocket server. + * + * @returns A promise that resolves when stopped. + */ + async stop(): Promise { + return new Promise((resolve) => { + if (!this.#wss) { + resolve(); + return; + } + + this.#wss.clients.forEach((client) => { + client.terminate(); + }); + + const forceCloseTimer = setTimeout(() => { + if (this.#wss) { + this.#wss = null; + resolve(); + } + }, FORCE_CLOSE_TIMEOUT_MS); + + this.#wss.close(() => { + clearTimeout(forceCloseTimer); + this.#wss = null; + resolve(); + }); + }); + } + + /** + * Get the port the bridge is listening on. + * + * @returns The port number. + */ + getPort(): number { + return this.#port; + } + + /** + * Parse the total transaction payload length from the first signing APDU chunk. + * + * The RLP encoding starts at the first payload byte. This includes the + * single-byte form (prefix 0x00–0x7f), where the prefix byte IS the value + * itself and contributes exactly one byte to the payload — it is not a + * header for the following bytes. + * + * @param firstChunkData - The payload bytes from the first APDU chunk (after the header). + * @returns The total payload length in bytes, or null if parsing fails. + */ + parseTxPayloadLength(firstChunkData: Buffer): number | null { + if (firstChunkData.length < MIN_SIGN_TX_FIRST_CHUNK_DATA_LENGTH) { + return null; + } + try { + const pathCount = firstChunkData[0] ?? 0; + const pathBytes = pathCount * 4; + const txStart = 1 + pathBytes; + if (txStart >= firstChunkData.length) { + return null; + } + const txData = firstChunkData.subarray(txStart); + if (txData.length === 0) { + return null; + } + const rlpResult = this.decodeRlpLength(txData, 0); + if (!rlpResult) { + return null; + } + return pathBytes + 1 + rlpResult.headerSize + rlpResult.length; + } catch { + return null; + } + } + + /** + * Decode an RLP length prefix at the given offset. + * + * @param data - The buffer containing RLP-encoded data. + * @param offset - The byte offset to start decoding from. + * @returns The header size and decoded length, or null if the data is incomplete. + */ + decodeRlpLength(data: Buffer, offset: number): RlpDecodeResult | null { + if (offset >= data.length) { + return null; + } + const prefix = data[offset]; + if (prefix === undefined) { + return null; + } + if (prefix <= 0x7f) { + return { headerSize: 0, length: 1 }; + } + if (prefix <= 0xb7) { + return { headerSize: 1, length: prefix - 0x80 }; + } + if (prefix <= 0xbf) { + const lenOfLen = prefix - 0xb7; + if (offset + 1 + lenOfLen > data.length) { + return null; + } + let decodedLen = 0; + for (let byteIdx = 0; byteIdx < lenOfLen; byteIdx++) { + const byteVal = data[offset + 1 + byteIdx] ?? 0; + // eslint-disable-next-line no-bitwise + decodedLen = (decodedLen << 8) | byteVal; + } + return { headerSize: 1 + lenOfLen, length: decodedLen }; + } + if (prefix <= 0xf7) { + return { headerSize: 1, length: prefix - 0xc0 }; + } + const lenOfLen2 = prefix - 0xf7; + if (offset + 1 + lenOfLen2 > data.length) { + return null; + } + let decodedLen2 = 0; + for (let byteIdx = 0; byteIdx < lenOfLen2; byteIdx++) { + const byteVal = data[offset + 1 + byteIdx] ?? 0; + // eslint-disable-next-line no-bitwise + decodedLen2 = (decodedLen2 << 8) | byteVal; + } + return { headerSize: 1 + lenOfLen2, length: decodedLen2 }; + } +} diff --git a/packages/hw-emulator/src/ledger/client.test.ts b/packages/hw-emulator/src/ledger/client.test.ts new file mode 100644 index 000000000..bedc62902 --- /dev/null +++ b/packages/hw-emulator/src/ledger/client.test.ts @@ -0,0 +1,308 @@ +import net from 'node:net'; + +import { SpeculosClient } from './client'; + +/** + * Build a framed APDU response (4-byte length header, payload, 2 status bytes). + * + * @param payload - The response payload. + * @returns The framed response buffer. + */ +function frameResponse(payload: Buffer): Buffer { + const header = Buffer.alloc(4); + header.writeUInt32BE(payload.length, 0); + + return Buffer.concat([header, payload, Buffer.from([0x90, 0x00])]); +} + +/** + * Start a local TCP server that records every connected socket. + * + * @returns The server, the list of connected server-side sockets, and a + * cleanup function that destroys all sockets and closes the server. + */ +async function startEchoServer(): Promise<{ + cleanup: () => Promise; + sockets: net.Socket[]; + port: number; +}> { + const sockets: net.Socket[] = []; + const server = net.createServer((socket) => { + sockets.push(socket); + socket.on('error', () => undefined); + // Respond to a received FIN so client sockets can close gracefully. + socket.on('end', () => { + socket.end(); + }); + }); + await new Promise((resolve) => { + server.listen(0, '127.0.0.1', () => resolve()); + }); + const address = server.address(); + const port = address && typeof address === 'object' ? address.port : 0; + const cleanup = async (): Promise => { + for (const socket of sockets) { + socket.destroy(); + } + await new Promise((resolve) => { + server.close(() => resolve()); + }); + }; + return { cleanup, sockets, port }; +} + +/** + * Wait until the echo server has recorded the socket at the given index. + * + * @param sockets - The recorded server-side sockets. + * @param index - The connection index to wait for. + * @returns The server-side socket. + */ +async function waitForServerSocket( + sockets: net.Socket[], + index: number, +): Promise { + for (let attempt = 0; attempt < 200; attempt++) { + const socket = sockets[index]; + if (socket) { + return socket; + } + await new Promise((resolve) => setTimeout(resolve, 10)); + } + throw new Error(`Server socket ${index} never connected`); +} + +/** + * Find a free TCP port and return it (the probe socket is closed). + * + * @returns A port number that was momentarily free. + */ +async function findFreePort(): Promise { + const probe = net.createServer(); + await new Promise((resolve) => { + probe.listen(0, '127.0.0.1', () => resolve()); + }); + const address = probe.address(); + const port = address && typeof address === 'object' ? address.port : 0; + await new Promise((resolve) => { + probe.close(() => resolve()); + }); + return port; +} + +describe('SpeculosClient', () => { + describe('constructor', () => { + it('uses default ports when no options provided', () => { + const client = new SpeculosClient(); + expect(client.isHealthy()).toBe(false); + }); + + it('uses custom ports when provided', () => { + const client = new SpeculosClient({ + apduPort: 9997, + apiPort: 5002, + }); + expect(client.isHealthy()).toBe(false); + }); + + it('builds correct base URL', () => { + const client = new SpeculosClient({ + apiHost: '192.168.1.1', + apiPort: 5003, + }); + expect(client.isHealthy()).toBe(false); + }); + }); + + describe('isHealthy', () => { + it('returns false before connecting', () => { + const client = new SpeculosClient(); + expect(client.isHealthy()).toBe(false); + }); + }); + + describe('exchange', () => { + it('throws if not connected', async () => { + const client = new SpeculosClient(); + await expect( + client.exchange(Buffer.from([0xe0, 0x06, 0x00, 0x00, 0x00])), + ).rejects.toThrow('Not connected to Speculos'); + }); + }); + + describe('disconnect', () => { + it('does not throw when not connected', async () => { + const client = new SpeculosClient(); + await client.disconnect(); + expect(true).toBe(true); + }); + }); + + describe('exchangeWithRetry', () => { + it('throws if not connected', async () => { + const client = new SpeculosClient(); + await expect( + client.exchangeWithRetry(Buffer.from([0xe0, 0x06, 0x00, 0x00, 0x00])), + ).rejects.toThrow('Not connected to Speculos'); + }); + }); + + describe('connectWithRetry', () => { + it('returns immediately if already connected', async () => { + // A real emulator may be listening on the default APDU port, so use a + // port known to be closed. + const client = new SpeculosClient({ apduPort: await findFreePort() }); + await client + .connectWithRetry({ + autoReconnect: false, + reconnectAttempts: 0, + }) + .catch(() => undefined); + expect(client.isHealthy()).toBe(false); + }); + }); + + describe('connect timeout', () => { + it('rejects and destroys the socket when the connection never establishes', async () => { + // A socket that is never connected and never errors simulates a + // blackholed host. + const blackholedSocket = new net.Socket(); + const createConnectionSpy = jest + .spyOn(net, 'createConnection') + .mockReturnValue(blackholedSocket); + try { + const client = new SpeculosClient({ connectTimeout: 150 }); + await expect(client.connect()).rejects.toThrow( + 'Timed out connecting to Speculos APDU endpoint', + ); + expect(blackholedSocket.destroyed).toBe(true); + expect(client.isHealthy()).toBe(false); + } finally { + createConnectionSpy.mockRestore(); + } + }, 5_000); + + it('rejects when the connection is refused', async () => { + const port = await findFreePort(); + const client = new SpeculosClient({ + apduPort: port, + connectTimeout: 2_000, + }); + await expect(client.connect()).rejects.toThrow('ECONNREFUSED'); + expect(client.isHealthy()).toBe(false); + }, 10_000); + }); + + describe('post-connect socket errors', () => { + it('marks the client unhealthy without unhandled rejections', async () => { + const { cleanup, sockets, port } = await startEchoServer(); + try { + const client = new SpeculosClient({ apduPort: port }); + await client.connect(); + expect(client.isHealthy()).toBe(true); + + // Abruptly reset the connection from the server side (RST). + const serverSocket = await waitForServerSocket(sockets, 0); + serverSocket.resetAndDestroy(); + await new Promise((resolve) => setTimeout(resolve, 150)); + + expect(client.isHealthy()).toBe(false); + } finally { + await cleanup(); + } + }, 10_000); + }); + + describe('stale response handling', () => { + it('discards late responses after an exchange timeout so they cannot answer the next exchange', async () => { + const { cleanup, sockets, port } = await startEchoServer(); + try { + const client = new SpeculosClient({ apduPort: port, timeout: 150 }); + await client.connect(); + + const stalePayload = Buffer.from([0x01]); + const freshPayload = Buffer.from([0x02]); + + // Exchange 1: the server stays silent, so the exchange times out. + await expect( + client.exchange(Buffer.from([0xe0, 0x01])), + ).rejects.toThrow('APDU exchange timeout'); + + // The server now sends the late response for exchange 1. With the fix + // this write lands on a destroyed socket and is discarded; without it + // the bytes stay buffered in the live socket. + sockets[0]?.write(frameResponse(stalePayload)); + + // Give the post-timeout reconnect a moment to settle. + await new Promise((resolve) => setTimeout(resolve, 200)); + expect(sockets).toHaveLength(2); + + // Exchange 2 on the reconnected socket must receive its own response, + // not the stale buffered one. The exchange response includes the + // 2-byte status word after the payload. + const exchange2 = client.exchange(Buffer.from([0xe0, 0x02])); + const freshSocket = sockets[1]; + freshSocket?.on('data', () => { + freshSocket?.write(frameResponse(freshPayload)); + }); + const response = await exchange2; + expect(response.equals(Buffer.from([0x02, 0x90, 0x00]))).toBe(true); + } finally { + await cleanup(); + } + }, 10_000); + }); + + describe('background reconnect suppression', () => { + it('stays disconnected when disconnect() follows an exchange timeout', async () => { + const { cleanup, port } = await startEchoServer(); + try { + const client = new SpeculosClient({ apduPort: port, timeout: 150 }); + await client.connect(); + + // The timeout queues a background reconnect on #resetChain. + await expect( + client.exchange(Buffer.from([0xe0, 0x01])), + ).rejects.toThrow('APDU exchange timeout'); + + // Disconnecting must supersede that reconnect: the generation + // guard abandons it instead of resurrecting the connection. + await client.disconnect(); + + await new Promise((resolve) => setTimeout(resolve, 300)); + expect(client.isHealthy()).toBe(false); + + // The guard must not wedge the client: an explicit connect works. + await client.connect(); + expect(client.isHealthy()).toBe(true); + } finally { + await cleanup(); + } + }, 10_000); + }); + + describe('disconnect waits for close', () => { + it('waits for the socket to close before resolving', async () => { + const { cleanup, sockets, port } = await startEchoServer(); + try { + const client = new SpeculosClient({ apduPort: port }); + await client.connect(); + + let serverSawFin = false; + const serverSocket = await waitForServerSocket(sockets, 0); + serverSocket.once('end', () => { + serverSawFin = true; + }); + + await client.disconnect(); + + expect(client.isHealthy()).toBe(false); + // The graceful close must have been transmitted to the peer by the + // time disconnect() resolves — not torn down asynchronously later. + expect(serverSawFin).toBe(true); + } finally { + await cleanup(); + } + }, 10_000); + }); +}); diff --git a/packages/hw-emulator/src/ledger/client.ts b/packages/hw-emulator/src/ledger/client.ts new file mode 100644 index 000000000..1c7ffa355 --- /dev/null +++ b/packages/hw-emulator/src/ledger/client.ts @@ -0,0 +1,679 @@ +// eslint-disable-next-line import-x/no-nodejs-modules +import net from 'node:net'; + +import { SPECULOS_APDU_PORT, SPECULOS_API_PORT } from './constants'; +import { withRetry, isRetryableError } from './resilience'; + +/** Default timeout in milliseconds for establishing the APDU TCP connection. */ +const DEFAULT_CONNECT_TIMEOUT_MS = 10_000; + +/** Default timeout in milliseconds for the socket to close on disconnect. */ +const DEFAULT_DISCONNECT_TIMEOUT_MS = 5_000; + +/** GET_APP_CONFIGURATION APDU as hex: CLA 0xe0, INS 0x06, no payload. */ +const GET_APP_CONFIGURATION_APDU = 'e006000000'; + +/** Length in bytes of the status word trailing every APDU response payload. */ +const STATUS_WORD_LENGTH = 2; + +/** Payload length of the classic 4-byte app-configuration response. */ +const CLASSIC_APP_CONFIG_PAYLOAD_LENGTH = 4; + +/** Offset of the flags byte in the classic app-configuration response. */ +const APP_CONFIG_FLAGS_OFFSET = 0; + +/** Offset of the major version byte in the app-configuration response. */ +const APP_CONFIG_MAJOR_OFFSET = 1; + +/** Offset of the minor version byte in the app-configuration response. */ +const APP_CONFIG_MINOR_OFFSET = 2; + +/** Offset of the patch version byte in the app-configuration response. */ +const APP_CONFIG_PATCH_OFFSET = 3; + +/** Offset of the flags byte in the extended app-configuration response. */ +const EXTENDED_APP_CONFIG_FLAGS_OFFSET = 7; + +/** Bit of the app-configuration flags byte reporting blind signing as enabled. */ +const BLIND_SIGNING_FLAG_MASK = 0x01; + +/** + * Options for configuring the SpeculosClient. + */ +export type SpeculosClientOptions = { + /** Hostname for the APDU TCP socket. */ + apduHost?: string; + /** Port for the APDU TCP socket. */ + apduPort?: number; + /** Hostname for the REST API. */ + apiHost?: string; + /** Port for the REST API. */ + apiPort?: number; + /** Timeout in milliseconds for APDU exchanges and API requests. */ + timeout?: number; + /** Timeout in milliseconds for establishing the APDU TCP connection (default 10s). */ + connectTimeout?: number; +}; + +/** + * Response from an APDU exchange. + */ +export type APDUResponse = { + /** Hex-encoded response data. */ + data: string; +}; + +/** + * TCP and REST client for communicating with a Speculos emulator instance. + */ +export class SpeculosClient { + #apduSocket: net.Socket | null = null; + + readonly #baseUrl: string; + + readonly #options: Required; + + #connected = false; + + #healthy = false; + + #exchangeChain: Promise = Promise.resolve(); + + #resetChain: Promise = Promise.resolve(); + + /** + * Monotonic connection generation. Incremented by every `connect()` + * attempt and by `disconnect()`, so background reconnects queued before + * a disconnect can detect they are stale and abandon instead of + * resurrecting the connection. + */ + #connectionGeneration = 0; + + /** + * @param options - Client configuration options. + */ + constructor(options: SpeculosClientOptions = {}) { + this.#options = { + apduHost: '127.0.0.1', + apduPort: SPECULOS_APDU_PORT, + apiHost: '127.0.0.1', + apiPort: SPECULOS_API_PORT, + timeout: 30000, + connectTimeout: DEFAULT_CONNECT_TIMEOUT_MS, + ...options, + }; + + this.#baseUrl = `http://${this.#options.apiHost}:${this.#options.apiPort}`; + } + + /** + * Connect to the Speculos APDU TCP socket. + * + * The connection attempt fails after `connectTimeout` milliseconds + * (default 10s) if the TCP connection cannot be established (e.g. a + * blackholed host that neither accepts nor refuses), destroying the pending + * socket. + * + * @returns A promise that resolves when connected. + */ + async connect(): Promise { + if (this.#connected) { + return; + } + + this.#connectionGeneration += 1; + const generation = this.#connectionGeneration; + + await new Promise((resolve, reject) => { + const socket = net.createConnection({ + host: this.#options.apduHost, + port: this.#options.apduPort, + }); + this.#apduSocket = socket; + + let connectTimer: ReturnType | undefined; + + // Connect-phase error listener. Removed as soon as the promise settles + // (connect or timeout) so later socket errors can never reject the + // already-settled promise; post-connect errors are handled by a + // persistent listener that only tracks health. + const onConnectError = (socketError: Error): void => { + if (connectTimer) { + clearTimeout(connectTimer); + } + socket.removeListener('error', onConnectError); + // Swallow errors emitted while the dying socket is destroyed. + socket.on('error', () => undefined); + socket.destroy(); + if (this.#apduSocket === socket) { + this.#apduSocket = null; + } + reject(socketError); + }; + + connectTimer = setTimeout(() => { + connectTimer = undefined; + socket.removeListener('error', onConnectError); + // Swallow errors emitted while the dying socket is destroyed. + socket.on('error', () => undefined); + socket.destroy(); + if (this.#apduSocket === socket) { + this.#apduSocket = null; + } + reject( + new Error( + `Timed out connecting to Speculos APDU endpoint ${this.#options.apduHost}:${this.#options.apduPort} after ${this.#options.connectTimeout}ms`, + ), + ); + }, this.#options.connectTimeout); + + socket.on('connect', () => { + if (connectTimer) { + clearTimeout(connectTimer); + } + // Remove the connect-phase listener so post-connect socket errors + // cannot touch this (now settled) promise. + socket.removeListener('error', onConnectError); + if (generation !== this.#connectionGeneration) { + // A disconnect() (or a newer connect attempt) superseded this + // attempt while it was in flight: destroy the socket instead of + // resurrecting the connection. + socket.destroy(); + resolve(); + return; + } + // Persistent handler: only tracks health, never rejects. Guarded so + // a superseded socket cannot flip the flags of the current one. + socket.on('error', () => { + if (this.#apduSocket === socket) { + this.#healthy = false; + } + }); + this.#connected = true; + this.#healthy = true; + resolve(); + }); + + socket.on('close', () => { + if (this.#apduSocket === socket) { + this.#connected = false; + this.#healthy = false; + } + }); + + socket.on('error', onConnectError); + }); + } + + /** + * Send an APDU and receive the response via TCP. + * + * @param apdu - The APDU buffer to send. + * @returns The response buffer. + */ + async exchange(apdu: Buffer): Promise { + if (!this.#apduSocket || !this.#connected) { + throw new Error('Not connected to Speculos'); + } + + // #exchangeChain is a promise-chain mutex: each exchange appends itself + // behind the previous one, serializing APDU exchanges on the shared socket. + let releaseMutex: () => void = () => undefined; + const mutexSlot = new Promise((resolve) => { + releaseMutex = resolve; + }); + const prior = this.#exchangeChain.catch(() => undefined); + this.#exchangeChain = prior.then(async () => mutexSlot); + + await prior; + + try { + // Wait for any in-flight post-timeout reconnect so buffered stale bytes + // from a previous timed-out exchange cannot leak into this one. + await this.#resetChain; + + if (!this.#apduSocket || !this.#connected) { + throw new Error('Not connected to Speculos'); + } + + return await this.exchangeOnce(apdu); + } finally { + releaseMutex(); + } + } + + /** + * Send a single APDU frame without mutual exclusion. + * + * If the exchange times out, the socket is destroyed and reconnected: a late + * response to the timed-out request would otherwise stay buffered in the + * socket and be misattributed to the next exchange as its answer. + * + * @param apdu - The APDU buffer to send. + * @returns The response buffer. + */ + async exchangeOnce(apdu: Buffer): Promise { + return new Promise((resolve, reject) => { + const chunks: Buffer[] = []; + // eslint-disable-next-line prefer-const + let timeoutId: ReturnType | undefined; + // eslint-disable-next-line prefer-const + let cleanup: () => void; + + const onData = (data: Buffer): void => { + chunks.push(data); + // eslint-disable-next-line no-restricted-globals + const combined = Buffer.concat(chunks); + + if (combined.length < 4) { + return; + } + const payloadSize = combined.readUInt32BE(0); + const expectedTotal = 4 + payloadSize + 2; + if (combined.length < expectedTotal) { + return; + } + + if (timeoutId) { + clearTimeout(timeoutId); + } + cleanup(); + resolve(combined.subarray(4, expectedTotal)); + }; + + const onError = (exchangeError: Error): void => { + if (timeoutId) { + clearTimeout(timeoutId); + } + cleanup(); + reject(exchangeError); + }; + + cleanup = (): void => { + if (this.#apduSocket) { + this.#apduSocket.off('data', onData); + this.#apduSocket.off('error', onError); + } + }; + + if (!this.#apduSocket) { + reject(new Error('APDU socket not initialized')); + return; + } + this.#apduSocket.on('data', onData); + this.#apduSocket.on('error', onError); + + timeoutId = setTimeout(() => { + cleanup(); + // Discard the socket (and any late response buffered in it) and + // reconnect, so a delayed reply cannot answer the NEXT exchange. + this.#resetConnectionAfterTimeout(); + reject(new Error('APDU exchange timeout')); + }, this.#options.timeout); + + // eslint-disable-next-line no-restricted-globals + const lengthHeader = Buffer.alloc(4); + lengthHeader.writeUInt32BE(apdu.length, 0); + // eslint-disable-next-line no-restricted-globals + this.#apduSocket.write(Buffer.concat([lengthHeader, apdu])); + }); + } + + /** + * Fetch a Speculos REST API endpoint with timeout support. + * + * @param urlPath - The API path (e.g. '/screenshot'). + * @param init - Fetch options with optional timeout override. + * @returns The fetch Response. + */ + async fetchEndpoint( + urlPath: string, + init: RequestInit & { timeout?: number } = {}, + ): Promise { + const { timeout: fetchTimeout = this.#options.timeout, ...requestInit } = + init; + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), fetchTimeout); + try { + const response = await fetch(`${this.#baseUrl}${urlPath}`, { + ...requestInit, + signal: controller.signal, + }); + if (!response.ok) { + throw new Error( + `Speculos API ${urlPath} returned ${response.status}: ${await response.text().catch(() => '')}`, + ); + } + return response; + } finally { + clearTimeout(timer); + } + } + + /** + * Press a button on the emulated device. + * + * @param button - Which button to press. + */ + async pressButton(button: 'left' | 'right' | 'both'): Promise { + await this.fetchEndpoint(`/button/${button}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ action: 'press-and-release' }), + }); + } + + /** + * Simulate a finger tap on the emulated touchscreen. + * + * @param tapX - X coordinate. + * @param tapY - Y coordinate. + * @param delay - Tap duration in seconds. + */ + async fingerTap(tapX: number, tapY: number, delay = 0.1): Promise { + await this.fetchEndpoint('/finger', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + action: 'press-and-release', + x: tapX, + y: tapY, + delay, + }), + }); + } + + /** + * Simulate a finger swipe on the emulated touchscreen. + * + * @param startX - Start X coordinate. + * @param startY - Start Y coordinate. + * @param endX - End X coordinate. + * @param endY - End Y coordinate. + * @param delay - Swipe duration in seconds. + */ + async fingerSwipe( + startX: number, + startY: number, + endX: number, + endY: number, + delay = 0.3, + ): Promise { + await this.fetchEndpoint('/finger', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + action: 'press-and-release', + x: startX, + y: startY, + x2: endX, + y2: endY, + delay, + }), + }); + } + + /** + * Take a screenshot of the emulated device screen. + * + * @returns A PNG buffer. + */ + async getScreenshot(): Promise { + const response = await this.fetchEndpoint('/screenshot'); + const arrayBuffer = await response.arrayBuffer(); + // eslint-disable-next-line no-restricted-globals + return Buffer.from(arrayBuffer); + } + + /** + * Get screen events from the emulator. + * + * @returns An array of screen events. + */ + async getEvents(): Promise< + { text?: string; x: number; y: number; w: number; h: number }[] + > { + const response = await this.fetchEndpoint('/events'); + const data = (await response.json()) as { + events: { text?: string; x: number; y: number; w: number; h: number }[]; + }; + return data.events; + } + + /** + * Set automation rules for the emulator. + * + * @param rulesJson - JSON string of automation rules. + */ + async setAutomation(rulesJson: string): Promise { + await this.fetchEndpoint('/automation', { + method: 'POST', + body: rulesJson, + }); + } + + /** + * Clear automation rules. + */ + async clearAutomation(): Promise { + await this.fetchEndpoint('/automation', { + method: 'POST', + body: JSON.stringify({ version: 1, rules: [] }), + }); + } + + /** + * Query the Ethereum app configuration via APDU. + * + * @returns App version and blind signing status. + */ + async getAppConfiguration(): Promise<{ + major: number; + minor: number; + patch: number; + blindSigningEnabled: boolean; + }> { + const resp = await this.sendAPDU(GET_APP_CONFIGURATION_APDU); + // eslint-disable-next-line no-restricted-globals + const bytes = Buffer.from(resp.data, 'hex'); + const payloadLen = bytes.length - STATUS_WORD_LENGTH; + if (payloadLen === CLASSIC_APP_CONFIG_PAYLOAD_LENGTH) { + const flags = bytes[APP_CONFIG_FLAGS_OFFSET] ?? 0; + return { + major: bytes[APP_CONFIG_MAJOR_OFFSET] ?? 0, + minor: bytes[APP_CONFIG_MINOR_OFFSET] ?? 0, + patch: bytes[APP_CONFIG_PATCH_OFFSET] ?? 0, + // eslint-disable-next-line no-bitwise + blindSigningEnabled: (flags & BLIND_SIGNING_FLAG_MASK) !== 0, + }; + } + const flags = + payloadLen > EXTENDED_APP_CONFIG_FLAGS_OFFSET + ? (bytes[EXTENDED_APP_CONFIG_FLAGS_OFFSET] ?? 0) + : 0; + return { + major: + payloadLen > APP_CONFIG_MAJOR_OFFSET + ? (bytes[APP_CONFIG_MAJOR_OFFSET] ?? 0) + : 0, + minor: + payloadLen > APP_CONFIG_MINOR_OFFSET + ? (bytes[APP_CONFIG_MINOR_OFFSET] ?? 0) + : 0, + patch: + payloadLen > APP_CONFIG_PATCH_OFFSET + ? (bytes[APP_CONFIG_PATCH_OFFSET] ?? 0) + : 0, + // eslint-disable-next-line no-bitwise + blindSigningEnabled: (flags & BLIND_SIGNING_FLAG_MASK) !== 0, + }; + } + + /** + * Send a raw APDU via the REST API. + * + * @param data - Hex-encoded APDU data. + * @returns The APDU response. + */ + async sendAPDU(data: string): Promise { + const response = await this.fetchEndpoint('/apdu', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ data }), + }); + return response.json(); + } + + /** + * Destroy the current socket and reconnect in the background, discarding any + * stale buffered data. Reconnection failures leave the client disconnected; + * the next exchange() then throws "Not connected to Speculos". + */ + #resetConnectionAfterTimeout(): void { + // Supersede the connection: any connect attempt that was already in + // flight when the timeout fired must not become the new connection. + this.#connectionGeneration += 1; + const scheduledGeneration = this.#connectionGeneration; + const socket = this.#apduSocket; + this.#apduSocket = null; + this.#connected = false; + this.#healthy = false; + if (socket) { + socket.removeAllListeners(); + socket.destroy(); + } + this.#resetChain = this.#resetChain.then(async () => + this.#reconnectAfterTimeout(scheduledGeneration), + ); + } + + /** + * Reconnect after a timed-out exchange. Never rejects — a failed reconnect + * simply leaves the client disconnected. + * + * @param scheduledGeneration - The connection generation captured when + * this reconnect was scheduled; if it no longer matches, an explicit + * connect()/disconnect() has superseded the reconnect and it abandons. + * @returns A promise that resolves once the reconnect attempt settles + * (or is abandoned). + */ + async #reconnectAfterTimeout(scheduledGeneration: number): Promise { + if (scheduledGeneration !== this.#connectionGeneration) { + return; + } + try { + await this.connect(); + } catch { + // The emulator may be gone; stay disconnected. + } + } + + /** + * Disconnect from the Speculos APDU socket. + * + * Awaits the socket close (bounded by a 5s force-destroy fallback) and + * removes all listeners instead of dropping the socket reference + * immediately. + */ + async disconnect(): Promise { + // Invalidate any queued background reconnect before the early return: + // a disconnect with no live socket can still race an in-flight + // post-timeout reconnect attempt. + this.#connectionGeneration += 1; + const socket = this.#apduSocket; + if (!socket) { + return; + } + this.#apduSocket = null; + this.#connected = false; + this.#healthy = false; + socket.removeAllListeners(); + + if (socket.readyState === 'closed') { + return; + } + + await new Promise((resolve) => { + const closeTimer = setTimeout(() => { + // Fallback: force-destroy if a graceful close never completes. + socket.destroy(); + }, DEFAULT_DISCONNECT_TIMEOUT_MS); + socket.once('close', () => { + clearTimeout(closeTimer); + resolve(); + }); + socket.once('error', () => { + socket.destroy(); + }); + socket.end(); + }); + } + + /** + * Connect with automatic retries on transient errors. + * + * The total number of connection attempts is `reconnectAttempts + 1`: + * one initial attempt plus up to `reconnectAttempts` reconnects. + * + * @param options - Reconnection options. + * @param options.autoReconnect - Whether to automatically reconnect. + * @param options.reconnectAttempts - Maximum number of reconnection attempts. + * @param options.reconnectDelayMs - Delay between reconnection attempts in milliseconds. + */ + async connectWithRetry(options?: { + autoReconnect?: boolean; + reconnectAttempts?: number; + reconnectDelayMs?: number; + }): Promise { + const autoReconnect = options?.autoReconnect ?? true; + const maxReconnects = options?.reconnectAttempts ?? 5; + const reconnectDelay = options?.reconnectDelayMs ?? 1000; + + if (this.#connected) { + return; + } + + let attempts = 0; + while (!this.#connected && attempts <= maxReconnects) { + try { + await this.connect(); + } catch (connectError: unknown) { + attempts += 1; + if (!autoReconnect || attempts > maxReconnects) { + throw connectError; + } + await new Promise((resolve) => setTimeout(resolve, reconnectDelay)); + continue; + } + } + } + + /** + * Exchange an APDU with automatic retries on transient errors. + * + * @param apdu - The APDU buffer to send. + * @param maxAttempts - Maximum number of attempts. + * @returns The response buffer. + */ + async exchangeWithRetry(apdu: Buffer, maxAttempts = 3): Promise { + const exchangeFn = async (): Promise => this.exchange(apdu); + return withRetry(exchangeFn, { + maxRetries: maxAttempts - 1, + shouldRetry: (retryError: Error) => isRetryableError(retryError), + onRetry: (retryError: Error, attempt: number) => { + console.warn( + `[SpeculosClient] APDU exchange retry ${attempt} due to: ${retryError.message ?? retryError}`, + ); + }, + }); + } + + /** + * Check if the client is healthy and connected. + * + * @returns True if connected and healthy. + */ + isHealthy(): boolean { + return this.#connected && this.#healthy; + } +} diff --git a/packages/hw-emulator/src/ledger/constants.test.ts b/packages/hw-emulator/src/ledger/constants.test.ts new file mode 100644 index 000000000..6ba844042 --- /dev/null +++ b/packages/hw-emulator/src/ledger/constants.test.ts @@ -0,0 +1,123 @@ +import { + DEVICE_MODELS, + DEFAULT_DEVICE_MODEL, + DEFAULT_DEVICE, + DEVICE_PRESETS, + SPECULOS_APDU_PORT, + SPECULOS_API_PORT, + SPECULOS_WS_BRIDGE_PORT, + SPECULOS_LEDGER_ADDRESSES, + SPECULOS_LEDGER_ADDRESS, + SPECULOS_SEED, + getDeviceModel, + detectRunMode, +} from './constants'; + +describe('constants', () => { + describe('DEVICE_MODELS', () => { + it('contains all expected device models', () => { + expect(Object.keys(DEVICE_MODELS)).toStrictEqual([ + 'nanosp', + 'nanox', + 'stax', + 'flex', + ]); + }); + + it('each model has required properties', () => { + for (const model of Object.values(DEVICE_MODELS)) { + expect(model.id).toBeDefined(); + expect(model.name).toBeDefined(); + expect(model.speculosModel).toBeDefined(); + expect(model.interactionType).toMatch(/^(button|touch)$/u); + expect(model.elfFile).toMatch(/\.elf$/u); + expect(model.screenSize.width).toBeGreaterThan(0); + expect(model.screenSize.height).toBeGreaterThan(0); + } + }); + + it('touch devices have button coordinates', () => { + const touchModels = Object.values(DEVICE_MODELS).filter( + (item) => item.interactionType === 'touch', + ); + for (const model of touchModels) { + expect(model.backButton).toBeDefined(); + expect(model.confirmButton).toBeDefined(); + } + }); + }); + + describe('DEFAULT_DEVICE_MODEL', () => { + it('is the flex model', () => { + expect(DEFAULT_DEVICE_MODEL.id).toBe('flex'); + }); + }); + + describe('DEFAULT_DEVICE', () => { + it('has expected port values', () => { + expect(DEFAULT_DEVICE.apduPort).toBe(9998); + expect(DEFAULT_DEVICE.apiPort).toBe(5001); + expect(DEFAULT_DEVICE.wsBridgePort).toBe(9876); + }); + }); + + describe('DEVICE_PRESETS', () => { + it('contains at least two presets', () => { + expect(DEVICE_PRESETS.length).toBeGreaterThanOrEqual(2); + }); + }); + + describe('port exports', () => { + it('matches DEFAULT_DEVICE', () => { + expect(SPECULOS_APDU_PORT).toBe(DEFAULT_DEVICE.apduPort); + expect(SPECULOS_API_PORT).toBe(DEFAULT_DEVICE.apiPort); + expect(SPECULOS_WS_BRIDGE_PORT).toBe(DEFAULT_DEVICE.wsBridgePort); + }); + }); + + describe('SPECULOS_LEDGER_ADDRESSES', () => { + it('contains 5 addresses', () => { + expect(SPECULOS_LEDGER_ADDRESSES).toHaveLength(5); + }); + + it('sPECULOS_LEDGER_ADDRESS is the first address', () => { + expect(SPECULOS_LEDGER_ADDRESS).toBe(SPECULOS_LEDGER_ADDRESSES[0]); + }); + + it('all addresses are valid hex', () => { + for (const address of SPECULOS_LEDGER_ADDRESSES) { + expect(address).toMatch(/^0x[0-9a-fA-F]{40}$/u); + } + }); + }); + + describe('SPECULOS_SEED', () => { + it('is a non-empty string', () => { + expect(typeof SPECULOS_SEED).toBe('string'); + expect(SPECULOS_SEED.length).toBeGreaterThan(0); + }); + }); + + describe('getDeviceModel', () => { + it('returns flex by default', () => { + expect(getDeviceModel().id).toBe('flex'); + }); + + it('returns nanosp when specified', () => { + expect(getDeviceModel('nanosp').id).toBe('nanosp'); + }); + + it('throws for unknown model', () => { + expect(() => getDeviceModel('unknown')).toThrow( + 'Unknown device model "unknown"', + ); + }); + }); + + describe('detectRunMode', () => { + it('returns a valid run mode', () => { + const mode = detectRunMode(); + expect(mode === 'native' || mode === 'docker').toBe(true); + }); + }); +}); diff --git a/packages/hw-emulator/src/ledger/constants.ts b/packages/hw-emulator/src/ledger/constants.ts new file mode 100644 index 000000000..fda2af850 --- /dev/null +++ b/packages/hw-emulator/src/ledger/constants.ts @@ -0,0 +1,174 @@ +/** + * Port and connection configuration for a Speculos device instance. + */ +export type DeviceConfig = { + /** Unique identifier for this device configuration. */ + id: string; + /** TCP port for the APDU protocol. */ + apduPort: number; + /** TCP port for the REST API. */ + apiPort: number; + /** TCP port for the WebSocket bridge. */ + wsBridgePort: number; +}; + +/** Default device configuration with standard ports. */ +export const DEFAULT_DEVICE: DeviceConfig = { + id: 'default', + apduPort: 9998, + apiPort: 5001, + wsBridgePort: 9876, +}; + +/** Pre-configured device presets supporting multiple concurrent emulator instances. */ +export const DEVICE_PRESETS: DeviceConfig[] = [ + DEFAULT_DEVICE, + { + id: 'second', + apduPort: 9997, + apiPort: 5002, + wsBridgePort: 9875, + }, +]; + +/** Default APDU port, derived from the default device configuration. */ +export const SPECULOS_APDU_PORT = DEFAULT_DEVICE.apduPort; +/** Default REST API port, derived from the default device configuration. */ +export const SPECULOS_API_PORT = DEFAULT_DEVICE.apiPort; +/** Default WebSocket bridge port, derived from the default device configuration. */ +export const SPECULOS_WS_BRIDGE_PORT = DEFAULT_DEVICE.wsBridgePort; + +/** Ethereum addresses derived from the default Speculos seed. */ +export const SPECULOS_LEDGER_ADDRESSES = [ + '0xb0358b8F2314F6f6a392a4be8C7C422e631d9F63', + '0xE004F1e6F8bB51106fD488550f7e6e6f54430018', + '0xd957f2200aEDA0Ac1604d29F6C823bD113A13780', + '0x797b3EF4B1807c30F6831381dE79be50217B53a5', + '0x335Fcb7dd8d2190c9698026Df2dBa62A990371F4', +] as const; + +/** Primary Ledger address derived from the default Speculos seed. */ +export const SPECULOS_LEDGER_ADDRESS = SPECULOS_LEDGER_ADDRESSES[0]; + +/** BIP-39 mnemonic seed used by default in the Speculos emulator. */ +export const SPECULOS_SEED = + 'grit essence story volume tip entry situate found february olympic monitor hybrid'; + +/** Interaction method used by the device — button-based or touch-based. */ +export type InteractionType = 'button' | 'touch'; + +/** + * Describes a Ledger device model with its Speculos configuration, screen size, + * and touch button coordinates (for touch-based devices). + */ +export type DeviceModel = { + /** Unique model identifier (e.g. 'nanosp', 'stax'). */ + id: string; + /** Human-readable model name. */ + name: string; + /** Model identifier passed to the Speculos binary. */ + speculosModel: string; + /** Whether the device uses button or touch interaction. */ + interactionType: InteractionType; + /** Filename of the Ethereum app ELF binary. */ + elfFile: string; + /** Screen dimensions in pixels. */ + screenSize: { width: number; height: number }; + /** Touch coordinate for the generic confirm button. */ + confirmButton?: { x: number; y: number }; + /** Touch coordinate for the generic reject button. */ + rejectButton?: { x: number; y: number }; + /** Touch coordinate for the back button. */ + backButton?: { x: number; y: number }; + /** Touch coordinate for the confirm button during transaction review. */ + reviewConfirmButton?: { x: number; y: number }; + /** Touch coordinate for the reject button during transaction review. */ + reviewRejectButton?: { x: number; y: number }; + /** Touch coordinate for the home button. */ + homeButton?: { x: number; y: number }; +}; + +/** Registry of all supported Ledger device models. */ +export const DEVICE_MODELS: Record = { + nanosp: { + id: 'nanosp', + name: 'Nano S+', + speculosModel: 'nanosp', + interactionType: 'button', + elfFile: 'ethereum-nanosp.elf', + screenSize: { width: 128, height: 64 }, + }, + nanox: { + id: 'nanox', + name: 'Nano X', + speculosModel: 'nanox', + interactionType: 'button', + elfFile: 'ethereum-nanox.elf', + screenSize: { width: 128, height: 64 }, + }, + stax: { + id: 'stax', + name: 'Stax', + speculosModel: 'stax', + interactionType: 'touch', + elfFile: 'ethereum-stax.elf', + screenSize: { width: 400, height: 672 }, + backButton: { x: 36, y: 36 }, + confirmButton: { x: 200, y: 606 }, + rejectButton: { x: 36, y: 606 }, + reviewConfirmButton: { x: 200, y: 515 }, + reviewRejectButton: { x: 36, y: 606 }, + homeButton: { x: 200, y: 606 }, + }, + flex: { + id: 'flex', + name: 'Flex', + speculosModel: 'flex', + interactionType: 'touch', + elfFile: 'ethereum-flex.elf', + screenSize: { width: 480, height: 600 }, + backButton: { x: 45, y: 45 }, + confirmButton: { x: 240, y: 550 }, + rejectButton: { x: 55, y: 530 }, + reviewConfirmButton: { x: 240, y: 435 }, + reviewRejectButton: { x: 55, y: 530 }, + homeButton: { x: 240, y: 550 }, + }, +}; + +const FLEX_MODEL = DEVICE_MODELS.flex; +if (!FLEX_MODEL) { + throw new Error('Flex device model not found in DEVICE_MODELS'); +} +/** The default device model used when none is specified. */ +export const DEFAULT_DEVICE_MODEL: DeviceModel = FLEX_MODEL; + +/** + * Look up a device model by its identifier. + * + * @param id - The device model identifier (defaults to 'flex'). + * @returns The matching DeviceModel. + * @throws If the model identifier is not recognized. + */ +export function getDeviceModel(id = 'flex'): DeviceModel { + const model = DEVICE_MODELS[id]; + if (!model) { + throw new Error( + `Unknown device model "${id}". Valid: ${Object.keys(DEVICE_MODELS).join(', ')}`, + ); + } + return model; +} + +/** Execution mode for Speculos — native binary or Docker container. */ +export type RunMode = 'native' | 'docker'; + +/** + * Detect the appropriate Speculos run mode based on the current platform. + * + * @returns 'native' on Linux, 'docker' on all other platforms. + */ +export function detectRunMode(): RunMode { + // eslint-disable-next-line no-restricted-globals + return process.platform === 'linux' ? 'native' : 'docker'; +} diff --git a/packages/hw-emulator/src/ledger/device-interaction.test.ts b/packages/hw-emulator/src/ledger/device-interaction.test.ts new file mode 100644 index 000000000..26ac54a6d --- /dev/null +++ b/packages/hw-emulator/src/ledger/device-interaction.test.ts @@ -0,0 +1,154 @@ +import type { SpeculosClient } from './client'; +import { DEVICE_MODELS } from './constants'; +import type { DeviceModel } from './constants'; +import { + createDeviceInteraction, + NanoInteraction, + TouchInteraction, +} from './device-interaction'; + +function createMockClient(): jest.Mocked { + return { + pressButton: jest.fn().mockResolvedValue(undefined), + fingerTap: jest.fn().mockResolvedValue(undefined), + fingerSwipe: jest.fn().mockResolvedValue(undefined), + } as unknown as jest.Mocked; +} + +describe('createDeviceInteraction', () => { + it('creates NanoInteraction for button devices', () => { + const client = createMockClient(); + const model = DEVICE_MODELS.nanosp as DeviceModel; + const interaction = createDeviceInteraction(client, model); + expect(interaction).toBeInstanceOf(NanoInteraction); + }); + + it('creates TouchInteraction for touch devices', () => { + const client = createMockClient(); + const model = DEVICE_MODELS.flex as DeviceModel; + const interaction = createDeviceInteraction(client, model); + expect(interaction).toBeInstanceOf(TouchInteraction); + }); +}); + +describe('NanoInteraction', () => { + describe('approveTransaction', () => { + it('presses right 6 times then both', async () => { + const client = createMockClient(); + const interaction = new NanoInteraction(client); + await interaction.approveTransaction(); + expect(client.pressButton).toHaveBeenCalledTimes(7); + for (let callIdx = 0; callIdx < 6; callIdx++) { + expect(client.pressButton).toHaveBeenNthCalledWith( + callIdx + 1, + 'right', + ); + } + expect(client.pressButton).toHaveBeenNthCalledWith(7, 'both'); + }, 10000); + }); + + describe('approveSigning', () => { + it('presses right 2 times then both', async () => { + const client = createMockClient(); + const interaction = new NanoInteraction(client); + await interaction.approveSigning(); + expect(client.pressButton).toHaveBeenCalledTimes(3); + }); + }); + + describe('rejectTransaction', () => { + it('presses right then both', async () => { + const client = createMockClient(); + const interaction = new NanoInteraction(client); + await interaction.rejectTransaction(); + expect(client.pressButton).toHaveBeenCalledWith('right'); + expect(client.pressButton).toHaveBeenCalledWith('both'); + }); + }); +}); + +describe('TouchInteraction', () => { + describe('approveTransaction', () => { + it('swipes left 3 times then taps confirm', async () => { + const client = createMockClient(); + const model = DEVICE_MODELS.flex as DeviceModel; + const interaction = new TouchInteraction(client, model); + await interaction.approveTransaction(); + expect(client.fingerSwipe).toHaveBeenCalledTimes(3); + expect(client.fingerTap).toHaveBeenCalledTimes(1); + }, 10000); + }); + + describe('rejectTransaction', () => { + it('taps reject button', async () => { + const client = createMockClient(); + const model = DEVICE_MODELS.flex as DeviceModel; + const interaction = new TouchInteraction(client, model); + await interaction.rejectTransaction(); + expect(client.fingerTap).toHaveBeenCalledTimes(1); + }); + }); + + describe('enableBlindSigning', () => { + it('does nothing for NBGL devices', async () => { + const client = createMockClient(); + const model = DEVICE_MODELS.flex as DeviceModel; + const interaction = new TouchInteraction(client, model); + await interaction.enableBlindSigning(); + expect(client.fingerTap).not.toHaveBeenCalled(); + expect(client.fingerSwipe).not.toHaveBeenCalled(); + }); + }); + + describe('missing coordinates', () => { + const minimalModel: DeviceModel = { + id: 'minimal-touch', + name: 'Minimal Touch', + speculosModel: 'minimal', + interactionType: 'touch', + elfFile: 'minimal.elf', + screenSize: { width: 400, height: 672 }, + }; + + it('throws when tapConfirm has no reviewConfirmButton coordinates', async () => { + const interaction = new TouchInteraction( + createMockClient(), + minimalModel, + ); + await expect(interaction.tapConfirm()).rejects.toThrow( + 'reviewConfirmButton coordinates', + ); + }); + + it('throws when tapReject has no reviewRejectButton coordinates', async () => { + const interaction = new TouchInteraction( + createMockClient(), + minimalModel, + ); + await expect(interaction.tapReject()).rejects.toThrow( + 'reviewRejectButton coordinates', + ); + }); + + it('throws when tapBack has no backButton coordinates', async () => { + const interaction = new TouchInteraction( + createMockClient(), + minimalModel, + ); + await expect(interaction.tapBack()).rejects.toThrow( + 'backButton coordinates', + ); + }); + + it('throws when approveBlindSigning has no confirmButton coordinates', async () => { + const interaction = new TouchInteraction( + createMockClient(), + minimalModel, + ); + await expect(interaction.approveBlindSigning()).rejects.toThrow( + 'confirmButton coordinates', + ); + }); + }); +}); diff --git a/packages/hw-emulator/src/ledger/device-interaction.ts b/packages/hw-emulator/src/ledger/device-interaction.ts new file mode 100644 index 000000000..fdbc3b3f3 --- /dev/null +++ b/packages/hw-emulator/src/ledger/device-interaction.ts @@ -0,0 +1,352 @@ +import type { SpeculosClient } from './client'; +import type { DeviceModel } from './constants'; + +/** + * Interface for device screen interaction — pressing buttons or tapping the screen + * to approve, reject, or navigate through on-screen prompts. + */ +export type DeviceInteraction = { + /** Approve a transaction on the device screen. */ + approveTransaction(): Promise; + /** Approve a personal message or typed signing request. */ + approveSigning(): Promise; + /** Reject a transaction on the device screen. */ + rejectTransaction(): Promise; + /** Approve a blind signing request, scrolling through review screens. */ + approveBlindSigning(scrollCount?: number): Promise; + /** Enable blind signing in the Ethereum app settings. */ + enableBlindSigning(): Promise; + /** Navigate back to the main menu. */ + navigateToMainMenu(): Promise; +}; + +// ---- Shared review-flow constants ---- + +/** Default number of review screens scrolled before confirming blind signing. */ +const DEFAULT_BLIND_SIGNING_SCROLL_COUNT = 4; + +// ---- Button-based (Nano S+/Nano X) interaction constants ---- + +/** Review screens scrolled when approving a transaction on button devices. */ +const TX_REVIEW_SCREEN_COUNT = 6; + +/** Review screens scrolled when approving a message on button devices. */ +const SIGNING_REVIEW_SCREEN_COUNT = 2; + +/** Settings entries scrolled when enabling blind signing on button devices. */ +const BLIND_SIGNING_SETTINGS_SCREEN_COUNT = 6; + +/** Delay after a regular button press, in milliseconds. */ +const BUTTON_PRESS_DELAY_MS = 500; + +/** Delay after a button press that triggers a screen transition, in milliseconds. */ +const BUTTON_TRANSITION_DELAY_MS = 800; + +/** Delay after the button press that navigates toward the reject option, in milliseconds. */ +const REJECT_NAVIGATION_DELAY_MS = 300; + +/** Delay between scrolls in the settings menu, in milliseconds. */ +const SETTINGS_SCROLL_DELAY_MS = 200; + +/** Delay after a navigation press, in milliseconds. */ +const NAVIGATION_DELAY_MS = 400; + +// ---- Touch-based (Stax/Flex) interaction constants ---- + +/** Review swipes when approving a transaction on touch devices. */ +const TOUCH_TX_REVIEW_SWIPE_COUNT = 3; + +/** Review swipes when approving a message on touch devices. */ +const TOUCH_SIGNING_REVIEW_SWIPE_COUNT = 2; + +/** Horizontal distance of a review swipe, in pixels. */ +const SWIPE_DISTANCE_PX = 10; + +/** Duration of a swipe gesture, in seconds. */ +const SWIPE_DURATION_SECONDS = 0.5; + +/** Delay after a swipe or screen-changing tap, in milliseconds. */ +const TOUCH_TRANSITION_DELAY_MS = 800; + +/** Delay between blind-signing review swipes, in milliseconds. */ +const BLIND_SIGNING_SWIPE_DELAY_MS = 300; + +/** Delay letting a confirm/reject tap settle, in milliseconds. */ +const TAP_SETTLE_DELAY_MS = 500; + +/** Duration of a short tap, in seconds. */ +const TAP_DURATION_SECONDS = 0.1; + +/** Duration the review-confirm button is held, in seconds. */ +const CONFIRM_HOLD_SECONDS = 3.0; + +async function delay(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +/** + * Device interaction handler for Nano S+ and Nano X (button-based). + */ +export class NanoInteraction implements DeviceInteraction { + readonly #client: SpeculosClient; + + /** + * @param client - The Speculos client for sending button presses. + */ + constructor(client: SpeculosClient) { + this.#client = client; + } + + /** + * Approve a transaction by scrolling through 6 review screens and confirming. + */ + async approveTransaction(): Promise { + for (let step = 0; step < TX_REVIEW_SCREEN_COUNT; step++) { + await this.#client.pressButton('right'); + await delay(BUTTON_PRESS_DELAY_MS); + } + await this.#client.pressButton('both'); + await delay(BUTTON_PRESS_DELAY_MS); + } + + /** + * Approve a personal signing request by scrolling through 2 review screens and confirming. + */ + async approveSigning(): Promise { + for (let step = 0; step < SIGNING_REVIEW_SCREEN_COUNT; step++) { + await this.#client.pressButton('right'); + await delay(BUTTON_PRESS_DELAY_MS); + } + await this.#client.pressButton('both'); + await delay(BUTTON_PRESS_DELAY_MS); + } + + /** + * Approve blind signing by enabling it and scrolling through review screens. + * + * @param scrollCount - Number of screens to scroll through (default 4). + */ + async approveBlindSigning( + scrollCount = DEFAULT_BLIND_SIGNING_SCROLL_COUNT, + ): Promise { + await this.#client.pressButton('both'); + await delay(BUTTON_TRANSITION_DELAY_MS); + for (let step = 0; step < scrollCount; step++) { + await this.#client.pressButton('right'); + await delay(BUTTON_PRESS_DELAY_MS); + } + await this.#client.pressButton('both'); + await delay(BUTTON_PRESS_DELAY_MS); + } + + /** + * Reject a transaction by scrolling to the reject option and pressing both buttons. + */ + async rejectTransaction(): Promise { + await this.#client.pressButton('right'); + await delay(REJECT_NAVIGATION_DELAY_MS); + await this.#client.pressButton('both'); + await delay(BUTTON_PRESS_DELAY_MS); + } + + /** + * Enable blind signing in the Ethereum app settings via button navigation. + */ + async enableBlindSigning(): Promise { + await this.#client.pressButton('both'); + await delay(BUTTON_TRANSITION_DELAY_MS); + await this.#client.pressButton('right'); + await delay(NAVIGATION_DELAY_MS); + await this.#client.pressButton('both'); + await delay(BUTTON_TRANSITION_DELAY_MS); + await this.#client.pressButton('both'); + await delay(BUTTON_TRANSITION_DELAY_MS); + for (let step = 0; step < BLIND_SIGNING_SETTINGS_SCREEN_COUNT; step++) { + await this.#client.pressButton('right'); + await delay(SETTINGS_SCROLL_DELAY_MS); + } + await this.#client.pressButton('both'); + await delay(BUTTON_PRESS_DELAY_MS); + await this.#client.pressButton('left'); + await delay(NAVIGATION_DELAY_MS); + } + + /** + * Navigate back to the main menu by pressing the left button. + */ + async navigateToMainMenu(): Promise { + await this.#client.pressButton('left'); + await delay(NAVIGATION_DELAY_MS); + } +} + +/** + * Device interaction handler for Stax and Flex (touch-based). + */ +export class TouchInteraction implements DeviceInteraction { + readonly #client: SpeculosClient; + + readonly #model: DeviceModel; + + /** + * @param client - The Speculos client for sending touch events. + * @param model - The device model with screen and button coordinates. + */ + constructor(client: SpeculosClient, model: DeviceModel) { + this.#client = client; + this.#model = model; + } + + /** + * Swipe left on the touchscreen from center to near-center left. + */ + async swipeLeft(): Promise { + const { width, height } = this.#model.screenSize; + const centerX = width / 2; + const centerY = height / 2; + await this.#client.fingerSwipe( + centerX, + centerY, + centerX - SWIPE_DISTANCE_PX, + centerY, + SWIPE_DURATION_SECONDS, + ); + await delay(TOUCH_TRANSITION_DELAY_MS); + } + + /** + * Tap and hold the review confirm button. + * + * @param holdSeconds - Duration to hold the tap in seconds. + * @throws If the device model does not define reviewConfirmButton coordinates. + */ + async tapConfirm(holdSeconds = CONFIRM_HOLD_SECONDS): Promise { + const button = this.#model.reviewConfirmButton; + if (!button) { + throw new Error( + `Device model "${this.#model.id}" does not define reviewConfirmButton coordinates`, + ); + } + await this.#client.fingerTap(button.x, button.y, holdSeconds); + } + + /** + * Tap the review reject button. + * + * @throws If the device model does not define reviewRejectButton coordinates. + */ + async tapReject(): Promise { + const button = this.#model.reviewRejectButton; + if (!button) { + throw new Error( + `Device model "${this.#model.id}" does not define reviewRejectButton coordinates`, + ); + } + await this.#client.fingerTap(button.x, button.y, TAP_DURATION_SECONDS); + } + + /** + * Tap the back button. + * + * @throws If the device model does not define backButton coordinates. + */ + async tapBack(): Promise { + const button = this.#model.backButton; + if (!button) { + throw new Error( + `Device model "${this.#model.id}" does not define backButton coordinates`, + ); + } + await this.#client.fingerTap(button.x, button.y, TAP_DURATION_SECONDS); + } + + /** + * Approve a transaction by swiping through review screens and tapping confirm. + */ + async approveTransaction(): Promise { + for (let step = 0; step < TOUCH_TX_REVIEW_SWIPE_COUNT; step++) { + await this.swipeLeft(); + } + await this.tapConfirm(); + await delay(TAP_SETTLE_DELAY_MS); + } + + /** + * Approve a personal signing request by swiping through review screens and tapping confirm. + */ + async approveSigning(): Promise { + for (let step = 0; step < TOUCH_SIGNING_REVIEW_SWIPE_COUNT; step++) { + await this.swipeLeft(); + } + await this.tapConfirm(); + await delay(TAP_SETTLE_DELAY_MS); + } + + /** + * Approve blind signing by tapping confirm, scrolling, and confirming. + * + * @param scrollCount - Number of screens to scroll through (default 4). + * @throws If the device model does not define confirmButton coordinates. + */ + async approveBlindSigning( + scrollCount = DEFAULT_BLIND_SIGNING_SCROLL_COUNT, + ): Promise { + const button = this.#model.confirmButton; + if (!button) { + throw new Error( + `Device model "${this.#model.id}" does not define confirmButton coordinates`, + ); + } + await this.#client.fingerTap(button.x, button.y, TAP_DURATION_SECONDS); + await delay(TOUCH_TRANSITION_DELAY_MS); + + for (let step = 0; step < scrollCount; step++) { + await this.swipeLeft(); + await delay(BLIND_SIGNING_SWIPE_DELAY_MS); + } + await this.tapConfirm(); + await delay(TAP_SETTLE_DELAY_MS); + } + + /** + * Reject a transaction by tapping the reject button. + */ + async rejectTransaction(): Promise { + await this.tapReject(); + await delay(TAP_SETTLE_DELAY_MS); + } + + /** + * Enable blind signing (no-op for NBGL devices — pre-enabled via NVRAM). + */ + async enableBlindSigning(): Promise { + console.log( + '[DeviceInteraction] Blind signing pre-enabled via NVRAM for NBGL device', + ); + } + + /** + * Navigate back to the main menu by tapping the back button. + */ + async navigateToMainMenu(): Promise { + await this.tapBack(); + await delay(NAVIGATION_DELAY_MS); + } +} + +/** + * Create the appropriate device interaction handler based on the device model. + * + * @param client - The Speculos client. + * @param model - The device model configuration. + * @returns A DeviceInteraction instance. + */ +export function createDeviceInteraction( + client: SpeculosClient, + model: DeviceModel, +): DeviceInteraction { + if (model.interactionType === 'touch') { + return new TouchInteraction(client, model); + } + return new NanoInteraction(client); +} diff --git a/packages/hw-emulator/src/ledger/docker-manager.test.ts b/packages/hw-emulator/src/ledger/docker-manager.test.ts new file mode 100644 index 000000000..41ca1f426 --- /dev/null +++ b/packages/hw-emulator/src/ledger/docker-manager.test.ts @@ -0,0 +1,257 @@ +import { DockerManager } from './docker-manager'; +import type { DockerCommandRunner } from './docker-manager'; + +describe('DockerManager', () => { + it('initializes with idle status', () => { + const manager = new DockerManager({ + composeFile: '/path/to/docker-compose.yml', + apduPort: 9998, + apiPort: 5001, + app: '/path/to/app.elf', + }); + expect(manager.getStatus()).toBe('idle'); + }); + + it('throws if start is called when not idle', async () => { + const manager = new DockerManager({ + composeFile: '/path/to/docker-compose.yml', + apduPort: 9998, + apiPort: 5001, + app: '/path/to/app.elf', + }); + // Direct start with invalid compose file should fail + await expect(manager.start()).rejects.toThrow('docker compose'); + expect(manager.getStatus()).toBe('idle'); + }, 10_000); + + it('buildDockerEnv includes SPECULOS_SEED when seed option is set', () => { + const manager = new DockerManager({ + composeFile: '/path/to/docker-compose.yml', + apduPort: 9998, + apiPort: 5001, + app: '/path/to/apps/ethereum-flex.elf', + model: 'flex', + seed: 'custom test seed phrase', + }); + + expect(manager.buildDockerEnv()).toStrictEqual({ + SPECULOS_DEVICE: 'flex', + SPECULOS_ELF_FILENAME: 'ethereum-flex.elf', + SPECULOS_APDU_PORT: '9998', + SPECULOS_API_PORT: '5001', + SPECULOS_SEED: 'custom test seed phrase', + }); + }); + + it('buildDockerEnv omits SPECULOS_SEED when seed option is unset', () => { + const manager = new DockerManager({ + composeFile: '/path/to/docker-compose.yml', + apduPort: 9998, + apiPort: 5001, + app: '/path/to/app.elf', + }); + + expect(manager.buildDockerEnv()).toStrictEqual({ + SPECULOS_DEVICE: 'nanosp', + SPECULOS_ELF_FILENAME: 'app.elf', + SPECULOS_APDU_PORT: '9998', + SPECULOS_API_PORT: '5001', + }); + }); + + it('buildDockerEnv maps non-default host ports for DEVICE_PRESETS', () => { + const manager = new DockerManager({ + composeFile: '/path/to/docker-compose.yml', + apduPort: 9997, + apiPort: 5002, + app: 'ethereum-nanosp.elf', + }); + + expect(manager.buildDockerEnv()).toMatchObject({ + SPECULOS_APDU_PORT: '9997', + SPECULOS_API_PORT: '5002', + }); + }); + + it('stop resolves immediately when idle', async () => { + const manager = new DockerManager({ + composeFile: '/path/to/docker-compose.yml', + apduPort: 9998, + apiPort: 5001, + app: '/path/to/app.elf', + }); + await manager.stop(); + expect(manager.getStatus()).toBe('idle'); + }); + + it('buildDockerEnv includes SPECULOS_DISPLAY when display option is set', () => { + const manager = new DockerManager({ + composeFile: '/path/to/docker-compose.yml', + apduPort: 9997, + apiPort: 5002, + app: '/apps/ethereum-flex.elf', + model: 'flex', + seed: 'test seed words', + display: 'headless', + }); + + expect(manager.buildDockerEnv()).toStrictEqual({ + SPECULOS_DEVICE: 'flex', + SPECULOS_ELF_FILENAME: 'ethereum-flex.elf', + SPECULOS_APDU_PORT: '9997', + SPECULOS_API_PORT: '5002', + SPECULOS_SEED: 'test seed words', + SPECULOS_DISPLAY: 'headless', + }); + }); +}); + +describe('DockerManager concurrent naming', () => { + it('derives a unique container and project name from the APDU port by default', () => { + const first = new DockerManager({ + composeFile: '/path/to/docker-compose.yml', + apduPort: 9998, + apiPort: 5001, + app: '/path/to/app.elf', + }); + const second = new DockerManager({ + composeFile: '/path/to/docker-compose.yml', + apduPort: 9997, + apiPort: 5002, + app: '/path/to/app.elf', + }); + + expect(first.getContainerName()).toBe('metamask-speculos-9998'); + expect(first.getProjectName()).toBe('metamask-speculos-9998'); + expect(second.getContainerName()).toBe('metamask-speculos-9997'); + expect(first.getContainerName()).not.toBe(second.getContainerName()); + }); + + it('honors explicit container and project names', () => { + const manager = new DockerManager({ + composeFile: '/path/to/docker-compose.yml', + apduPort: 9998, + apiPort: 5001, + app: '/path/to/app.elf', + containerName: 'Custom Container_Name', + projectName: 'Custom Project', + }); + + expect(manager.getContainerName()).toBe('custom-container_name'); + expect(manager.getProjectName()).toBe('custom-project'); + }); +}); + +describe('DockerManager lifecycle (injected runner)', () => { + type RecordedCall = { command: string; args: string[] }; + + function createRecordingRunner( + healthStatus: 'healthy' | 'starting' = 'healthy', + ): { + runner: DockerCommandRunner; + calls: RecordedCall[]; + failOn: (subcommand: string) => void; + } { + const calls: RecordedCall[] = []; + let failSubcommand: string | null = null; + const failOn = (subcommand: string): void => { + failSubcommand = subcommand; + }; + const runner: DockerCommandRunner = async (command, args) => { + calls.push({ command, args }); + if (failSubcommand && args.includes(failSubcommand)) { + throw new Error(`forced failure: ${failSubcommand}`); + } + if (args.includes('inspect')) { + return { stdout: `${healthStatus}\n`, stderr: '' }; + } + return { stdout: '', stderr: '' }; + }; + return { runner, calls, failOn }; + } + + function findCall( + calls: RecordedCall[], + subcommand: string, + ): RecordedCall | undefined { + return calls.find((call) => call.args.includes(subcommand)); + } + + const baseOptions = { + composeFile: '/path/to/docker-compose.yml', + apduPort: 9998, + apiPort: 5001, + app: '/path/to/app.elf', + }; + + it('uses the same project name for up and down', async () => { + const { runner, calls } = createRecordingRunner(); + const manager = new DockerManager({ + ...baseOptions, + execFileAsync: runner, + }); + + await manager.start(); + await manager.stop(); + + const upCall = findCall(calls, 'up'); + const downCall = findCall(calls, 'down'); + expect(upCall).toBeDefined(); + expect(downCall).toBeDefined(); + + const projectIndex = upCall?.args.indexOf('-p'); + expect(projectIndex).toBeGreaterThan(-1); + expect(upCall?.args[(projectIndex as number) + 1]).toBe( + 'metamask-speculos-9998', + ); + expect(downCall?.args).toContain('-p'); + expect(downCall?.args).toContain('metamask-speculos-9998'); + }); + + it('passes the configured stopTimeout (seconds) to docker compose down --timeout', async () => { + const { runner, calls } = createRecordingRunner(); + const manager = new DockerManager({ + ...baseOptions, + stopTimeout: 5_000, + execFileAsync: runner, + }); + + await manager.start(); + await manager.stop(); + + const downCall = findCall(calls, 'down'); + const timeoutIndex = downCall?.args.indexOf('--timeout'); + expect(timeoutIndex).toBeGreaterThan(-1); + expect(downCall?.args[(timeoutIndex as number) + 1]).toBe('5'); + }); + + it('runs docker compose down when the health check times out', async () => { + const { runner, calls } = createRecordingRunner('starting'); + const manager = new DockerManager({ + ...baseOptions, + startTimeout: 100, + stopTimeout: 1_000, + execFileAsync: runner, + }); + + await expect(manager.start()).rejects.toThrow('health check timed out'); + + expect(findCall(calls, 'down')).toBeDefined(); + expect(manager.getStatus()).toBe('idle'); + }); + + it('runs docker compose down when docker compose up fails', async () => { + const { runner, calls, failOn } = createRecordingRunner(); + failOn('up'); + const manager = new DockerManager({ + ...baseOptions, + execFileAsync: runner, + }); + + await expect(manager.start()).rejects.toThrow('forced failure: up'); + + // A failed start must tear the (possibly partial) container down. + expect(findCall(calls, 'down')).toBeDefined(); + expect(manager.getStatus()).toBe('idle'); + }); +}); diff --git a/packages/hw-emulator/src/ledger/docker-manager.ts b/packages/hw-emulator/src/ledger/docker-manager.ts new file mode 100644 index 000000000..c27977b00 --- /dev/null +++ b/packages/hw-emulator/src/ledger/docker-manager.ts @@ -0,0 +1,368 @@ +// eslint-disable-next-line import-x/no-nodejs-modules +import { execFile } from 'node:child_process'; +// eslint-disable-next-line import-x/no-nodejs-modules +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +// eslint-disable-next-line import-x/no-nodejs-modules +import { tmpdir } from 'node:os'; +// eslint-disable-next-line import-x/no-nodejs-modules +import path from 'node:path'; +// eslint-disable-next-line import-x/no-nodejs-modules +import { promisify } from 'node:util'; + +const execFileAsync = promisify(execFile); + +const CONTAINER_NAME_PREFIX = 'metamask-speculos'; +const HEALTH_CHECK_INTERVAL_MS = 1000; +const HEALTH_CHECK_TIMEOUT_MS = 60_000; +const DEFAULT_STOP_TIMEOUT_MS = 30_000; + +/** + * Injectable `docker` CLI runner. Production uses promisified `execFile`; + * tests can substitute a fake. Follows the signature of + * `util.promisify(child_process.execFile)`. + */ +export type DockerCommandRunner = ( + command: string, + args: string[], + options: { timeout: number; env?: Record }, +) => Promise<{ stdout: string; stderr: string }>; + +/** + * Check if a Docker container's health status is "healthy". + * + * @param containerName - The container to inspect. + * @param runDocker - The command runner used to invoke docker. + * @returns True if the container reports healthy. + */ +async function isContainerHealthy( + containerName: string, + runDocker: DockerCommandRunner, +): Promise { + try { + const { stdout } = await runDocker( + 'docker', + ['inspect', '--format={{.State.Health.Status}}', containerName], + { timeout: HEALTH_CHECK_TIMEOUT_MS }, + ); + return stdout.trim() === 'healthy'; + } catch { + return false; + } +} + +/** + * Compose project and container names only allow lowercase letters, digits, + * dashes and underscores. + * + * @param name - The raw name. + * @returns The sanitized name. + */ +function sanitizeName(name: string): string { + return name.toLowerCase().replace(/[^a-z0-9_-]/gu, '-'); +} + +/** + * Options for configuring the Docker-based Speculos manager. + */ +export type DockerManagerOptions = { + /** Path to the docker-compose.yml file. */ + composeFile: string; + /** TCP port for the APDU protocol. */ + apduPort: number; + /** TCP port for the REST API. */ + apiPort: number; + /** Path to the Ethereum app ELF binary. */ + app: string; + /** Speculos device model identifier. */ + model?: string; + /** BIP-39 mnemonic seed. */ + seed?: string; + /** Display backend. */ + display?: string; + /** Whether to load NVRAM state. */ + loadNvram?: boolean; + /** Maximum time in milliseconds to wait for the container to start. */ + startTimeout?: number; + /** Maximum time in milliseconds to wait for the container to stop. */ + stopTimeout?: number; + /** + * Container name. Defaults to a unique name derived from the APDU port so + * multiple instances can run concurrently. + */ + containerName?: string; + /** + * Docker Compose project name. Defaults to a name derived from the APDU + * port; the same project is targeted by both start() and stop(). + */ + projectName?: string; + /** + * Injectable `docker` CLI runner for tests. Production uses + * `execFile` from `node:child_process`. + */ + execFileAsync?: DockerCommandRunner; +}; + +/** Lifecycle status of the Docker container. */ +export type DockerManagerStatus = 'idle' | 'starting' | 'running' | 'stopping'; + +/** + * Manage a Speculos Docker container via docker-compose. + * + * Each instance pins its own container name (via a generated compose override + * file) and Compose project name so multiple managers can run concurrently + * without fighting over a single hardcoded `metamask-speculos` container. + */ +export class DockerManager { + readonly #options: DockerManagerOptions; + + readonly #exec: DockerCommandRunner; + + readonly #containerName: string; + + readonly #projectName: string; + + #containerStatus: DockerManagerStatus = 'idle'; + + #overrideDir: string | null = null; + + /** + * @param options - Docker manager configuration. + */ + constructor(options: DockerManagerOptions) { + this.#options = options; + this.#exec = options.execFileAsync ?? execFileAsync; + this.#containerName = sanitizeName( + options.containerName ?? `${CONTAINER_NAME_PREFIX}-${options.apduPort}`, + ); + this.#projectName = sanitizeName( + options.projectName ?? `${CONTAINER_NAME_PREFIX}-${options.apduPort}`, + ); + } + + /** + * Get the container name used by this manager. + * + * @returns The Docker container name. + */ + getContainerName(): string { + return this.#containerName; + } + + /** + * Get the Docker Compose project name used by this manager. + * + * @returns The Compose project name. + */ + getProjectName(): string { + return this.#projectName; + } + + /** + * Build the environment variables map for docker-compose variable substitution. + * + * @returns A record of environment variable names to values. + */ + buildDockerEnv(): Record { + // Extract ELF filename from full path for docker-compose.yml variable substitution + const elfFilename = path.basename(this.#options.app); + + const env: Record = { + SPECULOS_DEVICE: this.#options.model ?? 'nanosp', + SPECULOS_ELF_FILENAME: elfFilename, + SPECULOS_APDU_PORT: String(this.#options.apduPort), + SPECULOS_API_PORT: String(this.#options.apiPort), + }; + if (this.#options.seed) { + env.SPECULOS_SEED = this.#options.seed; + } + if (this.#options.display) { + env.SPECULOS_DISPLAY = this.#options.display; + } + return env; + } + + /** + * Write a compose override file pinning this instance's container name, and + * return the compose flags (-f/-p) shared by all compose invocations. + * + * @returns The compose command arguments. + */ + async #prepareComposeArgs(): Promise { + this.#overrideDir = await mkdtemp( + path.join(tmpdir(), `${CONTAINER_NAME_PREFIX}-`), + ); + const overrideFile = path.join( + this.#overrideDir, + 'docker-compose.override.yml', + ); + await writeFile( + overrideFile, + `services:\n speculos:\n container_name: ${this.#containerName}\n`, + 'utf8', + ); + return [ + '-f', + this.#options.composeFile, + '-f', + overrideFile, + '-p', + this.#projectName, + ]; + } + + /** + * Remove the temporary override directory, if any. + */ + async #removeOverrideDir(): Promise { + if (this.#overrideDir) { + await rm(this.#overrideDir, { recursive: true, force: true }); + this.#overrideDir = null; + } + } + + /** + * Run `docker compose down` for this instance's project. + * + * @param composeArgs - The compose flags from #prepareComposeArgs. + * @param timeoutMs - Timeout in milliseconds for the command. + */ + async #runComposeDown( + composeArgs: string[], + timeoutMs: number, + ): Promise { + // `docker compose down --timeout` takes seconds. + const timeoutSeconds = String(Math.max(1, Math.round(timeoutMs / 1000))); + await this.#exec( + 'docker', + ['compose', ...composeArgs, 'down', '--timeout', timeoutSeconds], + { timeout: timeoutMs }, + ); + } + + /** + * Start the Docker container and wait for health checks. + * + * If `docker compose up` or the health check fails, `docker compose down` + * is run for this project before the error is rethrown so no container is + * left running behind. + * + * @returns A promise that resolves when the container is healthy. + */ + async start(): Promise { + if (this.#containerStatus !== 'idle') { + throw new Error( + `Docker container not idle (current: ${this.#containerStatus})`, + ); + } + this.#containerStatus = 'starting'; + + const env = this.buildDockerEnv(); + + const timeout = this.#options.startTimeout ?? HEALTH_CHECK_TIMEOUT_MS; + + let composeArgs: string[]; + try { + composeArgs = await this.#prepareComposeArgs(); + } catch (prepareError) { + this.#containerStatus = 'idle'; + throw prepareError; + } + + try { + // Merge docker env vars into the process environment so that + // docker-compose.yml variable substitution picks them up. + // (docker compose up does NOT support -e flags — only docker compose run does.) + // eslint-disable-next-line no-restricted-globals + const childEnv = { ...process.env, ...env }; + + await this.#exec('docker', ['compose', ...composeArgs, 'up', '-d'], { + timeout, + env: childEnv, + }); + + const deadline = Date.now() + timeout; + while (Date.now() < deadline) { + if (await isContainerHealthy(this.#containerName, this.#exec)) { + this.#containerStatus = 'running'; + return; + } + await new Promise((resolve) => + setTimeout(resolve, HEALTH_CHECK_INTERVAL_MS), + ); + } + + throw new Error( + `Docker container health check timed out after ${timeout}ms`, + ); + } catch (startError: unknown) { + // Tear the (possibly partially started) container down so nothing is + // left running. Best effort — always rethrow the original error. + const stopTimeout = this.#options.stopTimeout ?? DEFAULT_STOP_TIMEOUT_MS; + try { + await this.#runComposeDown(composeArgs, stopTimeout); + } catch { + // Best effort — surface the original error instead. + } + await this.#removeOverrideDir().catch(() => undefined); + this.#containerStatus = 'idle'; + throw startError; + } + } + + /** + * Stop and remove the Docker container. + * + * @returns A promise that resolves when the container is stopped. + */ + async stop(): Promise { + // Only treat the manager as fully stopped when the container is idle AND + // no override directory is left behind. A failed start() resets the + // status to 'idle' in its catch block, but the best-effort override-dir + // cleanup there can itself fail — leaving #overrideDir set. Checking + // only the status would then leak that leftover directory, so stop() + // must still run to remove it. + if (this.#containerStatus === 'idle' && this.#overrideDir === null) { + return; + } + this.#containerStatus = 'stopping'; + + const timeout = this.#options.stopTimeout ?? DEFAULT_STOP_TIMEOUT_MS; + + try { + if (this.#overrideDir) { + const overrideFile = path.join( + this.#overrideDir, + 'docker-compose.override.yml', + ); + await this.#exec( + 'docker', + [ + 'compose', + '-f', + this.#options.composeFile, + '-f', + overrideFile, + '-p', + this.#projectName, + 'down', + '--timeout', + String(Math.max(1, Math.round(timeout / 1000))), + ], + { timeout }, + ); + } + } finally { + await this.#removeOverrideDir().catch(() => undefined); + this.#containerStatus = 'idle'; + } + } + + /** + * Get the current container status. + * + * @returns The container status. + */ + getStatus(): DockerManagerStatus { + return this.#containerStatus; + } +} diff --git a/packages/hw-emulator/src/ledger/index.ts b/packages/hw-emulator/src/ledger/index.ts new file mode 100644 index 000000000..f1d3e5b0e --- /dev/null +++ b/packages/hw-emulator/src/ledger/index.ts @@ -0,0 +1,50 @@ +export { Speculos, type SpeculosOptions } from './speculos'; +export { + SpeculosClient, + type SpeculosClientOptions, + type APDUResponse, +} from './client'; +export { ApduBridge, type InjectedErrorMatcher } from './apdu-bridge'; +export { + createDeviceInteraction, + NanoInteraction, + TouchInteraction, + type DeviceInteraction, +} from './device-interaction'; +export { + createProcessManager, + type ProcessManager, + type ProcessManagerOptions, + type ProcessManagerStatus, +} from './process-manager'; +export { + DockerManager, + type DockerManagerOptions, + type DockerManagerStatus, +} from './docker-manager'; +export { getWebHidMockScript } from './webhid-mock-script'; +export { + DEVICE_MODELS, + DEFAULT_DEVICE_MODEL, + DEFAULT_DEVICE, + DEVICE_PRESETS, + SPECULOS_APDU_PORT, + SPECULOS_API_PORT, + SPECULOS_WS_BRIDGE_PORT, + SPECULOS_LEDGER_ADDRESSES, + SPECULOS_LEDGER_ADDRESS, + SPECULOS_SEED, + getDeviceModel, + detectRunMode, + type DeviceModel, + type DeviceConfig, + type InteractionType, + type RunMode, +} from './constants'; +export { withRetry, ExponentialBackoff, isRetryableError } from './resilience'; +export { + createLedgerHidFramingSession, + pushLedgerHidFrame, + encodeLedgerHidResponse, + type LedgerHidFramingSession, +} from './ledger-hid-framing'; diff --git a/packages/hw-emulator/src/ledger/ledger-hid-framing.test.ts b/packages/hw-emulator/src/ledger/ledger-hid-framing.test.ts new file mode 100644 index 000000000..e1721bb1f --- /dev/null +++ b/packages/hw-emulator/src/ledger/ledger-hid-framing.test.ts @@ -0,0 +1,63 @@ +import type { LedgerHidFramingSession } from './ledger-hid-framing'; +import { + createLedgerHidFramingSession, + encodeLedgerHidResponse, + pushLedgerHidFrame, +} from './ledger-hid-framing'; + +/** HID packet size used by Ledger devices. */ +const PACKET_SIZE = 64; + +/** + * Build a session for a channel by seeding a first frame. + * + * @param channel - The communication channel ID. + * @returns A framing session for that channel. + */ +function createSession(channel: number): LedgerHidFramingSession { + const firstFrame = Buffer.alloc(PACKET_SIZE); + firstFrame.writeUInt16BE(channel, 0); + return createLedgerHidFramingSession(firstFrame); +} + +describe('ledger HID framing', () => { + it('round-trips a single-frame APDU response', () => { + const apdu = Buffer.from('9000', 'hex'); + const encoder = createSession(0x0101); + const frames = encodeLedgerHidResponse(encoder, apdu); + + expect(frames).toHaveLength(1); + expect(frames[0]).toHaveLength(PACKET_SIZE); + + const decoder = createSession(0x0101); + expect(pushLedgerHidFrame(decoder, frames[0] as Buffer)).toStrictEqual( + apdu, + ); + }); + + it('reassembles an APDU split across multiple frames', () => { + const apdu = Buffer.alloc(200, 0xab); + const encoder = createSession(0x0202); + const frames = encodeLedgerHidResponse(encoder, apdu); + + expect(frames.length).toBeGreaterThan(1); + + const decoder = createSession(0x0202); + const results = frames.map((frame) => pushLedgerHidFrame(decoder, frame)); + + expect(results.at(-1)).toStrictEqual(apdu); + // Only the final frame completes the APDU. + expect(results.slice(0, -1).every((result) => result === null)).toBe(true); + }); + + it('ignores frames for another channel', () => { + const encoder = createSession(0x0303); + const [frame] = encodeLedgerHidResponse( + encoder, + Buffer.from('9000', 'hex'), + ); + + const decoder = createSession(0x0404); + expect(pushLedgerHidFrame(decoder, frame as Buffer)).toBeNull(); + }); +}); diff --git a/packages/hw-emulator/src/ledger/ledger-hid-framing.ts b/packages/hw-emulator/src/ledger/ledger-hid-framing.ts new file mode 100644 index 000000000..7d7a80fdb --- /dev/null +++ b/packages/hw-emulator/src/ledger/ledger-hid-framing.ts @@ -0,0 +1,205 @@ +/* eslint-disable no-restricted-globals -- Buffer is required for Ledger HID framing. */ + +/** + * Ledger HID packet framing. + * + * Vendored from `@ledgerhq/devices`'s `lib/hid-framing` (MIT), which was + * removed in v8. Kept behavior-compatible with the v7 implementation so + * existing framing sessions and the APDU bridge keep working. + */ + +/** HID packet size in bytes used by Ledger devices. */ +const PACKET_SIZE = 64; + +/** Frame tag byte used by Ledger HID framing. */ +const TAG = 0x05; + +/** Error thrown when an incoming HID frame fails validation. */ +class LedgerHidFramingError extends Error { + readonly id: string; + + constructor(message: string, id: string) { + super(message); + this.name = 'LedgerHidFramingError'; + this.id = id; + } +} + +/** + * Accumulated response state while reassembling HID frames. + */ +export type ResponseAcc = { + /** Accumulated APDU payload bytes. */ + data: Buffer; + /** Total APDU payload length declared by the first frame. */ + dataLength: number; + /** Index of the next expected frame. */ + sequence: number; +}; + +const INITIAL_ACC: ResponseAcc = { + data: Buffer.alloc(0), + dataLength: 0, + sequence: 0, +}; + +/** + * Encode a 16-bit big-endian value. + * + * @param value - The value to encode. + * @returns A 2-byte buffer. + */ +function asUInt16BE(value: number): Buffer { + const buffer = Buffer.alloc(2); + buffer.writeUInt16BE(value, 0); + return buffer; +} + +/** + * HID framing codec for one channel. + */ +type HidFraming = { + /** Encode an APDU response into HID frames. */ + makeBlocks: (apdu: Buffer) => Buffer[]; + /** Reassemble one frame into the running accumulator. */ + reduceResponse: (acc: ResponseAcc | null, chunk: Buffer) => ResponseAcc; + /** Return the complete APDU once all frames have arrived. */ + getReducedResult: (acc: ResponseAcc | null) => Buffer | undefined; +}; + +/** + * Create a HID framing codec for a channel. + * + * @param channel - The communication channel ID. + * @param packetSize - The HID packet size in bytes. + * @returns The framing codec. + */ +function createHIDframing(channel: number, packetSize: number): HidFraming { + return { + makeBlocks(apdu: Buffer): Buffer[] { + let data = Buffer.concat([asUInt16BE(apdu.length), apdu]); + const blockSize = packetSize - 5; + const nbBlocks = Math.ceil(data.length / blockSize); + data = Buffer.concat([ + data, + Buffer.alloc(nbBlocks * blockSize - data.length + 1).fill(0), + ]); + const blocks: Buffer[] = []; + for (let blockIndex = 0; blockIndex < nbBlocks; blockIndex++) { + const head = Buffer.alloc(5); + head.writeUInt16BE(channel, 0); + head.writeUInt8(TAG, 2); + head.writeUInt16BE(blockIndex, 3); + const chunk = data.slice( + blockIndex * blockSize, + (blockIndex + 1) * blockSize, + ); + blocks.push(Buffer.concat([head, chunk])); + } + return blocks; + }, + reduceResponse(acc: ResponseAcc | null, chunk: Buffer): ResponseAcc { + const { data, dataLength, sequence } = acc ?? INITIAL_ACC; + if (chunk.readUInt16BE(0) !== channel) { + throw new LedgerHidFramingError('Invalid channel', 'InvalidChannel'); + } + if (chunk.readUInt8(2) !== TAG) { + throw new LedgerHidFramingError('Invalid tag', 'InvalidTag'); + } + if (chunk.readUInt16BE(3) !== sequence) { + throw new LedgerHidFramingError('Invalid sequence', 'InvalidSequence'); + } + const nextDataLength = acc ? dataLength : chunk.readUInt16BE(5); + const chunkData = chunk.slice(acc ? 5 : 7); + let nextData = Buffer.concat([data, chunkData]); + if (nextData.length > nextDataLength) { + nextData = nextData.slice(0, nextDataLength); + } + return { + data: nextData, + dataLength: nextDataLength, + sequence: sequence + 1, + }; + }, + getReducedResult(acc: ResponseAcc | null): Buffer | undefined { + if (acc && acc.dataLength === acc.data.length) { + return acc.data; + } + return undefined; + }, + }; +} + +/** + * Session state for reassembling and encoding Ledger HID frames. + */ +export type LedgerHidFramingSession = { + /** The communication channel ID. */ + channel: number; + /** The Ledger HID framing instance for encoding/decoding. */ + framing: ReturnType; + /** The accumulated response accumulator. */ + acc: ResponseAcc | null; +}; + +/** + * Create a framing session from the first HID frame. + * + * @param firstFrame - The first HID frame to initialize the session. + * @returns A new framing session. + */ +export function createLedgerHidFramingSession( + firstFrame: Buffer, +): LedgerHidFramingSession { + const channel = firstFrame.readUInt16BE(0); + return { + channel, + framing: createHIDframing(channel, PACKET_SIZE), + acc: null, + }; +} + +/** + * Push an incoming HID frame and return the complete APDU when ready. + * + * @param session - The framing session. + * @param frame - The HID frame to push. + * @returns The complete APDU buffer, or null if more frames are needed. + */ +export function pushLedgerHidFrame( + session: LedgerHidFramingSession, + frame: Buffer, +): Buffer | null { + try { + session.acc = session.framing.reduceResponse(session.acc, frame); + const result = session.framing.getReducedResult(session.acc); + if (result) { + session.acc = null; + return result; + } + return null; + } catch (rawError: unknown) { + const errorId = + rawError && typeof rawError === 'object' && 'id' in rawError + ? String((rawError as { id: string }).id) + : ''; + if (errorId === 'InvalidChannel') { + return null; + } + throw rawError; + } +} + +/** + * Encode a raw APDU response into HID frames. + * + * @param session - The framing session. + * @param apduResponse - The raw APDU response to encode. + * @returns An array of HID frame buffers. + */ +export function encodeLedgerHidResponse( + session: LedgerHidFramingSession, + apduResponse: Buffer, +): Buffer[] { + return session.framing.makeBlocks(apduResponse); +} diff --git a/packages/hw-emulator/src/ledger/process-manager.test.ts b/packages/hw-emulator/src/ledger/process-manager.test.ts new file mode 100644 index 000000000..5cd684f7b --- /dev/null +++ b/packages/hw-emulator/src/ledger/process-manager.test.ts @@ -0,0 +1,177 @@ +/* eslint-disable n/no-sync -- synchronous fs is acceptable for temp-file test fixtures. */ +import { + chmodSync, + mkdtempSync, + readFileSync, + realpathSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import net from 'node:net'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; + +import { createProcessManager } from './process-manager'; + +/** + * Find a free TCP port. + * + * @returns A momentarily free port number. + */ +async function findFreePort(): Promise { + const probe = net.createServer(); + await new Promise((resolve) => { + probe.listen(0, '127.0.0.1', () => resolve()); + }); + const address = probe.address(); + const port = address && typeof address === 'object' ? address.port : 0; + await new Promise((resolve) => { + probe.close(() => resolve()); + }); + return port; +} + +describe('createProcessManager', () => { + it('returns an object with start, stop, status, and pid', () => { + const manager = createProcessManager({ + binary: '/usr/bin/speculos', + app: '/path/to/app.elf', + }); + expect(manager.status).toBe('idle'); + expect(manager.pid).toBeUndefined(); + expect(typeof manager.start).toBe('function'); + expect(typeof manager.stop).toBe('function'); + }); + + it('throws if start is called when not idle', async () => { + const manager = createProcessManager({ + binary: '/usr/bin/speculos', + app: '/path/to/app.elf', + }); + // First start will try to spawn and fail (binary doesn't exist) + // But we can test the status check by mocking + await expect(manager.start()).rejects.toThrow('ENOENT'); + }); + + it('stop resolves immediately when idle', async () => { + const manager = createProcessManager({ + binary: '/usr/bin/speculos', + app: '/path/to/app.elf', + }); + await manager.stop(); + expect(manager.status).toBe('idle'); + }); + + it('passes --load-nvram and the configured cwd to the spawned process', async () => { + const apduPort = await findFreePort(); + const apiPort = await findFreePort(); + const fixtureDir = mkdtempSync(path.join(tmpdir(), 'pm-test-')); + const fixture = path.join(fixtureDir, 'server.js'); + const recordFile = path.join(fixtureDir, 'spawn.json'); + // The fixture records its argv and cwd, then opens both readiness ports so + // the manager considers startup complete. + writeFileSync( + fixture, + [ + '#!/usr/bin/env node', + 'const fs = require("fs");', + 'const net = require("net");', + `fs.writeFileSync(${JSON.stringify(recordFile)}, JSON.stringify({ argv: process.argv.slice(2), cwd: process.cwd() }));`, + `net.createServer(() => {}).listen(${apduPort}, "127.0.0.1");`, + `net.createServer(() => {}).listen(${apiPort}, "127.0.0.1");`, + 'setInterval(() => {}, 1000);', + ].join('\n'), + 'utf8', + ); + chmodSync(fixture, 0o755); + + try { + const manager = createProcessManager({ + binary: fixture, + app: 'app.elf', + loadNvram: true, + cwd: fixtureDir, + apduPort, + apiPort, + startTimeout: 15_000, + stopTimeout: 5_000, + }); + + await manager.start(); + + const record = JSON.parse(readFileSync(recordFile, 'utf8')) as { + argv: string[]; + cwd: string; + }; + + // `--load-nvram` is a boolean flag: it must be a bare token, not a + // `--load-nvram=` pair. + expect(record.argv).toStrictEqual([ + '--apdu-port', + String(apduPort), + '--api-port', + String(apiPort), + '--load-nvram', + 'app.elf', + ]); + // macOS tmpdirs are symlinked, so compare against the resolved path. + expect(record.cwd).toBe(realpathSync(fixtureDir)); + + await manager.stop(); + } finally { + rmSync(fixtureDir, { recursive: true, force: true }); + } + }, 30_000); + + it('reuses an in-flight stop on concurrent calls', async () => { + const apduPort = await findFreePort(); + const apiPort = await findFreePort(); + const fixtureDir = mkdtempSync(path.join(tmpdir(), 'pm-test-')); + const fixture = path.join(fixtureDir, 'server.js'); + // A tiny Node server (invoked via its shebang so the manager's leading + // --apdu-port/--api-port flags land in process.argv rather than being + // parsed by the node binary). It opens both readiness ports and stays + // alive until terminated. + writeFileSync( + fixture, + [ + '#!/usr/bin/env node', + 'const net = require("net");', + `net.createServer(() => {}).listen(${apduPort}, "127.0.0.1");`, + `net.createServer(() => {}).listen(${apiPort}, "127.0.0.1");`, + 'setInterval(() => {}, 1000);', + ].join('\n'), + 'utf8', + ); + chmodSync(fixture, 0o755); + + try { + const manager = createProcessManager({ + binary: fixture, + app: 'ignored', + apduPort, + apiPort, + startTimeout: 15_000, + stopTimeout: 5_000, + }); + + await manager.start(); + expect(manager.status).toBe('listening'); + + const firstStop = manager.stop(); + const secondStop = manager.stop(); + // Concurrent stops share the same in-flight promise instead of piling on + // extra 'exit' listeners and SIGKILL timers. + expect(secondStop).toBe(firstStop); + + await firstStop; + expect(manager.status).toBe('idle'); + + // A subsequent stop is a no-op. + await manager.stop(); + expect(manager.status).toBe('idle'); + } finally { + rmSync(fixtureDir, { recursive: true, force: true }); + } + }, 30_000); +}); diff --git a/packages/hw-emulator/src/ledger/process-manager.ts b/packages/hw-emulator/src/ledger/process-manager.ts new file mode 100644 index 000000000..cea06bbe1 --- /dev/null +++ b/packages/hw-emulator/src/ledger/process-manager.ts @@ -0,0 +1,344 @@ +// eslint-disable-next-line import-x/no-nodejs-modules +import { spawn } from 'node:child_process'; +// eslint-disable-next-line import-x/no-nodejs-modules +import type { ChildProcess } from 'node:child_process'; +// eslint-disable-next-line import-x/no-nodejs-modules +import { EventEmitter } from 'node:events'; +// eslint-disable-next-line import-x/no-nodejs-modules +import net from 'node:net'; + +const READINESS_POLL_INTERVAL_MS = 250; +const READINESS_PROBE_TIMEOUT_MS = 1000; +const DEFAULT_APDU_PORT = 9999; +const DEFAULT_API_PORT = 5000; + +/** + * Options for configuring the native Speculos process manager. + */ +export type ProcessManagerOptions = { + /** Path to the Speculos binary. */ + binary: string; + /** Path to the Ethereum app ELF binary. */ + app: string; + /** Speculos device model identifier. */ + model?: string; + /** BIP-39 mnemonic seed. */ + seed?: string; + /** TCP port for the APDU protocol. */ + apduPort?: number; + /** TCP port for the REST API. */ + apiPort?: number; + /** Display backend. */ + display?: string; + /** Whether to load NVRAM state. */ + loadNvram?: boolean; + /** Working directory for the spawned process. */ + cwd?: string; + /** Maximum time in milliseconds to wait for the process to start. */ + startTimeout?: number; + /** Maximum time in milliseconds to wait for the process to stop. */ + stopTimeout?: number; +}; + +/** Lifecycle status of the Speculos process. */ +export type ProcessManagerStatus = + | 'idle' + | 'starting' + | 'listening' + | 'stopping'; + +/** + * Interface for managing the Speculos native process lifecycle. + */ +export type ProcessManager = { + /** Start the Speculos process and wait until APDU and API ports are reachable. */ + start(): Promise; + /** Stop the Speculos process gracefully. */ + stop(): Promise; + /** Current process status. */ + readonly status: ProcessManagerStatus; + /** Process ID of the running Speculos instance, or undefined. */ + readonly pid: number | undefined; +}; + +/** + * Check if a TCP port is reachable within a given timeout. + * + * @param port - The port number to check. + * @param host - The hostname to connect to. + * @param timeoutMs - Connection timeout in milliseconds. + * @returns True if the port is reachable. + */ +async function isTcpReachable( + port: number, + host = '127.0.0.1', + timeoutMs = READINESS_PROBE_TIMEOUT_MS, +): Promise { + return new Promise((resolve) => { + const sock = new net.Socket(); + let settled = false; + const finish = (ok: boolean): void => { + if (settled) { + return; + } + settled = true; + sock.destroy(); + resolve(ok); + }; + sock.setTimeout(timeoutMs); + sock.once('connect', () => finish(true)); + sock.once('timeout', () => finish(false)); + sock.once('error', () => finish(false)); + sock.connect(port, host); + }); +} + +/** + * Create a process manager for spawning a native Speculos binary. + * + * @param options - Process configuration. + * @returns A ProcessManager instance. + */ +export function createProcessManager( + options: ProcessManagerOptions, +): ProcessManager { + let proc: ChildProcess | undefined; + let status: ProcessManagerStatus = 'idle'; + let stopPromise: Promise | undefined; + const emitter = new EventEmitter(); + + /** + * Send a signal to the child process, ignoring errors from processes that + * already exited (kill() throws for already-dead PIDs in some cases). + * + * @param processToKill - The child process to signal. + * @param signal - The signal to send. + */ + function killProcess( + processToKill: ChildProcess, + signal: NodeJS.Signals, + ): void { + try { + processToKill.kill(signal); + } catch { + // The process already exited; nothing to do. + } + } + + function buildArgs(): string[] { + const args: string[] = []; + if (options.model) { + args.push('--model', options.model); + } + if (options.seed) { + args.push('--seed', options.seed); + } + if (options.apduPort !== undefined) { + args.push('--apdu-port', String(options.apduPort)); + } + if (options.apiPort !== undefined) { + args.push('--api-port', String(options.apiPort)); + } + if (options.display) { + args.push('--display', options.display); + } + if (options.loadNvram) { + args.push('--load-nvram'); + } + args.push(options.app); + return args; + } + + async function start(): Promise { + if (status !== 'idle') { + throw new Error(`Speculos process not idle (current: ${status})`); + } + status = 'starting'; + + const binaryPath = options.binary; + const args = buildArgs(); + const timeout = options.startTimeout ?? 60_000; + const apduPort = options.apduPort ?? DEFAULT_APDU_PORT; + const apiPort = options.apiPort ?? DEFAULT_API_PORT; + + return new Promise((resolve, reject) => { + let lastLog: string | undefined; + let settled = false; + let pollHandle: ReturnType | undefined; + let startTimer: ReturnType | undefined; + + const onExit = (exitCode: number | null): void => { + if (settled) { + return; + } + if (status === 'starting') { + settled = true; + status = 'idle'; + if (pollHandle) { + clearTimeout(pollHandle); + pollHandle = undefined; + } + if (startTimer) { + clearTimeout(startTimer); + startTimer = undefined; + } + reject( + new Error( + `Speculos exited during startup${lastLog ? `: ${lastLog.trim()}` : ''} (code ${exitCode})`, + ), + ); + } + }; + + const cleanup = (): void => { + if (pollHandle) { + clearTimeout(pollHandle); + pollHandle = undefined; + } + if (startTimer) { + clearTimeout(startTimer); + startTimer = undefined; + } + proc?.removeListener('exit', onExit); + }; + + const onStdout = (data: Buffer): void => { + const line = data.toString(); + emitter.emit('log', line); + lastLog = line; + }; + + startTimer = setTimeout(() => { + if (settled) { + return; + } + settled = true; + cleanup(); + if (proc) { + killProcess(proc, 'SIGTERM'); + } + status = 'idle'; + reject(new Error('Speculos failed to start within timeout')); + }, timeout); + + const pollReady = async (): Promise => { + if (settled) { + return; + } + try { + const [apduOk, apiOk] = await Promise.all([ + isTcpReachable(apduPort), + isTcpReachable(apiPort), + ]); + if (apduOk && apiOk) { + if (settled) { + return; + } + settled = true; + status = 'listening'; + cleanup(); + resolve(); + return; + } + } catch { + // probe failure is non-fatal + } + if (!settled) { + pollHandle = setTimeout( + () => + // eslint-disable-next-line no-void + void pollReady(), + READINESS_POLL_INTERVAL_MS, + ); + } + }; + + const spawnOpts: import('node:child_process').SpawnOptions = { + stdio: ['pipe', 'pipe', 'pipe'], + }; + if (options.cwd) { + spawnOpts.cwd = options.cwd; + } + proc = spawn(binaryPath, args, spawnOpts); + proc.stdout?.on('data', onStdout); + proc.stderr?.on('data', onStdout); + proc.on('exit', onExit as (code: number | null) => void); + proc.on('error', (spawnError: Error) => { + if (settled) { + return; + } + settled = true; + cleanup(); + status = 'idle'; + reject(spawnError); + }); + + pollHandle = setTimeout( + () => + // eslint-disable-next-line no-void + void pollReady(), + READINESS_POLL_INTERVAL_MS, + ); + }); + } + + /** + * Stop the Speculos process gracefully (SIGTERM, SIGKILL after the stop + * timeout). Concurrent or repeated calls share the same in-flight stop + * instead of accumulating extra 'exit' listeners and SIGKILL timers. + * + * @returns A promise that resolves once the process has stopped. + */ + // eslint-disable-next-line @typescript-eslint/promise-function-async -- returns the shared in-flight promise (not async) so concurrent callers get the same object. + function stop(): Promise { + if (!stopPromise && (!proc || status === 'idle')) { + return Promise.resolve(); + } + if (stopPromise) { + // A stop is already in flight — reuse it. + return stopPromise; + } + status = 'stopping'; + const timeout = options.stopTimeout ?? 10_000; + + stopPromise = new Promise((resolve) => { + const stopTimer = setTimeout((): void => { + if (proc) { + killProcess(proc, 'SIGKILL'); + } + status = 'idle'; + resolve(); + }, timeout); + + if (proc) { + const currentProc = proc; + currentProc.once('exit', () => { + clearTimeout(stopTimer); + status = 'idle'; + proc = undefined; + resolve(); + }); + killProcess(currentProc, 'SIGTERM'); + } else { + clearTimeout(stopTimer); + status = 'idle'; + resolve(); + } + }).finally(() => { + stopPromise = undefined; + }); + + return stopPromise; + } + + return { + start, + stop, + get status(): ProcessManagerStatus { + return status; + }, + get pid(): number | undefined { + return proc?.pid; + }, + }; +} diff --git a/packages/hw-emulator/src/ledger/resilience.test.ts b/packages/hw-emulator/src/ledger/resilience.test.ts new file mode 100644 index 000000000..c4a294c38 --- /dev/null +++ b/packages/hw-emulator/src/ledger/resilience.test.ts @@ -0,0 +1,127 @@ +import { withRetry, ExponentialBackoff, isRetryableError } from './resilience'; + +describe('resilience', () => { + describe('withRetry', () => { + it('returns the result on first success', async () => { + const result = await withRetry(async () => Promise.resolve(42), { + maxRetries: 3, + }); + expect(result).toBe(42); + }); + + it('retries on failure and eventually succeeds', async () => { + let attempt = 0; + const fn = async (): Promise => { + attempt += 1; + if (attempt < 3) { + throw new Error('transient'); + } + return 'ok'; + }; + + const result = await withRetry(fn, { maxRetries: 3 }); + expect(result).toBe('ok'); + expect(attempt).toBe(3); + }, 15000); + + it('throws after exhausting retries', async () => { + const fn = async (): Promise => { + throw new Error('permanent'); + }; + + await expect(withRetry(fn, { maxRetries: 2 })).rejects.toThrow( + 'permanent', + ); + }, 15000); + + it('respects shouldRetry predicate', async () => { + const fn = async (): Promise => { + throw new Error('not-retryable'); + }; + + await expect( + withRetry(fn, { + maxRetries: 3, + shouldRetry: (error) => error.message === 'retryable', + }), + ).rejects.toThrow('not-retryable'); + }); + + it('calls onRetry callback', async () => { + const onRetry = jest.fn(); + let attempt = 0; + const fn = async (): Promise => { + attempt += 1; + if (attempt < 2) { + throw new Error('fail'); + } + return 'ok'; + }; + + await withRetry(fn, { maxRetries: 3, onRetry }); + expect(onRetry).toHaveBeenCalledTimes(1); + expect(onRetry).toHaveBeenCalledWith(expect.any(Error), 1); + }); + }); + + describe('ExponentialBackoff', () => { + it('starts with initial delay', () => { + const backoff = new ExponentialBackoff(100, 5000); + expect(backoff.next()).toBe(100); + }); + + it('doubles each step', () => { + const backoff = new ExponentialBackoff(100, 5000); + expect(backoff.next()).toBe(100); + expect(backoff.next()).toBe(200); + expect(backoff.next()).toBe(400); + }); + + it('caps at maxMs', () => { + const backoff = new ExponentialBackoff(100, 300); + expect(backoff.next()).toBe(100); + expect(backoff.next()).toBe(200); + expect(backoff.next()).toBe(300); + expect(backoff.next()).toBe(300); + }); + + it('resets to initial', () => { + const backoff = new ExponentialBackoff(100, 5000); + backoff.next(); + backoff.next(); + backoff.reset(); + expect(backoff.next()).toBe(100); + }); + + it('supports custom multiplier', () => { + const backoff = new ExponentialBackoff(100, 5000, 3); + expect(backoff.next()).toBe(100); + expect(backoff.next()).toBe(300); + expect(backoff.next()).toBe(900); + }); + }); + + describe('isRetryableError', () => { + it('returns true for ECONNREFUSED', () => { + const error = new Error() as Error & { code: string }; + error.code = 'ECONNREFUSED'; + expect(isRetryableError(error)).toBe(true); + }); + + it('returns true for ETIMEDOUT', () => { + const error = new Error() as Error & { code: string }; + error.code = 'ETIMEDOUT'; + expect(isRetryableError(error)).toBe(true); + }); + + it('returns true for error message containing ECONNRESET', () => { + const error = new Error('Connection failed: ECONNRESET'); + expect(isRetryableError(error)).toBe(true); + }); + + it('returns false for non-retryable errors', () => { + const error = new Error('Something else went wrong'); + expect(isRetryableError(error)).toBe(false); + }); + }); +}); diff --git a/packages/hw-emulator/src/ledger/resilience.ts b/packages/hw-emulator/src/ledger/resilience.ts new file mode 100644 index 000000000..31a9ec6f6 --- /dev/null +++ b/packages/hw-emulator/src/ledger/resilience.ts @@ -0,0 +1,115 @@ +/** Initial retry backoff delay in milliseconds. */ +const INITIAL_BACKOFF_MS = 1000; + +/** Maximum retry backoff delay in milliseconds. */ +const MAX_BACKOFF_MS = 8000; + +/** + * Exponential backoff delay calculator. + */ +export class ExponentialBackoff { + #current: number; + + readonly #initialMs: number; + + readonly #maxMs: number; + + readonly #multiplier: number; + + constructor(initialMs: number, maxMs: number, multiplier = 2) { + this.#initialMs = initialMs; + this.#maxMs = maxMs; + this.#multiplier = multiplier; + this.#current = initialMs; + } + + /** + * Get the next delay value and advance the backoff. + * + * @returns The delay in milliseconds. + */ + next(): number { + const wait = this.#current; + this.#current = Math.min(this.#current * this.#multiplier, this.#maxMs); + return wait; + } + + /** + * Reset the backoff to its initial state. + */ + reset(): void { + this.#current = this.#initialMs; + } +} + +/** + * Retry a function with exponential backoff. + * + * @param fn - The async function to retry. + * @param options - Retry configuration. + * @param options.maxRetries - Maximum number of retry attempts. + * @param options.shouldRetry - Optional predicate to determine if an error is retryable. + * @param options.onRetry - Optional callback invoked before each retry. + * @returns The result of the function. + */ +export async function withRetry( + fn: () => Promise, + options: { + maxRetries: number; + shouldRetry?: (error: Error) => boolean; + onRetry?: (error: Error, attempt: number) => void; + }, +): Promise { + const { maxRetries, shouldRetry, onRetry } = options; + const backoff = new ExponentialBackoff(INITIAL_BACKOFF_MS, MAX_BACKOFF_MS); + + for (let attempt = 0; attempt <= maxRetries; attempt++) { + try { + return await fn(); + } catch (rawError: unknown) { + const error = + rawError instanceof Error ? rawError : new Error(String(rawError)); + const canRetry = + attempt < maxRetries && (shouldRetry ? shouldRetry(error) : true); + if (!canRetry) { + throw error; + } + onRetry?.(error, attempt + 1); + await new Promise((resolve) => { + setTimeout(resolve, backoff.next()); + }); + } + } + throw new Error('Unreachable'); +} + +/** + * Check if an error is transient and worth retrying. + * + * @param error - The error to check. + * @returns True if the error is retryable. + */ +export function isRetryableError(error: Error): boolean { + const errorData = error as { message?: unknown; code?: unknown }; + const message = + typeof errorData.message === 'string' ? errorData.message : ''; + const code = typeof errorData.code === 'string' ? errorData.code : ''; + const retryableCodes = new Set([ + 'ECONNREFUSED', + 'ETIMEDOUT', + 'ECONNRESET', + 'EHOSTUNREACH', + 'EPIPE', + ]); + if (retryableCodes.has(code)) { + return true; + } + if ( + message.includes('ECONNREFUSED') || + message.includes('ETIMEDOUT') || + message.includes('ECONNRESET') + ) { + return true; + } + return false; +} diff --git a/packages/hw-emulator/src/ledger/speculos.test.ts b/packages/hw-emulator/src/ledger/speculos.test.ts new file mode 100644 index 000000000..c2e4a694c --- /dev/null +++ b/packages/hw-emulator/src/ledger/speculos.test.ts @@ -0,0 +1,267 @@ +import { basename, dirname } from 'node:path'; + +import { DEVICE_MODELS } from './constants'; +import type { DeviceModel } from './constants'; +import { Speculos } from './speculos'; + +// Mock the client and docker manager so start() lifecycle tests don't touch +// real Docker or TCP sockets. Class-based mocks (rather than jest.fn()) are +// used because the base jest config sets `resetMocks: true`, which strips +// jest.fn implementations before each test. Behavior is exposed via module +// properties created inside the factories. +jest.mock('./client', () => { + const behavior = { connectShouldFail: false }; + class SpeculosClient { + async connectWithRetry(): Promise { + if (behavior.connectShouldFail) { + return Promise.reject(new Error('connect failed')); + } + return Promise.resolve(); + } + + async disconnect(): Promise { + return Promise.resolve(); + } + } + return { SpeculosClient, __clientBehavior: behavior }; +}); + +jest.mock('./docker-manager', () => { + const behavior = { + start: jest.fn, []>(), + stop: jest.fn, []>(), + }; + class DockerManager { + async start(): Promise { + await behavior.start(); + } + + async stop(): Promise { + await behavior.stop(); + } + } + return { DockerManager, __dockerBehavior: behavior }; +}); + +jest.mock('./process-manager', () => { + const behavior: { + options: Record[]; + start: jest.Mock; + stop: jest.Mock; + } = { + options: [], + start: jest.fn(), + stop: jest.fn(), + }; + function createProcessManager(options: Record): { + start: () => Promise; + stop: () => Promise; + status: string; + pid: number | undefined; + } { + behavior.options.push(options); + return { + async start(): Promise { + await behavior.start(); + }, + async stop(): Promise { + await behavior.stop(); + }, + status: 'idle', + pid: undefined, + }; + } + return { createProcessManager, __processBehavior: behavior }; +}); + +/** + * Get the mutable client behavior object created by the client mock. + * + * @returns The client behavior holder. + */ +function getClientBehavior(): { connectShouldFail: boolean } { + return jest.requireMock('./client').__clientBehavior; +} + +/** + * Get the DockerManager behavior object created by the docker mock. + * + * @returns The docker behavior holder. + */ +function getDockerBehavior(): { start: jest.Mock; stop: jest.Mock } { + return jest.requireMock('./docker-manager').__dockerBehavior; +} + +/** + * Get the process-manager behavior object created by the native mock. + * + * @returns The process behavior holder, including the recorded options. + */ +function getProcessBehavior(): { + options: Record[]; + start: jest.Mock; + stop: jest.Mock; +} { + return jest.requireMock('./process-manager').__processBehavior; +} + +describe('Speculos', () => { + it('constructs with default options', () => { + const speculos = new Speculos(); + expect(speculos.isRunning()).toBe(false); + }); + + it('constructs with a string device id', () => { + const speculos = new Speculos({ device: 'nanosp' }); + expect(speculos.isRunning()).toBe(false); + expect(speculos.getDeviceModel().id).toBe('nanosp'); + }); + + it('constructs with a DeviceModel object', () => { + const model = DEVICE_MODELS.stax as DeviceModel; + const speculos = new Speculos({ device: model }); + expect(speculos.getDeviceModel().id).toBe('stax'); + }); + + it('returns default device config', () => { + const speculos = new Speculos(); + const config = speculos.getDeviceConfig(); + expect(config.apduPort).toBe(9998); + expect(config.apiPort).toBe(5001); + expect(config.wsBridgePort).toBe(9876); + }); + + it('uses custom ports', () => { + const speculos = new Speculos({ + apduPort: 9997, + apiPort: 5002, + wsBridgePort: 9875, + }); + const config = speculos.getDeviceConfig(); + expect(config.apduPort).toBe(9997); + expect(config.apiPort).toBe(5002); + expect(config.wsBridgePort).toBe(9875); + }); + + it('throws when getClient called before start', () => { + const speculos = new Speculos(); + expect(() => speculos.getClient()).toThrow('Speculos not started'); + }); + + it('throws when getInteraction called before start', () => { + const speculos = new Speculos(); + expect(() => speculos.getInteraction()).toThrow('Speculos not started'); + }); + + it('throws when startBridge called before start', async () => { + const speculos = new Speculos(); + await expect(speculos.startBridge()).rejects.toThrow( + 'Speculos not started', + ); + }); + + it('stop resolves when not started', async () => { + const speculos = new Speculos(); + await speculos.stop(); + expect(true).toBe(true); + }); + + it('returns WebHID mock script', () => { + const speculos = new Speculos(); + const script = speculos.getWebHIDMockScript(9999); + expect(script).toContain('9999'); + expect(script).toContain('WebSocket'); + expect(script).toContain('mockHID'); + }); + + it('detects device model for unknown id', () => { + const speculos = new Speculos({ device: 'nonexistent' }); + expect(() => speculos.getDeviceModel()).toThrow('Unknown device model'); + }); +}); + +describe('Speculos lifecycle', () => { + beforeEach(() => { + getClientBehavior().connectShouldFail = false; + jest.clearAllMocks(); + }); + + it('cleans up the docker manager when the client connect fails during start', async () => { + getClientBehavior().connectShouldFail = true; + + const speculos = new Speculos({ mode: 'docker' }); + await expect(speculos.start()).rejects.toThrow('connect failed'); + + expect(getDockerBehavior().stop).toHaveBeenCalledTimes(1); + + expect(speculos.isRunning()).toBe(false); + expect(() => speculos.getClient()).toThrow('Speculos not started'); + }); + + it('starts and stops the docker-based emulator', async () => { + const speculos = new Speculos({ mode: 'docker' }); + await speculos.start(); + expect(speculos.isRunning()).toBe(true); + expect(speculos.getClient()).toBeDefined(); + + await speculos.stop(); + + expect(speculos.isRunning()).toBe(false); + expect(getDockerBehavior().stop).toHaveBeenCalledTimes(1); + }); + + it('throws when startBridge is called while a bridge is already running', async () => { + const speculos = new Speculos({ mode: 'docker', wsBridgePort: 0 }); + await speculos.start(); + + await speculos.startBridge(0); + await expect(speculos.startBridge(0)).rejects.toThrow('already running'); + + await speculos.stop(); + }); +}); + +describe('Speculos native mode', () => { + beforeEach(() => { + getProcessBehavior().options.length = 0; + jest.clearAllMocks(); + }); + + it('spawns the native process from the bundled NVRAM directory', async () => { + const speculos = new Speculos({ + mode: 'native', + binary: '/usr/bin/speculos', + }); + + await speculos.start(); + + const [options] = getProcessBehavior().options; + expect(options).toBeDefined(); + // Speculos resolves `main_nvram.bin` relative to the cwd, so native mode + // must run from the directory that holds the bundled NVRAM file. + expect(options?.cwd).toBe(dirname(speculos.getNvramPath())); + expect(basename(options?.cwd as string)).toBe('nvram'); + // `--load-nvram` is a boolean flag, never a path argument. + expect(options?.loadNvram).toBe(true); + + await speculos.stop(); + expect(getProcessBehavior().stop).toHaveBeenCalledTimes(1); + }); + + it('does not override the cwd when NVRAM loading is disabled', async () => { + const speculos = new Speculos({ + mode: 'native', + binary: '/usr/bin/speculos', + loadNvram: false, + }); + + await speculos.start(); + + const [options] = getProcessBehavior().options; + expect(options).toBeDefined(); + expect(options?.loadNvram).toBe(false); + expect(options?.cwd).toBeUndefined(); + + await speculos.stop(); + }); +}); diff --git a/packages/hw-emulator/src/ledger/speculos.ts b/packages/hw-emulator/src/ledger/speculos.ts new file mode 100644 index 000000000..3ce555522 --- /dev/null +++ b/packages/hw-emulator/src/ledger/speculos.ts @@ -0,0 +1,474 @@ +// eslint-disable-next-line import-x/no-nodejs-modules +import { dirname } from 'node:path'; + +import type { + HardwareWalletEmulator, + DeviceInteraction as SharedDeviceInteraction, +} from '../types'; +import { ApduBridge } from './apdu-bridge'; +import { SpeculosClient } from './client'; +import { + getDeviceModel, + detectRunMode, + SPECULOS_SEED, + DEFAULT_DEVICE, +} from './constants'; +import type { DeviceModel, DeviceConfig, RunMode } from './constants'; +import { createDeviceInteraction } from './device-interaction'; +import type { DeviceInteraction } from './device-interaction'; +import { DockerManager } from './docker-manager'; +import { createProcessManager } from './process-manager'; +import type { ProcessManager } from './process-manager'; +import { getWebHidMockScript } from './webhid-mock-script'; + +/** + * Configuration options for the Speculos Ledger emulator. + */ +export type SpeculosOptions = { + /** Device model or model identifier string (defaults to 'flex'). */ + device?: DeviceModel | string; + /** BIP-39 mnemonic seed (defaults to SPECULOS_SEED). */ + seed?: string; + /** TCP port for the APDU protocol. */ + apduPort?: number; + /** TCP port for the REST API. */ + apiPort?: number; + /** TCP port for the WebSocket bridge. */ + wsBridgePort?: number; + /** Execution mode — 'native' or 'docker' (auto-detected by default). */ + mode?: RunMode; + /** Path to the Speculos binary (required in native mode). */ + binary?: string; + /** Display backend (defaults to 'headless'). */ + display?: string; + /** Whether to load NVRAM state (defaults to true). */ + loadNvram?: boolean; + /** Maximum time in milliseconds to wait for the emulator to start. */ + startTimeout?: number; +}; + +/** + * Fully resolved configuration after applying defaults. + */ +type ResolvedConfig = { + deviceModel: DeviceModel; + deviceConfig: DeviceConfig; + seed: string; + mode: RunMode; +}; + +const DEFAULT_DISPLAY = 'headless'; + +/** + * Speculos Ledger emulator — manages the full lifecycle of a Ledger device emulation, + * including starting/stopping the emulator process or Docker container, communicating + * via APDU, and providing device screen interaction capabilities. + */ +export class Speculos implements HardwareWalletEmulator { + readonly #options: SpeculosOptions; + + #resolvedConfig: ResolvedConfig | null = null; + + #processManager: ProcessManager | null = null; + + #dockerManager: DockerManager | null = null; + + #bridgeInstance: ApduBridge | null = null; + + #clientInstance: SpeculosClient | null = null; + + #interactionInstance: DeviceInteraction | null = null; + + #started = false; + + /** + * @param options - Configuration options for the emulator. + */ + constructor(options: SpeculosOptions = {}) { + this.#options = options; + } + + /** + * Resolve and cache the full configuration, applying defaults for any unset options. + * + * @returns The resolved configuration. + */ + resolveConfig(): ResolvedConfig { + if (this.#resolvedConfig) { + return this.#resolvedConfig; + } + + const deviceModel = + typeof this.#options.device === 'string' + ? getDeviceModel(this.#options.device) + : (this.#options.device ?? getDeviceModel()); + + const deviceConfig: DeviceConfig = { + id: 'default', + apduPort: this.#options.apduPort ?? DEFAULT_DEVICE.apduPort, + apiPort: this.#options.apiPort ?? DEFAULT_DEVICE.apiPort, + wsBridgePort: this.#options.wsBridgePort ?? DEFAULT_DEVICE.wsBridgePort, + }; + + const mode = this.#options.mode ?? detectRunMode(); + + this.#resolvedConfig = { + deviceModel, + deviceConfig, + seed: this.#options.seed ?? SPECULOS_SEED, + mode, + }; + + return this.#resolvedConfig; + } + + /** + * Get the filesystem path to the Ethereum app ELF binary for the configured device. + * + * @returns The absolute path to the ELF file. + */ + getElfPath(): string { + const config = this.resolveConfig(); + // eslint-disable-next-line no-restricted-globals + return `${__dirname}/../../apps/${config.deviceModel.elfFile}`; + } + + /** + * Get the filesystem path to the NVRAM binary file for persistent device state. + * + * @returns The absolute path to the NVRAM file. + */ + getNvramPath(): string { + // eslint-disable-next-line no-restricted-globals + return `${__dirname}/../../nvram/main_nvram.bin`; + } + + /** + * Get the filesystem path to the docker-compose.yml file. + * + * @returns The absolute path to the compose file. + */ + getDockerComposePath(): string { + // eslint-disable-next-line no-restricted-globals + return `${__dirname}/../../docker-compose.yml`; + } + + /** + * Attempt to resolve the speculos binary via @metamask/speculos-up. + * + * @returns The binary path if speculos-up is installed, null otherwise. + */ + async #resolveSpeculosUpBinary(): Promise { + try { + const mod = (await import('@metamask/speculos-up' as string)) as { + getSpeculosBinaryPath: () => string | null; + }; + return mod.getSpeculosBinaryPath(); + } catch { + return null; + } + } + + /** + * Start the Speculos emulator and connect the APDU client. + * + * If the client connect or interaction setup fails after the emulator + * process/container has started, all already-started resources are cleaned + * up before the error is rethrown, so nothing leaks. + * + * @throws If already started. + */ + async start(): Promise { + if (this.#started) { + throw new Error('Speculos already started'); + } + + const config = this.resolveConfig(); + + if (config.mode === 'native') { + await this.startNative(config); + } else { + await this.startDocker(config); + } + + try { + this.#clientInstance = new SpeculosClient({ + apduPort: config.deviceConfig.apduPort, + apiPort: config.deviceConfig.apiPort, + }); + + await this.#clientInstance.connectWithRetry({ + autoReconnect: true, + reconnectAttempts: 5, + reconnectDelayMs: 2000, + }); + + this.#interactionInstance = createDeviceInteraction( + this.#clientInstance, + config.deviceModel, + ); + } catch (startError: unknown) { + // The process/container is already running at this point — clean up all + // started resources so a failed start does not leak them. + await this.#cleanup(); + throw startError; + } + + this.#started = true; + } + + /** + * Start Speculos as a native process (Linux only). + * + * @param config - The resolved emulator configuration. + */ + async startNative(config: ResolvedConfig): Promise { + const speculosUpBinary = await this.#resolveSpeculosUpBinary(); + const binary = this.#options.binary ?? speculosUpBinary ?? 'speculos'; + const loadNvram = this.#options.loadNvram ?? true; + + this.#processManager = createProcessManager({ + binary, + app: this.getElfPath(), + model: config.deviceModel.speculosModel, + seed: config.seed, + apduPort: config.deviceConfig.apduPort, + apiPort: config.deviceConfig.apiPort, + display: this.#options.display ?? DEFAULT_DISPLAY, + loadNvram, + // Speculos resolves the NVRAM file relative to the process working + // directory (it opens `_nvram.bin`, i.e. `main_nvram.bin`, from + // the cwd). Run the native process from the bundled `nvram/` directory so + // `--load-nvram` actually finds the shipped file. Docker mode is + // unaffected: the image runs from `/speculos`, where the compose file + // bind-mounts the same file. + ...(loadNvram ? { cwd: dirname(this.getNvramPath()) } : {}), + ...(this.#options.startTimeout === undefined + ? {} + : { startTimeout: this.#options.startTimeout }), + }); + + await this.#processManager.start(); + } + + /** + * Start Speculos via Docker Compose. + * + * @param config - The resolved emulator configuration. + */ + async startDocker(config: ResolvedConfig): Promise { + this.#dockerManager = new DockerManager({ + composeFile: this.getDockerComposePath(), + apduPort: config.deviceConfig.apduPort, + apiPort: config.deviceConfig.apiPort, + app: this.getElfPath(), + model: config.deviceModel.speculosModel, + seed: config.seed, + display: this.#options.display ?? DEFAULT_DISPLAY, + loadNvram: this.#options.loadNvram ?? true, + ...(this.#options.startTimeout === undefined + ? {} + : { startTimeout: this.#options.startTimeout }), + }); + + await this.#dockerManager.start(); + } + + /** + * Stop the emulator and release all resources (bridge, process/docker, client). + * + * Safe to call even if start() failed partway: any resource that was created + * is cleaned up regardless of the `started` flag, and each step is attempted + * even when an earlier step fails. + */ + async stop(): Promise { + await this.#cleanup(); + this.#started = false; + } + + /** + * Best-effort cleanup of every created resource. Never throws: a failing + * step is logged and the remaining steps still run. + */ + async #cleanup(): Promise { + if (this.#bridgeInstance) { + const bridge = this.#bridgeInstance; + this.#bridgeInstance = null; + try { + await bridge.stop(); + } catch (stopError: unknown) { + this.#logCleanupError('bridge', stopError); + } + } + + if (this.#processManager) { + const processManager = this.#processManager; + this.#processManager = null; + try { + await processManager.stop(); + } catch (stopError: unknown) { + this.#logCleanupError('process manager', stopError); + } + } + + if (this.#dockerManager) { + const dockerManager = this.#dockerManager; + this.#dockerManager = null; + try { + await dockerManager.stop(); + } catch (stopError: unknown) { + this.#logCleanupError('docker manager', stopError); + } + } + + if (this.#clientInstance) { + const client = this.#clientInstance; + this.#clientInstance = null; + try { + await client.disconnect(); + } catch (stopError: unknown) { + this.#logCleanupError('client', stopError); + } + } + + this.#interactionInstance = null; + } + + /** + * Log a resource cleanup failure without interrupting the remaining steps. + * + * @param resource - Name of the resource being cleaned up. + * @param error - The error thrown while stopping it. + */ + #logCleanupError(resource: string, error: unknown): void { + const message = error instanceof Error ? error.message : String(error); + console.error(`[Speculos] Error stopping ${resource}: ${message}`); + } + + /** + * Get the Speculos client for direct APDU and API communication. + * + * @returns The connected SpeculosClient instance. + * @throws If the emulator has not been started. + */ + getClient(): SpeculosClient { + if (!this.#clientInstance) { + throw new Error('Speculos not started. Call start() first.'); + } + return this.#clientInstance; + } + + /** + * Get the device interaction handler for screen actions. + * + * @returns The device interaction instance. + * @throws If the emulator has not been started. + */ + getInteraction(): SharedDeviceInteraction { + if (!this.#interactionInstance) { + throw new Error('Speculos not started. Call start() first.'); + } + return this.#interactionInstance; + } + + /** + * Start a WebSocket bridge that relays HID-framed APDUs between a browser and Speculos. + * + * @param wsPort - Override port for the WebSocket server. + * @returns The started ApduBridge instance. + * @throws If the emulator has not been started, or a bridge is already + * running (call stop() first instead of silently replacing it). + */ + async startBridge(wsPort?: number): Promise { + if (!this.#clientInstance) { + throw new Error('Speculos not started. Call start() first.'); + } + if (this.#bridgeInstance) { + throw new Error( + 'A bridge is already running. Call stop() before starting another bridge.', + ); + } + + const config = this.resolveConfig(); + const port = wsPort ?? config.deviceConfig.wsBridgePort; + + this.#bridgeInstance = new ApduBridge(this.#clientInstance, port); + await this.#bridgeInstance.start(); + return this.#bridgeInstance; + } + + /** + * Generate the browser-side WebHID mock script for connecting to the WebSocket bridge. + * + * @param wsPort - Override port for the WebSocket connection. + * @returns JavaScript source code as a string. + */ + getWebHIDMockScript(wsPort?: number): string { + const config = this.resolveConfig(); + const port = wsPort ?? config.deviceConfig.wsBridgePort; + return getWebHidMockScript(port); + } + + /** + * Check whether the emulator is currently running. + * + * @returns True if started and running. + */ + isRunning(): boolean { + return this.#started; + } + + /** + * Get the resolved device model configuration. + * + * @returns The device model. + */ + getDeviceModel(): DeviceModel { + return this.resolveConfig().deviceModel; + } + + /** + * Get the resolved device port configuration. + * + * @returns The device config with port numbers. + */ + getDeviceConfig(): DeviceConfig { + return this.resolveConfig().deviceConfig; + } + + /** + * Approve a transaction on the device screen. + * + * @returns A promise that resolves when the approval is complete. + */ + async approveTransaction(): Promise { + return this.getInteraction().approveTransaction(); + } + + /** + * Approve a signing request on the device screen. + * + * @returns A promise that resolves when the approval is complete. + */ + async approveSigning(): Promise { + return this.getInteraction().approveSigning(); + } + + /** + * Reject a transaction on the device screen. + * + * @returns A promise that resolves when the rejection is complete. + */ + async rejectTransaction(): Promise { + return this.getInteraction().rejectTransaction(); + } + + /** + * Navigate to the main menu on the device screen. + * + * @returns A promise that resolves when navigation is complete. + */ + async navigateToMainMenu(): Promise { + return this.getInteraction().navigateToMainMenu(); + } +} diff --git a/packages/hw-emulator/src/ledger/webhid-mock-script.test.ts b/packages/hw-emulator/src/ledger/webhid-mock-script.test.ts new file mode 100644 index 000000000..244c0fc25 --- /dev/null +++ b/packages/hw-emulator/src/ledger/webhid-mock-script.test.ts @@ -0,0 +1,56 @@ +import { getWebHidMockScript } from './webhid-mock-script'; + +describe('getWebHidMockScript', () => { + it('removes pendingExchanges entries on HID_FRAME_ACK', () => { + const script = getWebHidMockScript(9876); + + const ackHandler = script.match( + /else if \(response\.type === 'HID_FRAME_ACK'\) \{[\s\S]*?\} else if \(response\.type === 'APDU_ERROR'\)/u, + )?.[0]; + + expect(ackHandler).toBeDefined(); + expect(ackHandler).toContain('pendingExchanges.delete(response.id)'); + expect(ackHandler).toContain('pending.resolve()'); + }); + + it('removes pendingExchanges entries on HID_EXCHANGE_COMPLETE and APDU_ERROR', () => { + const script = getWebHidMockScript(9876); + + expect(script).toMatch( + /HID_EXCHANGE_COMPLETE[\s\S]*?pendingExchanges\.delete\(response\.id\)/u, + ); + expect(script).toMatch( + /APDU_ERROR[\s\S]*?pendingExchanges\.delete\(response\.id\)/u, + ); + }); + + it('wraps JSON.parse in try/catch', () => { + const script = getWebHidMockScript(9876); + + expect(script).toMatch( + /try \{[\s\S]*?JSON\.parse\(event\.data\)[\s\S]*?\} catch \(parseError\)/u, + ); + }); + + it('rejects all pending exchanges on ws.onclose and ws.onerror', () => { + const script = getWebHidMockScript(9876); + + expect(script).toMatch(/const failAllPending = function\(message\)/u); + expect(script).toMatch(/pendingExchanges\.forEach[\s\S]*?pending\.reject/u); + expect(script).toMatch(/pendingExchanges\.clear\(\)/u); + // Both close and error paths invoke failAllPending. + const onclose = script.match( + /ws\.onclose = function\(\) \{[\s\S]*?\};/u, + )?.[0]; + const onerror = script.match(/ws\.onerror = function[\s\S]*?\};/u)?.[0]; + expect(onclose).toContain('failAllPending('); + expect(onerror).toContain('failAllPending('); + }); + + it('produces syntactically valid JavaScript for injection', () => { + const script = getWebHidMockScript(9876); + + // eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func + expect(() => new Function(script)).not.toThrow(); + }); +}); diff --git a/packages/hw-emulator/src/ledger/webhid-mock-script.ts b/packages/hw-emulator/src/ledger/webhid-mock-script.ts new file mode 100644 index 000000000..86a7f5848 --- /dev/null +++ b/packages/hw-emulator/src/ledger/webhid-mock-script.ts @@ -0,0 +1,218 @@ +/** + * Returns browser-side WebHID mock source for Speculos over WebSocket. + * + * @param wsPort - The WebSocket port to connect to. + * @returns The JavaScript source code as a string. + */ +export function getWebHidMockScript(wsPort: number): string { + return ` + (function() { + if (window.__webHIDMockInjected) return; + window.__webHIDMockInjected = true; + + const _WS = WebSocket; + const _WS_OPEN = WebSocket.OPEN; + const _WS_CONNECTING = WebSocket.CONNECTING; + + const wsPort = ${wsPort}; + let ws = null; + let messageId = 0; + const pendingExchanges = new Map(); + + const LEDGER_COLLECTIONS = [{ + usagePage: 0xffa0, + usage: 0x01, + inputReports: [{ reportId: 0 }], + outputReports: [{ reportId: 0 }], + featureReports: [], + }]; + + const connectWebSocket = function() { + if (ws && (ws.readyState === _WS_OPEN || ws.readyState === _WS_CONNECTING)) { + return; + } + ws = new _WS('ws://localhost:' + wsPort); + + const failAllPending = function(message) { + pendingExchanges.forEach(function(pending) { + pending.reject(new Error(message)); + }); + pendingExchanges.clear(); + }; + + ws.onopen = function() { + console.log('[WebHID Mock] WebSocket connected'); + }; + + ws.onmessage = function(event) { + let response; + try { + response = JSON.parse(event.data); + } catch (parseError) { + console.error('[WebHID Mock] Invalid JSON message from bridge:', parseError); + return; + } + if (response.type === 'HID_RECV') { + const pending = pendingExchanges.get(response.id); + if (!pending) return; + const cbs = window.__inputReportCallbacks || []; + const frame = new Uint8Array(response.data); + cbs.forEach(function(cb) { + cb({ + type: 'inputreport', + device: pending.device, + data: new DataView(frame.buffer, frame.byteOffset, frame.byteLength), + reportId: 0, + }); + }); + } else if (response.type === 'HID_EXCHANGE_COMPLETE') { + const pending = pendingExchanges.get(response.id); + if (pending) { + pendingExchanges.delete(response.id); + pending.resolve(); + } + } else if (response.type === 'HID_FRAME_ACK') { + const pending = pendingExchanges.get(response.id); + if (pending) { + pendingExchanges.delete(response.id); + pending.resolve(); + } + } else if (response.type === 'APDU_ERROR') { + const pending = pendingExchanges.get(response.id); + if (pending) { + pendingExchanges.delete(response.id); + pending.reject(new Error(response.error)); + } + } + }; + + ws.onclose = function() { + console.log('[WebHID Mock] WebSocket disconnected'); + failAllPending('WebSocket closed before the exchange completed'); + ws = null; + }; + + ws.onerror = function(socketError) { + console.error('[WebHID Mock] WebSocket error:', socketError); + failAllPending('WebSocket error before the exchange completed'); + }; + }; + + const runHidExchange = function(device, frameData) { + return new Promise(function(resolve, reject) { + const startSend = function() { + if (!ws || ws.readyState !== _WS_OPEN) { + reject(new Error('WebSocket not connected')); + return; + } + messageId += 1; + const exchangeId = messageId; + pendingExchanges.set(exchangeId, { resolve: resolve, reject: reject, device: device }); + ws.send(JSON.stringify({ + type: 'HID_SEND', + id: exchangeId, + data: Array.from(frameData), + })); + }; + + if (ws && ws.readyState === _WS_OPEN) { + startSend(); + return; + } + if (!ws || ws.readyState !== _WS_CONNECTING) { + connectWebSocket(); + } + const socket = ws; + if (!socket) { + reject(new Error('WebSocket not initialized')); + return; + } + const onOpen = function() { + socket.removeEventListener('open', onOpen); + socket.removeEventListener('error', onErr); + startSend(); + }; + const onErr = function() { + socket.removeEventListener('open', onOpen); + socket.removeEventListener('error', onErr); + reject(new Error('WebSocket failed to open')); + }; + socket.addEventListener('open', onOpen); + socket.addEventListener('error', onErr); + }); + }; + + const mockDevice = { + vendorId: 0x2c97, + productId: 0x0001, + productName: 'Ledger Nano S Plus', + collections: LEDGER_COLLECTIONS, + opened: false, + + open: function() { + this.opened = true; + return Promise.resolve(); + }, + + close: function() { + this.opened = false; + return Promise.resolve(); + }, + + forget: function() { + this.opened = false; + return Promise.resolve(); + }, + + sendReport: function(reportId, data) { + const frame = new Uint8Array(data); + return runHidExchange(this, frame); + }, + + receiveReport: function() { + return Promise.resolve(new DataView(new ArrayBuffer(0))); + }, + + addEventListener: function(type, cb) { + if (type === 'inputreport' && cb) { + window.__inputReportCallbacks = window.__inputReportCallbacks || []; + window.__inputReportCallbacks.push(cb); + } + }, + + removeEventListener: function(type, cb) { + if (type === 'inputreport' && cb) { + const cbs = window.__inputReportCallbacks || []; + const idx = cbs.indexOf(cb); + if (idx > -1) { + cbs.splice(idx, 1); + } + } + }, + }; + + const mockHID = { + getDevices: function() { + return Promise.resolve([mockDevice]); + }, + + requestDevice: function() { + return Promise.resolve([mockDevice]); + }, + + addEventListener: function() {}, + removeEventListener: function() {}, + }; + + Object.defineProperty(navigator, 'hid', { + value: mockHID, + writable: true, + configurable: true, + }); + + window.__speculosDevice = mockDevice; + connectWebSocket(); + console.log('[WebHID Mock] Installed (HID framing → ApduBridge)'); + })(); + `; +} diff --git a/packages/hw-emulator/src/qr/README.md b/packages/hw-emulator/src/qr/README.md new file mode 100644 index 000000000..45d547fe3 --- /dev/null +++ b/packages/hw-emulator/src/qr/README.md @@ -0,0 +1,169 @@ +# QR Hardware Wallet Emulator + +A fake QR hardware device for unit, integration, and E2E testing. It holds a +deterministic seed, derives accounts, produces BC-UR-encoded QR codes (single +frame and animated fountain-coded) the way a Keystone-class device would, and +signs transactions and messages with real ECDSA. + +The emulator is transport-agnostic: it produces QR payloads (PNG, Y4M) and +decodes QR screenshots, but it does not own the camera or any browser API. For +E2E, Chrome's `--use-file-for-fake-video-capture` flag feeds the emulator's Y4M +files to the production `getUserMedia` path — no script injection. + +See the [design spec](../../../../../docs/specs/qr-emulator.md) and +[ADR-0002 (no-scripts transport)](../../../../../docs/adr/0002-no-scripts-transport.md) +for the full architecture. + +## Public API + +The emulator is created via the shared factory and implements both +`HardwareWalletEmulator` (interface symmetry with the Ledger Speculos emulator) +and `QrKeyringBridge` (so it can be wired directly into a real `QrKeyring` in +Jest tests). + +```ts +export interface QrEmulator extends HardwareWalletEmulator, QrKeyringBridge { + start(): Promise; + stop(): Promise; + isRunning(): boolean; + requestScan(req: QrScanRequest): Promise; + getAccountUR(): SerializedUR; + handleSignRequest(ur: SerializedUR): Promise; + renderToY4m(ur: SerializedUR, opts): Promise; + renderToPng(ur: SerializedUR): Promise; + decodeQrScreenshots(pathsOrBuffers): Promise; + decodeQrImage(png: Buffer): Promise; + asBridge(): QrKeyringBridge; +} +``` + +### Constants + +- `QR_EMULATOR_SEED` — canonical BIP-39 12-word test vector (hardhat account #0). +- `QR_EMULATOR_ADDRESS` — `0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266` (the first + derived address, assertable in tests). +- `QR_EMULATOR_DEFAULT_XFP` — `0xdeadbeef`. +- `QR_FRAGMENT_SIZE` (`200`), `QR_REFRESH_MS` (`200`), `QR_CODE_SIZE_PX` (`225`), + `QR_UPPERCASE` (`true`) — mirror MetaMask's `player.js` exactly. + +## Usage + +### 1. Factory creation + +```ts +import { + createEmulator, + EmulatorType, + QR_EMULATOR_ADDRESS, +} from '@metamask/hw-emulator'; + +const emulator = createEmulator(EmulatorType.Qr, { + // All options optional; sensible defaults. + deviceName: 'Keystone Test', + pairMode: 'crypto-account', // or 'crypto-hdkey' + descriptorCount: 5, +}); + +const accountUR = emulator.getAccountUR(); +// { type: 'crypto-account', cbor: '...' } +``` + +### 2. `asBridge()` wired to a real `QrKeyring` (Jest integration test) + +The emulator satisfies the `QrKeyringBridge` contract, so the production +`QrKeyring` runs unmodified against it — pairing and signing flow back through +the emulator via `requestScan`. + +```ts +import { QrKeyring } from '@metamask/eth-qr-keyring'; +import { + createEmulator, + EmulatorType, + QR_EMULATOR_ADDRESS, +} from '@metamask/hw-emulator'; + +const emulator = createEmulator(EmulatorType.Qr, {}); +const keyring = new QrKeyring({ bridge: emulator.asBridge() }); + +// Triggers bridge pairing (requestScan PAIR), then derives the first account. +await keyring.getFirstPage(); +const [address] = await keyring.addAccounts(1); +expect(address).toBe(QR_EMULATOR_ADDRESS); + +// Signing calls back into the emulator via requestScan SIGN — real ECDSA. +const signature = await keyring.signPersonalMessage(address, '0x...'); +``` + +### 3. `renderToY4m()` for Playwright E2E (Chrome fake-camera transport) + +Render an animated QR to a Y4M file and feed it to Chrome's fake camera. The +production scanner, zxing decoder, and `@ngraveio/bc-ur` fountain decoder all +run unmodified. + +```ts +import { createEmulator, EmulatorType } from '@metamask/hw-emulator'; + +const emulator = createEmulator(EmulatorType.Qr, {}); +const accountUR = emulator.getAccountUR(); + +// Requires ffmpeg on PATH (`brew install ffmpeg` on macOS). +const feedPath = await emulator.renderToY4m(accountUR, { + fps: 5, + durationS: 4, + outputPath: '/tmp/qr-pair-feed.y4m', +}); + +// Launch Chromium with: +// --use-fake-device-for-media-stream +// --use-file-for-fake-video-capture=/tmp/qr-pair-feed.y4m +``` + +To decode the sign-request QR codes MetaMask renders (the bidirectional case), +capture frames via Playwright's `locator.screenshot()` and reconstruct the UR: + +```ts +const ur = await emulator.decodeQrScreenshots([ + 'frame-0.png', + 'frame-1.png', + // ... +]); +``` + +## Dependencies + +| Package | Purpose | +| -------------------------------- | --------------------------------------------------------------------------------- | +| `@ngraveio/bc-ur` | BC-UR fountain codec (encoder + decoder). | +| `@keystonehq/bc-ur-registry-eth` | Typed UR construction (CryptoAccount, CryptoHDKey, EthSignRequest, ETHSignature). | +| `qrcode-generator` | Render fragment string → QR matrix. | +| `@zxing/library` | Decode QR PNG → fragment string (Node-side). | + +### External runtime requirements + +- **`ffmpeg`** — required only by `renderToY4m()`. The pure-TypeScript paths + (UR synthesis, signing, PNG rendering, screenshot decoding) have **no** + external binary requirement. Install with `brew install ffmpeg` (macOS), + `sudo apt install ffmpeg` (Debian/Ubuntu), or `sudo dnf install ffmpeg` + (Fedora). `renderToY4m()` probes for ffmpeg once and throws a descriptive + `FfmpegUnavailableError` (with install instructions) if it is missing. + +## Layout + +``` +src/qr/ +├── index.ts ← Public exports +├── constants.ts ← Seed, derivation paths, codec/render constants +├── emulator.ts ← QrEmulator (factory lifecycle + bridge) +├── core/ +│ ├── ur-synth.ts ← seed → CryptoAccount / CryptoHDKey URs +│ ├── signer.ts ← real ECDSA: tx, EIP-712, personal_sign +│ └── registry.ts ← @keystonehq/bc-ur-registry-eth wrappers +├── codec/ +│ ├── encoder.ts ← UR → animated fragments +│ └── decoder.ts ← fragments → UR (fountain, order-independent) +├── render/ +│ ├── png.ts ← fragment string → QR PNG +│ └── y4m.ts ← PNG sequence → Y4M file (ffmpeg) +└── decode/ + └── screenshots.ts ← PNG screenshots → fragment string / UR +``` diff --git a/packages/hw-emulator/src/qr/codec/decoder.test.ts b/packages/hw-emulator/src/qr/codec/decoder.test.ts new file mode 100644 index 000000000..4ac6a6a1d --- /dev/null +++ b/packages/hw-emulator/src/qr/codec/decoder.test.ts @@ -0,0 +1,151 @@ +import { URDecoder } from '@ngraveio/bc-ur'; + +import { + QR_EMULATOR_ACCOUNT_DERIVATION_PATH, + QR_EMULATOR_CHILDREN_PATH, + QR_EMULATOR_DEFAULT_XFP, + QR_EMULATOR_SEED, +} from '../constants'; +import { buildCryptoAccountUR, buildCryptoHDKeyUR } from '../core/ur-synth'; +import type { SynthesizeOptions } from '../core/ur-synth'; +import { FragmentDecoder, decodeFragments } from './decoder'; +import { encodeToFragments } from './encoder'; + +const baseOptions: SynthesizeOptions = { + seed: QR_EMULATOR_SEED, + accountPath: QR_EMULATOR_ACCOUNT_DERIVATION_PATH, + childrenPath: QR_EMULATOR_CHILDREN_PATH, + xfp: QR_EMULATOR_DEFAULT_XFP, + deviceName: 'Keystone Test', + pairMode: 'crypto-account', + descriptorCount: 5, +}; + +describe('QR codec decoder', () => { + describe('FragmentDecoder', () => { + it('is not complete before receiving any fragments', () => { + const decoder = new FragmentDecoder(); + expect(decoder.isComplete()).toBe(false); + expect(decoder.isSuccess()).toBe(false); + }); + + it('accepts uppercase fragments (mirrors decoded screenshots from MM)', () => { + const ur = buildCryptoHDKeyUR({ + ...baseOptions, + pairMode: 'crypto-hdkey', + }); + const fragments = encodeToFragments(ur, 10_000); + const decoder = new FragmentDecoder(); + // MM uppercases the rendered QR value; the decoder must accept that. + const accepted = decoder.receivePart( + fragments[0]?.toUpperCase() as string, + ); + expect(accepted).toBe(true); + expect(decoder.isComplete()).toBe(true); + expect(decoder.resultUR()).toStrictEqual(ur); + }); + + it('reports monotonic progress as fragments arrive', () => { + const ur = buildCryptoAccountUR(baseOptions); + const fragments = encodeToFragments(ur, 50); + const decoder = new FragmentDecoder(); + const start = decoder.getProgress(); + expect(start).toBe(0); + for (const fragment of fragments) { + decoder.receivePart(fragment); + if (decoder.isComplete()) { + break; + } + } + expect(decoder.getProgress()).toBeGreaterThanOrEqual(start); + expect(decoder.isComplete()).toBe(true); + }); + + it('is compatible with the raw bc-ur URDecoder on the same fragments', () => { + const ur = buildCryptoHDKeyUR({ + ...baseOptions, + pairMode: 'crypto-hdkey', + }); + const fragments = encodeToFragments(ur, 10_000); + const raw = new URDecoder(); + for (const fragment of fragments) { + raw.receivePart(fragment); + } + expect(raw.isComplete()).toBe(true); + }); + + it('throws a clear error from resultUR before decoding completes', () => { + const decoder = new FragmentDecoder(); + expect(() => decoder.resultUR()).toThrow(/not yet complete/iu); + }); + }); + + describe('decodeFragments', () => { + it('round-trips an encoded crypto-account UR', () => { + const ur = buildCryptoAccountUR(baseOptions); + const fragments = encodeToFragments(ur); + const decoded = decodeFragments(fragments); + expect(decoded).toStrictEqual(ur); + }); + + it('round-trips an encoded crypto-hdkey UR', () => { + const ur = buildCryptoHDKeyUR({ + ...baseOptions, + pairMode: 'crypto-hdkey', + }); + const fragments = encodeToFragments(ur); + expect(decodeFragments(fragments)).toStrictEqual(ur); + }); + + it('reconstructs the UR regardless of fragment order', () => { + const ur = buildCryptoAccountUR(baseOptions); + const fragments = encodeToFragments(ur, 50); + // Shuffle deterministically (reverse is a sufficient order-independence + // probe for a fountain code; interleaving is exercised too). + const reversed = [...fragments].reverse(); + expect(decodeFragments(reversed)).toStrictEqual(ur); + + const interleaved = fragments + .filter((_, i) => i % 2 === 0) + .concat(fragments.filter((_, i) => i % 2 !== 0)); + expect(decodeFragments(interleaved)).toStrictEqual(ur); + }); + + it('throws when given insufficient fragments', () => { + const ur = buildCryptoAccountUR(baseOptions); + const fragments = encodeToFragments(ur, 50); + // Feed only the first fragment of a multi-fragment UR. + expect(() => decodeFragments([fragments[0] as string])).toThrow( + /incomplete/iu, + ); + }); + + it('throws a decoding-failed error when complete but not successful', () => { + const ur = buildCryptoAccountUR(baseOptions); + const fragments = encodeToFragments(ur, 50); + // Simulate a fountain decoder that reached completion but failed + // reconstruction (defensive branch; not reachable with well-formed + // fragments from this lib version). + const isSuccessSpy = jest + .spyOn(FragmentDecoder.prototype, 'isSuccess') + .mockReturnValue(false); + try { + expect(() => decodeFragments(fragments)).toThrow( + /bc-ur decoding failed/iu, + ); + } finally { + isSuccessSpy.mockRestore(); + } + }); + + it('tolerates a mix of complete and duplicate fragments', () => { + const ur = buildCryptoHDKeyUR({ + ...baseOptions, + pairMode: 'crypto-hdkey', + }); + const fragments = encodeToFragments(ur, 10_000); + // Duplicate fragments are harmless to a fountain decoder. + expect(decodeFragments([...fragments, ...fragments])).toStrictEqual(ur); + }); + }); +}); diff --git a/packages/hw-emulator/src/qr/codec/decoder.ts b/packages/hw-emulator/src/qr/codec/decoder.ts new file mode 100644 index 000000000..378bfe9d0 --- /dev/null +++ b/packages/hw-emulator/src/qr/codec/decoder.ts @@ -0,0 +1,106 @@ +import { UR, URDecoder } from '@ngraveio/bc-ur'; + +import type { SerializedUR } from '../core/ur-synth'; + +/** + * Normalise a fragment string to lowercase. BC-UR fragments are + * case-insensitive at the encoding layer, but MetaMask uppercases the rendered + * QR value (see `player.js`), so decoded fragments from a real screenshot are + * uppercase. Normalising here keeps the decoder agnostic to that. + * + * @param part - A BC-UR fragment string. + * @returns The lowercased fragment. + */ +function normalizePart(part: string): string { + return part.toLowerCase(); +} + +/** + * Accumulator for BC-UR fountain fragments. Accepts fragments in any order and + * exposes completion state. + */ +export class FragmentDecoder { + readonly #decoder: URDecoder; + + constructor() { + this.#decoder = new URDecoder(); + } + + /** + * Feed a single fragment to the fountain decoder. + * + * @param part - A BC-UR fragment string (any case). + * @returns `true` if the fragment was accepted as new information. + */ + receivePart(part: string): boolean { + return this.#decoder.receivePart(normalizePart(part)); + } + + /** + * Whether enough fragments have been received to reconstruct the UR. + * + * @returns `true` once the fountain decoder has enough fragments. + */ + isComplete(): boolean { + return Boolean(this.#decoder.isComplete()); + } + + /** + * Whether decoding completed successfully. + * + * @returns `true` if decoding succeeded. + */ + isSuccess(): boolean { + return Boolean(this.#decoder.isSuccess()); + } + + /** + * Estimated completion in the range [0, 1]. + * + * @returns The completion fraction. + */ + getProgress(): number { + return this.#decoder.getProgress(); + } + + /** + * Reconstruct the SerializedUR once complete. + * + * @returns The reconstructed SerializedUR. + * @throws If decoding is not yet complete or failed. + */ + resultUR(): SerializedUR { + if (!this.isSuccess()) { + throw new Error( + this.isComplete() + ? 'BC-UR decoding failed: fragments complete but reconstruction failed' + : 'BC-UR decoding failed: not yet complete', + ); + } + const ur: UR = this.#decoder.resultUR(); + return { type: ur.type, cbor: ur.cbor.toString('hex') }; + } +} + +/** + * Decode a list of BC-UR fragments (in any order) into a SerializedUR. + * + * @param parts - Fragment strings. + * @returns The reconstructed SerializedUR. + * @throws If the fragments are insufficient or invalid. + */ +export function decodeFragments(parts: string[]): SerializedUR { + const decoder = new FragmentDecoder(); + for (const part of parts) { + decoder.receivePart(part); + } + if (!decoder.isComplete()) { + throw new Error( + 'BC-UR decoding incomplete: insufficient or invalid fragments', + ); + } + if (!decoder.isSuccess()) { + throw new Error('BC-UR decoding failed: reconstruction error'); + } + return decoder.resultUR(); +} diff --git a/packages/hw-emulator/src/qr/codec/encoder.test.ts b/packages/hw-emulator/src/qr/codec/encoder.test.ts new file mode 100644 index 000000000..be2aa675c --- /dev/null +++ b/packages/hw-emulator/src/qr/codec/encoder.test.ts @@ -0,0 +1,109 @@ +import { UR } from '@ngraveio/bc-ur'; + +import { + QR_EMULATOR_ACCOUNT_DERIVATION_PATH, + QR_EMULATOR_CHILDREN_PATH, + QR_EMULATOR_DEFAULT_XFP, + QR_EMULATOR_SEED, + QR_FRAGMENT_SIZE, +} from '../constants'; +import { buildCryptoAccountUR, buildCryptoHDKeyUR } from '../core/ur-synth'; +import type { SynthesizeOptions } from '../core/ur-synth'; +import { createEncoder, encodeToFragments, toRegistryUR } from './encoder'; + +const baseOptions: SynthesizeOptions = { + seed: QR_EMULATOR_SEED, + accountPath: QR_EMULATOR_ACCOUNT_DERIVATION_PATH, + childrenPath: QR_EMULATOR_CHILDREN_PATH, + xfp: QR_EMULATOR_DEFAULT_XFP, + deviceName: 'Keystone Test', + pairMode: 'crypto-account', + descriptorCount: 5, +}; + +describe('QR codec encoder', () => { + describe('encodeToFragments', () => { + it('produces fragment strings that start with the ur: scheme', () => { + const ur = buildCryptoAccountUR(baseOptions); + const fragments = encodeToFragments(ur); + expect(fragments.length).toBeGreaterThan(0); + for (const fragment of fragments) { + expect(typeof fragment).toBe('string'); + expect(fragment.toLowerCase().startsWith('ur:')).toBe(true); + } + }); + + it('emits fragments tagged with the crypto-account type', () => { + const ur = buildCryptoAccountUR(baseOptions); + const fragments = encodeToFragments(ur); + expect(fragments[0]?.toLowerCase().startsWith('ur:crypto-account/')).toBe( + true, + ); + }); + + it('fits a small payload in a single fragment when fragmentSize is large', () => { + // A single crypto-hdkey is small relative to a generous fragment size. + const ur = buildCryptoHDKeyUR({ + ...baseOptions, + pairMode: 'crypto-hdkey', + }); + const fragments = encodeToFragments(ur, 10_000); + expect(fragments).toHaveLength(1); + }); + + it('scales fragment count with payload size', () => { + const ur = buildCryptoAccountUR(baseOptions); + const smallFragmentSize = 50; + const largeFragmentSize = 2_000; + + const many = encodeToFragments(ur, smallFragmentSize); + const few = encodeToFragments(ur, largeFragmentSize); + + expect(many.length).toBeGreaterThan(few.length); + expect(few.length).toBeGreaterThanOrEqual(1); + }); + + it('produces more fragments than one for the default 200-byte size on a 5-descriptor account', () => { + const ur = buildCryptoAccountUR(baseOptions); + const fragments = encodeToFragments(ur, QR_FRAGMENT_SIZE); + expect(fragments.length).toBeGreaterThan(1); + }); + + it('is deterministic: same UR and fragmentSize yield the same fragment sequence', () => { + const ur = buildCryptoAccountUR(baseOptions); + const a = encodeToFragments(ur); + const b = encodeToFragments(ur); + expect(a).toStrictEqual(b); + }); + }); + + describe('createEncoder', () => { + it('yields fragments one at a time via nextPart', () => { + const ur = buildCryptoAccountUR(baseOptions); + const encoder = createEncoder(ur); + const whole = encodeToFragments(ur); + + expect(encoder.fragmentsLength).toBe(whole.length); + const yielded = Array.from({ length: encoder.fragmentsLength }, () => + encoder.nextPart(), + ); + expect(yielded).toStrictEqual(whole); + for (const fragment of yielded) { + expect(fragment.toLowerCase().startsWith('ur:')).toBe(true); + } + }); + }); + + describe('toRegistryUR', () => { + it('reconstructs a bc-ur UR with the expected type and cbor', () => { + const ur = buildCryptoHDKeyUR({ + ...baseOptions, + pairMode: 'crypto-hdkey', + }); + const registryUR = toRegistryUR(ur); + expect(registryUR).toBeInstanceOf(UR); + expect(registryUR.type).toBe(ur.type); + expect(registryUR.cbor.toString('hex')).toBe(ur.cbor); + }); + }); +}); diff --git a/packages/hw-emulator/src/qr/codec/encoder.ts b/packages/hw-emulator/src/qr/codec/encoder.ts new file mode 100644 index 000000000..2deade7eb --- /dev/null +++ b/packages/hw-emulator/src/qr/codec/encoder.ts @@ -0,0 +1,53 @@ +/* eslint-disable no-restricted-globals -- Buffer is required for UR reconstruction. */ + +import { UR, UREncoder } from '@ngraveio/bc-ur'; + +import { QR_FRAGMENT_SIZE } from '../constants'; +import type { SerializedUR } from '../core/ur-synth'; + +/** + * Reconstruct a `@ngraveio/bc-ur` {@link UR} from a SerializedUR. + * + * @param ur - The SerializedUR (type + hex cbor). + * @returns A bc-ur UR instance. + */ +export function toRegistryUR(ur: SerializedUR): UR { + return new UR(Buffer.from(ur.cbor, 'hex'), ur.type); +} + +/** + * Encode a SerializedUR into the complete list of BC-UR fountain fragments. + * + * @param ur - The SerializedUR to encode. + * @param fragmentSize - Maximum fragment length in bytes (defaults to + * `QR_FRAGMENT_SIZE`, mirroring MetaMask's `player.js`). + * @returns The ordered list of fragment strings (`ur:/...`). + */ +export function encodeToFragments( + ur: SerializedUR, + fragmentSize: number = QR_FRAGMENT_SIZE, +): string[] { + return new UREncoder(toRegistryUR(ur), fragmentSize).encodeWhole(); +} + +/** + * Build a stateful BC-UR encoder that yields one fragment at a time, mirroring + * the way MetaMask's `player.js` animates a sign-request QR. + * + * @param ur - The SerializedUR to encode. + * @param fragmentSize - Maximum fragment length in bytes. + * @returns An object with a `nextPart()` method. + */ +export function createEncoder( + ur: SerializedUR, + fragmentSize: number = QR_FRAGMENT_SIZE, +): { + nextPart: () => string; + fragmentsLength: number; +} { + const encoder = new UREncoder(toRegistryUR(ur), fragmentSize); + return { + nextPart: () => encoder.nextPart(), + fragmentsLength: encoder.fragmentsLength, + }; +} diff --git a/packages/hw-emulator/src/qr/constants.test.ts b/packages/hw-emulator/src/qr/constants.test.ts new file mode 100644 index 000000000..2ab0ab6e5 --- /dev/null +++ b/packages/hw-emulator/src/qr/constants.test.ts @@ -0,0 +1,88 @@ +import { getChecksumAddress } from '@metamask/utils'; + +import { + QR_CODE_SIZE_PX, + QR_EMULATOR_ACCOUNT_DERIVATION_PATH, + QR_EMULATOR_ACCOUNT_PATH, + QR_EMULATOR_ADDRESS, + QR_EMULATOR_CHILDREN_PATH, + QR_EMULATOR_DEFAULT_XFP, + QR_EMULATOR_FIRST_ADDRESS_PATH, + QR_EMULATOR_ROOT_DERIVATION_PATH, + QR_EMULATOR_SEED, + QR_FRAGMENT_SIZE, + QR_REFRESH_MS, + QR_UPPERCASE, + deriveAddressFromSeed, +} from './constants'; + +describe('QR emulator constants', () => { + describe('seed and derivation paths', () => { + it('exposes a 12-word BIP-39 seed', () => { + expect(QR_EMULATOR_SEED.split(' ')).toHaveLength(12); + }); + + it('exposes the canonical live-chain root path', () => { + expect(QR_EMULATOR_ROOT_DERIVATION_PATH).toBe("m/44'/60'"); + }); + + it('exposes the account path component and full account path', () => { + expect(QR_EMULATOR_ACCOUNT_PATH).toBe("0'"); + expect(QR_EMULATOR_ACCOUNT_DERIVATION_PATH).toBe("m/44'/60'/0'"); + }); + + it('exposes the children path matching the QR keyring default', () => { + expect(QR_EMULATOR_CHILDREN_PATH).toBe('0/*'); + }); + + it('exposes the first-address full derivation path', () => { + expect(QR_EMULATOR_FIRST_ADDRESS_PATH).toBe("m/44'/60'/0'/0/0"); + }); + + it('exposes a 0x-prefixed device fingerprint', () => { + expect(QR_EMULATOR_DEFAULT_XFP).toBe('0xdeadbeef'); + }); + }); + + describe('QR_EMULATOR_ADDRESS', () => { + it('derives the canonical hardhat address #0 for the default seed', () => { + expect(QR_EMULATOR_ADDRESS).toBe( + '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', + ); + }); + + it('is the checksum-encoded first derived address', () => { + expect(QR_EMULATOR_ADDRESS).toBe(getChecksumAddress(QR_EMULATOR_ADDRESS)); + }); + + it('matches a fresh derivation from the seed', () => { + expect( + deriveAddressFromSeed(QR_EMULATOR_SEED, QR_EMULATOR_FIRST_ADDRESS_PATH), + ).toBe(QR_EMULATOR_ADDRESS); + }); + + it('derives a different address at index 1', () => { + expect(deriveAddressFromSeed(QR_EMULATOR_SEED, "m/44'/60'/0'/0/1")).toBe( + '0x70997970C51812dc3A010C7d01b50e0d17dc79C8', + ); + }); + }); + + describe('codec/rendering constants (mirror player.js)', () => { + it('uses fragment size 200', () => { + expect(QR_FRAGMENT_SIZE).toBe(200); + }); + + it('refreshes every 200 ms (5 fps)', () => { + expect(QR_REFRESH_MS).toBe(200); + }); + + it('renders QR codes at 225 px', () => { + expect(QR_CODE_SIZE_PX).toBe(225); + }); + + it('uppercases fragment strings before encoding', () => { + expect(QR_UPPERCASE).toBe(true); + }); + }); +}); diff --git a/packages/hw-emulator/src/qr/constants.ts b/packages/hw-emulator/src/qr/constants.ts new file mode 100644 index 000000000..1ace7c816 --- /dev/null +++ b/packages/hw-emulator/src/qr/constants.ts @@ -0,0 +1,118 @@ +/* eslint-disable no-restricted-globals -- Buffer is required for public-key-to-address derivation. */ + +import { publicToAddress } from '@ethereumjs/util'; +import { add0x, getChecksumAddress } from '@metamask/utils'; +import type { Hex } from '@metamask/utils'; +import { mnemonicToSeedSync } from 'ethereum-cryptography/bip39'; +import HdKey from 'hdkey'; + +/** + * Canonical BIP-39 12-word test vector. Default seed for the QR emulator; + * override per-instance via the factory `seed` option. + */ +export const QR_EMULATOR_SEED = + 'test test test test test test test test test test test junk'; + +/** + * Root derivation path. Matches the Keystone legacy live-chain path. + */ +export const QR_EMULATOR_ROOT_DERIVATION_PATH = "m/44'/60'"; + +/** + * Account-level hardened path component appended to the root path. + */ +export const QR_EMULATOR_ACCOUNT_PATH = "0'"; + +/** + * Children path within the account. Matches the QR keyring's + * `DEFAULT_CHILDREN_PATH` (`0/*`). + */ +export const QR_EMULATOR_CHILDREN_PATH = '0/*'; + +/** + * Full account-level derivation path (`m/44'/60'/0'`). The emulator derives an + * extended public key (xpub) at this path and then derives child addresses from + * it with the children path. + */ +export const QR_EMULATOR_ACCOUNT_DERIVATION_PATH = `${QR_EMULATOR_ROOT_DERIVATION_PATH}/${QR_EMULATOR_ACCOUNT_PATH}`; + +/** + * Device fingerprint (4-byte hex, `0x`-prefixed). Stable per default seed and + * independent of the BIP-32 master fingerprint by design, mirroring the way the + * QR keyring treats the fingerprint as an opaque device identifier. + */ +export const QR_EMULATOR_DEFAULT_XFP = '0xdeadbeef'; + +/** + * Full address derivation path for the first account + * (`m/44'/60'/0'/0/0`). + */ +export const QR_EMULATOR_FIRST_ADDRESS_PATH = `${QR_EMULATOR_ACCOUNT_DERIVATION_PATH}/0/0`; + +/** + * Internal helper: derive the checksum address at a given derivation path from + * a mnemonic seed. Passes the compressed public key to `publicToAddress`, + * which decompresses it internally before keccak-hashing — matching the way + * the QR keyring computes addresses from a `CryptoHDKey` public key. + * + * @param seed - The BIP-39 mnemonic seed. + * @param path - The full derivation path (e.g. `m/44'/60'/0'/0/0`). + * @returns The EIP-55 checksum address. + */ +export function deriveAddressFromSeed(seed: string, path: string): Hex { + const master = HdKey.fromMasterSeed(Buffer.from(mnemonicToSeedSync(seed))); + const child = master.derive(path); + const address = Buffer.from(publicToAddress(child.publicKey, true)).toString( + 'hex', + ); + return getChecksumAddress(add0x(address)); +} + +/** + * First derived address (`m/44'/60'/0'/0/0`) for the default seed. Equivalent + * to `SPECULOS_LEDGER_ADDRESS` for the Ledger emulator — assertable in tests + * and stable across instances. + */ +export const QR_EMULATOR_ADDRESS: Hex = deriveAddressFromSeed( + QR_EMULATOR_SEED, + QR_EMULATOR_FIRST_ADDRESS_PATH, +); + +// ── Codec / rendering constants (mirror MetaMask's `player.js` exactly) ────── + +/** + * Bytes per BC-UR fountain fragment. Matches `QR_FRAGMENT_SIZE` in MetaMask's + * `qr-hardware-sign-request/player.js`. + */ +export const QR_FRAGMENT_SIZE = 200; + +/** + * QR refresh interval in milliseconds (5 fps). Matches `QR_REFRESH_RATE` in + * MetaMask's `player.js`. + */ +export const QR_REFRESH_MS = 200; + +/** + * Rendered QR code edge length in pixels. Matches `QR_CODE_SIZE` in MetaMask's + * `player.js`. + */ +export const QR_CODE_SIZE_PX = 225; + +/** + * Target edge length (pixels) for QR PNGs rendered into Y4M video files for + * Chrome's `--use-file-for-fake-video-capture` fake camera. + * + * Larger than {@link QR_CODE_SIZE_PX} (which matches MM's in-DOM QRCodeSVG size) + * because Chrome's fake camera + zxing browser decoder needs more pixels per + * module for reliable fountain-decode of multi-account URs. At 225px a 5-account + * `crypto-account` (81 modules + 8 quiet zone) gets only ~2px/module — below + * zxing's decode threshold. At 648px it gets ~7px/module, validated end-to-end + * by the Phase-0 spike and Lane 4 sign-flow specs. See spec §12.1 (R1). + */ +export const QR_Y4M_RENDER_SIZE_PX = 648; + +/** + * Whether fragment strings are uppercased before QR encoding. Matches + * MetaMask's `player.js` (`currentQRCode.toUpperCase()`). + */ +export const QR_UPPERCASE = true; diff --git a/packages/hw-emulator/src/qr/core/registry.test.ts b/packages/hw-emulator/src/qr/core/registry.test.ts new file mode 100644 index 000000000..7cfbdb9f6 --- /dev/null +++ b/packages/hw-emulator/src/qr/core/registry.test.ts @@ -0,0 +1,133 @@ +import { CryptoAccount, CryptoHDKey } from '@keystonehq/bc-ur-registry-eth'; + +import { + createCryptoAccount, + createCryptoHDKey, + createCryptoOutput, + createKeypath, + parseXfp, + pathToComponents, +} from './registry'; + +describe('QR registry helpers', () => { + describe('parseXfp', () => { + it('parses a 0x-prefixed fingerprint into a 4-byte buffer', () => { + expect(parseXfp('0xdeadbeef')).toStrictEqual( + Buffer.from('deadbeef', 'hex'), + ); + }); + + it('parses a bare hex fingerprint', () => { + expect(parseXfp('deadbeef')).toStrictEqual( + Buffer.from('deadbeef', 'hex'), + ); + }); + + it('throws on a fingerprint that is too short', () => { + expect(() => parseXfp('0xdead')).toThrow(/invalid device fingerprint/iu); + }); + + it('throws on a fingerprint that is too long', () => { + expect(() => parseXfp('deadbeefff')).toThrow( + /invalid device fingerprint/iu, + ); + }); + + it('throws on an odd-length fingerprint', () => { + expect(() => parseXfp('deadbee')).toThrow(/invalid device fingerprint/iu); + }); + + it('throws on a non-hex fingerprint', () => { + expect(() => parseXfp('zzzzzzzz')).toThrow( + /invalid device fingerprint/iu, + ); + }); + }); + + describe('pathToComponents', () => { + it('parses a hardened path', () => { + const components = pathToComponents("44'/60'/0'/0/0"); + expect(components).toHaveLength(5); + expect(components[0]?.isHardened()).toBe(true); + expect(components[0]?.getIndex()).toBe(44); + expect(components[3]?.isHardened()).toBe(false); + expect(components[3]?.getIndex()).toBe(0); + }); + + it('handles a leading m/ or M/', () => { + expect(pathToComponents("m/44'/60'")).toHaveLength(2); + expect(pathToComponents("M/44'/60'")).toHaveLength(2); + }); + + it('handles a wildcard component', () => { + const components = pathToComponents('0/*'); + expect(components[0]?.getIndex()).toBe(0); + expect(components[1]?.isWildcard()).toBe(true); + }); + }); + + describe('createKeypath', () => { + it('round-trips its path through getPath', () => { + const keypath = createKeypath("44'/60'/0'/0/0"); + expect(keypath.getPath()).toBe("44'/60'/0'/0/0"); + }); + + it('round-trips a wildcard children path', () => { + const keypath = createKeypath('0/*'); + expect(keypath.getPath()).toBe('0/*'); + }); + }); + + describe('createCryptoHDKey', () => { + it('constructs a CryptoHDKey with the expected accessors', () => { + const hdKey = createCryptoHDKey({ + publicKey: Buffer.alloc(33, 0x02), + chainCode: Buffer.alloc(32, 0x03), + originPath: "44'/60'/0'", + sourceFingerprint: parseXfp('0xdeadbeef'), + childrenPath: '0/*', + name: 'Keystone Test', + note: 'Account #0', + }); + + expect(hdKey).toBeInstanceOf(CryptoHDKey); + expect(hdKey.getOrigin()?.getPath()).toBe("44'/60'/0'"); + expect(hdKey.getChildren()?.getPath()).toBe('0/*'); + expect(hdKey.getName()).toBe('Keystone Test'); + expect(hdKey.getNote()).toBe('Account #0'); + expect(hdKey.getKey().equals(Buffer.alloc(33, 0x02))).toBe(true); + expect(hdKey.getChainCode().equals(Buffer.alloc(32, 0x03))).toBe(true); + }); + + it('produces a round-trippable CBOR encoding', () => { + const hdKey = createCryptoHDKey({ + publicKey: Buffer.alloc(33, 0x02), + chainCode: Buffer.alloc(32, 0x03), + originPath: "44'/60'/0'", + sourceFingerprint: parseXfp('0xdeadbeef'), + childrenPath: '0/*', + }); + const redecoded = CryptoHDKey.fromCBOR(hdKey.toCBOR()); + expect(redecoded.getOrigin()?.getPath()).toBe("44'/60'/0'"); + expect(redecoded.getChildren()?.getPath()).toBe('0/*'); + }); + }); + + describe('createCryptoOutput / createCryptoAccount', () => { + it('wraps an HD key and bundles descriptors into an account', () => { + const hdKey = createCryptoHDKey({ + publicKey: Buffer.alloc(33, 0x02), + chainCode: Buffer.alloc(32, 0x03), + originPath: "44'/60'/0'", + sourceFingerprint: parseXfp('0xdeadbeef'), + }); + const output = createCryptoOutput(hdKey); + expect(output.getHDKey()).toBe(hdKey); + + const account = createCryptoAccount(parseXfp('0xdeadbeef'), [output]); + expect(account).toBeInstanceOf(CryptoAccount); + expect(account.getOutputDescriptors()).toHaveLength(1); + expect(account.getMasterFingerprint().toString('hex')).toBe('deadbeef'); + }); + }); +}); diff --git a/packages/hw-emulator/src/qr/core/registry.ts b/packages/hw-emulator/src/qr/core/registry.ts new file mode 100644 index 000000000..6171216a2 --- /dev/null +++ b/packages/hw-emulator/src/qr/core/registry.ts @@ -0,0 +1,135 @@ +/* eslint-disable no-restricted-globals -- Buffer is required for fingerprint/path encoding. */ + +import { + CryptoAccount, + CryptoHDKey, + CryptoKeypath, + CryptoOutput, + PathComponent, + ScriptExpressions, +} from '@keystonehq/bc-ur-registry-eth'; + +/** + * Parse a device fingerprint string (e.g. `0xdeadbeef` or `deadbeef`) into a + * 4-byte big-endian `Buffer`, the shape expected by the BC-UR registry. + * + * @param xfp - The hex-encoded fingerprint, optionally `0x`-prefixed. + * @returns A 4-byte Buffer. + * @throws If the fingerprint is not exactly 8 hex characters (optionally + * `0x`-prefixed), i.e. 4 bytes. + */ +export function parseXfp(xfp: string): Buffer { + const hexPart = xfp.startsWith('0x') ? xfp.slice(2) : xfp; + if (!/^[0-9a-f]{8}$/iu.test(hexPart)) { + throw new Error( + `Invalid device fingerprint '${xfp}': expected exactly 8 hex characters (4 bytes), optionally 0x-prefixed`, + ); + } + return Buffer.from(hexPart, 'hex'); +} + +/** + * Parse a BIP-32 derivation path string (e.g. `m/44'/60'/0'/0/0` or + * `0/*`) into the {@link PathComponent} list used by the BC-UR registry. + * + * Supports hardened suffixes (`'`) and wildcards (`*`). + * + * @param path - The derivation path, with or without a leading `m/` or `M/`. + * @returns The ordered list of path components. + */ +export function pathToComponents(path: string): PathComponent[] { + return path + .replace(/^[mM]\//u, '') + .split('/') + .filter((segment) => segment.length > 0) + .map((segment) => { + if (segment === '*') { + return new PathComponent({ hardened: false }); + } + const hardened = segment.endsWith("'"); + const index = parseInt(hardened ? segment.slice(0, -1) : segment, 10); + return new PathComponent({ index, hardened }); + }); +} + +/** + * Build a {@link CryptoKeypath} (a BC-UR registry path) from a derivation path + * string and an optional source fingerprint. + * + * @param path - The derivation path (e.g. `44'/60'/0'/0/0` or `0/*`). + * @param sourceFingerprint - Optional 4-byte source fingerprint Buffer. + * @returns A CryptoKeypath. + */ +export function createKeypath( + path: string, + sourceFingerprint?: Buffer, +): CryptoKeypath { + return new CryptoKeypath(pathToComponents(path), sourceFingerprint); +} + +type CryptoHDKeyOptions = { + /** Compressed (33-byte) public key. */ + publicKey: Buffer; + /** 32-byte chain code. */ + chainCode: Buffer; + /** Origin path (e.g. `44'/60'/0'`). */ + originPath: string; + /** 4-byte source fingerprint for the origin. */ + sourceFingerprint: Buffer; + /** Optional children path (e.g. `0/*`). */ + childrenPath?: string; + /** Optional human-readable name. */ + name?: string; + /** Optional free-form note / keyring account label. */ + note?: string; +}; + +/** + * Construct a {@link CryptoHDKey} (public-account form) suitable for use both as + * a standalone `crypto-hdkey` UR and as an output descriptor inside a + * `crypto-account` UR. + * + * @param options - Construction options. + * @returns A CryptoHDKey. + */ +export function createCryptoHDKey(options: CryptoHDKeyOptions): CryptoHDKey { + return new CryptoHDKey({ + isMaster: false, + isPrivateKey: false, + key: options.publicKey, + chainCode: options.chainCode, + origin: createKeypath(options.originPath, options.sourceFingerprint), + ...(options.childrenPath + ? { children: createKeypath(options.childrenPath) } + : {}), + ...(options.name === undefined ? {} : { name: options.name }), + ...(options.note === undefined ? {} : { note: options.note }), + }); +} + +/** + * Wrap a {@link CryptoHDKey} in a {@link CryptoOutput} using the + * `witness-public-key-hash` script expression (the convention Keystone-class + * devices use for Ethereum account descriptors). + * + * @param hdKey - The HD key to wrap. + * @returns A CryptoOutput descriptor. + */ +export function createCryptoOutput(hdKey: CryptoHDKey): CryptoOutput { + return new CryptoOutput([ScriptExpressions.WITNESS_PUBLIC_KEY_HASH], hdKey); +} + +/** + * Construct a {@link CryptoAccount} from a master fingerprint and a list of + * output descriptors. + * + * @param masterFingerprint - 4-byte device fingerprint Buffer. + * @param outputs - Output descriptors to bundle into the account. + * @returns A CryptoAccount. + */ +export function createCryptoAccount( + masterFingerprint: Buffer, + outputs: CryptoOutput[], +): CryptoAccount { + return new CryptoAccount(masterFingerprint, outputs); +} diff --git a/packages/hw-emulator/src/qr/core/signer.test.ts b/packages/hw-emulator/src/qr/core/signer.test.ts new file mode 100644 index 000000000..ae80179db --- /dev/null +++ b/packages/hw-emulator/src/qr/core/signer.test.ts @@ -0,0 +1,324 @@ +import { Common, Hardfork, Mainnet } from '@ethereumjs/common'; +/* eslint-disable id-length -- r/s/v are the canonical ECDSA signature component names. */ +import { RLP } from '@ethereumjs/rlp'; +import { createTx } from '@ethereumjs/tx'; +import type { TypedTransaction } from '@ethereumjs/tx'; +import type { AddressLike } from '@ethereumjs/util'; +import { + CryptoKeypath, + DataType, + ETHSignature, + EthSignRequest, +} from '@keystonehq/bc-ur-registry-eth'; +import { + recoverPersonalSignature, + recoverTypedSignature, + SignTypedDataVersion, +} from '@metamask/eth-sig-util'; +import type { MessageTypes, TypedMessage } from '@metamask/eth-sig-util'; +import { add0x, getChecksumAddress, remove0x } from '@metamask/utils'; +import type { Hex } from '@metamask/utils'; +import { randomUUID } from 'node:crypto'; +import { parse as uuidParse, stringify as uuidStringify } from 'uuid'; + +import { + QR_EMULATOR_ACCOUNT_DERIVATION_PATH, + QR_EMULATOR_ADDRESS, + QR_EMULATOR_DEFAULT_XFP, + QR_EMULATOR_SEED, +} from '../constants'; +import { decodeSignRequest, signRequest } from './signer'; +import type { SerializedUR } from './ur-synth'; + +const FIRST_ADDRESS_PATH = `${QR_EMULATOR_ACCOUNT_DERIVATION_PATH}/0/0`; +const OTHER_ADDRESS_PATH = `${QR_EMULATOR_ACCOUNT_DERIVATION_PATH}/0/1`; +const OTHER_ADDRESS = '0x70997970C51812dc3A010C7d01b50e0d17dc79C8'; + +const common = new Common({ + chain: Mainnet, + hardfork: Hardfork.SpuriousDragon, +}); + +function extractSignatureParts(ur: SerializedUR): { + r: Hex; + s: Hex; + v: Hex; + requestId: string; +} { + const signature = ETHSignature.fromCBOR(Buffer.from(ur.cbor, 'hex')); + const raw = signature.getSignature(); + const r = add0x(raw.subarray(0, 32).toString('hex')); + const s = add0x(raw.subarray(32, 64).toString('hex')); + const v = add0x(raw.subarray(64).toString('hex')); + const requestId = signature.getRequestId() + ? uuidStringify(signature.getRequestId() as Uint8Array) + : ''; + return { r, s, v, requestId }; +} + +function buildSignRequest( + signData: Buffer, + dataType: DataType, + hdPath: string, + requestId: string, + chainId?: number, + address?: string, +): SerializedUR { + const request = EthSignRequest.constructETHRequest( + signData, + dataType, + hdPath, + QR_EMULATOR_DEFAULT_XFP.replace('0x', ''), + requestId, + chainId, + address, + ); + const ur = request.toUR(); + return { type: ur.type, cbor: ur.cbor.toString('hex') }; +} + +describe('QR signer', () => { + it('decodes a sign request and exposes the derivation path', () => { + const ur = buildSignRequest( + Buffer.from('00', 'hex'), + DataType.personalMessage, + FIRST_ADDRESS_PATH, + randomUUID(), + ); + const request = decodeSignRequest(ur); + expect(request.getDerivationPath()).toBe( + FIRST_ADDRESS_PATH.replace('m/', ''), + ); + expect(request.getDataType()).toBe(DataType.personalMessage); + }); + + it('throws a descriptive error when the sign request has no derivation path', () => { + // An empty CryptoKeypath makes getDerivationPath() return undefined; + // without the guard this falls through to a cryptic hdkey derive error. + const request = new EthSignRequest({ + signData: Buffer.from('deadbeef', 'hex'), + dataType: DataType.personalMessage, + derivationPath: new CryptoKeypath([], undefined), + }); + const ur = request.toUR(); + expect(() => + signRequest( + { type: ur.type, cbor: ur.cbor.toString('hex') }, + { seed: QR_EMULATOR_SEED }, + ), + ).toThrow(/missing derivation path/iu); + }); + + describe('transactions', () => { + it('signs a legacy (type 0) transaction and recovers QR_EMULATOR_ADDRESS', () => { + const tx = createTx( + { + nonce: 1, + gasPrice: 10_000_000_000, + gasLimit: 21_000, + to: `0x${'11'.repeat(20)}` as AddressLike, + value: 1000, + data: '0x', + }, + { common }, + ); + const signData = Buffer.from(RLP.encode(tx.getMessageToSign() as never)); + const requestId = randomUUID(); + const ur = buildSignRequest( + signData, + DataType.transaction, + FIRST_ADDRESS_PATH, + requestId, + 1, + ); + + const signature = signRequest(ur, { seed: QR_EMULATOR_SEED }); + const { + r, + s, + v, + requestId: returnedId, + } = extractSignatureParts(signature); + expect(returnedId).toBe(requestId); + + const signed = createTx( + { ...tx.toJSON(), r, s, v }, + { common }, + ) as TypedTransaction; + + expect(signed.verifySignature()).toBe(true); + expect(getChecksumAddress(signed.getSenderAddress().toString())).toBe( + QR_EMULATOR_ADDRESS, + ); + }); + + it('signs an EIP-1559 (type 2) transaction and recovers QR_EMULATOR_ADDRESS', () => { + const londonCommon = new Common({ + chain: Mainnet, + hardfork: Hardfork.London, + }); + const tx = createTx( + { + type: 2, + nonce: 5, + maxFeePerGas: 20_000_000_000, + maxPriorityFeePerGas: 1_000_000_000, + gasLimit: 21_000, + to: `0x${'22'.repeat(20)}` as AddressLike, + value: 5000, + data: '0xabcd', + accessList: [], + chainId: 1, + }, + { common: londonCommon }, + ); + const signData = Buffer.from(tx.getMessageToSign() as Buffer); + const requestId = randomUUID(); + const ur = buildSignRequest( + signData, + DataType.typedTransaction, + FIRST_ADDRESS_PATH, + requestId, + 1, + ); + + const signature = signRequest(ur, { seed: QR_EMULATOR_SEED }); + const { r, s, v } = extractSignatureParts(signature); + + const signed = createTx( + { ...tx.toJSON(), r, s, v }, + { common: londonCommon }, + ) as TypedTransaction; + + expect(signed.verifySignature()).toBe(true); + expect(getChecksumAddress(signed.getSenderAddress().toString())).toBe( + QR_EMULATOR_ADDRESS, + ); + }); + }); + + describe('messages', () => { + const typedData: TypedMessage = { + types: { + EIP712Domain: [ + { name: 'name', type: 'string' }, + { name: 'version', type: 'string' }, + { name: 'chainId', type: 'uint256' }, + { name: 'verifyingContract', type: 'address' }, + ], + Mail: [ + { name: 'from', type: 'Person' }, + { name: 'contents', type: 'string' }, + ], + Person: [ + { name: 'name', type: 'string' }, + { name: 'wallet', type: 'address' }, + ], + }, + primaryType: 'Mail', + domain: { + name: 'Ether Mail', + version: '1', + chainId: 1, + verifyingContract: `0x${'cc'.repeat(20)}`, + }, + message: { + from: { name: 'Cow', wallet: QR_EMULATOR_ADDRESS }, + contents: 'Hello, QR', + }, + } as never; + + it('signs EIP-712 typed data v4 and recovers QR_EMULATOR_ADDRESS', () => { + const signData = Buffer.from(JSON.stringify(typedData), 'utf8'); + const requestId = randomUUID(); + const ur = buildSignRequest( + signData, + DataType.typedData, + FIRST_ADDRESS_PATH, + requestId, + undefined, + QR_EMULATOR_ADDRESS, + ); + + const signature = signRequest(ur, { seed: QR_EMULATOR_SEED }); + const { r, s, v } = extractSignatureParts(signature); + const combined = add0x(`${r.slice(2)}${s.slice(2)}${v.slice(2)}`); + + const recovered = recoverTypedSignature({ + data: typedData, + signature: combined, + version: SignTypedDataVersion.V4, + }); + expect(getChecksumAddress(recovered as Hex)).toBe(QR_EMULATOR_ADDRESS); + }); + + it('signs a personal_sign message and recovers QR_EMULATOR_ADDRESS', () => { + const message = add0x(Buffer.from('Hello QR emulator').toString('hex')); + const signData = Buffer.from(remove0x(message), 'hex'); + const requestId = randomUUID(); + const ur = buildSignRequest( + signData, + DataType.personalMessage, + FIRST_ADDRESS_PATH, + requestId, + undefined, + QR_EMULATOR_ADDRESS, + ); + + const signature = signRequest(ur, { seed: QR_EMULATOR_SEED }); + const { r, s, v } = extractSignatureParts(signature); + const combined = add0x(`${r.slice(2)}${s.slice(2)}${v.slice(2)}`); + + const recovered = recoverPersonalSignature({ + data: message, + signature: combined, + }); + expect(getChecksumAddress(recovered as Hex)).toBe(QR_EMULATOR_ADDRESS); + }); + }); + + describe('key isolation', () => { + it('signs with a different key for a different derivation path', () => { + const message = add0x(Buffer.from('second account').toString('hex')); + const signData = Buffer.from(remove0x(message), 'hex'); + const ur = buildSignRequest( + signData, + DataType.personalMessage, + OTHER_ADDRESS_PATH, + randomUUID(), + undefined, + OTHER_ADDRESS, + ); + + const signature = signRequest(ur, { seed: QR_EMULATOR_SEED }); + const { r, s, v } = extractSignatureParts(signature); + const combined = add0x(`${r.slice(2)}${s.slice(2)}${v.slice(2)}`); + expect( + getChecksumAddress( + recoverPersonalSignature({ + data: message, + signature: combined, + }) as Hex, + ), + ).toBe(OTHER_ADDRESS); + }); + }); + + it('echoes the request id back as a valid uuid', () => { + const requestId = randomUUID(); + const ur = buildSignRequest( + Buffer.from('deadbeef', 'hex'), + DataType.personalMessage, + FIRST_ADDRESS_PATH, + requestId, + ); + const signature = signRequest(ur, { seed: QR_EMULATOR_SEED }); + const ethSignature = ETHSignature.fromCBOR( + Buffer.from(signature.cbor, 'hex'), + ); + expect(uuidStringify(ethSignature.getRequestId() as Uint8Array)).toBe( + requestId, + ); + expect(uuidParse(requestId)).toBeDefined(); + }); +}); diff --git a/packages/hw-emulator/src/qr/core/signer.ts b/packages/hw-emulator/src/qr/core/signer.ts new file mode 100644 index 000000000..7cd9f0fa8 --- /dev/null +++ b/packages/hw-emulator/src/qr/core/signer.ts @@ -0,0 +1,224 @@ +/* eslint-disable no-restricted-globals -- Buffer is required for ECDSA signing. */ + +/* eslint-disable id-length -- r/s/v are the canonical ECDSA signature component names. */ + +import { RLP } from '@ethereumjs/rlp'; +import { + ETHSignature, + EthSignRequest, + DataType, +} from '@keystonehq/bc-ur-registry-eth'; +import { + personalSign, + signTypedData, + SignTypedDataVersion, +} from '@metamask/eth-sig-util'; +import { add0x } from '@metamask/utils'; +import { mnemonicToSeedSync } from 'ethereum-cryptography/bip39'; +import { keccak256 } from 'ethereum-cryptography/keccak'; +import HdKey from 'hdkey'; +import { ecdsaSign } from 'secp256k1'; + +import { QR_EMULATOR_SEED } from '../constants'; +import type { SerializedUR } from './ur-synth'; + +/** + * Result of a signing operation: the three ECDSA signature components. + * `v` is encoded as minimal big-endian bytes (1 byte for parity/27-28, more + * for EIP-155 legacy chain-id-encoded values). + */ +type SignatureParts = { + r: Buffer; + s: Buffer; + v: Buffer; +}; + +/** Options for the signer. */ +export type SignerOptions = { + /** BIP-39 mnemonic seed used to derive signing keys. */ + seed: string; +}; + +/** + * Convert a non-negative bigint to minimal big-endian bytes (matching + * `@ethereumjs/util`'s `bigIntToUnpaddedBytes`). + * + * @param value - The non-negative bigint. + * @returns Minimal big-endian bytes. + */ +function bigIntToUnpaddedBytes(value: bigint): Buffer { + if (value === 0n) { + return Buffer.alloc(0); + } + const hexString = value.toString(16); + const padded = hexString.length % 2 === 0 ? hexString : `0${hexString}`; + return Buffer.from(padded, 'hex'); +} + +/** + * Derive the 32-byte private key at a full derivation path from a seed. + * + * @param seed - The BIP-39 mnemonic. + * @param path - The full derivation path, with or without a leading `m/`. + * @returns The 32-byte private key. + */ +export function derivePrivateKey(seed: string, path: string): Buffer { + const normalized = path.startsWith('m') ? path : `m/${path}`; + const child = HdKey.fromMasterSeed( + Buffer.from(mnemonicToSeedSync(seed)), + ).derive(normalized); + return Buffer.from(child.privateKey); +} + +/** + * Sign a transaction signing payload (the output of + * `Transaction.getMessageToSign()`, RLP-encoded) with ECDSA and compute the + * correct `v` value. + * + * - Legacy (`DataType.transaction`): honours EIP-155 when the payload carries a + * chain id (9 RLP items); otherwise emits pre-EIP-155 `v` (27/28). + * - Typed (`DataType.typedTransaction`): emits parity `v` (0/1). + * + * @param signData - The RLP-encoded signing payload. + * @param dataType - The BC-UR registry data type. + * @param privateKey - The 32-byte private key. + * @returns The signature parts. + */ +function signTransactionPayload( + signData: Buffer, + dataType: DataType, + privateKey: Buffer, +): SignatureParts { + const hash = keccak256(signData); + const { signature, recid } = ecdsaSign( + Uint8Array.from(hash), + Uint8Array.from(privateKey), + ); + const r = Buffer.from(signature.subarray(0, 32)); + const s = Buffer.from(signature.subarray(32, 64)); + + let v: Buffer; + if (dataType === DataType.transaction) { + const decoded = RLP.decode(signData); + if (Array.isArray(decoded) && decoded.length === 9) { + const chainIdBytes = Buffer.from(decoded[6] as Uint8Array); + const chainIdHex = + chainIdBytes.length === 0 ? '0' : chainIdBytes.toString('hex'); + const chainId = BigInt(`0x${chainIdHex}`); + v = bigIntToUnpaddedBytes(chainId * 2n + 35n + BigInt(recid)); + } else { + v = Buffer.from([27 + recid]); + } + } else { + v = Buffer.from([recid]); + } + + return { r, s, v }; +} + +/** + * Sign an EIP-191 personal message payload using `@metamask/eth-sig-util`. + * + * @param signData - The raw message bytes (already hex-decoded by the keyring). + * @param privateKey - The 32-byte private key. + * @returns The signature parts (v is 27/28). + */ +function signPersonalMessagePayload( + signData: Buffer, + privateKey: Buffer, +): SignatureParts { + const signature = personalSign({ + privateKey, + data: add0x(signData.toString('hex')), + }); + const bytes = Buffer.from(signature.slice(2), 'hex'); + return { + r: bytes.subarray(0, 32), + s: bytes.subarray(32, 64), + v: bytes.subarray(64), + }; +} + +/** + * Sign EIP-712 typed data (v4) using `@metamask/eth-sig-util`. + * + * @param signData - The UTF-8 JSON-encoded typed data. + * @param privateKey - The 32-byte private key. + * @returns The signature parts (v is 27/28). + */ +function signTypedDataPayload( + signData: Buffer, + privateKey: Buffer, +): SignatureParts { + const data = JSON.parse(signData.toString('utf8')); + const signature = signTypedData({ + privateKey, + data, + version: SignTypedDataVersion.V4, + }); + const bytes = Buffer.from(signature.slice(2), 'hex'); + return { + r: bytes.subarray(0, 32), + s: bytes.subarray(32, 64), + v: bytes.subarray(64), + }; +} + +/** + * Decode an `EthSignRequest` SerializedUR into the registry object. + * + * @param ur - The SerializedUR (type `eth-sign-request`). + * @returns The decoded EthSignRequest. + */ +export function decodeSignRequest(ur: SerializedUR): EthSignRequest { + return EthSignRequest.fromCBOR(Buffer.from(ur.cbor, 'hex')); +} + +/** + * Sign an `EthSignRequest` SerializedUR and produce an `eth-signature` + * SerializedUR containing a real ECDSA signature from the derived key. + * + * The returned `requestId` mirrors the incoming request so the QR keyring's + * request-id validation succeeds. + * + * @param ur - The SerializedUR of the sign request. + * @param options - Signer options. + * @returns A SerializedUR (type `eth-signature`). + */ +export function signRequest( + ur: SerializedUR, + options: SignerOptions = { seed: QR_EMULATOR_SEED }, +): SerializedUR { + const request = decodeSignRequest(ur); + const dataType = request.getDataType(); + const signData = Buffer.from(request.getSignData()); + const path = request.getDerivationPath(); + if (!path) { + throw new Error('EthSignRequest missing derivation path'); + } + const privateKey = derivePrivateKey(options.seed, path); + + let parts: SignatureParts; + switch (dataType) { + case DataType.transaction: + case DataType.typedTransaction: + parts = signTransactionPayload(signData, dataType, privateKey); + break; + case DataType.personalMessage: + parts = signPersonalMessagePayload(signData, privateKey); + break; + case DataType.typedData: + parts = signTypedDataPayload(signData, privateKey); + break; + default: + throw new Error( + `Unsupported sign request data type: ${String(dataType)}`, + ); + } + + const signature = Buffer.concat([parts.r, parts.s, parts.v]); + const requestId = request.getRequestId(); + const ethSignature = new ETHSignature(signature, requestId); + const result = ethSignature.toUR(); + return { type: result.type, cbor: result.cbor.toString('hex') }; +} diff --git a/packages/hw-emulator/src/qr/core/ur-synth.test.ts b/packages/hw-emulator/src/qr/core/ur-synth.test.ts new file mode 100644 index 000000000..b0f286718 --- /dev/null +++ b/packages/hw-emulator/src/qr/core/ur-synth.test.ts @@ -0,0 +1,132 @@ +import { publicToAddress } from '@ethereumjs/util'; +import { CryptoAccount, CryptoHDKey } from '@keystonehq/bc-ur-registry-eth'; +import { add0x, getChecksumAddress } from '@metamask/utils'; +import HdKey from 'hdkey'; + +import { + QR_EMULATOR_ACCOUNT_DERIVATION_PATH, + QR_EMULATOR_ADDRESS, + QR_EMULATOR_CHILDREN_PATH, + QR_EMULATOR_DEFAULT_XFP, + QR_EMULATOR_SEED, +} from '../constants'; +import { + CRYPTO_ACCOUNT_TYPE, + CRYPTO_HDKEY_TYPE, + buildCryptoAccountUR, + buildCryptoHDKeyUR, + deriveAccountAddress, + synthesizeAccountUR, +} from './ur-synth'; +import type { SynthesizeOptions } from './ur-synth'; + +const baseOptions: SynthesizeOptions = { + seed: QR_EMULATOR_SEED, + accountPath: QR_EMULATOR_ACCOUNT_DERIVATION_PATH, + childrenPath: QR_EMULATOR_CHILDREN_PATH, + xfp: QR_EMULATOR_DEFAULT_XFP, + deviceName: 'Keystone Test', + pairMode: 'crypto-account', + descriptorCount: 5, +}; + +function addressFromPublicKey(publicKey: Buffer): string { + return getChecksumAddress( + add0x(Buffer.from(publicToAddress(publicKey, true)).toString('hex')), + ); +} + +describe('QR UR synthesizer', () => { + describe('crypto-account mode (default)', () => { + it('produces a SerializedUR with type crypto-account', () => { + const ur = synthesizeAccountUR(baseOptions); + expect(ur.type).toBe(CRYPTO_ACCOUNT_TYPE); + expect(typeof ur.cbor).toBe('string'); + expect(ur.cbor.length).toBeGreaterThan(0); + }); + + it('decodes to a CryptoAccount whose first descriptor matches QR_EMULATOR_ADDRESS', () => { + const ur = buildCryptoAccountUR(baseOptions); + const account = CryptoAccount.fromCBOR(Buffer.from(ur.cbor, 'hex')); + expect(account).toBeInstanceOf(CryptoAccount); + + const descriptors = account.getOutputDescriptors(); + expect(descriptors).toHaveLength(5); + + const firstHdKey = descriptors[0]?.getHDKey(); + expect(firstHdKey).toBeInstanceOf(CryptoHDKey); + expect(addressFromPublicKey((firstHdKey as CryptoHDKey).getKey())).toBe( + QR_EMULATOR_ADDRESS, + ); + }); + + it('derives distinct, ordered addresses across descriptors', () => { + const ur = buildCryptoAccountUR(baseOptions); + const account = CryptoAccount.fromCBOR(Buffer.from(ur.cbor, 'hex')); + const addresses = account + .getOutputDescriptors() + .map((descriptor) => + addressFromPublicKey(descriptor.getHDKey().getKey()), + ); + + expect(addresses[0]).toBe(QR_EMULATOR_ADDRESS); + for (let i = 0; i < addresses.length; i++) { + expect(addresses[i]).toBe( + deriveAccountAddress( + QR_EMULATOR_SEED, + QR_EMULATOR_ACCOUNT_DERIVATION_PATH, + i, + ), + ); + } + expect(new Set(addresses).size).toBe(addresses.length); + }); + + it('emits the device fingerprint as the master fingerprint', () => { + const ur = buildCryptoAccountUR(baseOptions); + const account = CryptoAccount.fromCBOR(Buffer.from(ur.cbor, 'hex')); + expect(account.getMasterFingerprint().toString('hex')).toBe('deadbeef'); + }); + }); + + describe('crypto-hdkey mode', () => { + it('produces a SerializedUR with type crypto-hdkey', () => { + const ur = synthesizeAccountUR({ + ...baseOptions, + pairMode: 'crypto-hdkey', + }); + expect(ur.type).toBe(CRYPTO_HDKEY_TYPE); + }); + + it('decodes to a CryptoHDKey whose xpub derives QR_EMULATOR_ADDRESS at 0/0', () => { + const ur = buildCryptoHDKeyUR({ + ...baseOptions, + pairMode: 'crypto-hdkey', + }); + const hdKey = CryptoHDKey.fromCBOR(Buffer.from(ur.cbor, 'hex')); + + expect(hdKey.getOrigin()?.getPath()).toBe("44'/60'/0'"); + expect(hdKey.getChildren()?.getPath()).toBe('0/*'); + + const child = HdKey.fromExtendedKey(hdKey.getBip32Key()).derive('m/0/0'); + expect(addressFromPublicKey(child.publicKey)).toBe(QR_EMULATOR_ADDRESS); + }); + }); + + describe('determinism', () => { + it('produces identical output across instances with the same seed', () => { + const a = synthesizeAccountUR(baseOptions); + const b = synthesizeAccountUR({ ...baseOptions }); + expect(a).toStrictEqual(b); + }); + + it('produces different output for a different seed', () => { + const a = synthesizeAccountUR(baseOptions); + const b = synthesizeAccountUR({ + ...baseOptions, + seed: 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong', + }); + expect(a.cbor).not.toBe(b.cbor); + }); + }); +}); diff --git a/packages/hw-emulator/src/qr/core/ur-synth.ts b/packages/hw-emulator/src/qr/core/ur-synth.ts new file mode 100644 index 000000000..5798f3d4a --- /dev/null +++ b/packages/hw-emulator/src/qr/core/ur-synth.ts @@ -0,0 +1,168 @@ +/* eslint-disable no-restricted-globals -- Buffer is required for HD-key and UR construction. */ + +import type { Hex } from '@metamask/utils'; +import { mnemonicToSeedSync } from 'ethereum-cryptography/bip39'; +import HdKey from 'hdkey'; + +import { + QR_EMULATOR_ACCOUNT_DERIVATION_PATH, + QR_EMULATOR_CHILDREN_PATH, + QR_EMULATOR_SEED, +} from '../constants'; +import { deriveAddressFromSeed } from '../constants'; +import { + createCryptoAccount, + createCryptoHDKey, + createCryptoOutput, + parseXfp, +} from './registry'; + +/** Pairing mode: bundle of derived addresses, or a single account xpub. */ +export type QrPairMode = 'crypto-account' | 'crypto-hdkey'; + +/** UR type string for a crypto-account UR. */ +export const CRYPTO_ACCOUNT_TYPE = 'crypto-account'; + +/** UR type string for a crypto-hdkey UR. */ +export const CRYPTO_HDKEY_TYPE = 'crypto-hdkey'; + +/** Serialized UR shape consumed by the QR keyring. */ +export type SerializedUR = { + type: string; + cbor: string; +}; + +/** + * Options for synthesizing a pairing UR from a seed. + */ +export type SynthesizeOptions = { + /** BIP-39 mnemonic seed. */ + seed: string; + /** Full account derivation path (e.g. `m/44'/60'/0'`). */ + accountPath: string; + /** Children path within the account (e.g. `0/*`). */ + childrenPath: string; + /** Device fingerprint, hex (optionally `0x`-prefixed). */ + xfp: string; + /** Human-readable device name. */ + deviceName: string; + /** Pairing mode. */ + pairMode: QrPairMode; + /** Number of address descriptors to emit in `crypto-account` mode. */ + descriptorCount: number; +}; + +/** Default descriptor count for `crypto-account` mode. */ +export const DEFAULT_DESCRIPTOR_COUNT = 5; + +/** + * Derive the root HD key from a mnemonic seed. + * + * @param seed - The BIP-39 mnemonic. + * @returns The master HDKey. + */ +export function getMasterKey(seed: string = QR_EMULATOR_SEED): HdKey { + return HdKey.fromMasterSeed(Buffer.from(mnemonicToSeedSync(seed))); +} + +/** + * Derive a child HD key from a seed at a full derivation path. + * + * @param seed - The BIP-39 mnemonic. + * @param path - The full derivation path (e.g. `m/44'/60'/0'/0/0`). + * @returns The derived HDKey. + */ +export function deriveKey(seed: string, path: string): HdKey { + return getMasterKey(seed).derive(path); +} + +/** + * Build a `crypto-account` UR (a bundle of output descriptors, one per derived + * address). This is the default pairing mode. + * + * @param options - Synthesize options. + * @returns A SerializedUR with type `crypto-account`. + */ +export function buildCryptoAccountUR(options: SynthesizeOptions): SerializedUR { + const sourceFingerprint = parseXfp(options.xfp); + const outputs = Array.from( + { length: options.descriptorCount }, + (_, index) => { + const path = `${options.accountPath}/0/${index}`; + const child = deriveKey(options.seed, path); + return createCryptoOutput( + createCryptoHDKey({ + publicKey: Buffer.from(child.publicKey), + chainCode: Buffer.from(child.chainCode), + originPath: options.accountPath + .replace(/^[mM]\//u, '') + .concat(`/0/${index}`), + sourceFingerprint, + name: options.deviceName, + note: options.deviceName, + }), + ); + }, + ); + + const account = createCryptoAccount(sourceFingerprint, outputs); + const ur = account.toUR(); + return { type: ur.type, cbor: ur.cbor.toString('hex') }; +} + +/** + * Build a `crypto-hdkey` UR (a single account-level extended public key). The + * consumer derives child addresses from it using the children path. + * + * @param options - Synthesize options. + * @returns A SerializedUR with type `crypto-hdkey`. + */ +export function buildCryptoHDKeyUR(options: SynthesizeOptions): SerializedUR { + const sourceFingerprint = parseXfp(options.xfp); + const accountKey = deriveKey(options.seed, options.accountPath); + + const hdKey = createCryptoHDKey({ + publicKey: Buffer.from(accountKey.publicKey), + chainCode: Buffer.from(accountKey.chainCode), + originPath: options.accountPath.replace(/^[mM]\//u, ''), + sourceFingerprint, + childrenPath: options.childrenPath.replace(/^[mM]\//u, ''), + name: options.deviceName, + note: options.deviceName, + }); + + const ur = hdKey.toUR(); + return { type: ur.type, cbor: ur.cbor.toString('hex') }; +} + +/** + * Synthesize the pairing UR for the given mode. Defaults to + * `crypto-account` (the canonical Keystone pairing format). + * + * @param options - Synthesize options. + * @returns A SerializedUR the QR keyring can deserialize. + */ +export function synthesizeAccountUR(options: SynthesizeOptions): SerializedUR { + return options.pairMode === 'crypto-hdkey' + ? buildCryptoHDKeyUR(options) + : buildCryptoAccountUR(options); +} + +/** + * Convenience: derive the address at a given index relative to an account path, + * matching the children-path convention (`0/*`). + * + * @param seed - The BIP-39 mnemonic. + * @param accountPath - The full account derivation path. + * @param index - The child index. + * @returns The EIP-55 checksum address. + */ +export function deriveAccountAddress( + seed: string, + accountPath: string, + index: number, +): Hex { + return deriveAddressFromSeed(seed, `${accountPath}/0/${index}`); +} + +export { QR_EMULATOR_CHILDREN_PATH, QR_EMULATOR_ACCOUNT_DERIVATION_PATH }; diff --git a/packages/hw-emulator/src/qr/decode/screenshots.test.ts b/packages/hw-emulator/src/qr/decode/screenshots.test.ts new file mode 100644 index 000000000..6fa030680 --- /dev/null +++ b/packages/hw-emulator/src/qr/decode/screenshots.test.ts @@ -0,0 +1,254 @@ +/* eslint-disable n/no-sync -- synchronous zlib/fs is acceptable in test fixtures. */ +/* eslint-disable no-bitwise -- CRC-32 and pixel packing in the PNG fixture require bitwise ops. */ + +/* eslint-disable @typescript-eslint/no-non-null-assertion -- CRC table index is provably in range. */ + +import { encodeToFragments } from '../codec/encoder'; +import { + QR_EMULATOR_ACCOUNT_DERIVATION_PATH, + QR_EMULATOR_CHILDREN_PATH, + QR_EMULATOR_DEFAULT_XFP, + QR_EMULATOR_SEED, +} from '../constants'; +import { buildCryptoAccountUR, buildCryptoHDKeyUR } from '../core/ur-synth'; +import type { SynthesizeOptions } from '../core/ur-synth'; +import { renderQrPng } from '../render/png'; +import { + decodePngToRgb, + decodeQrImage, + decodeQrScreenshots, +} from './screenshots'; + +const baseOptions: SynthesizeOptions = { + seed: QR_EMULATOR_SEED, + accountPath: QR_EMULATOR_ACCOUNT_DERIVATION_PATH, + childrenPath: QR_EMULATOR_CHILDREN_PATH, + xfp: QR_EMULATOR_DEFAULT_XFP, + deviceName: 'Keystone Test', + pairMode: 'crypto-account', + descriptorCount: 5, +}; + +const PNG_SIGNATURE = Buffer.from([ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, +]); +const PNG_SIGNATURE_LEN = PNG_SIGNATURE.length; + +describe('QR screenshot decoder', () => { + describe('decodeQrImage', () => { + it('decodes a rendered single-frame PNG back to its fragment string', async () => { + const ur = buildCryptoHDKeyUR({ + ...baseOptions, + pairMode: 'crypto-hdkey', + }); + const fragment = encodeToFragments(ur, 10_000)[0] as string; + const png = renderQrPng(fragment); + const decoded = await decodeQrImage(png); + expect(decoded).toBe(fragment.toUpperCase()); + }); + + it('returns null for a PNG with no QR code', async () => { + // A valid PNG structure (grayscale) that is all-white: no QR decodable. + const { deflateSync } = await import('node:zlib'); + const size = 32; + const scanlines = Buffer.concat( + Array.from({ length: size }, () => + Buffer.concat([Buffer.from([0]), Buffer.alloc(size, 255)]), + ), + ); + const signature = Buffer.from([ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, + ]); + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(size, 0); + ihdr.writeUInt32BE(size, 4); + ihdr[8] = 8; + ihdr[9] = 0; + const blankPng = Buffer.concat([ + signature, + chunk('IHDR', ihdr), + chunk('IDAT', deflateSync(scanlines)), + chunk('IEND', Buffer.alloc(0)), + ]); + const decoded = await decodeQrImage(blankPng); + expect(decoded).toBeNull(); + }); + }); + + describe('decodePngToRgb', () => { + it('throws on a malformed (non-PNG) buffer', () => { + const junk = Buffer.from('not a png at all, just random text'); + expect(() => decodePngToRgb(junk)).toThrow(/not a png/iu); + }); + + it('round-trips a rendered PNG into width/height/data', () => { + const ur = buildCryptoHDKeyUR({ + ...baseOptions, + pairMode: 'crypto-hdkey', + }); + const fragment = encodeToFragments(ur, 10_000)[0] as string; + const png = renderQrPng(fragment); + const { width, height, data } = decodePngToRgb(png); + expect(width).toBeGreaterThan(0); + expect(height).toBeGreaterThan(0); + expect(width).toBe(height); + expect(data).toHaveLength(width * height); + }); + + it('throws on a truncated PNG whose last chunk extends past the buffer', () => { + const ur = buildCryptoHDKeyUR({ + ...baseOptions, + pairMode: 'crypto-hdkey', + }); + const fragment = encodeToFragments(ur, 10_000)[0] as string; + const png = renderQrPng(fragment); + // Cut 2 bytes off the trailing IEND chunk: its 8-byte header survives, + // but the chunk's trailing CRC no longer fits in the buffer. + const truncated = png.subarray(0, png.length - 2); + expect(() => decodePngToRgb(truncated)).toThrow( + /corrupt png: .* extends past end of buffer/iu, + ); + }); + + it('throws on a truncated chunk header', () => { + const ur = buildCryptoHDKeyUR({ + ...baseOptions, + pairMode: 'crypto-hdkey', + }); + const fragment = encodeToFragments(ur, 10_000)[0] as string; + const png = renderQrPng(fragment); + // Keep the signature plus only 4 bytes of the next chunk header (the + // length prefix) — not enough for length + type. + const truncated = png.subarray(0, PNG_SIGNATURE_LEN + 4); + expect(() => decodePngToRgb(truncated)).toThrow( + /corrupt png: truncated chunk header/iu, + ); + }); + + it('throws on a chunk CRC mismatch', () => { + const ur = buildCryptoHDKeyUR({ + ...baseOptions, + pairMode: 'crypto-hdkey', + }); + const fragment = encodeToFragments(ur, 10_000)[0] as string; + const png = Buffer.from(renderQrPng(fragment)); + // The file ends with IEND's 4-byte CRC; corrupt its last byte. + png[png.length - 1] = (png[png.length - 1] as number) ^ 0xff; + expect(() => decodePngToRgb(png)).toThrow( + /corrupt png: crc mismatch in 'iend'/iu, + ); + }); + + it('throws on a truncated IDAT stream that inflates short', async () => { + const { deflateSync } = await import('node:zlib'); + const size = 32; + const rowCount = 10; // IHDR declares 32 rows but only 10 are supplied. + const scanlines = Buffer.concat( + Array.from({ length: rowCount }, () => + Buffer.concat([Buffer.from([0]), Buffer.alloc(size, 255)]), + ), + ); + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(size, 0); + ihdr.writeUInt32BE(size, 4); + ihdr[8] = 8; + ihdr[9] = 0; + const truncatedIdatPng = Buffer.concat([ + PNG_SIGNATURE, + chunk('IHDR', ihdr), + chunk('IDAT', deflateSync(scanlines)), + chunk('IEND', Buffer.alloc(0)), + ]); + expect(() => decodePngToRgb(truncatedIdatPng)).toThrow( + /corrupt png: inflated idat/iu, + ); + }); + }); + + describe('decodeQrScreenshots', () => { + it('reconstructs a multi-fragment UR from a sequence of rendered PNGs', async () => { + const ur = buildCryptoAccountUR(baseOptions); + const fragments = encodeToFragments(ur, 50); + expect(fragments.length).toBeGreaterThan(1); + + const pngs = fragments.map((fragment) => renderQrPng(fragment)); + const decoded = await decodeQrScreenshots(pngs); + expect(decoded).toStrictEqual(ur); + }); + + it('reconstructs the UR regardless of screenshot order', async () => { + const ur = buildCryptoAccountUR(baseOptions); + const fragments = encodeToFragments(ur, 50); + const pngs = fragments.map((fragment) => renderQrPng(fragment)); + // Reverse the frame order (fountain decoding is order-independent). + const decoded = await decodeQrScreenshots([...pngs].reverse()); + expect(decoded).toStrictEqual(ur); + }); + + it('accepts a mix of decodable and non-decodable frames', async () => { + const ur = buildCryptoAccountUR(baseOptions); + const fragments = encodeToFragments(ur, 50); + const pngs = fragments.map((fragment) => renderQrPng(fragment)); + // Inject a blank (non-QR) frame in the middle; the decoder skips nulls. + const blank = renderQrPng('no-qr-here-just-text-padding'); + pngs.splice(Math.floor(pngs.length / 2), 0, blank); + const decoded = await decodeQrScreenshots(pngs); + expect(decoded).toStrictEqual(ur); + }); + + it('surfaces rejected invalid fragments through the onLog debug sink', async () => { + const ur = buildCryptoAccountUR(baseOptions); + const fragments = encodeToFragments(ur, 50); + const pngs = fragments.map((fragment) => renderQrPng(fragment)); + // A QR that is not a valid BC-UR fragment: tolerated, but logged. + const invalid = renderQrPng('no-qr-here-just-text-padding'); + const logs: string[] = []; + const decoded = await decodeQrScreenshots([invalid, ...pngs], { + onLog: (message) => { + logs.push(message); + }, + }); + expect(decoded).toStrictEqual(ur); + expect(logs.length).toBeGreaterThan(0); + expect(logs[0]).toMatch(/rejected invalid bc-ur fragment/iu); + }); + + it('throws when the screenshots are insufficient to reconstruct the UR', async () => { + const ur = buildCryptoAccountUR(baseOptions); + const fragments = encodeToFragments(ur, 50); + // Provide only the first frame of a multi-fragment UR. + const partial = [renderQrPng(fragments[0] as string)]; + await expect(decodeQrScreenshots(partial)).rejects.toThrow( + /incomplete/iu, + ); + }); + }); +}); + +// PNG CRC-32 table (standard IEEE polynomial) for synthesizing a blank PNG fixture. +const CRC_TABLE: Uint32Array = ((): Uint32Array => { + const table = new Uint32Array(256); + for (let entry = 0; entry < 256; entry++) { + let current = entry; + for (let bit = 0; bit < 8; bit++) { + current = current & 1 ? 0xedb88320 ^ (current >>> 1) : current >>> 1; + } + table[entry] = current >>> 0; + } + return table; +})(); + +// Minimal PNG chunk helper for synthesizing a blank PNG in tests. +function chunk(type: string, data: Buffer): Buffer { + const length = Buffer.alloc(4); + length.writeUInt32BE(data.length, 0); + const typeBuf = Buffer.from(type, 'ascii'); + let current = 0xffffffff; + for (let i = 0; i < typeBuf.length + data.length; i++) { + const byte = i < typeBuf.length ? typeBuf[i] : data[i - typeBuf.length]; + current = CRC_TABLE[(current ^ (byte as number)) & 0xff]! ^ (current >>> 8); + } + const crc = Buffer.alloc(4); + crc.writeUInt32BE((current ^ 0xffffffff) >>> 0, 0); + return Buffer.concat([length, typeBuf, data, crc]); +} diff --git a/packages/hw-emulator/src/qr/decode/screenshots.ts b/packages/hw-emulator/src/qr/decode/screenshots.ts new file mode 100644 index 000000000..f68035932 --- /dev/null +++ b/packages/hw-emulator/src/qr/decode/screenshots.ts @@ -0,0 +1,358 @@ +/* eslint-disable no-restricted-globals -- Buffer is required for PNG decoding. */ +/* eslint-disable no-bitwise -- PNG de-filtering, CRC-32, and pixel packing require bitwise ops. */ +/* eslint-disable import-x/no-nodejs-modules -- zlib and fs are required for PNG decoding. */ +/* eslint-disable id-length -- Single-letter x/y/pixel loop variables are idiomatic in image code. */ +/* eslint-disable @typescript-eslint/no-non-null-assertion -- CRC table index and readByte indices are provably in range. */ + +import { + BinaryBitmap, + HybridBinarizer, + QRCodeReader, + RGBLuminanceSource, +} from '@zxing/library'; +import { inflateSync } from 'zlib'; + +import { FragmentDecoder } from '../codec/decoder'; +import type { SerializedUR } from '../core/ur-synth'; + +/** Bytes-per-pixel for each supported PNG 8-bit color type. */ +const BYTES_PER_PIXEL_BY_COLOR_TYPE: Record = { + 0: 1, // grayscale + 2: 3, // RGB + 3: 1, // indexed + 4: 2, // grayscale + alpha + 6: 4, // RGBA +}; + +/** Decoded RGB image: width, height, and packed ARGB pixels (0xFFRRGGBB). */ +type DecodedImage = { + width: number; + height: number; + /** Packed ARGB pixels, one Int32 per pixel. */ + data: Int32Array; +}; + +const PNG_SIGNATURE = Buffer.from([ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, +]); + +// Precomputed CRC-32 table (PNG uses the standard IEEE polynomial). No CRC +// dependency exists in package.json, so this is a small local implementation. +const CRC_TABLE: Uint32Array = ((): Uint32Array => { + const table = new Uint32Array(256); + for (let entry = 0; entry < 256; entry++) { + let current = entry; + for (let bit = 0; bit < 8; bit++) { + current = current & 1 ? 0xedb88320 ^ (current >>> 1) : current >>> 1; + } + table[entry] = current >>> 0; + } + return table; +})(); + +/** + * Compute the CRC-32 of a buffer (PNG chunk checksum, per the PNG spec). + * + * @param data - The bytes to checksum. + * @returns The unsigned 32-bit CRC. + */ +function crc32(data: Buffer): number { + let current = 0xffffffff; + for (const byte of data) { + current = CRC_TABLE[(current ^ byte) & 0xff]! ^ (current >>> 8); + } + return (current ^ 0xffffffff) >>> 0; +} + +/** + * Paeth predictor used in PNG filtering. + * + * @param a - Left pixel. + * @param b - Up pixel. + * @param c - Up-left pixel. + * @returns The predicted byte value. + */ +function paethPredictor(a: number, b: number, c: number): number { + const p = a + b - c; + const pa = Math.abs(p - a); + const pb = Math.abs(p - b); + const pc = Math.abs(p - c); + if (pa <= pb && pa <= pc) { + return a; + } + if (pb <= pc) { + return b; + } + return c; +} + +/** + * Minimal, dependency-free PNG decoder that handles the 8-bit colour types + * produced by `qrcode-generator` and by Playwright screenshots (grayscale, + * RGB, RGBA, and indexed). This avoids pulling in a native image dependency. + * + * @param png - A PNG-encoded Buffer. + * @returns The decoded image as packed ARGB pixels. + * @throws If the buffer is not a valid 8-bit PNG. + */ +export function decodePngToRgb(png: Buffer): DecodedImage { + if (!png.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)) { + throw new Error('Not a PNG: invalid signature'); + } + + let offset = PNG_SIGNATURE.length; + let width = 0; + let height = 0; + let bitDepth = 0; + let colorType = 0; + const idatChunks: Buffer[] = []; + const palette: number[][] = []; + + while (offset < png.length) { + // A chunk header is 8 bytes (4 length + 4 type); a full chunk adds the + // data length and a 4-byte trailing CRC. + if (offset + 8 > png.length) { + throw new Error( + `Corrupt PNG: truncated chunk header at offset ${String(offset)}`, + ); + } + const length = png.readUInt32BE(offset); + const type = png.toString('ascii', offset + 4, offset + 8); + if (offset + 12 + length > png.length) { + throw new Error( + `Corrupt PNG: chunk '${type}' of length ${String(length)} extends past end of buffer`, + ); + } + const data = png.subarray(offset + 8, offset + 8 + length); + const expectedCrc = png.readUInt32BE(offset + 8 + length); + const actualCrc = crc32(png.subarray(offset + 4, offset + 8 + length)); + if (actualCrc !== expectedCrc) { + throw new Error( + `Corrupt PNG: CRC mismatch in '${type}' chunk at offset ${String(offset)} (expected 0x${expectedCrc.toString(16)}, got 0x${actualCrc.toString(16)})`, + ); + } + offset += 8 + length + 4; // length + type + data + CRC + + switch (type) { + case 'IHDR': + width = data.readUInt32BE(0); + height = data.readUInt32BE(4); + bitDepth = data.readUInt8(8); + colorType = data.readUInt8(9); + break; + case 'PLTE': + for (let i = 0; i < data.length; i += 3) { + palette.push([data[i] ?? 0, data[i + 1] ?? 0, data[i + 2] ?? 0]); + } + break; + case 'IDAT': + idatChunks.push(Buffer.from(data)); + break; + case 'IEND': + break; + default: + // Ignore ancillary chunks (tEXt, pHYs, etc.) + break; + } + } + + if (bitDepth !== 8) { + throw new Error( + `Unsupported PNG bit depth: ${bitDepth} (only 8-bit is supported)`, + ); + } + + const bytesPerPixel = BYTES_PER_PIXEL_BY_COLOR_TYPE[colorType] ?? 0; + if (bytesPerPixel === 0) { + throw new Error(`Unsupported PNG color type: ${colorType}`); + } + + const inflated = inflateSync(Buffer.concat(idatChunks)); + const stride = width * bytesPerPixel; + const expectedInflatedLength = height * (stride + 1); + if (inflated.length !== expectedInflatedLength) { + // A truncated IDAT stream would otherwise inflate "successfully" and be + // silently padded with zeroes by readByte, decoding into garbage pixels. + throw new Error( + `Corrupt PNG: inflated IDAT stream is ${String(inflated.length)} bytes, expected ${String(expectedInflatedLength)} (${String(height)} rows × (${String(stride)} + 1) bytes)`, + ); + } + const raw = Buffer.alloc(stride * height); + + /** + * Read a byte from `inflated`. The length assertion above guarantees the + * index is in range. + * + * @param idx - The byte index to read. + * @returns The byte value. + */ + const readByte = (idx: number): number => inflated[idx]!; + + let inIdx = 0; + let outIdx = 0; + for (let y = 0; y < height; y++) { + const filter = readByte(inIdx); + inIdx += 1; + for (let x = 0; x < stride; x++) { + const filtByte = readByte(inIdx); + inIdx += 1; + const leftIdx = x >= bytesPerPixel ? outIdx - bytesPerPixel : -1; + const upIdx = y > 0 ? outIdx - stride : -1; + const upLeftIdx = + x >= bytesPerPixel && y > 0 ? outIdx - stride - bytesPerPixel : -1; + const left = leftIdx >= 0 ? (raw[leftIdx] ?? 0) : 0; + const up = upIdx >= 0 ? (raw[upIdx] ?? 0) : 0; + const upLeft = upLeftIdx >= 0 ? (raw[upLeftIdx] ?? 0) : 0; + + let recon: number; + switch (filter) { + case 0: // None + recon = filtByte; + break; + case 1: // Sub + recon = (filtByte + left) & 0xff; + break; + case 2: // Up + recon = (filtByte + up) & 0xff; + break; + case 3: // Average + recon = (filtByte + ((left + up) >> 1)) & 0xff; + break; + case 4: // Paeth + recon = (filtByte + paethPredictor(left, up, upLeft)) & 0xff; + break; + default: + throw new Error(`Unknown PNG filter type: ${filter}`); + } + raw[outIdx] = recon; + outIdx += 1; + } + } + + const data = new Int32Array(width * height); + for (let i = 0; i < width * height; i++) { + const p = i * bytesPerPixel; + let r = 0; + let g = 0; + let b = 0; + switch (colorType) { + case 0: // grayscale + r = raw[p] ?? 0; + g = r; + b = r; + break; + case 2: // RGB + r = raw[p] ?? 0; + g = raw[p + 1] ?? 0; + b = raw[p + 2] ?? 0; + break; + case 3: // indexed + { + const entry = palette[raw[p] ?? 0] ?? []; + r = entry[0] ?? 0; + g = entry[1] ?? 0; + b = entry[2] ?? 0; + } + break; + case 4: // grayscale + alpha + r = raw[p] ?? 0; + g = r; + b = r; + break; + case 6: // RGBA + r = raw[p] ?? 0; + g = raw[p + 1] ?? 0; + b = raw[p + 2] ?? 0; + break; + default: + break; + } + data[i] = (0xff << 24) | (r << 16) | (g << 8) | b; + } + + return { width, height, data }; +} + +/** + * Decode a single QR PNG buffer back into its fragment string using + * `@zxing/library`'s luminance + binarizer + QR reader pipeline. + * + * @param png - A PNG buffer containing a QR code. + * @returns The decoded fragment string, or `null` if no QR code was found. + */ +export async function decodeQrImage(png: Buffer): Promise { + const { width, height, data } = decodePngToRgb(png); + const source = new RGBLuminanceSource(data, width, height); + const bitmap = new BinaryBitmap(new HybridBinarizer(source)); + try { + const result = new QRCodeReader().decode(bitmap); + return result.getText(); + } catch { + return null; + } +} + +/** Options for {@link decodeQrScreenshots}. */ +export type DecodeQrScreenshotsOptions = { + /** + * Optional debug sink. Invoked when a frame decodes to a QR code but the + * BC-UR fountain decoder rejects it as an invalid fragment (e.g. an + * unrelated QR captured in the frame). Invalid fragments remain tolerated; + * this only makes the rejection observable instead of silently swallowed. + */ + onLog?: (message: string) => void; +}; + +/** + * Decode a sequence of QR-code PNG screenshots (captured from an animated QR, + * e.g. via Playwright's `locator.screenshot()`) into the original SerializedUR. + * + * Fragments are accumulated through a BC-UR fountain decoder and may arrive in + * any order. + * + * @param pathsOrBuffers - Either filesystem paths to PNG files, or PNG buffers. + * For string entries, the file is read from disk. + * @param options - Optional decoding options (e.g. a debug `onLog` sink). + * @returns The reconstructed SerializedUR. + * @throws If the fragments are insufficient to reconstruct the UR. + */ +export async function decodeQrScreenshots( + pathsOrBuffers: (string | Buffer)[], + options: DecodeQrScreenshotsOptions = {}, +): Promise { + const { readFile } = await import('node:fs/promises'); + const decoder = new FragmentDecoder(); + + for (const entry of pathsOrBuffers) { + const png = typeof entry === 'string' ? await readFile(entry) : entry; + const fragment = await decodeQrImage(png); + if (fragment !== null) { + // Tolerate frames that decode to a QR but are not valid BC-UR fragments + // (e.g. noise, partial reads, or an unrelated QR in the frame). The + // rejection is surfaced through the optional debug sink so real bugs + // are not silently hidden. + try { + decoder.receivePart(fragment); + } catch (error) { + options.onLog?.( + `Rejected invalid BC-UR fragment: ${ + error instanceof Error ? error.message : String(error) + }`, + ); + } + } + if (decoder.isComplete()) { + break; + } + } + + if (!decoder.isComplete()) { + throw new Error( + 'QR screenshot decoding incomplete: insufficient fragments', + ); + } + if (!decoder.isSuccess()) { + throw new Error('QR screenshot decoding failed: reconstruction error'); + } + return decoder.resultUR(); +} diff --git a/packages/hw-emulator/src/qr/emulator.test.ts b/packages/hw-emulator/src/qr/emulator.test.ts new file mode 100644 index 000000000..a049bcbf4 --- /dev/null +++ b/packages/hw-emulator/src/qr/emulator.test.ts @@ -0,0 +1,389 @@ +import { Common, Hardfork, Mainnet } from '@ethereumjs/common'; +import { createTx } from '@ethereumjs/tx'; +import type { TypedTransaction } from '@ethereumjs/tx'; +import type { AddressLike } from '@ethereumjs/util'; +import { + recoverPersonalSignature, + recoverTypedSignature, + SignTypedDataVersion, +} from '@metamask/eth-sig-util'; +import type { MessageTypes, TypedMessage } from '@metamask/eth-sig-util'; +import { add0x, getChecksumAddress, remove0x } from '@metamask/utils'; +import type { Hex } from '@metamask/utils'; +import { randomUUID } from 'node:crypto'; + +// Import directly from the sibling source: the `@metamask/eth-qr-keyring` +// package name does not match its directory (`packages/keyring-eth-qr`), so +// this repo's `@metamask/* -> ../$1/src` mapping misses it, and the package's +// `dist/` (where its `types` field points) is not built in this branch. The +// relative source import is resolved natively by both ts-jest and jest, and +// the build excludes `*.test.ts` so it never enters the dist bundle. +// WORKAROUND: relative path instead of bare `@metamask/eth-qr-keyring` specifier. +// The sibling `keyring-eth-qr` package has a broken v2 build +// (`src/v2/qr-keyring.ts` references `this.inner`/`this.registry`/`this.withLock` +// which don't exist on `QrKeyring`), so its `dist/` is never produced and the +// package's `types`/`main` fields don't resolve. The relative path bypasses the +// build and imports the source `QrKeyring` directly. This is a known issue in +// `keyring-eth-qr` (out of scope for the QR emulator work); switch to the bare +// specifier once `keyring-eth-qr`'s build is repaired. +import { QrKeyring, QrScanRequestType } from '../../../keyring-eth-qr/src'; +import { createEmulator } from '../factory'; +import { EmulatorType } from '../types'; +import type { HardwareWalletEmulator } from '../types'; +import { encodeToFragments } from './codec/encoder'; +import { QR_EMULATOR_ADDRESS, QR_EMULATOR_SEED } from './constants'; +import type { SerializedUR } from './core/ur-synth'; +import { QrEmulator } from './emulator'; +import type { QrKeyringBridge } from './emulator'; + +const common = new Common({ + chain: Mainnet, + hardfork: Hardfork.SpuriousDragon, +}); +const londonCommon = new Common({ chain: Mainnet, hardfork: Hardfork.London }); + +// Build a minimal valid eth-sign-request SerializedUR the way the keyring does. +async function buildSignRequestUr(): Promise { + const { EthSignRequest, DataType } = + await import('@keystonehq/bc-ur-registry-eth'); + const request = EthSignRequest.constructETHRequest( + Buffer.from('deadbeef', 'hex'), + DataType.personalMessage, + "m/44'/60'/0'/0/0", + 'deadbeef', + randomUUID(), + ); + const ur = request.toUR(); + return { type: ur.type, cbor: ur.cbor.toString('hex') }; +} + +describe('QrEmulator', () => { + describe('factory', () => { + it('createEmulator(EmulatorType.Qr, {}) returns a QrEmulator', () => { + const emulator = createEmulator(EmulatorType.Qr, {}); + expect(emulator).toBeInstanceOf(QrEmulator); + }); + + it('satisfies the HardwareWalletEmulator interface', () => { + const emulator: HardwareWalletEmulator = createEmulator( + EmulatorType.Qr, + {}, + ); + expect(typeof emulator.start).toBe('function'); + expect(typeof emulator.stop).toBe('function'); + expect(typeof emulator.isRunning).toBe('function'); + }); + }); + + describe('lifecycle', () => { + it('start/isRunning/stop toggle the running flag', async () => { + const emulator = new QrEmulator({}); + expect(emulator.isRunning()).toBe(false); + await emulator.start(); + expect(emulator.isRunning()).toBe(true); + await emulator.stop(); + expect(emulator.isRunning()).toBe(false); + }); + }); + + describe('getAccountUR', () => { + it('defaults to crypto-account mode', () => { + const emulator = new QrEmulator({}); + const ur = emulator.getAccountUR(); + expect(ur.type).toBe('crypto-account'); + expect(ur.cbor.length).toBeGreaterThan(0); + }); + + it('produces a crypto-hdkey UR in crypto-hdkey mode', () => { + const emulator = new QrEmulator({ pairMode: 'crypto-hdkey' }); + const ur = emulator.getAccountUR(); + expect(ur.type).toBe('crypto-hdkey'); + }); + }); + + describe('asBridge', () => { + it('returns an object satisfying the QrKeyringBridge contract', () => { + const emulator = new QrEmulator({}); + const bridge: QrKeyringBridge = emulator.asBridge(); + expect(typeof bridge.requestScan).toBe('function'); + }); + + it('requestScan(PAIR) returns the same UR as getAccountUR', async () => { + const emulator = new QrEmulator({}); + const accountUR = emulator.getAccountUR(); + const scanned = await emulator.requestScan({ + type: QrScanRequestType.PAIR, + }); + expect(scanned).toStrictEqual(accountUR); + }); + }); + + describe('approve/reject semantics', () => { + it('rejectTransaction arms the next handleSignRequest to throw', async () => { + const emulator = new QrEmulator({}); + const accountUR = emulator.getAccountUR(); + // Build a minimal sign request the way the keyring does. + const { EthSignRequest, DataType } = + await import('@keystonehq/bc-ur-registry-eth'); + const request = EthSignRequest.constructETHRequest( + Buffer.from('deadbeef', 'hex'), + DataType.personalMessage, + "m/44'/60'/0'/0/0", + 'deadbeef', + randomUUID(), + ); + const ur: SerializedUR = { + type: request.toUR().type, + cbor: request.toUR().cbor.toString('hex'), + }; + + await emulator.rejectTransaction(); + await expect( + emulator.requestScan({ + type: QrScanRequestType.SIGN, + request: { requestId: 'x', payload: ur }, + }), + ).rejects.toThrow(/rejected/iu); + // The reject flag is consumed; the next sign succeeds (uses accountUR as + // a throwaway payload — it will not be a valid sign request, but we only + // assert the rejection is not re-triggered). + expect(accountUR.type).toBe('crypto-account'); + }); + + it('approveTransaction permits the next handleSignRequest', async () => { + const emulator = new QrEmulator({}); + const { EthSignRequest, DataType } = + await import('@keystonehq/bc-ur-registry-eth'); + const request = EthSignRequest.constructETHRequest( + Buffer.from(remove0x(add0x(Buffer.from('hi').toString('hex'))), 'hex'), + DataType.personalMessage, + "m/44'/60'/0'/0/0", + 'deadbeef', + randomUUID(), + ); + const ur: SerializedUR = { + type: request.toUR().type, + cbor: request.toUR().cbor.toString('hex'), + }; + await emulator.approveTransaction(); + const result = await emulator.requestScan({ + type: QrScanRequestType.SIGN, + request: { requestId: 'x', payload: ur }, + }); + expect(result.type).toBe('eth-signature'); + }); + }); + + describe('targeted rejection', () => { + it('a rejection armed with a request id only consumes the matching request', async () => { + const emulator = new QrEmulator({}); + const ur = await buildSignRequestUr(); + + await emulator.rejectTransaction('req-1'); + + // A different request id is signed normally; the rejection stays armed. + const other = await emulator.requestScan({ + type: QrScanRequestType.SIGN, + request: { requestId: 'req-2', payload: ur }, + }); + expect(other.type).toBe('eth-signature'); + + // The matching request id is rejected and consumes the rejection. + await expect( + emulator.requestScan({ + type: QrScanRequestType.SIGN, + request: { requestId: 'req-1', payload: ur }, + }), + ).rejects.toThrow(/rejected/iu); + + // After consumption, the same request id signs again. + const after = await emulator.requestScan({ + type: QrScanRequestType.SIGN, + request: { requestId: 'req-1', payload: ur }, + }); + expect(after.type).toBe('eth-signature'); + }); + + it('an untargeted rejection consumes the next sign request regardless of id', async () => { + const emulator = new QrEmulator({}); + const ur = await buildSignRequestUr(); + + await emulator.rejectTransaction(); + + await expect( + emulator.requestScan({ + type: QrScanRequestType.SIGN, + request: { requestId: 'any-id', payload: ur }, + }), + ).rejects.toThrow(/rejected/iu); + + const next = await emulator.requestScan({ + type: QrScanRequestType.SIGN, + request: { requestId: 'any-id', payload: ur }, + }); + expect(next.type).toBe('eth-signature'); + }); + }); + + describe('renderToPng', () => { + it('renders a single-fragment UR to a decodable PNG', async () => { + const emulator = new QrEmulator({}); + // Minimal UR that fits in one default-size BC-UR fragment. + const ur: SerializedUR = { type: 'bytes', cbor: '44deadbeef' }; + expect(encodeToFragments(ur)).toHaveLength(1); + + const png = await emulator.renderToPng(ur); + expect(png[0]).toBe(0x89); + expect(png.subarray(1, 4).toString('ascii')).toBe('PNG'); + + const fragment = encodeToFragments(ur)[0] as string; + expect(await emulator.decodeQrImage(png)).toBe(fragment.toUpperCase()); + }); + + it('throws when the UR encodes to multiple fragments', async () => { + const emulator = new QrEmulator({}); + // The default 5-descriptor crypto-account exceeds one fragment. + const ur = emulator.getAccountUR(); + expect(encodeToFragments(ur).length).toBeGreaterThan(1); + + await expect(emulator.renderToPng(ur)).rejects.toThrow(/renderToY4m/iu); + }); + }); + + describe('integration with real QrKeyring', () => { + let emulator: QrEmulator; + let keyring: QrKeyring; + + beforeEach(async () => { + emulator = new QrEmulator({ seed: QR_EMULATOR_SEED }); + keyring = new QrKeyring({ bridge: emulator.asBridge() }); + // Trigger bridge-based pairing (mirrors the real scan flow). + await keyring.getFirstPage(); + }); + + it('addAccounts returns the canonical emulator address', async () => { + const accounts = await keyring.addAccounts(1); + expect(accounts).toHaveLength(1); + expect(getChecksumAddress(accounts[0] as Hex)).toBe(QR_EMULATOR_ADDRESS); + const allAccounts = await keyring.getAccounts(); + expect(allAccounts).toStrictEqual(accounts); + }); + + it('signs a legacy transaction through the keyring and recovers the emulator address', async () => { + const [address] = await keyring.addAccounts(1); + const tx = createTx( + { + nonce: 1, + gasPrice: 10_000_000_000, + gasLimit: 21_000, + to: `0x${'11'.repeat(20)}` as AddressLike, + value: 1000, + data: '0x', + }, + { common }, + ); + const signed = (await keyring.signTransaction( + address as Hex, + tx, + )) as TypedTransaction; + expect(signed.verifySignature()).toBe(true); + expect(getChecksumAddress(signed.getSenderAddress().toString())).toBe( + QR_EMULATOR_ADDRESS, + ); + }); + + it('signs an EIP-1559 transaction through the keyring', async () => { + const [address] = await keyring.addAccounts(1); + const tx = createTx( + { + type: 2, + nonce: 5, + maxFeePerGas: 20_000_000_000, + maxPriorityFeePerGas: 1_000_000_000, + gasLimit: 21_000, + to: `0x${'22'.repeat(20)}` as AddressLike, + value: 5000, + data: '0xabcd', + accessList: [], + chainId: 1, + }, + { common: londonCommon }, + ); + const signed = (await keyring.signTransaction( + address as Hex, + tx, + )) as TypedTransaction; + expect(signed.verifySignature()).toBe(true); + expect(getChecksumAddress(signed.getSenderAddress().toString())).toBe( + QR_EMULATOR_ADDRESS, + ); + }); + + it('signs a personal_sign message through the keyring and recovers the emulator address', async () => { + const [address] = await keyring.addAccounts(1); + const message = add0x(Buffer.from('Hello QR keyring').toString('hex')); + const signature = await keyring.signPersonalMessage( + address as Hex, + message, + ); + expect(typeof signature).toBe('string'); + const recovered = recoverPersonalSignature({ + data: message, + signature, + }); + expect(getChecksumAddress(recovered as Hex)).toBe(QR_EMULATOR_ADDRESS); + }); + + it('signs EIP-712 typed data v4 through the keyring', async () => { + const [address] = await keyring.addAccounts(1); + const typedData: TypedMessage = { + types: { + EIP712Domain: [ + { name: 'name', type: 'string' }, + { name: 'version', type: 'string' }, + { name: 'chainId', type: 'uint256' }, + { name: 'verifyingContract', type: 'address' }, + ], + Mail: [ + { name: 'from', type: 'Person' }, + { name: 'contents', type: 'string' }, + ], + Person: [ + { name: 'name', type: 'string' }, + { name: 'wallet', type: 'address' }, + ], + }, + primaryType: 'Mail', + domain: { + name: 'Ether Mail', + version: '1', + chainId: 1, + verifyingContract: `0x${'cc'.repeat(20)}`, + }, + message: { + from: { name: 'Cow', wallet: QR_EMULATOR_ADDRESS }, + contents: 'Hello, QR', + }, + } as never; + + const signature = await keyring.signTypedData(address as Hex, typedData); + expect(typeof signature).toBe('string'); + const recovered = recoverTypedSignature({ + data: typedData, + signature, + version: SignTypedDataVersion.V4, + }); + expect(getChecksumAddress(recovered as Hex)).toBe(QR_EMULATOR_ADDRESS); + }); + + it('serialize/deserialize round-trips the paired device', async () => { + await keyring.addAccounts(1); + const state = await keyring.serialize(); + const fresh = new QrKeyring({ bridge: emulator.asBridge() }); + await fresh.deserialize(state); + const accounts = await fresh.getAccounts(); + expect(accounts).toHaveLength(1); + expect(getChecksumAddress(accounts[0] as Hex)).toBe(QR_EMULATOR_ADDRESS); + }); + }); +}); diff --git a/packages/hw-emulator/src/qr/emulator.ts b/packages/hw-emulator/src/qr/emulator.ts new file mode 100644 index 000000000..cd1dd72a5 --- /dev/null +++ b/packages/hw-emulator/src/qr/emulator.ts @@ -0,0 +1,422 @@ +import type { DeviceInteraction, HardwareWalletEmulator } from '../types'; +import { decodeFragments } from './codec/decoder'; +import { encodeToFragments } from './codec/encoder'; +import { + QR_EMULATOR_ACCOUNT_DERIVATION_PATH, + QR_EMULATOR_CHILDREN_PATH, + QR_EMULATOR_DEFAULT_XFP, + QR_EMULATOR_SEED, +} from './constants'; +import { signRequest } from './core/signer'; +import { + CRYPTO_ACCOUNT_TYPE, + CRYPTO_HDKEY_TYPE, + DEFAULT_DESCRIPTOR_COUNT, + synthesizeAccountUR, +} from './core/ur-synth'; +import type { + QrPairMode, + SerializedUR, + SynthesizeOptions, +} from './core/ur-synth'; +import { decodeQrImage, decodeQrScreenshots } from './decode/screenshots'; +import type { DecodeQrScreenshotsOptions } from './decode/screenshots'; +import { renderQrPng } from './render/png'; +import { renderUrToY4m } from './render/y4m'; +import type { Y4mRenderOptions } from './render/y4m'; + +/** + * Scan-request type discriminator. Mirrors `QrScanRequestType` from + * `@metamask/eth-qr-keyring` (values `'pair'` and `'sign'`) so this package has + * no runtime dependency on the keyring package. + */ +export const QrScanRequestType = { + Pair: 'pair', + Sign: 'sign', +} as const; + +/** + * A signature scan request payload (the animated sign-request QR decoded back + * to a SerializedUR). + */ +export type QrSignatureRequest = { + requestId: string; + payload: SerializedUR; + requestTitle?: string; + requestDescription?: string; +}; + +/** + * A scan request — either a pairing request or a signature request. + * Structurally compatible with `QrScanRequest` from `@metamask/eth-qr-keyring`. + */ +export type QrScanRequest = { + type: (typeof QrScanRequestType)[keyof typeof QrScanRequestType]; + request?: QrSignatureRequest; +}; + +/** + * Bridge contract the QR keyring calls into. Structurally compatible with + * `QrKeyringBridge` from `@metamask/eth-qr-keyring`. + */ +export type QrKeyringBridge = { + requestScan: (request: QrScanRequest) => Promise; +}; + +/** + * Options for constructing a {@link QrEmulator} via the factory. + */ +export type QrEmulatorOptions = { + /** BIP-39 mnemonic seed (defaults to {@link QR_EMULATOR_SEED}). */ + seed?: string; + /** Human-readable device name (defaults to `'Keystone Test'`). */ + deviceName?: string; + /** Device fingerprint, hex (defaults to {@link QR_EMULATOR_DEFAULT_XFP}). */ + xfp?: string; + /** Full account derivation path (defaults to `m/44'/60'/0'`). */ + derivationPath?: string; + /** Children path within the account (defaults to `0/*`). */ + childrenPath?: string; + /** Pairing mode (defaults to `'crypto-account'`). */ + pairMode?: QrPairMode; + /** Number of address descriptors in `crypto-account` mode (defaults to 5). */ + descriptorCount?: number; +}; + +const DEFAULT_DEVICE_NAME = 'Keystone Test'; + +/** + * QR hardware wallet emulator. + * + * Holds a deterministic seed, derives accounts, produces BC-UR-encoded pairing + * URs the way a Keystone-class device would, and signs transactions and + * messages with real ECDSA. Implements both {@link HardwareWalletEmulator} + * (interface symmetry with the Ledger Speculos emulator) and + * {@link QrKeyringBridge} (so it can be wired directly into a real + * `QrKeyring` in Jest tests). + */ +export class QrEmulator implements HardwareWalletEmulator, QrKeyringBridge { + readonly #options: Required; + + #running = false; + + #rejectNext = false; + + #rejectNextRequestId: string | undefined; + + /** + * @param options - Configuration options (all optional; sensible defaults). + */ + constructor(options: QrEmulatorOptions = {}) { + this.#options = { + seed: options.seed ?? QR_EMULATOR_SEED, + deviceName: options.deviceName ?? DEFAULT_DEVICE_NAME, + xfp: options.xfp ?? QR_EMULATOR_DEFAULT_XFP, + derivationPath: + options.derivationPath ?? QR_EMULATOR_ACCOUNT_DERIVATION_PATH, + childrenPath: options.childrenPath ?? QR_EMULATOR_CHILDREN_PATH, + pairMode: options.pairMode ?? 'crypto-account', + descriptorCount: options.descriptorCount ?? DEFAULT_DESCRIPTOR_COUNT, + }; + } + + /** + * Resolved seed. + * + * @returns The mnemonic seed string. + */ + get seed(): string { + return this.#options.seed; + } + + /** + * Resolved pairing mode. + * + * @returns The pair mode (`crypto-account` or `crypto-hdkey`). + */ + get pairMode(): QrPairMode { + return this.#options.pairMode; + } + + /** + * Build the synthesize options for the UR synth helpers. + * + * @returns The resolved SynthesizeOptions. + */ + #synthOptions(): SynthesizeOptions { + return { + seed: this.#options.seed, + accountPath: this.#options.derivationPath, + childrenPath: this.#options.childrenPath, + xfp: this.#options.xfp, + deviceName: this.#options.deviceName, + pairMode: this.#options.pairMode, + descriptorCount: this.#options.descriptorCount, + }; + } + + // ── HardwareWalletEmulator ────────────────────────────────────────────── + + /** + * Start the emulator. No-op for the QR emulator (pure TypeScript, no process + * to spawn). + */ + async start(): Promise { + this.#running = true; + } + + /** + * Stop the emulator and release any held resources. No-op beyond flipping the + * running flag (ffmpeg child handles are scoped per-render). + */ + async stop(): Promise { + this.#running = false; + } + + /** + * Whether the emulator is currently running. + * + * @returns `true` if the emulator has been started and not stopped. + */ + isRunning(): boolean { + return this.#running; + } + + /** + * Get the device interaction handler. For the QR emulator the interaction is + * a thin shim that toggles the internal reject flag consumed by the next sign + * request. + * + * @returns The device interaction. + */ + getInteraction(): DeviceInteraction { + return { + approveTransaction: async (): Promise => { + await this.approveTransaction(); + }, + approveSigning: async (): Promise => { + await this.approveTransaction(); + }, + rejectTransaction: async (): Promise => { + await this.rejectTransaction(); + }, + navigateToMainMenu: async (): Promise => { + // No device screen to navigate; intentional no-op. + }, + }; + } + + /** + * Pre-approve the next incoming sign request. Clears any armed rejection so + * the next `handleSignRequest` call proceeds. + * + * @returns Resolves once approval is armed. + */ + async approveTransaction(): Promise { + this.#rejectNext = false; + this.#rejectNextRequestId = undefined; + } + + /** + * Pre-approve the next incoming sign request (semantic alias for + * {@link approveTransaction}). + */ + async approveSigning(): Promise { + await this.approveTransaction(); + } + + /** + * Pre-reject the next incoming sign request. The rejection is consumed by + * the next sign request, which will throw. + * + * To guard against rapid-fire flows where an untargeted rejection could be + * consumed by the wrong request, pass a `requestId`: the rejection then + * stays armed until a sign request with exactly that id arrives (requests + * carrying a different id — or none — are signed normally). + * + * @param requestId - Optional request id to target the rejection at; when + * omitted, the next sign request consumes the rejection. + * @returns Resolves once rejection is armed. + */ + async rejectTransaction(requestId?: string): Promise { + this.#rejectNext = true; + this.#rejectNextRequestId = requestId; + } + + /** + * Consume an armed rejection if it applies to the given request id. + * + * @param requestId - The incoming sign request's id, if known. + * @returns `true` if the rejection applies to this request and was consumed. + */ + #consumeRejection(requestId: string | undefined): boolean { + if (!this.#rejectNext) { + return false; + } + if ( + this.#rejectNextRequestId !== undefined && + this.#rejectNextRequestId !== requestId + ) { + // Armed for a different (or unknown) request id; leave it armed. + return false; + } + this.#rejectNext = false; + this.#rejectNextRequestId = undefined; + return true; + } + + /** + * Navigate to the main menu. No-op for the QR emulator (no device screen). + */ + async navigateToMainMenu(): Promise { + // Intentional no-op. + } + + // ── QrKeyringBridge ───────────────────────────────────────────────────── + + /** + * Handle a scan request from the QR keyring, routing by type. + * + * @param req - The scan request (pair or sign). + * @returns The resulting SerializedUR. + */ + async requestScan(req: QrScanRequest): Promise { + switch (req.type) { + case QrScanRequestType.Pair: + return this.getAccountUR(); + case QrScanRequestType.Sign: + if (!req.request) { + throw new Error('Sign request missing payload'); + } + if (this.#consumeRejection(req.request.requestId)) { + throw new Error('Sign request rejected by emulator'); + } + return this.handleSignRequest(req.request.payload); + default: + throw new Error(`Unknown scan request type: ${String(req.type)}`); + } + } + + // ── UR production ─────────────────────────────────────────────────────── + + /** + * Produce the pairing SerializedUR (for the PAIR flow). Routes by pair mode. + * + * @returns The pairing SerializedUR (`crypto-account` or `crypto-hdkey`). + */ + getAccountUR(): SerializedUR { + return synthesizeAccountUR(this.#synthOptions()); + } + + /** + * Handle an incoming sign-request SerializedUR (for the SIGN flow). Produces + * a real ECDSA signature from the derived key. + * + * If a rejection was armed via {@link rejectTransaction}, the next call + * throws and the rejection flag is cleared. A rejection armed with a + * specific request id is only consumed by a matching id (see + * `requestScan`). By default (and after an explicit + * {@link approveTransaction}) signing is permitted. + * + * @param ur - The `eth-sign-request` SerializedUR. + * @returns The `eth-signature` SerializedUR. + * @throws If a rejection is armed. + */ + async handleSignRequest(ur: SerializedUR): Promise { + if (this.#consumeRejection(undefined)) { + throw new Error('Sign request rejected by emulator'); + } + return signRequest(ur, { seed: this.#options.seed }); + } + + // ── QR rendering (test driver) ────────────────────────────────────────── + + /** + * Render a SerializedUR to an animated Y4M file via ffmpeg (for the Chrome + * fake-camera transport). + * + * @param ur - The SerializedUR to animate. + * @param opts - Render options (`outputPath` required). + * @param opts.fps - Frames per second (optional, forwarded to ffmpeg). + * @param opts.durationS - Total duration in seconds (optional). + * @param opts.outputPath - Destination `.y4m` file path. + * @param opts.size - Target square edge length in pixels (optional, defaults to `QR_Y4M_RENDER_SIZE_PX`). + * @returns The output path. + */ + async renderToY4m(ur: SerializedUR, opts: Y4mRenderOptions): Promise { + return renderUrToY4m(ur, opts); + } + + /** + * Render a (small) SerializedUR as a single-frame QR PNG. Only suitable for + * URs that fit in a single BC-UR fragment. + * + * @param ur - The SerializedUR to render. + * @returns A PNG Buffer. + * @throws If the UR encodes to more than one BC-UR fragment (use + * {@link renderToY4m} for animated multi-fragment QRs). + */ + async renderToPng(ur: SerializedUR): Promise { + const fragments = encodeToFragments(ur); + if (fragments.length !== 1) { + throw new Error( + `renderToPng requires a UR that fits in a single BC-UR fragment, but it encodes to ${String(fragments.length)} fragments; use renderToY4m for animated multi-fragment QRs`, + ); + } + return renderQrPng(fragments[0] as string); + } + + // ── QR decoding (test driver) ─────────────────────────────────────────── + + /** + * Decode a sequence of QR-code PNG screenshots into the original SerializedUR + * (fragments may arrive in any order). + * + * @param pathsOrBuffers - PNG file paths or buffers. + * @param options - Optional decoding options (e.g. a debug `onLog` sink). + * @returns The reconstructed SerializedUR. + */ + async decodeQrScreenshots( + pathsOrBuffers: (string | Buffer)[], + options: DecodeQrScreenshotsOptions = {}, + ): Promise { + return decodeQrScreenshots(pathsOrBuffers, options); + } + + /** + * Decode a single QR PNG buffer into its fragment string. + * + * @param png - A PNG buffer. + * @returns The fragment string, or `null` if no QR was found. + */ + async decodeQrImage(png: Buffer): Promise { + return decodeQrImage(png); + } + + // ── Convenience ───────────────────────────────────────────────────────── + + /** + * Return this emulator typed as a {@link QrKeyringBridge}, for wiring + * directly into a real `QrKeyring` in Jest unit/integration tests. + * + * @returns This instance as a QrKeyringBridge. + */ + asBridge(): QrKeyringBridge { + return this; + } + + /** + * Reconstruct a SerializedUR from a list of fragments. Exposed as a + * convenience for tests that capture fragments directly. Named + * `reconstructFromFragments` (rather than `decodeFragments`) so it does + * not shadow the free function from `./codec/decoder` it delegates to. + * + * @param fragments - BC-UR fragment strings. + * @returns The reconstructed SerializedUR. + */ + reconstructFromFragments(fragments: string[]): SerializedUR { + return decodeFragments(fragments); + } +} + +export { CRYPTO_ACCOUNT_TYPE, CRYPTO_HDKEY_TYPE }; diff --git a/packages/hw-emulator/src/qr/index.ts b/packages/hw-emulator/src/qr/index.ts new file mode 100644 index 000000000..caef23b80 --- /dev/null +++ b/packages/hw-emulator/src/qr/index.ts @@ -0,0 +1,71 @@ +export { QrEmulator, type QrEmulatorOptions } from './emulator'; +export type { + QrKeyringBridge, + QrScanRequest, + QrSignatureRequest, +} from './emulator'; +export { QrScanRequestType } from './emulator'; +export type { + QrPairMode, + SerializedUR, + SynthesizeOptions, +} from './core/ur-synth'; +export { + synthesizeAccountUR, + buildCryptoAccountUR, + buildCryptoHDKeyUR, + deriveAccountAddress, + deriveKey, + getMasterKey, + CRYPTO_ACCOUNT_TYPE, + CRYPTO_HDKEY_TYPE, +} from './core/ur-synth'; +export { + signRequest, + decodeSignRequest, + derivePrivateKey, +} from './core/signer'; +export type { SignerOptions } from './core/signer'; +export { + parseXfp, + pathToComponents, + createKeypath, + createCryptoHDKey, + createCryptoOutput, + createCryptoAccount, +} from './core/registry'; +export { + encodeToFragments, + createEncoder, + toRegistryUR, +} from './codec/encoder'; +export { FragmentDecoder, decodeFragments } from './codec/decoder'; +export { renderQrPng } from './render/png'; +export { + renderUrToY4m, + ensureFfmpegAvailable, + isFfmpegAvailable, + FfmpegUnavailableError, + type Y4mRenderOptions, +} from './render/y4m'; +export { + decodeQrImage, + decodeQrScreenshots, + decodePngToRgb, + type DecodeQrScreenshotsOptions, +} from './decode/screenshots'; +export { + QR_EMULATOR_SEED, + QR_EMULATOR_ROOT_DERIVATION_PATH, + QR_EMULATOR_ACCOUNT_PATH, + QR_EMULATOR_CHILDREN_PATH, + QR_EMULATOR_ACCOUNT_DERIVATION_PATH, + QR_EMULATOR_FIRST_ADDRESS_PATH, + QR_EMULATOR_DEFAULT_XFP, + QR_EMULATOR_ADDRESS, + QR_FRAGMENT_SIZE, + QR_REFRESH_MS, + QR_CODE_SIZE_PX, + QR_UPPERCASE, + deriveAddressFromSeed, +} from './constants'; diff --git a/packages/hw-emulator/src/qr/render/png.test.ts b/packages/hw-emulator/src/qr/render/png.test.ts new file mode 100644 index 000000000..5c1b0147a --- /dev/null +++ b/packages/hw-emulator/src/qr/render/png.test.ts @@ -0,0 +1,96 @@ +import { + BinaryBitmap, + HybridBinarizer, + QRCodeReader, + RGBLuminanceSource, +} from '@zxing/library'; + +import { encodeToFragments } from '../codec/encoder'; +import { + QR_CODE_SIZE_PX, + QR_EMULATOR_ACCOUNT_DERIVATION_PATH, + QR_EMULATOR_CHILDREN_PATH, + QR_EMULATOR_DEFAULT_XFP, + QR_EMULATOR_SEED, + QR_UPPERCASE, +} from '../constants'; +import { buildCryptoHDKeyUR } from '../core/ur-synth'; +import type { SynthesizeOptions } from '../core/ur-synth'; +import { decodePngToRgb } from '../decode/screenshots'; +import { renderQrPng } from './png'; + +const baseOptions: SynthesizeOptions = { + seed: QR_EMULATOR_SEED, + accountPath: QR_EMULATOR_ACCOUNT_DERIVATION_PATH, + childrenPath: QR_EMULATOR_CHILDREN_PATH, + xfp: QR_EMULATOR_DEFAULT_XFP, + deviceName: 'Keystone Test', + pairMode: 'crypto-hdkey', + descriptorCount: 1, +}; + +// Decode a QR PNG buffer back to its text using @zxing/library directly. +function decodeWithZxing(png: Buffer): string { + const { width, height, data } = decodePngToRgb(png); + const source = new RGBLuminanceSource(data, width, height); + const bitmap = new BinaryBitmap(new HybridBinarizer(source)); + return new QRCodeReader().decode(bitmap).getText(); +} + +describe('QR PNG renderer', () => { + it('produces a PNG buffer with the expected signature', () => { + const png = renderQrPng('ur:crypto-hdkey/oxttest'); + // PNG signature: 89 50 4E 47 0D 0A 1A 0A + expect(png[0]).toBe(0x89); + expect(png.subarray(1, 4).toString('ascii')).toBe('PNG'); + expect(png.length).toBeGreaterThan(0); + }); + + it('renders at a size derived from QR_CODE_SIZE_PX', () => { + const fragment = encodeToFragments( + buildCryptoHDKeyUR(baseOptions), + 10_000, + )[0] as string; + const png = renderQrPng(fragment); + const { width, height } = decodePngToRgb(png); + // The renderer uses the largest integer cell multiple that fits within + // QR_CODE_SIZE_PX; the result is always <= QR_CODE_SIZE_PX. + expect(width).toBeLessThanOrEqual(QR_CODE_SIZE_PX); + expect(height).toBeLessThanOrEqual(QR_CODE_SIZE_PX); + expect(width).toBe(height); + }); + + it('round-trips: rendered fragment decodes back to the same (uppercased) value', () => { + const fragment = encodeToFragments( + buildCryptoHDKeyUR(baseOptions), + 10_000, + )[0] as string; + const png = renderQrPng(fragment); + const decoded = decodeWithZxing(png); + // The renderer uppercases the value (mirrors MM's player.js), so the + // decoded text is the uppercased fragment. + expect(decoded).toBe(QR_UPPERCASE ? fragment.toUpperCase() : fragment); + }); + + it('uppercases the encoded value to match MM player.js', () => { + const pngLower = renderQrPng('ur:crypto-hdkey/lowercase-test'); + const pngUpper = renderQrPng('UR:CRYPTO-HDKEY/LOWERCASE-TEST'); + // Both render the same uppercase payload, so both decode to the same text. + const decodedLower = decodeWithZxing(pngLower); + expect(decodedLower).toBe(decodeWithZxing(pngUpper)); + // The lowercase input is rendered as its uppercase form (the intended + // check — not a tautology against itself). + expect(decodedLower).toBe('UR:CRYPTO-HDKEY/LOWERCASE-TEST'); + }); + + it('honours a custom target size', () => { + const fragment = encodeToFragments( + buildCryptoHDKeyUR(baseOptions), + 10_000, + )[0] as string; + const png = renderQrPng(fragment, 100); + const { width, height } = decodePngToRgb(png); + expect(width).toBeLessThanOrEqual(100); + expect(height).toBeLessThanOrEqual(100); + }); +}); diff --git a/packages/hw-emulator/src/qr/render/png.ts b/packages/hw-emulator/src/qr/render/png.ts new file mode 100644 index 000000000..49610c19d --- /dev/null +++ b/packages/hw-emulator/src/qr/render/png.ts @@ -0,0 +1,141 @@ +/* eslint-disable no-restricted-globals -- Buffer is required for binary PNG encoding. */ +/* eslint-disable no-bitwise -- CRC-32 checksums and pixel packing require bitwise ops. */ +/* eslint-disable import-x/no-nodejs-modules -- zlib is required for PNG IDAT compression. */ +/* eslint-disable id-length -- single-letter pixel/crc loop variables are idiomatic in image code. */ +/* eslint-disable @typescript-eslint/no-non-null-assertion -- CRC table index is provably in range. */ + +import { deflateSync } from 'node:zlib'; +import qrcode from 'qrcode-generator'; + +import { QR_CODE_SIZE_PX, QR_UPPERCASE } from '../constants'; + +/** QR error-correction level (mirrors `qrcode-generator`'s union). */ +type ErrorCorrectionLevel = 'L' | 'M' | 'Q' | 'H'; + +const PNG_SIGNATURE = Buffer.from([ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, +]); + +// Quiet-zone width in modules — the standard 4-module margin the QR spec +// requires around the code for reliable decoding. +const QR_QUIET_ZONE_MODULES = 4; + +// Precomputed CRC-32 table (PNG uses the standard IEEE polynomial). +const CRC_TABLE: Uint32Array = ((): Uint32Array => { + const table = new Uint32Array(256); + for (let entry = 0; entry < 256; entry++) { + let current = entry; + for (let bit = 0; bit < 8; bit++) { + current = current & 1 ? 0xedb88320 ^ (current >>> 1) : current >>> 1; + } + table[entry] = current >>> 0; + } + return table; +})(); + +/** + * Compute the CRC-32 of a buffer (PNG chunk checksum). + * + * @param data - The bytes to checksum. + * @returns The unsigned 32-bit CRC. + */ +function crc32(data: Buffer): number { + let current = 0xffffffff; + for (const byte of data) { + current = CRC_TABLE[(current ^ byte) & 0xff]! ^ (current >>> 8); + } + return (current ^ 0xffffffff) >>> 0; +} +/** + * Build a PNG chunk (length + type + data + CRC). + * + * @param type - The 4-byte chunk type. + * @param data - The chunk payload. + * @returns The serialized chunk. + */ +function pngChunk(type: string, data: Buffer): Buffer { + const length = Buffer.alloc(4); + length.writeUInt32BE(data.length, 0); + const typeBuf = Buffer.from(type, 'ascii'); + const crc = Buffer.alloc(4); + crc.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])), 0); + return Buffer.concat([length, typeBuf, data, crc]); +} + +/** + * Render a BC-UR fragment string to a QR code PNG buffer. + * + * The value is uppercased before encoding when `QR_UPPERCASE` is set (mirroring + * MetaMask's `player.js`, which renders `currentQRCode.toUpperCase()`). The + * target edge length is {@link QR_CODE_SIZE_PX}; the actual size is the largest + * integer multiple of the module size that fits, ensuring a crisp 1:1 cell + * mapping (no sub-pixel scaling) and a standard 4-module quiet zone for + * reliable decoding. + * + * The QR module matrix is read from `qrcode-generator` and encoded as an + * 8-bit grayscale PNG directly (no native image dependency), so the output is + * a real PNG that `decodePngToRgb` and `@zxing/library` can read back. + * + * @param value - The fragment string to encode. + * @param targetSize - Target edge length in pixels (defaults to + * `QR_CODE_SIZE_PX`). + * @param errorCorrectionLevel - QR error-correction level (defaults to `'M'`). + * @returns A PNG-encoded Buffer. + */ +export function renderQrPng( + value: string, + targetSize: number = QR_CODE_SIZE_PX, + errorCorrectionLevel: ErrorCorrectionLevel = 'M', +): Buffer { + const encoded = QR_UPPERCASE ? value.toUpperCase() : value; + const qr = qrcode(0, errorCorrectionLevel); + qr.addData(encoded); + qr.make(); + + const moduleCount = qr.getModuleCount(); + const margin = QR_QUIET_ZONE_MODULES; + const cellSize = Math.max( + 1, + Math.floor(targetSize / (moduleCount + margin * 2)), + ); + const pixelsPerSide = (moduleCount + margin * 2) * cellSize; + + // Build raw grayscale scanlines (filter byte 0 = None, 0 = black, 255 = white). + const scanlines: Buffer[] = []; + for (let y = 0; y < pixelsPerSide; y++) { + scanlines.push(Buffer.from([0])); + const row = Buffer.alloc(pixelsPerSide, 255); + const my = Math.floor(y / cellSize) - margin; + for (let x = 0; x < pixelsPerSide; x++) { + const mx = Math.floor(x / cellSize) - margin; + if ( + mx >= 0 && + mx < moduleCount && + my >= 0 && + my < moduleCount && + qr.isDark(my, mx) + ) { + row[x] = 0; + } + } + scanlines.push(row); + } + + const idat = deflateSync(Buffer.concat(scanlines)); + + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(pixelsPerSide, 0); // width + ihdr.writeUInt32BE(pixelsPerSide, 4); // height + ihdr.writeUInt8(8, 8); // bit depth + ihdr.writeUInt8(0, 9); // color type: grayscale + ihdr.writeUInt8(0, 10); // compression method + ihdr.writeUInt8(0, 11); // filter method + ihdr.writeUInt8(0, 12); // interlace: none + + return Buffer.concat([ + PNG_SIGNATURE, + pngChunk('IHDR', ihdr), + pngChunk('IDAT', idat), + pngChunk('IEND', Buffer.alloc(0)), + ]); +} diff --git a/packages/hw-emulator/src/qr/render/y4m.test.ts b/packages/hw-emulator/src/qr/render/y4m.test.ts new file mode 100644 index 000000000..c8d5ed965 --- /dev/null +++ b/packages/hw-emulator/src/qr/render/y4m.test.ts @@ -0,0 +1,164 @@ +/* eslint-disable n/no-sync -- synchronous fs is acceptable for temp-file test fixtures. */ + +import { + chmodSync, + existsSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { + QR_EMULATOR_ACCOUNT_DERIVATION_PATH, + QR_EMULATOR_CHILDREN_PATH, + QR_EMULATOR_DEFAULT_XFP, + QR_EMULATOR_SEED, +} from '../constants'; +import { buildCryptoHDKeyUR } from '../core/ur-synth'; +import type { SynthesizeOptions } from '../core/ur-synth'; +import { + FfmpegUnavailableError, + ensureFfmpegAvailable, + isFfmpegAvailable, + renderUrToY4m, +} from './y4m'; + +const baseOptions: SynthesizeOptions = { + seed: QR_EMULATOR_SEED, + accountPath: QR_EMULATOR_ACCOUNT_DERIVATION_PATH, + childrenPath: QR_EMULATOR_CHILDREN_PATH, + xfp: QR_EMULATOR_DEFAULT_XFP, + deviceName: 'Keystone Test', + pairMode: 'crypto-hdkey', + descriptorCount: 1, +}; + +const ffmpegAvailable = isFfmpegAvailable(); +const maybeDescribe = ffmpegAvailable ? describe : describe.skip; + +describe('QR Y4M renderer', () => { + describe('ffmpeg probe', () => { + it('ensureFfmpegAvailable throws iff ffmpeg is absent', () => { + let threw = false; + try { + ensureFfmpegAvailable(); + } catch { + threw = true; + } + expect(threw).toBe(!ffmpegAvailable); + }); + + it('isFfmpegAvailable returns a boolean', () => { + expect(typeof isFfmpegAvailable()).toBe('boolean'); + }); + + it('throws a descriptive FfmpegUnavailableError when ffmpeg is missing', () => { + // This documents the error shape; the actual throw only happens when + // ffmpeg is absent, which is environment-dependent. + const error = new FfmpegUnavailableError(); + expect(error).toBeInstanceOf(Error); + expect(error.name).toBe('FfmpegUnavailableError'); + expect(error.message).toMatch(/ffmpeg/u); + expect(error.message).toMatch(/brew install/u); + }); + }); + + maybeDescribe('renderUrToY4m (ffmpeg present)', () => { + let tempDir: string; + + beforeEach(() => { + tempDir = mkdtempSync(join(tmpdir(), 'qr-y4m-test-')); + }); + + afterEach(() => { + rmSync(tempDir, { recursive: true, force: true }); + }); + + // These tests spawn ffmpeg and encode real frames; on loaded machines the + // default 2s timeout is flaky, so allow 15s per render. + const FFMPEG_TEST_TIMEOUT_MS = 15_000; + + it( + 'produces a non-empty Y4M file that starts with the YUV4MPEG2 signature', + async () => { + const ur = buildCryptoHDKeyUR(baseOptions); + const outputPath = join(tempDir, 'account.y4m'); + const result = await renderUrToY4m(ur, { + outputPath, + fps: 5, + durationS: 1, + }); + + expect(result).toBe(outputPath); + expect(existsSync(outputPath)).toBe(true); + const stat = statSync(outputPath); + expect(stat.size).toBeGreaterThan(0); + + const header = readFileSync(outputPath) + .subarray(0, 10) + .toString('ascii'); + // Y4M files begin with the "YUV4MPEG2" signature. + expect(header.startsWith('YUV4MPEG2')).toBe(true); + }, + FFMPEG_TEST_TIMEOUT_MS, + ); + + it( + 'honours the requested fps and duration', + async () => { + const ur = buildCryptoHDKeyUR(baseOptions); + const outputPath = join(tempDir, 'account-dur.y4m'); + await renderUrToY4m(ur, { + outputPath, + fps: 5, + durationS: 2, + }); + const header = readFileSync(outputPath).toString('ascii').slice(0, 64); + // The Y4M header carries the framerate, e.g. "F5:1" for 5 fps. + expect(header).toMatch(/F5:1/u); + }, + FFMPEG_TEST_TIMEOUT_MS, + ); + + it( + 'returns the output path', + async () => { + const ur = buildCryptoHDKeyUR(baseOptions); + const outputPath = join(tempDir, 'return-path.y4m'); + const returned = await renderUrToY4m(ur, { outputPath }); + expect(returned).toBe(outputPath); + }, + FFMPEG_TEST_TIMEOUT_MS, + ); + + it( + 'removes the partial output file when ffmpeg exits non-zero', + async () => { + if (process.getuid?.() === 0) { + // A read-only file does not block ffmpeg's output open when running + // as root, so the forced failure (and cleanup assertion) would be + // non-deterministic there. + return; + } + const ur = buildCryptoHDKeyUR(baseOptions); + const outputPath = join(tempDir, 'partial.y4m'); + // Pre-create a sentinel "partial output" and make it read-only so + // ffmpeg fails to open it for writing and exits non-zero. + writeFileSync(outputPath, 'partial-output-sentinel'); + chmodSync(outputPath, 0o444); + await expect( + renderUrToY4m(ur, { outputPath, fps: 5, durationS: 1 }), + // The rejection is either ffmpeg's non-zero exit (with its stderr + // attached) or the resulting stdin EPIPE when it dies mid-write. + ).rejects.toThrow(/ffmpeg|epipe/iu); + // The failed render must not leave the poisoned partial file behind. + expect(existsSync(outputPath)).toBe(false); + }, + FFMPEG_TEST_TIMEOUT_MS, + ); + }); +}); diff --git a/packages/hw-emulator/src/qr/render/y4m.ts b/packages/hw-emulator/src/qr/render/y4m.ts new file mode 100644 index 000000000..b1d0d3eaa --- /dev/null +++ b/packages/hw-emulator/src/qr/render/y4m.ts @@ -0,0 +1,210 @@ +/* eslint-disable import-x/no-nodejs-modules -- child_process and fs are required to spawn ffmpeg and clean up partial output. */ + +import { spawn, spawnSync } from 'node:child_process'; +import { rm } from 'node:fs/promises'; + +import { encodeToFragments } from '../codec/encoder'; +import { QR_REFRESH_MS, QR_Y4M_RENDER_SIZE_PX } from '../constants'; +import type { SerializedUR } from '../core/ur-synth'; +import { renderQrPng } from './png'; + +/** Options for rendering an animated QR to a Y4M video file. */ +export type Y4mRenderOptions = { + /** Frames per second (defaults to 5, matching `QR_REFRESH_MS`). */ + fps?: number; + /** Total duration in seconds (defaults to 4). */ + durationS?: number; + /** Output file path for the `.y4m` file. */ + outputPath: string; + /** Target square edge length in pixels (defaults to `QR_Y4M_RENDER_SIZE_PX`). */ + size?: number; +}; + +const DEFAULT_FPS = Math.round(1000 / QR_REFRESH_MS); // 5 +const DEFAULT_DURATION_S = 4; +const DEFAULT_PIX_FMT = 'yuv420p'; + +let ffmpegChecked: boolean | undefined; + +/** Error thrown when ffmpeg is required but not installed. */ +export class FfmpegUnavailableError extends Error { + constructor() { + super( + [ + 'ffmpeg is required to render Y4M video but was not found on PATH.', + 'Install it with one of:', + ' macOS: brew install ffmpeg', + ' Debian/Ubuntu: sudo apt install ffmpeg', + ' Fedora: sudo dnf install ffmpeg', + 'The PNG rendering and screenshot-decoding paths do not require ffmpeg.', + ].join('\n'), + ); + this.name = 'FfmpegUnavailableError'; + } +} + +/** + * Probe for the `ffmpeg` binary. Runs once per process; the result is cached. + * + * @throws {FfmpegUnavailableError} If ffmpeg is not available, with + * platform-specific install advice. + */ +export function ensureFfmpegAvailable(): void { + if (ffmpegChecked !== undefined) { + if (!ffmpegChecked) { + throw new FfmpegUnavailableError(); + } + return; + } + const result = spawnSync('ffmpeg', ['-version'], { stdio: 'ignore' }); + const available = result.status === 0; + ffmpegChecked = available; + if (!available) { + throw new FfmpegUnavailableError(); + } +} + +/** + * Check whether ffmpeg is available without throwing. + * + * @returns `true` if ffmpeg is installed and invokable. + */ +export function isFfmpegAvailable(): boolean { + try { + ensureFfmpegAvailable(); + return true; + } catch { + return false; + } +} + +/** + * Build the ffmpeg argument list for piping PNG frames into a Y4M file. + * + * @param opts - Resolved render options. + * @returns The ffmpeg argv (without the leading `ffmpeg`). + */ +function buildFfmpegArgs( + opts: Required> & { + outputPath: string; + }, +): string[] { + return [ + '-y', + '-f', + 'image2pipe', + '-framerate', + String(opts.fps), + '-i', + '-', + '-t', + String(opts.durationS), + '-vf', + `scale=${opts.size}:${opts.size}:flags=neighbor`, + '-pix_fmt', + DEFAULT_PIX_FMT, + opts.outputPath, + ]; +} + +/** + * Render a SerializedUR into an animated QR Y4M file via ffmpeg. + * + * Each fountain fragment is rendered to a PNG and piped to ffmpeg's + * `image2pipe` input; fragments are cycled for the full duration so the BC-UR + * fountain decoder on the receiving side has ample opportunity to reconstruct + * the UR. + * + * @param ur - The SerializedUR to animate. + * @param options - Render options (output path required). + * @returns The output path on success. + * @throws {FfmpegUnavailableError} If ffmpeg is not installed. + */ +export async function renderUrToY4m( + ur: SerializedUR, + options: Y4mRenderOptions, +): Promise { + ensureFfmpegAvailable(); + + const fps = options.fps ?? DEFAULT_FPS; + const durationS = options.durationS ?? DEFAULT_DURATION_S; + const size = options.size ?? QR_Y4M_RENDER_SIZE_PX; + + const fragments = encodeToFragments(ur); + const frameCount = Math.max(1, fps * durationS); + + const args = buildFfmpegArgs({ + fps, + durationS, + size, + outputPath: options.outputPath, + }); + + await new Promise((resolve, reject) => { + const child = spawn('ffmpeg', args, { stdio: ['pipe', 'ignore', 'pipe'] }); + + let settled = false; + /** + * Settle the render promise exactly once. On failure, best-effort remove + * the partial output file first so it cannot poison later runs, then + * reject. + * + * @param error - The failure reason, or `undefined` on success. + */ + const finish = (error?: Error): void => { + if (settled) { + return; + } + settled = true; + if (!error) { + resolve(); + return; + } + // eslint-disable-next-line promise/no-promise-in-callback -- best-effort removal of the partial output file before rejecting + rm(options.outputPath, { force: true }) + .catch(() => undefined) + .finally(() => { + reject(error); + }); + }; + + let stderr = ''; + child.stderr?.on('data', (chunk: Buffer) => { + stderr += chunk.toString('utf8'); + }); + child.on('error', (error: Error) => finish(error)); + child.on('close', (code) => { + if (code === 0) { + finish(); + } else { + finish(new Error(`ffmpeg exited with code ${String(code)}\n${stderr}`)); + } + }); + + const { stdin } = child; + if (!stdin) { + finish(new Error('ffmpeg stdin stream unavailable')); + return; + } + + // An early ffmpeg exit surfaces as an EPIPE 'error' event on stdin; + // without a listener the process would crash. + stdin.on('error', (error: Error) => finish(error)); + + try { + for (let i = 0; i < frameCount; i++) { + // encodeToFragments (BC-UR fountain encoding) always yields at + // least one fragment, so direct indexing is safe. + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- fragment index is provably in range + const fragment = fragments[i % fragments.length]!; + const png = renderQrPng(fragment, size); + stdin.write(png); + } + stdin.end(); + } catch (error) { + finish(error instanceof Error ? error : new Error(String(error))); + } + }); + + return options.outputPath; +} diff --git a/packages/hw-emulator/src/trezor/constants.test.ts b/packages/hw-emulator/src/trezor/constants.test.ts new file mode 100644 index 000000000..006742281 --- /dev/null +++ b/packages/hw-emulator/src/trezor/constants.test.ts @@ -0,0 +1,38 @@ +import { + TREZOR_EMULATOR_SEED, + TREZOR_DEFAULT_MODEL, + TREZOR_CONNECT_SRC, + TREZOR_TRANSPORT_BRIDGE_PORT, + TREZOR_CONTROLLER_PORT, + TREZOR_MSG, +} from './constants'; + +describe('trezor constants', () => { + it('exposes the SLIP-14 canonical seed', () => { + expect(TREZOR_EMULATOR_SEED).toBe( + 'all all all all all all all all all all all all', + ); + }); + + it('defaults to Model T (T2T1)', () => { + expect(TREZOR_DEFAULT_MODEL).toBe('T2T1'); + }); + + it('exposes the local connect-web iframe connectSrc', () => { + expect(TREZOR_CONNECT_SRC).toBe('http://localhost:8088/'); + }); + + it('targets @trezor/transport-bridge on port 21328', () => { + expect(TREZOR_TRANSPORT_BRIDGE_PORT).toBe(21328); + }); + + it('targets the WS controller on 9001', () => { + expect(TREZOR_CONTROLLER_PORT).toBe(9001); + }); + + it('maps the Ethereum signing protobuf message type ids', () => { + expect(TREZOR_MSG.EthereumSignTx).toBe(58); + expect(TREZOR_MSG.EthereumSignMessage).toBe(60); + expect(TREZOR_MSG.EthereumSignTypedData).toBe(495); + }); +}); diff --git a/packages/hw-emulator/src/trezor/constants.ts b/packages/hw-emulator/src/trezor/constants.ts new file mode 100644 index 000000000..d72f41e02 --- /dev/null +++ b/packages/hw-emulator/src/trezor/constants.ts @@ -0,0 +1,41 @@ +import type { TrezorModel } from './model-profiles'; + +/** Canonical SLIP-14 test mnemonic (matches trezor-connect's own test preset). */ +export const TREZOR_EMULATOR_SEED = + 'all all all all all all all all all all all all'; + +/** Default model: Trezor Model T / Safe 3 (touchscreen, flagship). */ +export const TREZOR_DEFAULT_MODEL: TrezorModel = 'T2T1'; + +/** + * connectSrc override: URL of the locally-served connect-web iframe assets. + * Injected via window.__TREZOR_CONNECT_SRC (see html-injector.ts). + */ +export const TREZOR_CONNECT_SRC = 'http://localhost:8088/'; + +/** + * @trezor/transport-bridge HTTP port (default). The iframe's BridgeTransport + * hits this; the sidecar's CORS proxy listens on it (see sidecar-manager.ts). + */ +export const TREZOR_TRANSPORT_BRIDGE_PORT = 21328; + +/** trezor-user-env WebSocket controller port. */ +export const TREZOR_CONTROLLER_PORT = 9001; + +/** + * Emulator UDP debug-link port (informational; transport-bridge talks to + * this). The port mapping lives in the trezor-user-env docker-compose file + * rather than in runtime source, so no runtime code binds or dials it. Kept + * as part of the package's public constants surface. + */ +export const TREZOR_EMULATOR_PORT = 21324; + +/** Trezor protobuf message type IDs used for signing detection. */ +export const TREZOR_MSG = { + EthereumSignTx: 58, + EthereumSignMessage: 60, + EthereumSignTypedData: 495, +} as const; + +/** Models supported by trezor-user-env. (Type re-exported for convenience.) */ +export type { TrezorModel }; diff --git a/packages/hw-emulator/src/trezor/controller-client.test.ts b/packages/hw-emulator/src/trezor/controller-client.test.ts new file mode 100644 index 000000000..0e4c92894 --- /dev/null +++ b/packages/hw-emulator/src/trezor/controller-client.test.ts @@ -0,0 +1,179 @@ +import { EventEmitter } from 'events'; + +import { TrezorControllerClient } from './controller-client'; + +type SentMessage = { + id: string; + type: string; +}; + +type MockSocket = EventEmitter & { + send: (payload: string) => void; + close: () => void; +}; + +type MockSocketHandle = { + socket: MockSocket; + sent: SentMessage[]; + reply: (id: string, response: unknown, success?: boolean) => void; + setSendImplementation: (implementation: (payload: string) => void) => void; + factory: () => Promise; +}; + +function createMockSocket(): MockSocketHandle { + const socket = new EventEmitter() as MockSocket; + const sent: SentMessage[] = []; + let sendImplementation: (payload: string) => void = ( + payload: string, + ): void => { + sent.push(JSON.parse(payload) as SentMessage); + }; + socket.send = (payload: string): void => { + sendImplementation(payload); + }; + socket.close = (): void => { + socket.emit('close'); + }; + const reply = (id: string, response: unknown, success = true): void => { + socket.emit( + 'message', + Buffer.from(JSON.stringify({ id, success, response })), + ); + }; + + return { + socket, + sent, + reply, + setSendImplementation: ( + implementation: (payload: string) => void, + ): void => { + sendImplementation = implementation; + }, + factory: async (): Promise => { + // emit 'open' on next tick so the connect() promise resolves + setImmediate(() => { + socket.emit('open'); + }); + return socket; + }, + }; +} + +describe('TrezorControllerClient', () => { + it('sends emulator-start with a generated id and resolves on the matching reply', async () => { + const { factory, sent, reply } = createMockSocket(); + const client = new TrezorControllerClient({ socketFactory: factory }); + await client.connect(); + const pending = client.emulatorStart({ model: 'T2T1', wipe: true }); + await new Promise((resolve) => setImmediate(resolve)); + const startMessage = sent[0]; + if (!startMessage) { + throw new Error('emulator-start was not sent'); + } + expect(sent).toStrictEqual([ + expect.objectContaining({ + type: 'emulator-start', + model: 'T2T1', + wipe: true, + id: expect.any(String), + }), + ]); + reply(startMessage.id, { ok: true }); + expect(await pending).toStrictEqual({ ok: true }); + }); + + it('rejects when the controller returns success:false', async () => { + const { factory, sent, reply } = createMockSocket(); + const client = new TrezorControllerClient({ socketFactory: factory }); + await client.connect(); + const pending = client.emulatorSetup({ + mnemonic: 'x', + pin: '', + passphrase_protection: false, + label: 't', + }); + await new Promise((resolve) => setImmediate(resolve)); + const setupMessage = sent[0]; + if (!setupMessage) { + throw new Error('emulator-setup was not sent'); + } + reply(setupMessage.id, { error: 'bad mnemonic' }, false); + await expect(pending).rejects.toThrow('bad mnemonic'); + }); + + it('maps pressYes/pressNo to emulator-press-yes/no', async () => { + const { factory, sent } = createMockSocket(); + const client = new TrezorControllerClient({ socketFactory: factory }); + await client.connect(); + // Fire-and-forget: these stay pending (no reply is sent for them). + client.pressYes().catch(() => undefined); + client.pressNo().catch(() => undefined); + await new Promise((resolve) => setImmediate(resolve)); + expect(sent.map((message: SentMessage) => message.type)).toStrictEqual([ + 'emulator-press-yes', + 'emulator-press-no', + ]); + }); + + it('maps a touchscreen click to emulator-click with coords', async () => { + const { factory, sent } = createMockSocket(); + const client = new TrezorControllerClient({ socketFactory: factory }); + await client.connect(); + client.click({ x: 120, y: 200 }).catch(() => undefined); + await new Promise((resolve) => setImmediate(resolve)); + expect(sent[0]).toStrictEqual( + expect.objectContaining({ + type: 'emulator-click', + x: 120, + y: 200, + }), + ); + }); + + it('rejects and stays usable when the socket send throws synchronously', async () => { + const { socket, sent, factory, setSendImplementation } = createMockSocket(); + setSendImplementation((payload: string) => { + sent.push(JSON.parse(payload) as SentMessage); + throw new Error('send failed'); + }); + const client = new TrezorControllerClient({ socketFactory: factory }); + await client.connect(); + + await expect(client.ping()).rejects.toThrow('send failed'); + + // The failed request must not corrupt the client: a subsequent request + // on the same connection resolves normally. + setSendImplementation((payload: string) => { + sent.push(JSON.parse(payload) as SentMessage); + }); + const second = client.ping(); + await new Promise((resolve) => setImmediate(resolve)); + const secondMessage = sent[1]; + if (!secondMessage) { + throw new Error('second ping was not sent'); + } + socket.emit( + 'message', + Buffer.from( + JSON.stringify({ + id: secondMessage.id, + success: true, + response: { ok: 1 }, + }), + ), + ); + expect(await second).toStrictEqual({ ok: 1 }); + socket.close(); + }); + + it('rejects pending requests when the socket errors after connect', async () => { + const { socket, factory } = createMockSocket(); + const client = new TrezorControllerClient({ socketFactory: factory }); + await client.connect(); + + const pending = client.ping(); + socket.emit('error', new Error('socket gone')); + await expect(pending).rejects.toThrow('socket gone'); + }); +}); diff --git a/packages/hw-emulator/src/trezor/controller-client.ts b/packages/hw-emulator/src/trezor/controller-client.ts new file mode 100644 index 000000000..b767e966a --- /dev/null +++ b/packages/hw-emulator/src/trezor/controller-client.ts @@ -0,0 +1,299 @@ +// eslint-disable-next-line import-x/no-nodejs-modules +import type { EventEmitter } from 'events'; +// eslint-disable-next-line import-x/no-nodejs-modules +import { Buffer } from 'node:buffer'; +// eslint-disable-next-line import-x/no-nodejs-modules +import { randomUUID } from 'node:crypto'; + +import { TREZOR_CONTROLLER_PORT } from './constants'; +import type { TrezorModel } from './model-profiles'; + +export type ControllerClientOptions = { + host?: string; + port?: number; + /** Injectable for tests. Default opens a real `ws` WebSocket. */ + socketFactory?: ( + url: string, + ) => Promise; +}; + +export type SetupParams = { + mnemonic: string; + pin: string; + // The controller protocol uses snake_case keys on the wire. + // eslint-disable-next-line @typescript-eslint/naming-convention + passphrase_protection: boolean; + label: string; + // eslint-disable-next-line @typescript-eslint/naming-convention + needs_backup?: boolean; +}; + +/** + * Payload of a successful controller response. Commands that return data + * (e.g. screenshots) add fields on top of this shape. + */ +export type ControllerResponse = { + /** Base64-encoded screenshot payload (screenshot responses only). */ + base64?: string; + /** Error text, present on failed responses. */ + error?: string; +}; + +/** A message received from the trezor-user-env WebSocket controller. */ +type ControllerMessage = { + id?: string; + success?: boolean; + response?: ControllerResponse; + error?: string; +}; + +type WireSocket = EventEmitter & { + send(payload: string): void; + close(): void; +}; + +type PendingRequest = { + resolve: (value: unknown) => void; + reject: (error: Error) => void; +}; + +export class TrezorControllerClient { + readonly #url: string; + + readonly #socketFactory: (url: string) => Promise; + + #socket: WireSocket | null = null; + + readonly #pending = new Map(); + + constructor(opts: ControllerClientOptions = {}) { + const host = opts.host ?? '127.0.0.1'; + const port = opts.port ?? TREZOR_CONTROLLER_PORT; + this.#url = `ws://${host}:${port}/`; + this.#socketFactory = opts.socketFactory ?? defaultFactory; + } + + async connect(): Promise { + const socket = await this.#socketFactory(this.#url); + this.#socket = socket; + socket.on('message', (data: Buffer) => this.#handleMessage(data)); + socket.on('close', () => + this.#rejectAll(new Error('controller socket closed')), + ); + // Errors after connect reject every in-flight request. On `ws` sockets a + // 'close' event follows 'error', so this complements the close handler. + socket.on('error', (error: Error) => this.#rejectAll(error)); + } + + async disconnect(): Promise { + this.#socket?.close(); + this.#socket = null; + } + + #handleMessage(data: Buffer): void { + let message: ControllerMessage; + try { + message = JSON.parse(data.toString()) as ControllerMessage; + } catch { + return; + } + if (!message.id) { + return; + } + const pending = this.#pending.get(message.id); + if (!pending) { + return; + } + this.#pending.delete(message.id); + if (message.success) { + pending.resolve(message.response); + } else { + pending.reject( + new Error( + message.response?.error ?? message.error ?? 'controller error', + ), + ); + } + } + + #rejectAll(error: Error): void { + for (const [, pending] of this.#pending) { + pending.reject(error); + } + this.#pending.clear(); + } + + async #send(request: Record): Promise { + const socket = this.#socket; + if (!socket) { + throw new Error('not connected'); + } + const id = randomUUID(); + return new Promise((resolve, reject) => { + this.#pending.set(id, { + resolve: resolve as (value: unknown) => void, + reject, + }); + try { + socket.send(JSON.stringify({ ...request, id })); + } catch (error) { + // A synchronous send failure must not leak the pending entry, + // otherwise the map grows without bound. + this.#pending.delete(id); + reject(error instanceof Error ? error : new Error(String(error))); + } + }); + } + + // ── controller commands ────────────────────────────────────────────── + + /** + * Start the emulated device, optionally wiping its state first. + * + * @param params - The emulator start parameters. + * @param params.model - The device model to emulate. + * @param params.wipe - Whether to wipe device state before starting. + * @returns The controller response. + */ + async emulatorStart(params: { + model: TrezorModel; + wipe?: boolean; + }): Promise { + return this.#send({ type: 'emulator-start', ...params }); + } + + /** + * Initialize the emulated device with a mnemonic and settings. + * + * @param params - The device setup parameters. + * @returns The controller response. + */ + async emulatorSetup(params: SetupParams): Promise { + return this.#send({ type: 'emulator-setup', ...params }); + } + + /** + * Start the trezord bridge (e.g. `node-bridge`) in trezor-user-env. + * + * @param version - Optional bridge version to start. + * @returns The controller response. + */ + async bridgeStart(version?: string): Promise { + return this.#send({ type: 'bridge-start', version }); + } + + /** + * Stop the running trezord bridge. + * + * @returns The controller response. + */ + async bridgeStop(): Promise { + return this.#send({ type: 'bridge-stop' }); + } + + /** + * Verify that the trezor-user-env background services are healthy. + * + * @returns The controller response. + */ + async backgroundCheck(): Promise { + return this.#send({ type: 'background-check' }); + } + + /** + * Ping the controller to verify that the WebSocket connection works. + * + * @returns The controller response. + */ + async ping(): Promise { + return this.#send({ type: 'ping' }); + } + + // ── device interaction ─────────────────────────────────────────────── + + /** + * Press the physical Yes button (button-only models). + * + * @returns The controller response. + */ + async pressYes(): Promise { + return this.#send({ type: 'emulator-press-yes' }); + } + + /** + * Press the physical No button (button-only models). + * + * @returns The controller response. + */ + async pressNo(): Promise { + return this.#send({ type: 'emulator-press-no' }); + } + + /** + * Type a value on the emulated device keyboard. + * + * @param value - The value to type. + * @returns The controller response. + */ + async input(value: string): Promise { + return this.#send({ type: 'emulator-input', value }); + } + + /** + * Tap the touchscreen at the given coordinates. + * + * @param params - The tap coordinates. + * @param params.x - The horizontal coordinate. + * @param params.y - The vertical coordinate. + * @returns The controller response. + */ + async click(params: { x: number; y: number }): Promise { + return this.#send({ type: 'emulator-click', x: params.x, y: params.y }); + } + + /** + * Swipe the touchscreen in the given direction. + * + * @param direction - The swipe direction. + * @returns The controller response. + */ + async swipe(direction: 'up' | 'down' | 'left' | 'right'): Promise { + return this.#send({ type: 'emulator-swipe', direction }); + } + + /** + * Capture the emulated device screen as a PNG buffer. + * + * @returns The screenshot payload. + */ + async getScreenshot(): Promise { + const response = await this.#send({ + type: 'emulator-get-screenshot', + }); + const payload = + typeof response === 'string' ? response : (response?.base64 ?? ''); + return Buffer.from(payload, 'base64'); + } +} + +async function defaultFactory(url: string): Promise { + const wsModule = await import('ws'); + return new Promise((resolve, reject) => { + const socket = new wsModule.WebSocket(url) as unknown as WireSocket; + let opened = false; + const onConnectError = (error: Error): void => { + if (!opened) { + reject(error); + } + }; + socket.on('error', onConnectError); + socket.once('open', () => { + opened = true; + // The socket now belongs to the client, which attaches its own + // persistent handlers in connect(). Drop this one-shot rejection + // listener so a post-connect error cannot reject a settled promise. + socket.removeListener('error', onConnectError); + resolve(socket); + }); + }); +} diff --git a/packages/hw-emulator/src/trezor/device-interaction.test.ts b/packages/hw-emulator/src/trezor/device-interaction.test.ts new file mode 100644 index 000000000..a4de3f615 --- /dev/null +++ b/packages/hw-emulator/src/trezor/device-interaction.test.ts @@ -0,0 +1,77 @@ +import { TrezorControllerClient } from './controller-client'; +import { TrezorDeviceInteraction } from './device-interaction'; +import { MODEL_PROFILES } from './model-profiles'; + +class FakeController extends TrezorControllerClient { + calls: string[] = []; + + constructor() { + super({}); + } + + override async pressYes(): Promise { + this.calls.push('press-yes'); + return Promise.resolve({}); + } + + override async pressNo(): Promise { + this.calls.push('press-no'); + return Promise.resolve({}); + } + + override async click(params: { x: number; y: number }): Promise { + this.calls.push(`click:${params.x},${params.y}`); + return Promise.resolve({}); + } + + override async swipe( + direction: 'up' | 'down' | 'left' | 'right', + ): Promise { + this.calls.push(`swipe:${direction}`); + return Promise.resolve({}); + } +} + +describe('TrezorDeviceInteraction', () => { + it('t1B1 approve dispatches press-yes', async () => { + const ctl = new FakeController(); + const ix = new TrezorDeviceInteraction(ctl, MODEL_PROFILES.T1B1); + await ix.approveTransaction(); + expect(ctl.calls).toStrictEqual(['press-yes']); + }); + + it('t2T1 approve dispatches click at the profile confirm coords', async () => { + const ctl = new FakeController(); + const ix = new TrezorDeviceInteraction(ctl, MODEL_PROFILES.T2T1); + await ix.approveTransaction(); + expect(ctl.calls).toStrictEqual(['click:120,200']); + }); + + it('reject dispatches the profile reject action', async () => { + const ctl = new FakeController(); + const ix = new TrezorDeviceInteraction(ctl, MODEL_PROFILES.T1B1); + await ix.rejectTransaction(); + expect(ctl.calls).toStrictEqual(['press-no']); + }); + + it('approveSigning is a semantic alias of approveTransaction', async () => { + const ctl = new FakeController(); + const ix = new TrezorDeviceInteraction(ctl, MODEL_PROFILES.T2T1); + await ix.approveSigning(); + expect(ctl.calls).toStrictEqual(['click:120,200']); + }); + + it('dismissSummaryScreen swipes per the profile scroll approach', async () => { + const ctl = new FakeController(); + const ix = new TrezorDeviceInteraction(ctl, MODEL_PROFILES.T2T1); + await ix.dismissSummaryScreen(); + expect(ctl.calls).toStrictEqual(['swipe:up']); + }); + + it('dismissSummaryScreen does nothing without a scroll approach', async () => { + const ctl = new FakeController(); + const ix = new TrezorDeviceInteraction(ctl, MODEL_PROFILES.T1B1); + await ix.dismissSummaryScreen(); + expect(ctl.calls).toStrictEqual([]); + }); +}); diff --git a/packages/hw-emulator/src/trezor/device-interaction.ts b/packages/hw-emulator/src/trezor/device-interaction.ts new file mode 100644 index 000000000..79c89ccf3 --- /dev/null +++ b/packages/hw-emulator/src/trezor/device-interaction.ts @@ -0,0 +1,79 @@ +import type { TrezorControllerClient } from './controller-client'; +import type { ModelProfile, PressAction } from './model-profiles'; + +export type DeviceInteraction = { + approveTransaction(): Promise; + approveSigning(): Promise; + rejectTransaction(): Promise; + /** Dismiss a long transaction summary by scrolling to its end. */ + dismissSummaryScreen(): Promise; + /** + * Navigate back to the main menu. Alias of {@link dismissSummaryScreen}, + * retained to satisfy the package-wide `DeviceInteraction` contract in + * `src/types.ts`. + * + * @deprecated Use {@link dismissSummaryScreen} instead. + */ + navigateToMainMenu(): Promise; +}; + +export class TrezorDeviceInteraction implements DeviceInteraction { + readonly #controller: TrezorControllerClient; + + readonly #profile: ModelProfile; + + constructor(controller: TrezorControllerClient, profile: ModelProfile) { + this.#controller = controller; + this.#profile = profile; + } + + async approveTransaction(): Promise { + await this.#run(this.#profile.confirm); + } + + async approveSigning(): Promise { + await this.approveTransaction(); + } + + async rejectTransaction(): Promise { + await this.#run(this.#profile.reject); + } + + /** + * Dismiss a long transaction summary screen. + * + * Transaction summaries on touchscreen models can span several screens; + * scrolling to the end reveals the confirm/reject buttons. Profiles + * without a configured scroll approach (e.g. button-only models) do + * nothing here. + */ + async dismissSummaryScreen(): Promise { + if (this.#profile.scrollApproach) { + await this.#controller.swipe( + this.#profile.scrollApproach === 'swipe-up' ? 'up' : 'down', + ); + } + } + + /** + * Alias of {@link dismissSummaryScreen}, retained for the package-wide + * `DeviceInteraction` contract. + * + * @deprecated Use {@link dismissSummaryScreen} instead. + */ + async navigateToMainMenu(): Promise { + await this.dismissSummaryScreen(); + } + + async #run(action: PressAction): Promise { + if (action === 'press-yes') { + await this.#controller.pressYes(); + return; + } + if (action === 'press-no') { + await this.#controller.pressNo(); + return; + } + await this.#controller.click(action.click); + } +} diff --git a/packages/hw-emulator/src/trezor/docker-manager.test.ts b/packages/hw-emulator/src/trezor/docker-manager.test.ts new file mode 100644 index 000000000..2510922e0 --- /dev/null +++ b/packages/hw-emulator/src/trezor/docker-manager.test.ts @@ -0,0 +1,48 @@ +import { TrezorDockerManager } from './docker-manager'; + +describe('TrezorDockerManager', () => { + it('runs docker compose up -d with the given compose file', async () => { + const calls: string[][] = []; + const mgr = new TrezorDockerManager({ + composeFile: '/tmp/trezor.yml', + runner: async ( + file: string, + args: string[], + ): Promise<{ stdout: string; stderr: string }> => { + calls.push([file, ...args]); + return { stdout: '', stderr: '' }; + }, + }); + await mgr.start(); + expect(calls[0]).toStrictEqual([ + 'docker', + 'compose', + '-f', + '/tmp/trezor.yml', + 'up', + '-d', + ]); + }); + + it('runs docker compose down on stop', async () => { + const calls: string[][] = []; + const mgr = new TrezorDockerManager({ + composeFile: '/tmp/trezor.yml', + runner: async ( + file: string, + args: string[], + ): Promise<{ stdout: string; stderr: string }> => { + calls.push([file, ...args]); + return { stdout: '', stderr: '' }; + }, + }); + await mgr.stop(); + expect(calls[0]).toStrictEqual([ + 'docker', + 'compose', + '-f', + '/tmp/trezor.yml', + 'down', + ]); + }); +}); diff --git a/packages/hw-emulator/src/trezor/docker-manager.ts b/packages/hw-emulator/src/trezor/docker-manager.ts new file mode 100644 index 000000000..8fc1a9bbd --- /dev/null +++ b/packages/hw-emulator/src/trezor/docker-manager.ts @@ -0,0 +1,47 @@ +// eslint-disable-next-line import-x/no-nodejs-modules +import { execFile } from 'node:child_process'; +// eslint-disable-next-line import-x/no-nodejs-modules +import { promisify } from 'node:util'; + +const execFileAsync = promisify(execFile); + +export type DockerRunner = ( + file: string, + args: string[], +) => Promise<{ stdout: string; stderr: string }>; + +export type DockerManagerOptions = { + composeFile: string; + runner?: DockerRunner; +}; + +export class TrezorDockerManager { + readonly #composeFile: string; + + readonly #runner: DockerRunner; + + constructor(opts: DockerManagerOptions) { + this.#composeFile = opts.composeFile; + this.#runner = + opts.runner ?? + (async ( + file: string, + args: string[], + ): Promise<{ stdout: string; stderr: string }> => + execFileAsync(file, args)); + } + + async start(): Promise { + await this.#runner('docker', [ + 'compose', + '-f', + this.#composeFile, + 'up', + '-d', + ]); + } + + async stop(): Promise { + await this.#runner('docker', ['compose', '-f', this.#composeFile, 'down']); + } +} diff --git a/packages/hw-emulator/src/trezor/html-injector.test.ts b/packages/hw-emulator/src/trezor/html-injector.test.ts new file mode 100644 index 000000000..47d6cb82e --- /dev/null +++ b/packages/hw-emulator/src/trezor/html-injector.test.ts @@ -0,0 +1,19 @@ +import { TREZOR_CONNECT_SRC } from './constants'; +import { getTrezorConnectSrcInjectionScript } from './html-injector'; + +describe('getTrezorConnectSrcInjectionScript', () => { + it('returns a script that sets window.__TREZOR_CONNECT_SRC to the connectSrc constant', () => { + const script = getTrezorConnectSrcInjectionScript(); + expect(script).toBe( + `window.__TREZOR_CONNECT_SRC = '${TREZOR_CONNECT_SRC}';`, + ); + expect(script).toContain(TREZOR_CONNECT_SRC); + }); + + it('is usable as a `; + expect(full).toContain(''); + }); +}); diff --git a/packages/hw-emulator/src/trezor/html-injector.ts b/packages/hw-emulator/src/trezor/html-injector.ts new file mode 100644 index 000000000..1f05a00b7 --- /dev/null +++ b/packages/hw-emulator/src/trezor/html-injector.ts @@ -0,0 +1,24 @@ +import { TREZOR_CONNECT_SRC } from './constants'; + +/** + * Produces a script string that sets `window.__TREZOR_CONNECT_SRC` on the + * offscreen document before the `@trezor/connect-web` bundle runs. + * + * This is the Trezor equivalent of Ledger's HTML-injection pattern: + * a build/wiring-time ``, + * ); + * writeFileSync('dist/offscreen.html', injected); + * + * @returns The JavaScript source snippet to inject. + */ +export function getTrezorConnectSrcInjectionScript(): string { + return `window.__TREZOR_CONNECT_SRC = '${TREZOR_CONNECT_SRC}';`; +} diff --git a/packages/hw-emulator/src/trezor/index.ts b/packages/hw-emulator/src/trezor/index.ts new file mode 100644 index 000000000..efa2ff44e --- /dev/null +++ b/packages/hw-emulator/src/trezor/index.ts @@ -0,0 +1,34 @@ +export { + TREZOR_EMULATOR_SEED, + TREZOR_DEFAULT_MODEL, + TREZOR_CONNECT_SRC, + TREZOR_TRANSPORT_BRIDGE_PORT, + TREZOR_CONTROLLER_PORT, + TREZOR_EMULATOR_PORT, + TREZOR_MSG, +} from './constants'; +export { MODEL_PROFILES } from './model-profiles'; +export type { + TrezorModel, + ModelProfile, + Interaction, + PressAction, +} from './model-profiles'; +export { TrezorControllerClient } from './controller-client'; +export type { + ControllerClientOptions, + ControllerResponse, + SetupParams, +} from './controller-client'; +export { createSidecarManager } from './sidecar-manager'; +export type { + SidecarManagerOptions, + TrezorSidecarManager, +} from './sidecar-manager'; +export { getTrezorConnectSrcInjectionScript } from './html-injector'; +export { TrezorDockerManager } from './docker-manager'; +export type { DockerManagerOptions, DockerRunner } from './docker-manager'; +export { TrezorDeviceInteraction } from './device-interaction'; +export type { DeviceInteraction } from './device-interaction'; +export { TrezorEmulator } from './trezor-emulator'; +export type { TrezorEmulatorOptions } from './trezor-emulator'; diff --git a/packages/hw-emulator/src/trezor/model-profiles.test.ts b/packages/hw-emulator/src/trezor/model-profiles.test.ts new file mode 100644 index 000000000..b3ac4ea36 --- /dev/null +++ b/packages/hw-emulator/src/trezor/model-profiles.test.ts @@ -0,0 +1,53 @@ +import { MODEL_PROFILES } from './model-profiles'; +import type { ModelProfile, TrezorModel } from './model-profiles'; + +const ALL_MODELS: TrezorModel[] = ['T1B1', 'T2T1', 'T3B1', 'T3T1', 'T3W1']; + +describe('MODEL_PROFILES', () => { + it('has a profile for every supported model', () => { + for (const model of ALL_MODELS) { + expect(MODEL_PROFILES[model]).toBeDefined(); + } + }); + + it('t1B1 uses physical buttons (press-yes/press-no)', () => { + expect(MODEL_PROFILES.T1B1.interaction).toBe('button'); + expect(MODEL_PROFILES.T1B1.confirm).toBe('press-yes'); + expect(MODEL_PROFILES.T1B1.reject).toBe('press-no'); + expect(MODEL_PROFILES.T1B1.layout).toBe('oled-128x64'); + }); + + it('touchscreen models use click coordinates', () => { + for (const model of ['T2T1', 'T3B1', 'T3T1', 'T3W1'] as TrezorModel[]) { + const profile = MODEL_PROFILES[model]; + expect(profile.interaction).toBe('touch'); + expect(profile.layout).toBe('touch-240x280'); + expect(typeof profile.confirm).toBe('object'); + expect( + (profile.confirm as { click: { x: number; y: number } }).click, + ).toBeDefined(); + } + }); + + it('every profile has confirm + reject actions matching its interaction paradigm', () => { + const confirmActions = ALL_MODELS.map((model) => { + const profile: ModelProfile = MODEL_PROFILES[model]; + return profile.interaction === 'button' + ? profile.confirm + : (profile.confirm as { click: unknown }).click; + }); + const rejectActions = ALL_MODELS.map((model) => { + const profile: ModelProfile = MODEL_PROFILES[model]; + return profile.interaction === 'button' + ? profile.reject + : (profile.reject as { click: unknown }).click; + }); + + for (const confirm of confirmActions) { + expect(confirm).toBeDefined(); + } + for (const reject of rejectActions) { + expect(reject).toBeDefined(); + } + }); +}); diff --git a/packages/hw-emulator/src/trezor/model-profiles.ts b/packages/hw-emulator/src/trezor/model-profiles.ts new file mode 100644 index 000000000..de5786891 --- /dev/null +++ b/packages/hw-emulator/src/trezor/model-profiles.ts @@ -0,0 +1,79 @@ +export type TrezorModel = 'T1B1' | 'T2T1' | 'T3B1' | 'T3T1' | 'T3W1'; +export type Interaction = 'button' | 'touch'; + +export type PressAction = + | 'press-yes' + | 'press-no' + | { click: { x: number; y: number } }; + +export type ModelProfile = { + model: TrezorModel; + interaction: Interaction; + layout: 'oled-128x64' | 'touch-240x280'; + confirm: PressAction; + reject: PressAction; + /** Swipe direction used to scroll through long transaction summaries. */ + scrollApproach?: 'swipe-up' | 'swipe-down'; +}; + +/** + * X coordinate of the centered confirm/reject button column on the + * 240×280 touchscreen (the screen's horizontal midpoint). + */ +const TOUCH_CONFIRM_X = 240 / 2; + +/** Y coordinate of the lower confirm button on the 240×280 touchscreen. */ +const TOUCH_CONFIRM_Y = 200; + +/** Y coordinate of the upper reject button on the 240×280 touchscreen. */ +const TOUCH_REJECT_Y = 40; + +/** + * Per-model device-interaction config. + * + * Touchscreen confirm/reject coordinates are firmware-layout-dependent. + * T2T1 (Model T) values are validated against trezor-user-env; the Safe 5 + * family (T3*) coords are best-effort and may need tuning if a firmware + * bump shifts the confirm button (see spec §12.2 R2). + */ +export const MODEL_PROFILES: Record = { + T1B1: { + model: 'T1B1', + interaction: 'button', + layout: 'oled-128x64', + confirm: 'press-yes', + reject: 'press-no', + }, + T2T1: { + model: 'T2T1', + interaction: 'touch', + layout: 'touch-240x280', + confirm: { click: { x: TOUCH_CONFIRM_X, y: TOUCH_CONFIRM_Y } }, + reject: { click: { x: TOUCH_CONFIRM_X, y: TOUCH_REJECT_Y } }, + scrollApproach: 'swipe-up', + }, + T3B1: { + model: 'T3B1', + interaction: 'touch', + layout: 'touch-240x280', + confirm: { click: { x: TOUCH_CONFIRM_X, y: TOUCH_CONFIRM_Y } }, + reject: { click: { x: TOUCH_CONFIRM_X, y: TOUCH_REJECT_Y } }, + scrollApproach: 'swipe-up', + }, + T3T1: { + model: 'T3T1', + interaction: 'touch', + layout: 'touch-240x280', + confirm: { click: { x: TOUCH_CONFIRM_X, y: TOUCH_CONFIRM_Y } }, + reject: { click: { x: TOUCH_CONFIRM_X, y: TOUCH_REJECT_Y } }, + scrollApproach: 'swipe-up', + }, + T3W1: { + model: 'T3W1', + interaction: 'touch', + layout: 'touch-240x280', + confirm: { click: { x: TOUCH_CONFIRM_X, y: TOUCH_CONFIRM_Y } }, + reject: { click: { x: TOUCH_CONFIRM_X, y: TOUCH_REJECT_Y } }, + scrollApproach: 'swipe-up', + }, +}; diff --git a/packages/hw-emulator/src/trezor/sidecar-manager.test.ts b/packages/hw-emulator/src/trezor/sidecar-manager.test.ts new file mode 100644 index 000000000..cbc52cd8d --- /dev/null +++ b/packages/hw-emulator/src/trezor/sidecar-manager.test.ts @@ -0,0 +1,285 @@ +import fs from 'node:fs/promises'; +import http from 'node:http'; +import net from 'node:net'; +import os from 'node:os'; +import path from 'node:path'; + +import { createSidecarManager } from './sidecar-manager'; + +const ASSET_SERVER_PORT = 8088; +const SECONDARY_PROXY_PORT = 21325; + +type HttpResponse = { + status: number; + body: string; +}; + +/** + * Checks whether a TCP port accepts connections on the loopback interface. + * + * @param port - The port to check. + * @returns Whether the port is open. + */ +async function isPortOpen(port: number): Promise { + return new Promise((resolve) => { + const socket = net.connect({ port, host: '127.0.0.1' }); + socket.once('connect', () => { + socket.destroy(); + resolve(true); + }); + socket.once('error', () => { + resolve(false); + }); + }); +} + +async function request( + port: number, + requestOptions: http.RequestOptions, + body?: string, +): Promise { + return new Promise((resolve, reject) => { + const req = http.request( + { host: '127.0.0.1', port, ...requestOptions }, + (res) => { + const chunks: Buffer[] = []; + res.on('data', (chunk) => { + chunks.push(chunk as Buffer); + }); + res.on('end', () => { + resolve({ + status: res.statusCode ?? 0, + body: Buffer.concat(chunks).toString('utf8'), + }); + }); + }, + ); + req.on('error', reject); + if (body !== undefined) { + req.write(body); + } + req.end(); + }); +} + +async function createAssetDir( + fileName: string, + content: string, +): Promise { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'sidecar-assets-')); + await fs.writeFile(path.join(root, fileName), content); + return root; +} + +describe('TrezorSidecarManager', () => { + let activeManager: ReturnType | null = null; + + afterEach(async () => { + const manager = activeManager; + activeManager = null; + if (manager) { + await manager.stop(); + } + }); + + it('start() serves assets, stop() closes the server', async () => { + const assetDir = await createAssetDir('iframe.html', ''); + const manager = createSidecarManager({ assetDir }); + activeManager = manager; + + await manager.start(); + expect(manager.isRunning()).toBe(true); + + const response = await request(ASSET_SERVER_PORT, { path: '/' }); + expect(response.status).toBe(200); + expect(response.body).toBe(''); + + await manager.stop(); + expect(manager.isRunning()).toBe(false); + + // After stop the port should be closed: refused, or reset if the socket + // lingers briefly (a reset surfaces as "socket hang up", so match the code). + await expect( + request(ASSET_SERVER_PORT, { path: '/' }), + ).rejects.toMatchObject({ + code: expect.stringMatching(/^ECONN(RESET|REFUSED)$/u), + }); + }, 10_000); + + it('rejects when the asset dir does not exist', async () => { + const manager = createSidecarManager({ + assetDir: '/does/not/exist', + corsProxyPort: 21348, + }); + activeManager = manager; + + await expect(manager.start()).rejects.toThrow( + 'connect-web iframe assets not found', + ); + + // A failed start() must not leave half-started servers behind: the + // manager reports stopped and no proxy port is held open. + expect(manager.isRunning()).toBe(false); + expect(await isPortOpen(21348)).toBe(false); + }); + + it('stop() also closes the secondary CORS proxy on port 21325', async () => { + const assetDir = await createAssetDir('iframe.html', ''); + const manager = createSidecarManager({ + assetDir, + corsProxyPort: 21358, + }); + activeManager = manager; + + await manager.start(); + expect(await isPortOpen(21358)).toBe(true); + expect(await isPortOpen(SECONDARY_PROXY_PORT)).toBe(true); + + await manager.stop(); + expect(await isPortOpen(21358)).toBe(false); + expect(await isPortOpen(SECONDARY_PROXY_PORT)).toBe(false); + }, 10_000); + + it('logs (does not swallow) EADDRINUSE when the secondary proxy port is taken', async () => { + const assetDir = await createAssetDir('iframe.html', ''); + + // Occupy the secondary proxy port so the manager's best-effort bind on + // 21325 fails with EADDRINUSE. + const blocker = net.createServer(); + await new Promise((resolve) => { + blocker.listen(SECONDARY_PROXY_PORT, '127.0.0.1', () => resolve()); + }); + + const warnSpy = jest + .spyOn(console, 'warn') + .mockImplementation(() => undefined); + + const manager = createSidecarManager({ + assetDir, + corsProxyPort: 21388, + }); + activeManager = manager; + + try { + await manager.start(); + + // The primary proxy is still up, so the sidecar reports running even + // though the secondary proxy could not bind. + expect(manager.isRunning()).toBe(true); + expect(warnSpy).toHaveBeenCalledWith( + expect.stringContaining('secondary CORS proxy'), + expect.anything(), + ); + } finally { + warnSpy.mockRestore(); + await new Promise((resolve) => { + blocker.close(() => resolve()); + }); + } + }, 10_000); + + it('responds 413 when a proxied request body exceeds the 10MB cap', async () => { + const assetDir = await createAssetDir('iframe.html', ''); + const manager = createSidecarManager({ + assetDir, + corsProxyPort: 21368, + }); + activeManager = manager; + + await manager.start(); + + const oversizedBody = 'a'.repeat(10 * 1024 * 1024 + 1); + const response = await request( + 21368, + { + path: '/post', + method: 'POST', + headers: { 'content-type': 'application/json' }, + }, + oversizedBody, + ); + expect(response.status).toBe(413); + expect(JSON.parse(response.body).error).toContain('exceeds'); + }, 20_000); + + it('proxies origin-form targets to the bridge and rejects URL overrides', async () => { + const assetDir = await createAssetDir('iframe.html', ''); + const upstreamHits: string[] = []; + const upstream = http.createServer((req, res) => { + upstreamHits.push(req.url ?? ''); + res.writeHead(200, { 'content-type': 'application/json' }); + res.end('{"ok":true}'); + }); + await new Promise((resolve) => { + upstream.listen(21398, '127.0.0.1', () => resolve()); + }); + const manager = createSidecarManager({ + assetDir, + corsProxyPort: 21408, + bridgeUrl: 'http://127.0.0.1:21398', + }); + activeManager = manager; + + try { + await manager.start(); + + const forwarded = await request(21408, { + path: '/bridge/ping?a=1', + method: 'GET', + }); + expect(forwarded.status).toBe(200); + expect(upstreamHits).toStrictEqual(['/bridge/ping?a=1']); + + // Absolute-form and protocol-relative targets would point the proxy at + // another origin if it resolved them; reject them instead. + for (const target of [ + 'http://example.com/steal', + '//example.com/steal', + '/\\example.com/steal', + ]) { + const response = await request(21408, { path: target, method: 'GET' }); + expect(response.status).toBe(400); + } + expect(upstreamHits).toStrictEqual(['/bridge/ping?a=1']); + } finally { + await new Promise((resolve) => { + upstream.close(() => resolve()); + }); + } + }, 15_000); + + it('blocks paths that escape the asset directory via prefix tricks', async () => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'sidecar-guard-')); + const assetDir = path.join(root, 'assets'); + // Sibling whose name extends the asset dir name, so a naive + // `startsWith(assetDir)` check would let it through after `..` removal. + const siblingDir = path.join(root, 'assets-evil'); + await fs.mkdir(assetDir); + await fs.mkdir(siblingDir); + await fs.writeFile(path.join(siblingDir, 'secret.txt'), 'secret'); + await fs.writeFile(path.join(assetDir, 'iframe.html'), ''); + + try { + const manager = createSidecarManager({ + assetDir, + corsProxyPort: 21378, + }); + activeManager = manager; + await manager.start(); + + const escaped = await request(ASSET_SERVER_PORT, { + path: '/../assets-evil/secret.txt', + }); + expect(escaped.status).toBe(403); + expect(escaped.body).toBe(''); + + // Regular files inside the asset dir still load. + const ok = await request(ASSET_SERVER_PORT, { + path: '/iframe.html', + }); + expect(ok.status).toBe(200); + } finally { + await fs.rm(root, { recursive: true, force: true }); + } + }, 10_000); +}); diff --git a/packages/hw-emulator/src/trezor/sidecar-manager.ts b/packages/hw-emulator/src/trezor/sidecar-manager.ts new file mode 100644 index 000000000..adc80c6d9 --- /dev/null +++ b/packages/hw-emulator/src/trezor/sidecar-manager.ts @@ -0,0 +1,353 @@ +// eslint-disable-next-line import-x/no-nodejs-modules +import { Buffer } from 'node:buffer'; +// eslint-disable-next-line import-x/no-nodejs-modules +import fs from 'node:fs'; +// eslint-disable-next-line import-x/no-nodejs-modules +import http from 'node:http'; +// eslint-disable-next-line import-x/no-nodejs-modules +import path from 'node:path'; +// eslint-disable-next-line import-x/no-nodejs-modules +import process from 'node:process'; + +import { TREZOR_TRANSPORT_BRIDGE_PORT } from './constants'; + +export type SidecarManagerOptions = { + assetServerPort?: number; + assetDir?: string; + corsProxyPort?: number; + bridgeUrl?: string; +}; + +export type TrezorSidecarManager = { + start(): Promise; + stop(): Promise; + isRunning(): boolean; +}; + +/** Default port for the static connect-web iframe asset server. */ +const DEFAULT_ASSET_SERVER_PORT = 8088; + +/** + * Default upstream port of the trezor-user-env bridge that the CORS proxy + * forwards to. + */ +const DEFAULT_UPSTREAM_BRIDGE_PORT = 21329; + +/** + * Port of the iframe's secondary BridgeTransport default. Proxied + * best-effort alongside the primary CORS proxy. + */ +const SECONDARY_CORS_PROXY_PORT = 21325; + +/** + * Maximum request-body size the CORS proxy buffers before rejecting with + * `413 Content Too Large` (10 MB). + */ +const MAX_PROXY_BODY_BYTES = 10 * 1024 * 1024; + +const CORS_RESPONSE_HEADERS: Record = { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'GET, POST, OPTIONS', + 'access-control-allow-headers': 'content-type', +}; + +async function closeServer(server: http.Server): Promise { + return new Promise((resolve) => { + server.close(() => { + resolve(); + }); + }); +} + +/** + * Buffer a request body, up to `maxBytes`. + * + * Drains the whole stream (discarding data once the cap is exceeded) so the + * connection stays consistent, but never buffers unbounded request bodies in + * memory. HEAD requests carry no body, so nothing is read for them. + * + * @param req - The incoming request. + * @param maxBytes - The maximum number of bytes to buffer. + * @returns The buffered body, or `null` when it exceeds `maxBytes`. + */ +async function bufferRequestBody( + req: http.IncomingMessage, + maxBytes: number, +): Promise { + // HEAD responses have no body; attempting to read one would stall the + // request until the client times out. + if (req.method === 'HEAD') { + return Buffer.alloc(0); + } + const chunks: Buffer[] = []; + let buffered = 0; + let tooLarge = false; + for await (const chunk of req) { + const data = chunk as Buffer; + if (tooLarge) { + continue; + } + chunks.push(data); + buffered += data.length; + if (buffered > maxBytes) { + tooLarge = true; + chunks.length = 0; + } + } + return tooLarge ? null : Buffer.concat(chunks); +} + +async function handleCorsRequest( + req: http.IncomingMessage, + res: http.ServerResponse, + upstreamBase: URL, +): Promise { + if (req.method === 'OPTIONS') { + res.writeHead(204, CORS_RESPONSE_HEADERS); + res.end(); + return; + } + try { + // Accept origin-form request targets only ("/path?query"). An absolute-form + // ("http://host/...") or protocol-relative ("//host/...") target must not + // be rewritten into a proxy request: fail closed instead. + const requestTarget = req.url ?? '/'; + if ( + !requestTarget.startsWith('/') || + requestTarget.startsWith('//') || + requestTarget.includes('\\') + ) { + res.writeHead(400, CORS_RESPONSE_HEADERS); + res.end(JSON.stringify({ error: 'invalid request target' })); + return; + } + const body = await bufferRequestBody(req, MAX_PROXY_BODY_BYTES); + if (body === null) { + res.writeHead(413, CORS_RESPONSE_HEADERS); + res.end( + JSON.stringify({ + error: `request body exceeds ${MAX_PROXY_BODY_BYTES} bytes`, + }), + ); + return; + } + const headers: Record = { + 'content-type': req.headers['content-type'] ?? 'application/json', + }; + // Forward Origin so the bridge's whitelist check passes + if (req.headers.origin) { + headers.origin = req.headers.origin; + } + const requestInit: RequestInit = { + method: req.method ?? 'GET', + headers, + }; + // HEAD (like GET) must not carry a body. + if (requestInit.method !== 'GET' && requestInit.method !== 'HEAD') { + requestInit.body = new Uint8Array(body); + } + const parsedIncomingUrl = new URL(requestTarget, 'http://localhost'); + let decodedPathname: string; + try { + decodedPathname = decodeURIComponent(parsedIncomingUrl.pathname); + } catch { + res.writeHead(400, CORS_RESPONSE_HEADERS); + res.end(JSON.stringify({ error: 'invalid request path encoding' })); + return; + } + const normalizedPathname = path.posix.normalize(decodedPathname); + if (!normalizedPathname.startsWith('/')) { + res.writeHead(400, CORS_RESPONSE_HEADERS); + res.end(JSON.stringify({ error: 'invalid request path' })); + return; + } + if ( + normalizedPathname === '/..' || + normalizedPathname.startsWith('/../') || + normalizedPathname.includes('/../') + ) { + res.writeHead(400, CORS_RESPONSE_HEADERS); + res.end(JSON.stringify({ error: 'path traversal is not allowed' })); + return; + } + // The upstream origin comes from the configured bridge only. Assigning the + // request path and query onto it cannot change the host, unlike resolving + // a caller-supplied string against the bridge URL. + const upstreamUrl = new URL(upstreamBase.origin); + upstreamUrl.pathname = normalizedPathname; + upstreamUrl.search = parsedIncomingUrl.search; + const upstreamResponse = await fetch(upstreamUrl, requestInit); + const responseBody = Buffer.from(await upstreamResponse.arrayBuffer()); + res.writeHead(upstreamResponse.status, { + 'content-type': + upstreamResponse.headers.get('content-type') ?? 'application/json', + ...CORS_RESPONSE_HEADERS, + }); + res.end(responseBody); + } catch (error) { + res.writeHead(502, CORS_RESPONSE_HEADERS); + res.end(JSON.stringify({ error: String((error as Error).message) })); + } +} + +async function createCorsProxy( + port: number, + upstream: string, +): Promise { + const upstreamBase = new URL(upstream); + if (upstreamBase.protocol !== 'http:' && upstreamBase.protocol !== 'https:') { + throw new TypeError( + `Unsupported bridge URL protocol: ${upstreamBase.protocol}`, + ); + } + return new Promise((resolve, reject) => { + const server = http.createServer((req, res) => { + // handleCorsRequest handles its own errors (502 responses); the + // trailing catch is a safety net for the error path itself. + handleCorsRequest(req, res, upstreamBase).catch(() => undefined); + }); + server.on('error', reject); + server.listen(port, '127.0.0.1', () => { + resolve(server); + }); + }); +} + +class SidecarManager implements TrezorSidecarManager { + readonly #assetPort: number; + + readonly #assetDir: string; + + readonly #corsProxyPort: number; + + readonly #upstreamBridge: string; + + #assetServer: http.Server | null = null; + + #corsProxy: http.Server | null = null; + + #secondaryCorsProxy: http.Server | null = null; + + constructor(opts: SidecarManagerOptions = {}) { + this.#assetPort = opts.assetServerPort ?? DEFAULT_ASSET_SERVER_PORT; + this.#assetDir = + opts.assetDir ?? + path.join(process.cwd(), 'test/e2e/trezor/iframe-assets'); + this.#corsProxyPort = opts.corsProxyPort ?? TREZOR_TRANSPORT_BRIDGE_PORT; + this.#upstreamBridge = + opts.bridgeUrl ?? `http://127.0.0.1:${DEFAULT_UPSTREAM_BRIDGE_PORT}`; + } + + async start(): Promise { + await this.stop(); + + // Validate the asset dir before binding anything so a missing dir + // cannot leave half-started listening servers behind. + if (!fs.existsSync(this.#assetDir)) { + throw new Error( + `connect-web iframe assets not found at ${this.#assetDir}`, + ); + } + const resolvedAssetDir = path.resolve(this.#assetDir); + + try { + this.#corsProxy = await createCorsProxy( + this.#corsProxyPort, + this.#upstreamBridge, + ); + // Also proxy 21325 (the iframe's secondary BridgeTransport default) + try { + this.#secondaryCorsProxy = await createCorsProxy( + SECONDARY_CORS_PROXY_PORT, + this.#upstreamBridge, + ); + } catch (error) { + // Best-effort: the port may already be in use by another instance. + // Log so the failure (e.g. EADDRINUSE) is not silent. + console.warn( + `TrezorSidecarManager: failed to start secondary CORS proxy on port ${SECONDARY_CORS_PROXY_PORT}:`, + error, + ); + } + + const assetServer = http.createServer((req, res) => { + const url = req.url === '/' ? '/iframe.html' : (req.url ?? ''); + // `path.join` normalizes `..` segments while keeping the result + // anchored at the asset dir; the resolved-prefix check then ensures + // the normalized path cannot escape it (e.g. via `/../sibling-dir/`). + const filePath = path.join(resolvedAssetDir, url); + if (!filePath.startsWith(resolvedAssetDir + path.sep)) { + res.writeHead(403); + res.end(); + return; + } + try { + const content = fs.readFileSync(filePath); + const ext = path.extname(filePath); + res.writeHead(200, { + 'content-type': + { + '.html': 'text/html', + '.js': 'application/javascript', + }[ext] ?? 'application/octet-stream', + 'access-control-allow-origin': '*', + }); + res.end(content); + } catch { + res.writeHead(404); + res.end(); + } + }); + await new Promise((resolve) => { + assetServer.listen(this.#assetPort, '127.0.0.1', () => { + resolve(); + }); + }); + this.#assetServer = assetServer; + } catch (startError: unknown) { + // A later startup step failed: tear down everything already bound + // so start() never leaves half-open servers behind. + await this.stop(); + throw startError; + } + } + + async stop(): Promise { + const staleSecondaryProxy = this.#secondaryCorsProxy; + const stalePrimaryProxy = this.#corsProxy; + const staleAssetServer = this.#assetServer; + this.#secondaryCorsProxy = null; + this.#corsProxy = null; + this.#assetServer = null; + if (staleSecondaryProxy) { + await closeServer(staleSecondaryProxy); + } + if (stalePrimaryProxy) { + await closeServer(stalePrimaryProxy); + } + if (staleAssetServer) { + await closeServer(staleAssetServer); + } + } + + isRunning(): boolean { + return ( + this.#corsProxy !== null || + this.#secondaryCorsProxy !== null || + this.#assetServer !== null + ); + } +} + +/** + * Creates a Trezor sidecar manager: a CORS proxy for the Trezor bridge and + * a static file server for the connect-web iframe assets. + * + * @param opts - Optional overrides for ports, asset directory, and bridge URL. + * @returns The sidecar manager. + */ +export function createSidecarManager( + opts: SidecarManagerOptions = {}, +): TrezorSidecarManager { + return new SidecarManager(opts); +} diff --git a/packages/hw-emulator/src/trezor/start-android-script.test.ts b/packages/hw-emulator/src/trezor/start-android-script.test.ts new file mode 100644 index 000000000..34bc83d3e --- /dev/null +++ b/packages/hw-emulator/src/trezor/start-android-script.test.ts @@ -0,0 +1,43 @@ +import fs from 'node:fs/promises'; +import path from 'node:path'; + +const scriptPath = path.join( + __dirname, + '..', + '..', + 'scripts', + 'start-android.sh', +); + +const composePath = path.join(__dirname, '..', '..', 'docker-compose.yml'); + +describe('scripts/start-android.sh', () => { + let scriptContents: string; + + beforeAll(async () => { + scriptContents = await fs.readFile(scriptPath, 'utf8'); + }); + + it('stops and removes the detached speculos container in the cleanup trap', () => { + expect(scriptContents).toContain('docker stop speculos-ledger'); + expect(scriptContents).toContain('docker rm speculos-ledger'); + }); + + it('defaults host ports to 9998 (APDU) and 5001 (API), matching docker-compose.yml and src/ledger/constants.ts', () => { + expect(scriptContents).toContain('SPECULOS_APDU_PORT:-9998'); + expect(scriptContents).toContain('SPECULOS_API_PORT:-5001'); + }); +}); + +describe('docker-compose.yml', () => { + let composeContents: string; + + beforeAll(async () => { + composeContents = await fs.readFile(composePath, 'utf8'); + }); + + it('pins the Speculos image to the bundled version instead of :latest', () => { + expect(composeContents).toContain('ghcr.io/ledgerhq/speculos:0.25.13'); + expect(composeContents).not.toContain('ghcr.io/ledgerhq/speculos:latest'); + }); +}); diff --git a/packages/hw-emulator/src/trezor/trezor-emulator.test.ts b/packages/hw-emulator/src/trezor/trezor-emulator.test.ts new file mode 100644 index 000000000..379162501 --- /dev/null +++ b/packages/hw-emulator/src/trezor/trezor-emulator.test.ts @@ -0,0 +1,151 @@ +import type { TrezorControllerClient } from './controller-client'; +import type { TrezorDockerManager } from './docker-manager'; +import type { TrezorSidecarManager } from './sidecar-manager'; +import { TrezorEmulator } from './trezor-emulator'; + +function stubOf(shape: Partial = {}): TManager { + return shape as TManager; +} + +describe('TrezorEmulator', () => { + it('start() brings up docker, controller-setup, and the sidecar in order', async () => { + const order: string[] = []; + const docker = stubOf({ + start: async () => { + order.push('docker'); + }, + stop: async () => undefined, + }); + const ctl = stubOf({ + connect: async () => { + order.push('ctl-connect'); + }, + ping: async () => { + order.push('ping'); + return {}; + }, + emulatorStart: async () => { + order.push('emu-start'); + return {}; + }, + emulatorSetup: async () => { + order.push('emu-setup'); + return {}; + }, + bridgeStart: async () => { + order.push('bridge-start'); + return {}; + }, + disconnect: async () => undefined, + pressYes: async () => ({}), + pressNo: async () => ({}), + click: async () => ({}), + swipe: async () => ({}), + input: async () => ({}), + getScreenshot: async () => Buffer.alloc(0), + }); + const sidecar = stubOf({ + start: async () => { + order.push('sidecar'); + }, + stop: async () => undefined, + isRunning: () => true, + }); + + const emu = new TrezorEmulator({ + model: 'T2T1', + docker, + controller: ctl, + sidecarManager: sidecar, + composeFile: '/tmp/x.yml', + }); + await emu.start(); + expect(order).toStrictEqual([ + 'docker', + 'ctl-connect', + 'ping', + 'emu-start', + 'emu-setup', + 'bridge-start', + 'sidecar', + ]); + }, 15_000); + + it('stops the Docker stack when the controller never becomes available', async () => { + const dockerStop = jest.fn(async () => undefined); + const docker = stubOf({ + start: async () => undefined, + stop: dockerStop, + }); + const ctl = stubOf({ + connect: async () => { + throw new Error('connection refused'); + }, + ping: async () => { + throw new Error('connection refused'); + }, + disconnect: async () => undefined, + }); + + const emu = new TrezorEmulator({ + model: 'T2T1', + docker, + controller: ctl, + sidecarManager: stubOf(), + composeFile: '/tmp/x.yml', + }); + + jest.useFakeTimers(); + try { + let caught: Error | undefined; + const startPromise = emu + .start() + .then(() => undefined) + .catch((error: Error) => { + caught = error; + }); + // Fast-forward through the 60 × 2s retry loop. + await jest.advanceTimersByTimeAsync(120_000); + await startPromise; + + expect(caught).toBeInstanceOf(Error); + expect(caught?.message).toBe('Controller not reachable within 120s'); + expect(emu.isRunning()).toBe(false); + expect(dockerStop).toHaveBeenCalledTimes(1); + } finally { + jest.useRealTimers(); + } + }); + + it('getModel returns the configured model', () => { + const emu = new TrezorEmulator({ + model: 'T1B1', + docker: stubOf(), + controller: stubOf(), + sidecarManager: stubOf(), + composeFile: '/tmp/x.yml', + }); + expect(emu.getModel()).toBe('T1B1'); + }); + + it('constructs with defaults when no mocks are injected', () => { + const emu = new TrezorEmulator({ + composeFile: '/tmp/x.yml', + }); + expect(emu.getModel()).toBe('T2T1'); + expect(emu.isRunning()).toBe(false); + }); + + it('rejects construction without composeFile when no docker manager is injected', () => { + expect(() => new TrezorEmulator({})).toThrow(/composeFile/u); + }); + + it('allows a missing composeFile when a docker manager is injected', () => { + const emu = new TrezorEmulator({ + docker: stubOf(), + controller: stubOf(), + sidecarManager: stubOf(), + }); + expect(emu.isRunning()).toBe(false); + }); +}); diff --git a/packages/hw-emulator/src/trezor/trezor-emulator.ts b/packages/hw-emulator/src/trezor/trezor-emulator.ts new file mode 100644 index 000000000..8016f7711 --- /dev/null +++ b/packages/hw-emulator/src/trezor/trezor-emulator.ts @@ -0,0 +1,245 @@ +import type { HardwareWalletEmulator } from '../types'; +import { + TREZOR_DEFAULT_MODEL, + TREZOR_EMULATOR_SEED, + TREZOR_TRANSPORT_BRIDGE_PORT, +} from './constants'; +import type { TrezorControllerClient } from './controller-client'; +import { TrezorControllerClient as RealTrezorControllerClient } from './controller-client'; +import type { DeviceInteraction } from './device-interaction'; +import { TrezorDeviceInteraction } from './device-interaction'; +import type { TrezorDockerManager } from './docker-manager'; +import { TrezorDockerManager as RealTrezorDockerManager } from './docker-manager'; +import { MODEL_PROFILES } from './model-profiles'; +import type { TrezorModel } from './model-profiles'; +import type { + SidecarManagerOptions, + TrezorSidecarManager, +} from './sidecar-manager'; +import { createSidecarManager } from './sidecar-manager'; + +/** + * Attempts to connect and ping the trezor-user-env WebSocket controller + * before giving up. Docker startup of trezor-user-env takes 30+ s, so this + * is deliberately generous. + */ +const CONTROLLER_CONNECT_MAX_ATTEMPTS = 60; + +/** Delay between controller connection attempts. */ +const CONTROLLER_CONNECT_INTERVAL_MS = 2000; + +/** Time to wait for the bridge HTTP server to bind inside the container. */ +const BRIDGE_READY_DELAY_MS = 5000; + +export type TrezorEmulatorOptions = { + model?: TrezorModel; + seed?: string; + label?: string; + /** + * Path to the trezor-user-env docker-compose.yml used by the built-in + * Docker manager. Required unless a `docker` manager is injected. + */ + composeFile?: string; + connectSrcPort?: number; + /** + * Port the iframe's BridgeTransport talks to (the sidecar's CORS proxy + * listens here). + */ + transportBridgePort?: number; + controllerPort?: number; + /** Absolute path to the connect-web iframe assets directory. */ + assetDir?: string; + // Injectable for tests; production constructs real instances: + docker?: TrezorDockerManager; + controller?: TrezorControllerClient; + sidecarManager?: TrezorSidecarManager; +}; + +export class TrezorEmulator implements HardwareWalletEmulator { + readonly #docker: TrezorDockerManager; + + readonly #controller: TrezorControllerClient; + + readonly #sidecar: TrezorSidecarManager; + + readonly #model: TrezorModel; + + readonly #seed: string; + + readonly #label: string; + + readonly #composeFile: string; + + readonly #connectSrcPort: number; + + readonly #transportBridgePort: number; + + #interaction: TrezorDeviceInteraction | null = null; + + #running = false; + + constructor(opts: TrezorEmulatorOptions) { + this.#model = opts.model ?? TREZOR_DEFAULT_MODEL; + this.#seed = opts.seed ?? TREZOR_EMULATOR_SEED; + this.#label = opts.label ?? 'MetaMask Test'; + // The compose file is only needed when constructing the real Docker + // manager below; an injected test double never reads it. + if (!opts.composeFile && !opts.docker) { + throw new Error( + 'TrezorEmulator: the composeFile option (path to the trezor-user-env docker-compose.yml) is required when no docker manager is injected.', + ); + } + this.#composeFile = opts.composeFile ?? ''; + this.#connectSrcPort = opts.connectSrcPort ?? 8088; + this.#transportBridgePort = + opts.transportBridgePort ?? TREZOR_TRANSPORT_BRIDGE_PORT; + this.#docker = + opts.docker ?? + new RealTrezorDockerManager({ composeFile: this.#composeFile }); + this.#controller = + opts.controller ?? + new RealTrezorControllerClient( + opts.controllerPort ? { port: opts.controllerPort } : {}, + ); + const sidecarOpts: SidecarManagerOptions = { + assetServerPort: this.#connectSrcPort, + corsProxyPort: this.#transportBridgePort, + }; + if (opts.assetDir) { + sidecarOpts.assetDir = opts.assetDir; + } + this.#sidecar = opts.sidecarManager ?? createSidecarManager(sidecarOpts); + } + + getModel(): TrezorModel { + return this.#model; + } + + isRunning(): boolean { + return this.#running; + } + + /** + * Get the controller client used to talk to trezor-user-env. + * + * Available before `start()`; commands fail until the controller + * WebSocket is connected, which `start()` manages. + * + * @returns The controller client. + */ + getControllerClient(): TrezorControllerClient { + return this.#controller; + } + + /** + * Get the sidecar manager (bridge CORS proxy + iframe asset server). + * + * Available before `start()`; its servers only listen after `start()`. + * + * @returns The sidecar manager. + */ + getSidecarManager(): TrezorSidecarManager { + return this.#sidecar; + } + + /** + * Get the device interaction helper for confirm/reject/scroll actions. + * + * @returns The interaction helper. + * @throws If the emulator has not been started. + */ + getInteraction(): DeviceInteraction { + if (!this.#interaction) { + throw new Error('emulator not started'); + } + return this.#interaction; + } + + /** + * Capture a screenshot of the emulated device screen. + * + * @returns The screenshot as a PNG buffer. + * @throws If the emulator has not been started (the controller connection + * is only established by `start()`). + */ + async getScreenshot(): Promise { + return this.#controller.getScreenshot(); + } + + async start(): Promise { + await this.#docker.start(); + + // Wait for the controller to become available (Docker startup takes 30+ s) + for ( + let attempt = 0; + attempt < CONTROLLER_CONNECT_MAX_ATTEMPTS; + attempt++ + ) { + try { + await this.#controller.connect(); + await this.#controller.ping(); + break; + } catch { + await this.#controller.disconnect().catch(() => undefined); + if (attempt === CONTROLLER_CONNECT_MAX_ATTEMPTS - 1) { + // Do not leave the Docker stack running when the controller + // never becomes available. + await this.#docker.stop().catch(() => undefined); + const timeoutSeconds = + (CONTROLLER_CONNECT_MAX_ATTEMPTS * CONTROLLER_CONNECT_INTERVAL_MS) / + 1000; + throw new Error(`Controller not reachable within ${timeoutSeconds}s`); + } + await new Promise((resolve) => + setTimeout(resolve, CONTROLLER_CONNECT_INTERVAL_MS), + ); + } + } + + await this.#controller.emulatorStart({ + model: this.#model, + wipe: true, + }); + await this.#controller.emulatorSetup({ + mnemonic: this.#seed, + pin: '', + passphrase_protection: false, + label: this.#label, + }); + await this.#controller.bridgeStart('node-bridge'); + // Wait for the bridge HTTP server to bind inside the container + await new Promise((resolve) => setTimeout(resolve, BRIDGE_READY_DELAY_MS)); + await this.#sidecar.start(); + this.#interaction = new TrezorDeviceInteraction( + this.#controller, + MODEL_PROFILES[this.#model], + ); + this.#running = true; + } + + async stop(): Promise { + await this.#sidecar.stop(); + await this.#controller.disconnect(); + await this.#docker.stop(); + this.#interaction = null; + this.#running = false; + } + + async approveTransaction(): Promise { + await this.getInteraction().approveTransaction(); + } + + async approveSigning(): Promise { + await this.getInteraction().approveSigning(); + } + + async rejectTransaction(): Promise { + await this.getInteraction().rejectTransaction(); + } + + async navigateToMainMenu(): Promise { + // HardwareWalletEmulator-facing name; on Trezor this dismisses a long + // transaction summary by scrolling to its end. + await this.getInteraction().dismissSummaryScreen(); + } +} diff --git a/packages/hw-emulator/src/types.ts b/packages/hw-emulator/src/types.ts new file mode 100644 index 000000000..361417e46 --- /dev/null +++ b/packages/hw-emulator/src/types.ts @@ -0,0 +1,76 @@ +/** + * Supported hardware wallet emulator types. + */ +export const EmulatorType = { + Ledger: 'ledger', + Trezor: 'trezor', + Qr: 'qr', +} as const; + +/** + * String union of supported emulator type identifiers. + */ +export type EmulatorType = (typeof EmulatorType)[keyof typeof EmulatorType]; + +/** + * Interface for interacting with an emulated hardware wallet device screen. + * Provides methods to approve, reject, and navigate through on-screen prompts. + */ +export type DeviceInteraction = { + /** + * Approve a transaction on the device screen. + */ + approveTransaction(): Promise; + /** + * Approve a signing request on the device screen. + */ + approveSigning(): Promise; + /** + * Reject a transaction on the device screen. + */ + rejectTransaction(): Promise; + /** + * Navigate back to the main menu on the device screen. + */ + navigateToMainMenu(): Promise; +}; + +/** + * Hardware wallet emulator providing lifecycle management and device interaction. + */ +export type HardwareWalletEmulator = { + /** + * Start the emulator. + */ + start(): Promise; + /** + * Stop the emulator and release all resources. + */ + stop(): Promise; + /** + * Check whether the emulator is currently running. + */ + isRunning(): boolean; + /** + * Get the device interaction handler for screen actions. + * + * @returns The device interaction instance. + */ + getInteraction(): DeviceInteraction; + /** + * Approve a transaction via the device screen. + */ + approveTransaction(): Promise; + /** + * Approve a signing request via the device screen. + */ + approveSigning(): Promise; + /** + * Reject a transaction via the device screen. + */ + rejectTransaction(): Promise; + /** + * Navigate to the main menu on the device screen. + */ + navigateToMainMenu(): Promise; +}; diff --git a/packages/hw-emulator/tests/python/conftest.py b/packages/hw-emulator/tests/python/conftest.py new file mode 100644 index 000000000..173112bda --- /dev/null +++ b/packages/hw-emulator/tests/python/conftest.py @@ -0,0 +1,100 @@ +"""Shared test fixtures and mocks.""" +from __future__ import annotations + +import sys +import types +from unittest.mock import MagicMock + +import pytest + + +def _make_bumble_mock() -> types.ModuleType: + bumble = types.ModuleType("bumble") + gatt = types.ModuleType("bumble.gatt") + device = types.ModuleType("bumble.device") + + _Props = type("Properties", (), {"WRITE": 2, "WRITE_WITHOUT_RESPONSE": 4, "READ": 1, "NOTIFY": 16}) + _Access = type("Access", (), {"WRITEABLE": 2, "READABLE": 1}) + + class _CharacteristicValue: + def __init__(self, **kw): + self._cb = kw.get("write") + + class _Characteristic: + Properties = _Props + WRITEABLE = _Access.WRITEABLE + READABLE = _Access.READABLE + + def __init__(self, uuid, props, access, value=None, **kw): + self.uuid = uuid + self.properties = props + self.access = access + self.value = value + self._handlers = {} + + def on(self, event, handler): + self._handlers[event] = handler + + class _Service: + def __init__(self, uuid, chars=None, **kw): + self.uuid = uuid + self.characteristics = chars or [] + + gatt.Characteristic = _Characteristic + gatt.CharacteristicValue = _CharacteristicValue + gatt.Service = _Service + bumble.gatt = gatt + + # Minimal bumble.device stubs so speculos_ble.device can be imported + # (VirtualLedgerDevice subclasses Device.Listener / Connection.Listener). + class _Device: + class Listener: + pass + + @staticmethod + def with_hci(**kwargs): + return _Device() + + class _Connection: + class Listener: + pass + + device.Device = _Device + device.Connection = _Connection + bumble.device = device + + # Remaining submodules imported by speculos_ble.device (only used at + # runtime in start(); stubs suffice for import + unit tests). + data_types = types.ModuleType("bumble.data_types") + core = types.ModuleType("bumble.core") + hci = types.ModuleType("bumble.hci") + pairing = types.ModuleType("bumble.pairing") + transport = types.ModuleType("bumble.transport") + + core.AdvertisingData = lambda *entries: b"" + core.UUID = lambda value: value + hci.Address = type("Address", (), {"__init__": lambda self, value: None}) + pairing.PairingConfig = type("PairingConfig", (), {}) + pairing.PairingDelegate = type( + "PairingDelegate", (), {"IoCapability": type("IoCapability", (), {"NO_OUTPUT_NO_INPUT": 0})} + ) + transport.open_transport = lambda *args, **kwargs: None + + bumble.data_types = data_types + bumble.core = core + bumble.hci = hci + bumble.pairing = pairing + bumble.transport = transport + + return bumble + + +bumble_mock = _make_bumble_mock() +sys.modules.setdefault("bumble", bumble_mock) +sys.modules.setdefault("bumble.gatt", bumble_mock.gatt) +sys.modules.setdefault("bumble.device", bumble_mock.device) +sys.modules.setdefault("bumble.data_types", bumble_mock.data_types) +sys.modules.setdefault("bumble.core", bumble_mock.core) +sys.modules.setdefault("bumble.hci", bumble_mock.hci) +sys.modules.setdefault("bumble.pairing", bumble_mock.pairing) +sys.modules.setdefault("bumble.transport", bumble_mock.transport) diff --git a/packages/hw-emulator/tests/python/test_apdu_bridge.py b/packages/hw-emulator/tests/python/test_apdu_bridge.py new file mode 100644 index 000000000..b5bcde33e --- /dev/null +++ b/packages/hw-emulator/tests/python/test_apdu_bridge.py @@ -0,0 +1,158 @@ +"""Tests for ApduBridge signing detection and error injection.""" + +import asyncio +import pytest +from unittest.mock import AsyncMock + +from speculos_ble.apdu_bridge import ApduBridge +from speculos_ble.types import SIGNING_INS_BYTES + + +class TestSigningDetection: + def test_sign_personal_message(self): + apdu = bytes([0xE0, 0x08, 0x00, 0x00, 0x04, 0x01, 0x02, 0x03, 0x04]) + assert ApduBridge._is_signing_apdu(apdu) + + def test_sign_eip712(self): + apdu = bytes([0xE0, 0x0C, 0x00, 0x00, 0x04, 0x01, 0x02, 0x03, 0x04]) + assert ApduBridge._is_signing_apdu(apdu) + + def test_sign_eip1559(self): + apdu = bytes([0xE0, 0x20, 0x00, 0x00, 0x04, 0x01, 0x02, 0x03, 0x04]) + assert ApduBridge._is_signing_apdu(apdu) + + def test_sign_eip2930(self): + apdu = bytes([0xE0, 0x22, 0x00, 0x00, 0x04, 0x01, 0x02, 0x03, 0x04]) + assert ApduBridge._is_signing_apdu(apdu) + + def test_get_public_key(self): + apdu = bytes([0xE0, 0x02, 0x00, 0x00, 0x04, 0x01, 0x02, 0x03, 0x04]) + assert ApduBridge._is_signing_apdu(apdu) + + def test_non_signing_apdu(self): + apdu = bytes([0xE0, 0x10, 0x00, 0x00, 0x00]) + assert not ApduBridge._is_signing_apdu(apdu) + + def test_too_short_apdu(self): + assert not ApduBridge._is_signing_apdu(bytes([0xE0])) + assert not ApduBridge._is_signing_apdu(b"") + + def test_all_signing_ins_bytes(self): + for ins in SIGNING_INS_BYTES: + apdu = bytes([0xE0, ins, 0x00, 0x00, 0x00]) + assert ApduBridge._is_signing_apdu(apdu), f"INS 0x{ins:02X} not detected" + + +class TestErrorInjection: + def test_inject_error(self): + bridge = ApduBridge() + bridge.inject_error(bytes([0x6D, 0x00])) + assert bridge._error_injection == bytes([0x6D, 0x00]) + + def test_error_cleared_after_use_flag(self): + bridge = ApduBridge() + bridge.inject_error(bytes([0x6D, 0x00])) + assert bridge._error_injection is not None + bridge._error_injection = None + assert bridge._error_injection is None + + +class TestApduBridgeAsync: + @pytest.mark.asyncio + async def test_handle_apdu_calls_speculos_exchange(self): + bridge = ApduBridge() + mock_response = bytes([0x90, 0x00]) + bridge._speculos.exchange = AsyncMock(return_value=mock_response) + bridge._speculos.connect = AsyncMock() + bridge._speculos.disconnect = AsyncMock() + await bridge.start() + + result = await bridge.handle_apdu(bytes([0xB0, 0x01, 0x00, 0x00, 0x00])) + assert result == mock_response + bridge._speculos.exchange.assert_called_once() + await bridge.stop() + + @pytest.mark.asyncio + async def test_signing_detected_event(self): + bridge = ApduBridge() + bridge._speculos.exchange = AsyncMock(return_value=bytes([0x90, 0x00])) + bridge._speculos.connect = AsyncMock() + bridge._speculos.disconnect = AsyncMock() + await bridge.start() + + bridge.clear_signing_flag() + assert not bridge.signing_detected.is_set() + await bridge.handle_apdu(bytes([0xE0, 0x08, 0x00, 0x00, 0x00])) + assert bridge.signing_detected.is_set() + await bridge.stop() + + @pytest.mark.asyncio + async def test_error_injection_returns_injected(self): + bridge = ApduBridge() + bridge._speculos.exchange = AsyncMock(return_value=bytes([0x90, 0x00])) + bridge._speculos.connect = AsyncMock() + bridge._speculos.disconnect = AsyncMock() + await bridge.start() + + bridge.inject_error(bytes([0x69, 0x85])) + result = await bridge.handle_apdu(bytes([0xE0, 0x08, 0x00, 0x00, 0x00])) + assert result == bytes([0x69, 0x85]) + bridge._speculos.exchange.assert_not_called() + await bridge.stop() + + @pytest.mark.asyncio + async def test_error_injection_cleared_after_use(self): + bridge = ApduBridge() + bridge._speculos.exchange = AsyncMock(return_value=bytes([0x90, 0x00])) + bridge._speculos.connect = AsyncMock() + bridge._speculos.disconnect = AsyncMock() + await bridge.start() + + bridge.inject_error(bytes([0x69, 0x85])) + r1 = await bridge.handle_apdu(bytes([0xE0, 0x08, 0x00, 0x00, 0x00])) + assert r1 == bytes([0x69, 0x85]) + assert bridge._error_injection is None + await bridge.handle_apdu(bytes([0xE0, 0x08, 0x00, 0x00, 0x00])) + bridge._speculos.exchange.assert_called_once() + await bridge.stop() + + @pytest.mark.asyncio + async def test_non_signing_apdu_does_not_set_event(self): + bridge = ApduBridge() + bridge._speculos.exchange = AsyncMock(return_value=bytes([0x90, 0x00])) + bridge._speculos.connect = AsyncMock() + bridge._speculos.disconnect = AsyncMock() + await bridge.start() + + bridge.clear_signing_flag() + await bridge.handle_apdu(bytes([0xE0, 0x10, 0x00, 0x00, 0x00])) + assert not bridge.signing_detected.is_set() + await bridge.stop() + + @pytest.mark.asyncio + async def test_error_injection_applied_to_exactly_one_concurrent_apdu(self): + """Concurrent APDUs: the injected error hits exactly one, atomically.""" + bridge = ApduBridge() + + async def slow_exchange(apdu): + await asyncio.sleep(0.05) + return bytes([0x90, 0x00]) + + bridge._speculos.exchange = AsyncMock(side_effect=slow_exchange) + bridge._speculos.connect = AsyncMock() + bridge._speculos.disconnect = AsyncMock() + await bridge.start() + + injected = bytes([0x6D, 0x00]) + bridge.inject_error(injected) + + results = await asyncio.gather( + bridge.handle_apdu(bytes([0xE0, 0x10, 0x00, 0x00, 0x00])), + bridge.handle_apdu(bytes([0xE0, 0x11, 0x00, 0x00, 0x00])), + ) + + assert results.count(injected) == 1 + assert bytes([0x90, 0x00]) in results + assert bridge._error_injection is None + bridge._speculos.exchange.assert_called_once() + await bridge.stop() diff --git a/packages/hw-emulator/tests/python/test_apdu_framing.py b/packages/hw-emulator/tests/python/test_apdu_framing.py new file mode 100644 index 000000000..3b9819aec --- /dev/null +++ b/packages/hw-emulator/tests/python/test_apdu_framing.py @@ -0,0 +1,279 @@ +"""Tests for APDU fragmentation and reassembly.""" + +import struct +import pytest + +from speculos_ble.apdu_framing import ( + MAX_APDU_SIZE, + ApduReassembler, + fragment_apdu, +) +from speculos_ble.types import BLE_TAG_ID + + +class TestFragmentApdu: + def test_single_byte_apdu(self): + chunks = fragment_apdu(bytes([0xE0]), mtu=23) + assert len(chunks) == 1 + tag, idx, total = struct.unpack_from(">BHH", chunks[0], 0) + assert tag == BLE_TAG_ID + assert idx == 0 + assert total == 1 + assert chunks[0][5:] == bytes([0xE0]) + + def test_apdu_fits_single_chunk(self): + apdu = bytes(range(15)) + chunks = fragment_apdu(apdu, mtu=23) + assert len(chunks) == 1 + header = chunks[0][:5] + tag, idx, total = struct.unpack_from(">BHH", header, 0) + assert tag == BLE_TAG_ID + assert idx == 0 + assert total == 15 + assert chunks[0][5:] == apdu + + def test_apdu_requires_two_chunks(self): + mtu = 23 + max_payload_0 = mtu - 5 # 18 bytes in first chunk + max_payload_1 = mtu - 3 # 20 bytes in subsequent chunks + apdu = bytes(range(max_payload_0 + 5)) # 23 bytes total + chunks = fragment_apdu(apdu, mtu) + + assert len(chunks) == 2 + + tag0, idx0, total0 = struct.unpack_from(">BHH", chunks[0], 0) + assert tag0 == BLE_TAG_ID + assert idx0 == 0 + assert total0 == len(apdu) + assert chunks[0][5:] == apdu[:max_payload_0] + + tag1, idx1 = struct.unpack_from(">BH", chunks[1], 0) + assert tag1 == BLE_TAG_ID + assert idx1 == 1 + assert chunks[1][3:] == apdu[max_payload_0:] + + def test_large_apdu_many_chunks(self): + mtu = 23 + apdu = bytes(range(200)) + chunks = fragment_apdu(apdu, mtu) + + reassembler = ApduReassembler() + for chunk in chunks: + result = reassembler.feed(chunk) + if result is not None: + assert result == apdu + return + pytest.fail("Should have reassembled the complete APDU") + + def test_exact_mtu_boundary(self): + mtu = 23 + apdu = bytes(range(mtu - 5)) # exactly fills first chunk + chunks = fragment_apdu(apdu, mtu) + assert len(chunks) == 1 + + def test_mtu_too_small(self): + with pytest.raises(ValueError, match="MTU too small"): + fragment_apdu(bytes([0x01]), mtu=5) + + def test_empty_apdu(self): + chunks = fragment_apdu(b"", mtu=23) + assert len(chunks) == 0 + + def test_high_mtu_single_chunk(self): + apdu = bytes(range(100)) + chunks = fragment_apdu(apdu, mtu=156) + assert len(chunks) == 1 + tag, idx, total = struct.unpack_from(">BHH", chunks[0], 0) + assert total == 100 + + def test_oversize_apdu_rejected(self): + """APDUs larger than the 16-bit total-length field are rejected.""" + apdu = b"\x00" * (MAX_APDU_SIZE + 1) + with pytest.raises(ValueError, match="too large"): + fragment_apdu(apdu, mtu=156) + + def test_max_size_apdu_fragmented_and_reassembled(self): + """An APDU of exactly 65535 bytes round-trips at the 16-bit limit.""" + apdu = b"\xAB" * MAX_APDU_SIZE + chunks = fragment_apdu(apdu, mtu=156) + assert len(chunks) > 1 + tag, idx, total = struct.unpack_from(">BHH", chunks[0], 0) + assert tag == BLE_TAG_ID + assert idx == 0 + assert total == MAX_APDU_SIZE + + reassembler = ApduReassembler() + result = None + for chunk in chunks: + result = reassembler.feed(chunk) + assert result == apdu + + +class TestApduReassembler: + def test_single_chunk_reassembly(self): + reassembler = ApduReassembler() + frame = struct.pack(">BHH", BLE_TAG_ID, 0, 3) + bytes([0xA0, 0xB0, 0xC0]) + result = reassembler.feed(frame) + assert result == bytes([0xA0, 0xB0, 0xC0]) + + def test_multi_chunk_reassembly(self): + reassembler = ApduReassembler() + mtu = 23 + apdu = bytes(range(30)) + + chunks = fragment_apdu(apdu, mtu) + results = [] + for chunk in chunks: + r = reassembler.feed(chunk) + if r is not None: + results.append(r) + + assert len(results) == 1 + assert results[0] == apdu + + def test_wrong_tag_ignored(self): + reassembler = ApduReassembler() + frame = struct.pack(">BHH", 0xFF, 0, 3) + bytes([0x01, 0x02, 0x03]) + result = reassembler.feed(frame) + assert result is None + + def test_out_of_order_chunk_resets(self): + reassembler = ApduReassembler() + chunk0 = struct.pack(">BHH", BLE_TAG_ID, 0, 10) + bytes(range(5)) + chunk2 = struct.pack(">BH", BLE_TAG_ID, 2) + bytes(range(5)) + + reassembler.feed(chunk0) + result = reassembler.feed(chunk2) + assert result is None + + def test_reset_clears_state(self): + reassembler = ApduReassembler() + frame = struct.pack(">BHH", BLE_TAG_ID, 0, 100) + bytes(range(5)) + reassembler.feed(frame) + reassembler.reset() + + short_frame = struct.pack(">BHH", BLE_TAG_ID, 0, 3) + bytes([1, 2, 3]) + result = reassembler.feed(short_frame) + assert result == bytes([1, 2, 3]) + + def test_frame_too_short(self): + reassembler = ApduReassembler() + assert reassembler.feed(bytes([0x05])) is None + assert reassembler.feed(bytes([0x05, 0x00])) is None + + def test_chunk0_data_exceeding_declared_total_rejected(self): + """Chunk 0 carrying more data than its header declares is rejected.""" + reassembler = ApduReassembler() + frame = struct.pack(">BHH", BLE_TAG_ID, 0, 2) + bytes([0x01, 0x02, 0x03]) + with pytest.raises(ValueError, match="overflow"): + reassembler.feed(frame) + + def test_subsequent_chunk_overflow_rejected(self): + """Accumulated data exceeding the declared total raises, not truncates.""" + reassembler = ApduReassembler() + chunk0 = struct.pack(">BHH", BLE_TAG_ID, 0, 5) + bytes([0x01, 0x02, 0x03]) + assert reassembler.feed(chunk0) is None + + chunk1 = struct.pack(">BH", BLE_TAG_ID, 1) + bytes([0x04, 0x05, 0x06, 0x07]) + with pytest.raises(ValueError, match="overflow"): + reassembler.feed(chunk1) + + def test_overflow_resets_reassembler_state(self): + """After an overflow rejection, a fresh APDU assembles normally.""" + reassembler = ApduReassembler() + bad_chunk = struct.pack(">BHH", BLE_TAG_ID, 0, 2) + bytes([0x01, 0x02, 0x03]) + with pytest.raises(ValueError): + reassembler.feed(bad_chunk) + + good_chunk = struct.pack(">BHH", BLE_TAG_ID, 0, 3) + bytes([0xAA, 0xBB, 0xCC]) + assert reassembler.feed(good_chunk) == bytes([0xAA, 0xBB, 0xCC]) + + def test_zero_declared_total_rejected(self): + """A chunk-0 header declaring a zero-length APDU is dropped.""" + reassembler = ApduReassembler() + frame = struct.pack(">BHH", BLE_TAG_ID, 0, 0) + assert reassembler.feed(frame) is None + + # State stays usable afterwards. + good = struct.pack(">BHH", BLE_TAG_ID, 0, 2) + bytes([0x01, 0x02]) + assert reassembler.feed(good) == bytes([0x01, 0x02]) + + def test_roundtrip_all_sizes(self): + for size in [1, 5, 18, 20, 50, 100, 200, 255]: + mtu = 23 + apdu = bytes(range(size)) + chunks = fragment_apdu(apdu, mtu) + reassembler = ApduReassembler() + result = None + for chunk in chunks: + result = reassembler.feed(chunk) + assert result == apdu, f"Roundtrip failed for size {size}" + + +class TestLedgerTransportCompatibility: + def test_getAddress_apdu_roundtrip(self): + apdu = bytes.fromhex("E002000014058000002C8000003C800000008000000000000000") + chunks = fragment_apdu(apdu, mtu=150) + assert len(chunks) == 1 + + reassembler = ApduReassembler() + result = reassembler.feed(chunks[0]) + assert result == apdu + + def test_signTransaction_large_apdu_roundtrip(self): + apdu = bytes([0xE0, 0x04, 0x00, 0x00]) + bytes(range(200)) + chunks = fragment_apdu(apdu, mtu=23) + assert len(chunks) > 1 + + reassembler = ApduReassembler() + final = None + for chunk in chunks: + final = reassembler.feed(chunk) + assert final == apdu + + def test_mtu_probe_not_mangled(self): + reassembler = ApduReassembler() + probe = bytes([0x08, 0x00, 0x00, 0x00, 0x00, 0x9C, 0x00]) + result = reassembler.feed(probe) + assert result is None + + def test_mtu_156_single_chunk_getAddress(self): + apdu = bytes.fromhex("E002000014058000002C8000003C800000008000000000000000") + chunks = fragment_apdu(apdu, mtu=156) + assert len(chunks) == 1 + tag, idx, total = struct.unpack_from(">BHH", chunks[0]) + assert tag == BLE_TAG_ID + assert idx == 0 + assert total == len(apdu) + + def test_send_format_matches_ledgerhq(self): + apdu = bytes([0xE0, 0x02, 0x00, 0x00, 0x04, 0x01, 0x02, 0x03, 0x04]) + mtu = 23 + chunks = fragment_apdu(apdu, mtu) + + assert chunks[0][0] == 0x05 + seq_idx = struct.unpack_from(">H", chunks[0], 1)[0] + assert seq_idx == 0 + total_len = struct.unpack_from(">H", chunks[0], 3)[0] + assert total_len == len(apdu) + assert chunks[0][5:] == apdu[: mtu - 5] + + if len(chunks) > 1: + assert chunks[1][0] == 0x05 + seq_idx_1 = struct.unpack_from(">H", chunks[1], 1)[0] + assert seq_idx_1 == 1 + assert chunks[1][3:] == apdu[mtu - 5 :] + + def test_receive_chunk0_header_layout(self): + reassembler = ApduReassembler() + data = bytes([0xAA, 0xBB, 0xCC]) + frame = struct.pack(">BHH", 0x05, 0, len(data)) + data + + result = reassembler.feed(frame) + assert result == data + + def test_receive_rejects_wrong_tag_like_ledgerhq(self): + reassembler = ApduReassembler() + frame = bytes([0x06, 0x00, 0x00, 0x00, 0x03, 0x01, 0x02, 0x03]) + result = reassembler.feed(frame) + assert result is None diff --git a/packages/hw-emulator/tests/python/test_control_api.py b/packages/hw-emulator/tests/python/test_control_api.py new file mode 100644 index 000000000..f556bd12b --- /dev/null +++ b/packages/hw-emulator/tests/python/test_control_api.py @@ -0,0 +1,292 @@ +"""Tests for ControlApiServer REST endpoints.""" + +from __future__ import annotations + +import asyncio + +import pytest +import pytest_asyncio +from aiohttp.test_utils import TestClient, TestServer + +from speculos_ble.control_api import ( + MAX_INJECTED_ERROR_SIZE, + ControlApiServer, +) +from speculos_ble.types import ( + MAX_BUTTON_PRESS_COUNT, + ConnectionState, +) + + +class FakeDevice: + def __init__(self): + self._state = ConnectionState.ADVERTISING + self.apdu_bridge = self._FakeBridge() + self.gatt_server = self._FakeGatt() + self._button_presses = [] + self.signing_times_out = False + self.last_signing_timeout = None + + @property + def state(self): + return self._state + + async def press_button(self, button, count=1): + self._button_presses.append((button, count)) + + async def take_screenshot(self): + return b"\x89PNG\r\n\x1a\n" + b"\x00" * 100 + + async def start_advertising(self): + pass + + async def stop_advertising(self): + pass + + async def disconnect_peer(self): + pass + + async def wait_for_signing_and_approve(self, sequence, timeout=60.0): + self.last_signing_timeout = timeout + if self.signing_times_out: + raise asyncio.TimeoutError() + self._button_presses.extend( + (step["button"], step.get("count", 1)) for step in sequence + ) + + class _FakeBridge: + is_connected = True + + def __init__(self): + self.injected = [] + + def inject_error(self, response): + self.injected.append(response) + + class _FakeGatt: + connection = None + apdu_log = [] + + +@pytest_asyncio.fixture +async def api_server(): + fake_device = FakeDevice() + server = ControlApiServer(device=fake_device, port=0) + await server.start() + yield server, fake_device + await server.stop() + + +@pytest_asyncio.fixture +async def client(api_server): + server, fake_device = api_server + tc = TestClient(TestServer(server._app)) + await tc.start_server() + tc._fake_device = fake_device + yield tc + await tc.close() + + +@pytest.mark.asyncio +async def test_health(client): + resp = await client.get("/health") + assert resp.status == 200 + body = await resp.json() + assert body["status"] == "ready" + assert "ble_state" in body + assert body["speculos_connected"] is True + + +@pytest.mark.asyncio +async def test_button_press(client): + resp = await client.post("/button/press", json={"button": "right", "count": 3}) + assert resp.status == 200 + body = await resp.json() + assert body["ok"] is True + assert ("right", 3) in client._fake_device._button_presses + + +@pytest.mark.asyncio +async def test_screenshot(client): + resp = await client.get("/screenshot") + assert resp.status == 200 + assert resp.content_type == "image/png" + data = await resp.read() + assert len(data) > 0 + + +@pytest.mark.asyncio +async def test_ble_connection(client): + resp = await client.get("/ble/connection") + assert resp.status == 200 + body = await resp.json() + assert "state" in body + assert "has_connection" in body + + +@pytest.mark.asyncio +async def test_error_inject(client): + resp = await client.post("/error/inject", json={"response": "6985"}) + assert resp.status == 200 + body = await resp.json() + assert body["ok"] is True + + +@pytest.mark.asyncio +async def test_apdu_log(client): + resp = await client.get("/debug/apdu-log") + assert resp.status == 200 + body = await resp.json() + assert isinstance(body, list) + + +@pytest.mark.asyncio +async def test_signing_auto_approve(client): + resp = await client.post( + "/signing/auto-approve", + json={ + "presses": [ + {"button": "right", "count": 2}, + {"button": "both", "count": 1}, + ], + }, + ) + assert resp.status == 200 + body = await resp.json() + assert body["ok"] is True + assert ("right", 2) in client._fake_device._button_presses + + +@pytest.mark.asyncio +async def test_advertise_start(client): + resp = await client.post("/ble/advertise/start") + assert resp.status == 200 + + +@pytest.mark.asyncio +async def test_advertise_stop(client): + resp = await client.post("/ble/advertise/stop") + assert resp.status == 200 + + +@pytest.mark.asyncio +async def test_blind_signing_enable(client): + resp = await client.post("/blind-signing/enable") + assert resp.status == 200 + body = await resp.json() + assert body["ok"] is True + + +@pytest.mark.asyncio +@pytest.mark.parametrize("button", ["left", "right", "both"]) +async def test_button_press_valid_buttons(client, button): + resp = await client.post("/button/press", json={"button": button}) + assert resp.status == 200 + assert (button, 1) in client._fake_device._button_presses + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "button", ["middle", "", "RIGHT", "up", None, 3], +) +async def test_button_press_invalid_button_returns_400(client, button): + resp = await client.post("/button/press", json={"button": button}) + assert resp.status == 400 + body = await resp.json() + assert body["ok"] is False + assert "button" in body["error"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("count", [0, -1, MAX_BUTTON_PRESS_COUNT + 1, "3", 3.5, True]) +async def test_button_press_invalid_count_returns_400(client, count): + resp = await client.post("/button/press", json={"button": "right", "count": count}) + assert resp.status == 400 + body = await resp.json() + assert body["ok"] is False + assert "count" in body["error"] + + +@pytest.mark.asyncio +async def test_button_press_count_upper_bound_accepted(client): + resp = await client.post( + "/button/press", json={"button": "right", "count": MAX_BUTTON_PRESS_COUNT} + ) + assert resp.status == 200 + assert ("right", MAX_BUTTON_PRESS_COUNT) in client._fake_device._button_presses + + +@pytest.mark.asyncio +async def test_button_press_malformed_json_returns_400(client): + resp = await client.post( + "/button/press", data=b"this is not json", headers={"Content-Type": "application/json"} + ) + assert resp.status == 400 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("response_hex", ["6985", "6D00", "00" * MAX_INJECTED_ERROR_SIZE]) +async def test_error_inject_valid_hex_accepted(client, response_hex): + resp = await client.post("/error/inject", json={"response": response_hex}) + assert resp.status == 200 + assert bytes.fromhex(response_hex) in client._fake_device.apdu_bridge.injected + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "response_hex", ["XYZ", "6E0", "", "6E 8", "00" * (MAX_INJECTED_ERROR_SIZE + 1), 1234], +) +async def test_error_inject_invalid_hex_returns_400(client, response_hex): + resp = await client.post("/error/inject", json={"response": response_hex}) + assert resp.status == 400 + body = await resp.json() + assert body["ok"] is False + + +@pytest.mark.asyncio +async def test_error_inject_empty_body_uses_default(client): + resp = await client.post("/error/inject", json={}) + assert resp.status == 200 + assert bytes.fromhex("6D00") in client._fake_device.apdu_bridge.injected + + +@pytest.mark.asyncio +async def test_signing_auto_approve_timeout_returns_504(client): + client._fake_device.signing_times_out = True + resp = await client.post("/signing/auto-approve", json={"timeout": 5}) + assert resp.status == 504 + body = await resp.json() + assert body["ok"] is False + assert "not detected" in body["error"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("timeout", [-1, 0, "60", 301, None]) +async def test_signing_auto_approve_invalid_timeout_returns_400(client, timeout): + resp = await client.post("/signing/auto-approve", json={"timeout": timeout}) + assert resp.status == 400 + + +@pytest.mark.asyncio +async def test_signing_auto_approve_timeout_forwarded(client): + resp = await client.post("/signing/auto-approve", json={"timeout": 300}) + assert resp.status == 200 + assert client._fake_device.last_signing_timeout == 300 + + +@pytest.mark.asyncio +async def test_signing_auto_approve_invalid_sequence_returns_400(client): + resp = await client.post( + "/signing/auto-approve", + json={"presses": [{"button": "middle", "count": 1}]}, + ) + assert resp.status == 400 + + +@pytest.mark.asyncio +async def test_signing_auto_approve_invalid_press_count_returns_400(client): + resp = await client.post( + "/signing/auto-approve", + json={"presses": [{"button": "right", "count": 99}]}, + ) + assert resp.status == 400 diff --git a/packages/hw-emulator/tests/python/test_device.py b/packages/hw-emulator/tests/python/test_device.py new file mode 100644 index 000000000..198dd88b3 --- /dev/null +++ b/packages/hw-emulator/tests/python/test_device.py @@ -0,0 +1,66 @@ +"""Tests for VirtualLedgerDevice (stop idempotency, input validation).""" + +from __future__ import annotations + +import asyncio + +import pytest + +from speculos_ble.device import VirtualLedgerDevice +from speculos_ble.types import ( + MAX_BUTTON_PRESS_COUNT, + ConnectionState, + VirtualLedgerConfig, + validate_button_press, +) + + +def _make_device() -> VirtualLedgerDevice: + return VirtualLedgerDevice(VirtualLedgerConfig(transport="vhci")) + + +@pytest.mark.asyncio +async def test_stop_is_idempotent(): + """stop() may be called twice (signal handler + finally) safely.""" + device = _make_device() + + await device.stop() + assert device.state == ConnectionState.IDLE + + # Second call is a no-op and must not raise or re-run teardown. + await device.stop() + assert device.state == ConnectionState.IDLE + + +@pytest.mark.asyncio +async def test_stop_is_idempotent_under_concurrency(): + """Concurrent stop() calls do not interleave teardown.""" + device = _make_device() + + await asyncio.gather(device.stop(), device.stop()) + assert device.state == ConnectionState.IDLE + + +@pytest.mark.parametrize("button,count", [("left", 1), ("right", 5), ("both", MAX_BUTTON_PRESS_COUNT)]) +def test_validate_button_press_accepts_valid(button, count): + validate_button_press(button, count) # does not raise + + +@pytest.mark.parametrize( + "button,count", + [ + ("middle", 1), + ("", 1), + (None, 1), + (3, 1), + ("right", 0), + ("right", -1), + ("right", MAX_BUTTON_PRESS_COUNT + 1), + ("right", "3"), + ("right", 3.5), + ("right", True), + ], +) +def test_validate_button_press_rejects_invalid(button, count): + with pytest.raises(ValueError): + validate_button_press(button, count) diff --git a/packages/hw-emulator/tests/python/test_gatt_server.py b/packages/hw-emulator/tests/python/test_gatt_server.py new file mode 100644 index 000000000..ec612b9d9 --- /dev/null +++ b/packages/hw-emulator/tests/python/test_gatt_server.py @@ -0,0 +1,363 @@ +"""Tests for LedgerGattServer.""" +from __future__ import annotations + +import asyncio +import struct + +import pytest + +from speculos_ble.gatt_server import LedgerGattServer +from speculos_ble.types import BLE_TAG_ID, MTU_PROBE_BYTE + + +def _chunk0(total: int, data: bytes) -> bytes: + return struct.pack(">BHH", BLE_TAG_ID, 0, total) + data + + +def _chunkn(idx: int, data: bytes) -> bytes: + return struct.pack(">BH", BLE_TAG_ID, idx) + data + + +@pytest.mark.asyncio +async def test_mtu_probe_calls_callback(): + received_probes = [] + + async def on_mtu_probe(connection, value): + received_probes.append((connection, value)) + + async def on_apdu(apdu): + return b"\x90\x00" + + server = LedgerGattServer(on_apdu=on_apdu, on_mtu_probe=on_mtu_probe) + probe_value = bytes([MTU_PROBE_BYTE, 0x00, 0x00, 0x00, 0x00, 0x17, 0x00]) + mock_connection = object() + await server._on_write(mock_connection, probe_value) + assert len(received_probes) == 1 + assert received_probes[0][1] == probe_value + + +@pytest.mark.asyncio +async def test_mtu_probe_does_not_call_on_apdu(): + called_apdu = [] + + async def on_apdu(apdu): + called_apdu.append(apdu) + return b"\x90\x00" + + server = LedgerGattServer(on_apdu=on_apdu) + probe_value = bytes([MTU_PROBE_BYTE, 0x00, 0x00, 0x00, 0x00, 0x17, 0x00]) + await server._on_write(object(), probe_value) + assert len(called_apdu) == 0 + + +@pytest.mark.asyncio +async def test_single_chunk_apdu(): + complete_apdus = [] + + async def on_apdu(apdu): + complete_apdus.append(apdu) + return b"\x90\x00" + + server = LedgerGattServer(on_apdu=on_apdu) + apdu_data = b"\xB0\x01\x00\x00\x00" + chunk = _chunk0(total=len(apdu_data), data=apdu_data) + await server._on_write(object(), chunk) + assert len(complete_apdus) == 1 + assert complete_apdus[0] == apdu_data + + +@pytest.mark.asyncio +async def test_two_chunk_apdu(): + complete_apdus = [] + + async def on_apdu(apdu): + complete_apdus.append(apdu) + return b"\x90\x00" + + server = LedgerGattServer(on_apdu=on_apdu) + data0 = bytes(range(20)) + data1 = bytes(range(20, 40)) + total_len = len(data0) + len(data1) + await server._on_write(object(), _chunk0(total_len, data0)) + assert len(complete_apdus) == 0 + await server._on_write(object(), _chunkn(1, data1)) + assert len(complete_apdus) == 1 + assert len(complete_apdus[0]) == total_len + + +@pytest.mark.asyncio +async def test_on_apdu_exception_sends_error(): + """When on_apdu raises, server sends 0x6D00 and doesn't crash.""" + + async def failing_on_apdu(apdu): + raise RuntimeError("Speculos connection lost") + + server = LedgerGattServer(on_apdu=failing_on_apdu) + chunk = _chunk0(total=5, data=b"\xB0\x01\x00\x00\x00") + await server._on_write(object(), chunk) + + +@pytest.mark.asyncio +async def test_reset_clears_reassembler(): + async def on_apdu(apdu): + return b"\x90\x00" + + server = LedgerGattServer(on_apdu=on_apdu) + data0 = bytes(range(20)) + data1 = bytes(range(20, 40)) + await server._on_write(object(), _chunk0(len(data0) + len(data1), data0)) + server.reset() + + complete_count = [] + original_on_apdu = server._on_apdu + + async def counting_on_apdu(apdu): + complete_count.append(1) + return b"\x90\x00" + + server._on_apdu = counting_on_apdu + await server._on_write(object(), _chunkn(1, bytes(range(20, 40)))) + assert len(complete_count) == 0 + + +@pytest.mark.asyncio +async def test_apdu_log_records_chunks_and_complete(): + async def on_apdu(apdu): + return b"\x90\x00" + + server = LedgerGattServer(on_apdu=on_apdu) + apdu_data = b"\xB0\x01\x00\x00\x00" + chunk = _chunk0(total=len(apdu_data), data=apdu_data) + await server._on_write(object(), chunk) + log = server.apdu_log + tags = [e.tag for e in log] + assert "chunk" in tags + assert "apdu_complete" in tags + + +@pytest.mark.asyncio +async def test_apdu_log_size_limit(): + async def on_apdu(apdu): + return b"\x90\x00" + + server = LedgerGattServer(on_apdu=on_apdu, apdu_log_size=3) + for i in range(5): + chunk = _chunk0(total=1, data=bytes([i])) + await server._on_write(object(), chunk) + assert len(server.apdu_log) <= 3 + + +@pytest.mark.asyncio +async def test_send_notification_no_subscribers(): + async def on_apdu(apdu): + return b"\x90\x00" + + server = LedgerGattServer(on_apdu=on_apdu) + await server.send_notification(b"\x90\x00") + + +@pytest.mark.asyncio +async def test_send_notification_to_no_device(): + async def on_apdu(apdu): + return b"\x90\x00" + + server = LedgerGattServer(on_apdu=on_apdu) + await server.send_notification_to(object(), b"\x90\x00") + + +@pytest.mark.asyncio +async def test_subscription_tracking(): + async def on_apdu(apdu): + return b"\x90\x00" + + server = LedgerGattServer(on_apdu=on_apdu) + + conn1 = object() + conn2 = object() + + server._on_subscription(conn1, notify_enabled=True, indicate_enabled=False) + assert conn1 in server._subscribed_connections + + server._on_subscription(conn2, notify_enabled=True, indicate_enabled=False) + assert conn2 in server._subscribed_connections + assert len(server._subscribed_connections) == 2 + + server._on_subscription(conn1, notify_enabled=False, indicate_enabled=False) + assert conn1 not in server._subscribed_connections + assert conn2 in server._subscribed_connections + + server.reset() + assert len(server._subscribed_connections) == 0 + + +@pytest.mark.asyncio +async def test_exchange_lock_serializes_apdus(): + call_order = [] + + async def slow_on_apdu(apdu): + call_order.append(f"start-{apdu[0]}") + await asyncio.sleep(0.1) + call_order.append(f"end-{apdu[0]}") + return b"\x90\x00" + + server = LedgerGattServer(on_apdu=slow_on_apdu) + + chunk1 = _chunk0(total=1, data=bytes([0x01])) + chunk2 = _chunk0(total=1, data=bytes([0x02])) + + await asyncio.gather( + server._on_write(object(), chunk1), + server._on_write(object(), chunk2), + ) + + assert call_order[0].startswith("start-") + assert call_order[1].startswith("end-") + assert call_order[2].startswith("start-") + assert call_order[3].startswith("end-") + + +def test_reset_keeps_same_exchange_lock(): + """reset() must not replace the lock a coroutine may still hold.""" + + async def on_apdu(apdu): + return b"\x90\x00" + + server = LedgerGattServer(on_apdu=on_apdu) + lock_before = server._exchange_lock + server.reset() + assert server._exchange_lock is lock_before + + +@pytest.mark.asyncio +async def test_reset_cancels_inflight_exchange(): + """An exchange in flight when reset() is called gets cancelled.""" + exchange_started = asyncio.Event() + + async def slow_on_apdu(apdu): + exchange_started.set() + await asyncio.sleep(30) + return b"\x90\x00" + + server = LedgerGattServer(on_apdu=slow_on_apdu) + + task = asyncio.ensure_future( + server._on_write(object(), _chunk0(total=1, data=bytes([0x01]))) + ) + await asyncio.wait_for(exchange_started.wait(), timeout=5) + + server.reset() + + with pytest.raises(asyncio.CancelledError): + await task + + +@pytest.mark.asyncio +async def test_reset_lets_waiting_exchange_proceed(): + """A queued writer is not orphaned when reset() runs mid-exchange.""" + first_started = asyncio.Event() + release_first = asyncio.Event() + + async def controlled_on_apdu(apdu): + if apdu[0] == 0x01: + first_started.set() + await release_first.wait() + return b"\x90\x00" + + server = LedgerGattServer(on_apdu=controlled_on_apdu) + + first = asyncio.ensure_future( + server._on_write(object(), _chunk0(total=1, data=bytes([0x01]))) + ) + second = asyncio.ensure_future( + server._on_write(object(), _chunk0(total=1, data=bytes([0x02]))) + ) + + await asyncio.wait_for(first_started.wait(), timeout=5) + server.reset() # cancels the first (in-flight) exchange + second_done, _ = await asyncio.wait({second}, timeout=5) + assert second in second_done # acquired the same, never-replaced lock + + release_first.set() + with pytest.raises(asyncio.CancelledError): + await first + + +class _OkDevice: + def __init__(self): + self.sent_chunks = [] + + async def notify_subscriber(self, connection, characteristic): + self.sent_chunks.append(characteristic.value) + + +class _FailingDevice: + def __init__(self, fail_on_call=1): + self.calls = 0 + self.fail_on_call = fail_on_call + + async def notify_subscriber(self, connection, characteristic): + self.calls += 1 + if self.calls >= self.fail_on_call: + raise RuntimeError("notify failed") + + +@pytest.mark.asyncio +async def test_send_response_success_logs_sent_after_delivery(): + async def on_apdu(apdu): + return b"\x90\x00" + + server = LedgerGattServer(on_apdu=on_apdu) + device = _OkDevice() + server.bind(device) + + response = bytes([0x30, 0x31, 0x32]) + await server._send_response(object(), response) + + tags = [e.tag for e in server.apdu_log] + assert tags[-1] == "apdu_response_sent" + assert b"".join(device.sent_chunks) == struct.pack(">BHH", 0x05, 0, 3) + response + + +@pytest.mark.asyncio +async def test_send_response_failure_propagates(): + """Notification failures are raised, not silently swallowed.""" + + async def on_apdu(apdu): + return b"\x90\x00" + + server = LedgerGattServer(on_apdu=on_apdu) + server.bind(_FailingDevice(fail_on_call=1)) + + with pytest.raises(RuntimeError, match="notify failed"): + await server._send_response(object(), b"\x90\x00") + + tags = [e.tag for e in server.apdu_log] + assert tags[-1] == "apdu_response_failed" + + +@pytest.mark.asyncio +async def test_send_response_partial_chunk_failure_propagates(): + """A failure on a later chunk still surfaces the error.""" + + async def on_apdu(apdu): + return b"\x90\x00" + + server = LedgerGattServer(on_apdu=on_apdu) + device = _FailingDevice(fail_on_call=2) + server.bind(device) + + # 30-byte response with MTU 23 → 2 chunks; second chunk fails. + with pytest.raises(RuntimeError, match="notify failed"): + await server._send_response(object(), bytes(range(30))) + assert device.calls == 2 + + +@pytest.mark.asyncio +async def test_send_response_without_device_raises(): + async def on_apdu(apdu): + return b"\x90\x00" + + server = LedgerGattServer(on_apdu=on_apdu) + + with pytest.raises(RuntimeError, match="No device bound"): + await server._send_response(object(), b"\x90\x00") diff --git a/packages/hw-emulator/tests/python/test_integration_android.py b/packages/hw-emulator/tests/python/test_integration_android.py new file mode 100644 index 000000000..2ccefbfe9 --- /dev/null +++ b/packages/hw-emulator/tests/python/test_integration_android.py @@ -0,0 +1,103 @@ +"""Integration tests — require running Speculos + speculos-ble. + +Run with: RUN_INTEGRATION_TESTS=1 pytest tests/test_integration_android.py -v +Skip otherwise (default). +""" + +from __future__ import annotations + +import os + +import aiohttp +import pytest +import pytest_asyncio + +CONTROL_API = os.environ.get("CONTROL_API_URL", "http://127.0.0.1:5002") +SPECULOS_API = os.environ.get("SPECULOS_API_URL", "http://127.0.0.1:5100") + + +def _is_integration_enabled(): + return os.environ.get("RUN_INTEGRATION_TESTS", "").lower() in ("1", "true", "yes") + + +pytestmark = pytest.mark.skipif( + not _is_integration_enabled(), + reason="Integration tests disabled. Set RUN_INTEGRATION_TESTS=1 to enable.", +) + + +@pytest_asyncio.fixture +async def http(): + async with aiohttp.ClientSession() as session: + yield session + + +@pytest.mark.asyncio +async def test_control_api_health(http): + async with http.get(f"{CONTROL_API}/health") as resp: + assert resp.status == 200 + body = await resp.json() + assert body["status"] == "ready" + + +@pytest.mark.asyncio +async def test_speculos_api_ping(http): + async with http.get(f"{SPECULOS_API}/ping") as resp: + assert resp.status == 200 + + +@pytest.mark.asyncio +async def test_button_press_and_screenshot(http): + async with http.post( + f"{CONTROL_API}/button/press", + json={"button": "right", "count": 1}, + ) as resp: + assert resp.status == 200 + + async with http.get(f"{CONTROL_API}/screenshot") as resp: + assert resp.status == 200 + data = await resp.read() + assert len(data) > 100 + assert data[:4] == b"\x89PNG" + + +@pytest.mark.asyncio +async def test_apdu_exchange_via_speculos(http): + """Send a getAppNameAndVersion APDU (B0 01 00 00 00) via Speculos HTTP API.""" + async with http.post( + f"{SPECULOS_API}/apdu", + json={"data": "B001000000"}, + ) as resp: + assert resp.status == 200 + body = await resp.json() + assert "data" in body + data = bytes.fromhex(body["data"]) + sw = (data[-2] << 8) | data[-1] + assert sw == 0x9000 + + +@pytest.mark.asyncio +async def test_ble_connection_state(http): + async with http.get(f"{CONTROL_API}/ble/connection") as resp: + assert resp.status == 200 + body = await resp.json() + assert "state" in body + + +@pytest.mark.asyncio +async def test_error_injection(http): + async with http.post( + f"{CONTROL_API}/error/inject", + json={"response": "6985"}, + ) as resp: + assert resp.status == 200 + body = await resp.json() + assert body["ok"] is True + + +@pytest.mark.asyncio +async def test_advertise_start_stop(http): + async with http.post(f"{CONTROL_API}/ble/advertise/stop") as resp: + assert resp.status == 200 + async with http.post(f"{CONTROL_API}/ble/advertise/start") as resp: + assert resp.status == 200 diff --git a/packages/hw-emulator/tests/python/test_speculos_client.py b/packages/hw-emulator/tests/python/test_speculos_client.py new file mode 100644 index 000000000..f54ec8509 --- /dev/null +++ b/packages/hw-emulator/tests/python/test_speculos_client.py @@ -0,0 +1,267 @@ +"""Tests for Speculos TCP client framing.""" + +import asyncio +import struct +import pytest + +from speculos_ble.speculos_client import ( + MAX_RESPONSE_SIZE, + SpeculosProtocolError, + SpeculosTcpClient, +) + +# Start of the IANA ephemeral port range; the reconnect test binds a fixed +# port in that range so it can rebind the same port after closing the server. +EPHEMERAL_PORT_START = 49152 + + +async def _start_echo_server(sw: bytes = b"\x90\x00"): + """Start a TCP echo server that mirrors the Speculos protocol. + + Request: [4-byte BE length] [raw APDU] + Response: [4-byte BE length covering data only] [data] [2-byte SW] + """ + + async def handle_client(reader, writer): + try: + while True: + length_data = await reader.readexactly(4) + length = struct.unpack(">I", length_data)[0] + apdu = await reader.readexactly(length) + resp_frame = struct.pack(">I", len(apdu)) + apdu + sw + writer.write(resp_frame) + await writer.drain() + except asyncio.IncompleteReadError: + pass + finally: + writer.close() + try: + await writer.wait_closed() + except Exception: + pass + + server = await asyncio.start_server(handle_client, "127.0.0.1", 0) + port = server.sockets[0].getsockname()[1] + return server, port + + +async def _start_oversize_server(declared_length: int): + """Server that replies with an oversized declared response length.""" + + async def handle_client(reader, writer): + try: + length_data = await reader.readexactly(4) + length = struct.unpack(">I", length_data)[0] + await reader.readexactly(length) + writer.write(struct.pack(">I", declared_length)) + await writer.drain() + # Wait for the client to give up and close the connection. + await reader.read() + except (asyncio.IncompleteReadError, ConnectionError): + pass + finally: + writer.close() + try: + await writer.wait_closed() + except Exception: + pass + + server = await asyncio.start_server(handle_client, "127.0.0.1", 0) + port = server.sockets[0].getsockname()[1] + return server, port + + +@pytest.mark.asyncio +async def test_exchange_simple_apdu(): + server, port = await _start_echo_server() + + client = SpeculosTcpClient("127.0.0.1", port) + try: + await client.connect() + apdu = bytes([0xE0, 0x40, 0x00, 0x00, 0x00]) + response = await client.exchange(apdu) + assert response == apdu + b"\x90\x00" + finally: + await client.disconnect() + server.close() + await server.wait_closed() + + +@pytest.mark.asyncio +async def test_exchange_with_status_word(): + """The client returns data followed by the 2-byte status word.""" + server, port = await _start_echo_server(sw=b"\x6E\x00") + + client = SpeculosTcpClient("127.0.0.1", port) + try: + await client.connect() + apdu = bytes([0xB0, 0x01, 0x00, 0x00, 0x00]) + response = await client.exchange(apdu) + assert response == apdu + b"\x6E\x00" + assert response[-2:] == b"\x6E\x00" + finally: + await client.disconnect() + server.close() + await server.wait_closed() + + +@pytest.mark.asyncio +async def test_response_length_encoding(): + """The 4-byte length prefix covers the data only, not the SW.""" + server, port = await _start_echo_server() + + client = SpeculosTcpClient("127.0.0.1", port) + try: + await client.connect() + apdu = bytes([0x01, 0x02, 0x03, 0x04]) + response = await client.exchange(apdu) + assert response == apdu + b"\x90\x00" + assert len(response) == 6 + finally: + await client.disconnect() + server.close() + await server.wait_closed() + + +@pytest.mark.asyncio +async def test_auto_connect_on_exchange(): + server, port = await _start_echo_server() + + client = SpeculosTcpClient("127.0.0.1", port) + try: + assert not client.is_connected + apdu = bytes([0xB0, 0x01, 0x00, 0x00, 0x00]) + response = await client.exchange(apdu) + assert client.is_connected + assert response == apdu + b"\x90\x00" + finally: + await client.disconnect() + server.close() + await server.wait_closed() + + +@pytest.mark.asyncio +async def test_disconnect_and_reconnect(): + server, port = await _start_echo_server() + + client = SpeculosTcpClient("127.0.0.1", port) + try: + apdu = bytes([0x01]) + await client.connect() + r1 = await client.exchange(apdu) + await client.disconnect() + assert not client.is_connected + r2 = await client.exchange(apdu) + assert client.is_connected + assert r1 == r2 == apdu + b"\x90\x00" + finally: + await client.disconnect() + server.close() + await server.wait_closed() + + +@pytest.mark.asyncio +async def test_exchange_reconnects_on_connection_drop(): + """When the TCP connection drops, the client reconnects and retries.""" + received_apdus = [] + + async def echo_handler(reader, writer): + try: + while True: + length_data = await reader.readexactly(4) + length = struct.unpack(">I", length_data)[0] + apdu = await reader.readexactly(length) + received_apdus.append(apdu) + response = struct.pack(">I", len(apdu)) + apdu + b"\x90\x00" + writer.write(response) + await writer.drain() + writer.close() + await writer.wait_closed() + break + except asyncio.IncompleteReadError: + pass + + async def create_server(port): + return await asyncio.start_server(echo_handler, "127.0.0.1", port) + + # Use a fixed port in the ephemeral range + port = EPHEMERAL_PORT_START + + server1 = await create_server(port) + client = SpeculosTcpClient("127.0.0.1", port) + try: + apdu = bytes.fromhex("B001000000") + + response1 = await client.exchange(apdu) + assert response1 == apdu + b"\x90\x00" + + server1.close() + await server1.wait_closed() + + server2 = await create_server(port) + + response2 = await client.exchange(apdu) + assert response2 == apdu + b"\x90\x00" + + assert len(received_apdus) == 2 + + server2.close() + await server2.wait_closed() + finally: + await client.disconnect() + + +@pytest.mark.asyncio +async def test_oversize_declared_length_rejected(): + """A declared response length above the 64 KiB cap raises a protocol error.""" + server, port = await _start_oversize_server(MAX_RESPONSE_SIZE + 1) + + client = SpeculosTcpClient("127.0.0.1", port) + try: + await client.connect() + with pytest.raises(SpeculosProtocolError, match="exceeds the maximum"): + await client.exchange(bytes([0xB0, 0x01, 0x00, 0x00, 0x00])) + # The connection is torn down after a protocol error. + assert not client.is_connected + finally: + await client.disconnect() + server.close() + await server.wait_closed() + + +@pytest.mark.asyncio +async def test_max_response_size_accepted(): + """A declared response length exactly at the cap is accepted.""" + payload = bytes([0xAA]) * MAX_RESPONSE_SIZE + + async def handle_client(reader, writer): + try: + while True: + length_data = await reader.readexactly(4) + length = struct.unpack(">I", length_data)[0] + await reader.readexactly(length) + writer.write( + struct.pack(">I", len(payload)) + payload + b"\x90\x00" + ) + await writer.drain() + except asyncio.IncompleteReadError: + pass + finally: + writer.close() + try: + await writer.wait_closed() + except Exception: + pass + + server = await asyncio.start_server(handle_client, "127.0.0.1", 0) + port = server.sockets[0].getsockname()[1] + + client = SpeculosTcpClient("127.0.0.1", port) + try: + await client.connect() + response = await client.exchange(bytes([0xB0, 0x01, 0x00, 0x00, 0x00])) + assert response == payload + b"\x90\x00" + finally: + await client.disconnect() + server.close() + await server.wait_closed() diff --git a/packages/hw-emulator/tsconfig.build.json b/packages/hw-emulator/tsconfig.build.json new file mode 100644 index 000000000..7fffda54d --- /dev/null +++ b/packages/hw-emulator/tsconfig.build.json @@ -0,0 +1,13 @@ +{ + "extends": "../../tsconfig.packages.build.json", + "compilerOptions": { + "baseUrl": "./", + "outDir": "dist", + "rootDir": "src", + "moduleResolution": "NodeNext", + "skipLibCheck": true, + "paths": {} + }, + "include": ["./src/**/*.ts"], + "exclude": ["./src/**/*.test.ts", "./src/**/*.test-d.ts"] +} diff --git a/packages/hw-emulator/tsconfig.json b/packages/hw-emulator/tsconfig.json new file mode 100644 index 000000000..0d2dc33a6 --- /dev/null +++ b/packages/hw-emulator/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig.packages.json", + "compilerOptions": { + "baseUrl": "./", + "moduleResolution": "NodeNext", + "skipLibCheck": true + }, + "include": ["./src"], + "exclude": ["./dist/**/*"] +} diff --git a/packages/keyring-eth-trezor/src/trezor-keyring.test.ts b/packages/keyring-eth-trezor/src/trezor-keyring.test.ts index cb4d8f466..65522aa08 100644 --- a/packages/keyring-eth-trezor/src/trezor-keyring.test.ts +++ b/packages/keyring-eth-trezor/src/trezor-keyring.test.ts @@ -93,6 +93,23 @@ describe('TrezorKeyring', function () { let keyring: TrezorKeyring; let bridge: TrezorBridge; + /** + * Restores an environment variable to its previous value after a test + * mutated it. + * + * @param name - The environment variable name. + * @param value - The value to restore (`undefined` unsets it). + */ + function restoreEnvVariable(name: string, value: string | undefined): void { + if (value === undefined) { + // eslint-disable-next-line n/no-process-env + delete process.env[name]; + } else { + // eslint-disable-next-line n/no-process-env + process.env[name] = value; + } + } + beforeEach(async function () { bridge = {} as TrezorBridge; keyring = new TrezorKeyring({ bridge }); @@ -147,6 +164,27 @@ describe('TrezorKeyring', function () { lazyLoad: true, }); }); + + it('passes lazyLoad: true regardless of the IN_TEST environment variable', async function () { + const initStub = stub().resolves(); + bridge.init = initStub; + // eslint-disable-next-line n/no-process-env + const previousValue = process.env.IN_TEST; + // eslint-disable-next-line n/no-process-env + process.env.IN_TEST = '1'; + + try { + await keyring.init(); + + expect(initStub.calledOnce).toBe(true); + assert.calledWithExactly(initStub, { + manifest: TREZOR_CONNECT_MANIFEST, + lazyLoad: true, + }); + } finally { + restoreEnvVariable('IN_TEST', previousValue); + } + }); }); describe('destroy', function () { diff --git a/packages/speculos-up/CHANGELOG.md b/packages/speculos-up/CHANGELOG.md new file mode 100644 index 000000000..120e673ce --- /dev/null +++ b/packages/speculos-up/CHANGELOG.md @@ -0,0 +1,48 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +### Added + +- Initial release of `@metamask/speculos-up` ([#560](https://github.com/MetaMask/accounts/pull/560)) + - Download and manage pre-built Speculos Ledger emulator binaries from GitHub releases + - `downloadAndInstall()` — downloads, caches, and symlinks the speculos binary + - `getSpeculosBinaryPath()` — resolves the path to the managed binary + - `isSpeculosInstalled()` — checks if the managed binary exists + - `cleanCache()` — removes cached installations + - HTTP streaming download with redirect support + - tar.gz extraction with optional SHA-256 checksum verification + - CLI entry point `mm-speculos-up` + - Add pre-packaged speculos binaries (linux-amd64 + linux-arm64) to avoid runtime downloads + - `verifyBundledChecksum()` — verify a bundled archive against `bundled/checksums.json` + - Honor `XDG_CACHE_HOME` (when absolute) when computing the default cache directory + +### Changed + +- Bump the bundled Speculos binary from `0.25.13` to `0.27.8` and update the build scripts, CI workflow, and docs to match ([#560](https://github.com/MetaMask/accounts/pull/560)) + - The release builds now start `speculos.main` through a launcher script (0.27 moved imports into `speculos/__init__.py`), bundle `backports.tarfile` for `pkg_resources`, and smoke-test the binary with `--help`. + - The `@metamask/hw-emulator` Docker image stays pinned to `0.25.13`, the newest tag published at `ghcr.io/ledgerhq/speculos`. + +- **Breaking:** Remote downloads now require HTTPS and enforce SHA-256 verification against `bundled/checksums.json`; downloads fail closed on checksum mismatch or a missing checksum entry ([#560](https://github.com/MetaMask/accounts/pull/560)) + - `checkAndDownloadBinaries()` now takes a `packageDir` argument instead of optional per-binary checksums, downloads the archive to a temporary file, verifies its checksum, and only then extracts it + - `http:` URLs and redirects that downgrade to `http:` are rejected + - Installing a version that has no entry in `checksums.json` now fails instead of downloading an unverified archive +- **Breaking:** `normalizeSystemArchitecture()` now throws for unsupported architectures (such as `arm`/`armv7l`/`ia32`) instead of falling back to `amd64` ([#560](https://github.com/MetaMask/accounts/pull/560)) +- **Breaking:** `cleanCache()` only deletes the default cache directory or paths inside it, and throws for anything else ([#560](https://github.com/MetaMask/accounts/pull/560)) + +### Fixed + +- Fix bundled archive checksum verification failing open on unreadable or malformed `checksums.json` and on missing checksum entries; verification now fails closed ([#560](https://github.com/MetaMask/accounts/pull/560)) +- Fix empty cache directories being treated as valid installations, which returned paths to a non-existent binary ([#560](https://github.com/MetaMask/accounts/pull/560)) +- Harden tar extraction: reject symlink, hardlink, and other non-regular entries, treat tar warnings as errors (`strict` mode), and abort archives whose decompressed size exceeds 1 GiB ([#560](https://github.com/MetaMask/accounts/pull/560)) +- Pin `pyinstaller` in the release build scripts for reproducible, verifiable builds ([#560](https://github.com/MetaMask/accounts/pull/560)) +- Fix package-directory resolution so bundled archives and checksum verification work in the published build, and support Node versions without `Dirent.parentPath` ([#560](https://github.com/MetaMask/accounts/pull/560)) + - Resolve `package.json` instead of the extensionless `./utils` specifier, which never resolved against the `.cjs`/`.mjs`-only `dist/` output, causing `downloadAndInstall()` to throw "Unable to resolve the speculos-up package directory" in both the CJS and ESM builds. + - Fall back to `sourceDir` in `installBinaries()` when `Dirent.parentPath` is unavailable (Node versions before 18.20/20.12). + +[Unreleased]: https://github.com/MetaMask/accounts/ diff --git a/packages/speculos-up/LICENSE b/packages/speculos-up/LICENSE new file mode 100644 index 000000000..fe29e78e0 --- /dev/null +++ b/packages/speculos-up/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 MetaMask + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/speculos-up/README.md b/packages/speculos-up/README.md new file mode 100644 index 000000000..7a7a57c28 --- /dev/null +++ b/packages/speculos-up/README.md @@ -0,0 +1,135 @@ +# `@metamask/speculos-up` + +Download and manage pre-built [Speculos](https://github.com/LedgerHQ/speculos) Ledger emulator binaries from GitHub releases. + +Inspired by [`@metamask/foundryup`](https://github.com/MetaMask/core/tree/main/packages/foundryup) — provides zero-dependency, cross-platform binary management for the Speculos hardware wallet emulator. + +## Installation + +`yarn add @metamask/speculos-up` + +or + +`npm install @metamask/speculos-up` + +## Overview + +Speculos is a Python-based Ledger device emulator. This package downloads pre-built standalone Speculos binaries (produced by PyInstaller on Linux) from GitHub releases, caches them locally, and provides a simple API for resolving the binary path at runtime. + +This avoids requiring developers to install Python, set up a virtual environment, or manage Speculos manually. + +## Usage + +### CLI + +```bash +# Download and install the default version +yarn mm-speculos-up + +# The binary is available at node_modules/.bin/speculos +``` + +### Programmatic + +```typescript +import { + getSpeculosBinaryPath, + downloadAndInstall, +} from '@metamask/speculos-up'; + +// Check if already installed +const binaryPath = getSpeculosBinaryPath(); + +// Or download explicitly +await downloadAndInstall(); +``` + +### With `@metamask/hw-emulator` + +`hw-emulator` automatically resolves the managed binary via an optional peer dependency: + +```typescript +import { createEmulator, EmulatorType } from '@metamask/hw-emulator'; + +const emulator = createEmulator(EmulatorType.Ledger, { + device: 'flex', + mode: 'native', + // No `binary` option needed — uses speculos-up's managed binary +}); + +await emulator.start(); +``` + +## API + +### `downloadAndInstall(options?)` + +Download, cache, and symlink the Speculos binary. + +Binaries are installed into the version-named directory `/speculos---` — the same directory that `getSpeculosBinaryPath()` and `isSpeculosInstalled()` check — and symlinked into `node_modules/.bin`. + +Bundled archives (shipped with this package) are used when their SHA-256 checksum verifies against `bundled/checksums.json`. Otherwise the archive is downloaded over HTTPS from the release URL and its checksum is verified against the same file before extraction. Downloads fail closed: a missing or mismatching checksum entry aborts the install instead of proceeding unverified. Throws for unsupported system architectures. + +### `getSpeculosBinaryPath(options?)` + +Returns the absolute path to the managed binary, or `null` if not installed. + +### `isSpeculosInstalled(options?)` + +Returns `true` if the managed binary exists on disk. + +### `verifyBundledChecksum(archivePath, packageDir)` + +Verifies an archive's SHA-256 checksum against a package's `bundled/checksums.json`. Returns `true`/`false` on checksum match/mismatch, and throws when the checksums file is unreadable or malformed or has no entry for the archive (fail closed). + +### `cleanCache(options?)` + +Removes cached installations. Only the default cache directory itself or paths inside it can be deleted; anything else throws. The default cache directory is `$XDG_CACHE_HOME/metamask/speculos-up` when `XDG_CACHE_HOME` is set to an absolute path, and `~/.cache/metamask/speculos-up` otherwise. + +### `SpeculosupOptions` + +| Option | Type | Default | Description | +| ---------- | -------------- | ------------------------------- | ---------------------------------- | +| `version` | string | `'0.27.8'` | Speculos version to install. | +| `repo` | string | `'MetaMask/accounts'` | GitHub repo hosting releases. | +| `cacheDir` | string | `~/.cache/metamask/speculos-up` | Custom cache directory. | +| `platform` | `Platform` | `Platform.Linux` | Target platform. | +| `arch` | `Architecture` | Auto-detected | Target architecture (amd64/arm64). | + +## How It Works + +1. Computes an HTTPS download URL for the target platform/architecture +2. Checks the version-named install directory (`~/.cache/metamask/speculos-up/speculos---/`) for existing binaries; a cached entry only counts if the binary file actually exists +3. If a bundled archive exists and its checksum verifies, extracts it directly — no network needed +4. Otherwise downloads the tar.gz over HTTPS (rejecting `http:` URLs and redirects), verifies its SHA-256 checksum against `bundled/checksums.json`, and extracts it only if the checksum matches +5. Extracts with hardened tar settings: symlinks, hardlinks, and other non-regular entries are rejected, warnings are treated as errors, and archives that decompress beyond 1 GiB are aborted +6. Symlinks (or copies) into `node_modules/.bin/speculos` + +## Requirements + +- **Linux** — native binary (pre-built via PyInstaller) +- **macOS / Windows** — use Docker mode via `@metamask/hw-emulator` instead + +## Building release binaries (maintainers) + +Release archives are **Linux ELF** binaries (`speculos-v-linux-.tar.gz`). CI builds **linux-amd64** only (see `.github/workflows/build-speculos.yml`); build **linux-arm64** locally with the Docker script below. + +On **macOS** (including Apple Silicon) or Windows, use Docker so PyInstaller runs inside Linux: + +```bash +cd packages/speculos-up + +# Both linux-amd64 and linux-arm64 (arm64 is fast on M-series; amd64 uses emulation) +./scripts/build-speculos-docker.sh 0.27.8 + +# Single architecture +./scripts/build-speculos-docker.sh 0.27.8 arm64 +``` + +Artifacts land in `packages/speculos-up/dist-build/`. Upload them to a GitHub release tagged `speculos-v` on `MetaMask/accounts`. + +On **Linux**, you can use `./scripts/build-speculos.sh` for the host architecture only, or the Docker script for both arches. + +## Contributing + +This package is part of a monorepo. Instructions for contributing can be found in the [monorepo README](https://github.com/MetaMask/accounts#readme). diff --git a/packages/speculos-up/bundled/checksums.json b/packages/speculos-up/bundled/checksums.json new file mode 100644 index 000000000..003924b73 --- /dev/null +++ b/packages/speculos-up/bundled/checksums.json @@ -0,0 +1,4 @@ +{ + "speculos-v0.27.8-linux-amd64.tar.gz": "9395238bffecdcfd9a11b7aaa2fb702b5a818debc53b41e8372698318146f1a3", + "speculos-v0.27.8-linux-arm64.tar.gz": "1424e2439b6cf2f77ccfeeeb14f75730662ee9308bd2b3f870c75b19fe3f7189" +} diff --git a/packages/speculos-up/bundled/speculos-v0.27.8-linux-amd64.tar.gz b/packages/speculos-up/bundled/speculos-v0.27.8-linux-amd64.tar.gz new file mode 100644 index 000000000..c64a37e04 Binary files /dev/null and b/packages/speculos-up/bundled/speculos-v0.27.8-linux-amd64.tar.gz differ diff --git a/packages/speculos-up/bundled/speculos-v0.27.8-linux-arm64.tar.gz b/packages/speculos-up/bundled/speculos-v0.27.8-linux-arm64.tar.gz new file mode 100644 index 000000000..8f685442d Binary files /dev/null and b/packages/speculos-up/bundled/speculos-v0.27.8-linux-arm64.tar.gz differ diff --git a/packages/speculos-up/jest.config.js b/packages/speculos-up/jest.config.js new file mode 100644 index 000000000..02fa61a3e --- /dev/null +++ b/packages/speculos-up/jest.config.js @@ -0,0 +1,20 @@ +/** @type {import('ts-jest').JestConfigWithTsJest} */ +const merge = require('deepmerge'); +const path = require('path'); +const baseConfig = require('../../jest.config.packages'); + +module.exports = merge( + baseConfig, + { + displayName: path.basename(__dirname), + // Unlike the base config, index.ts contains real (security-relevant) + // logic in this package, so its coverage is collected. + coveragePathIgnorePatterns: [], + coverageThreshold: { + global: { branches: 10, functions: 20, lines: 20, statements: 20 }, + }, + }, + // Replace base-config arrays (such as coveragePathIgnorePatterns) instead + // of concatenating them. + { arrayMerge: (_destinationArray, sourceArray) => sourceArray }, +); diff --git a/packages/speculos-up/package.json b/packages/speculos-up/package.json new file mode 100644 index 000000000..0ae3464f8 --- /dev/null +++ b/packages/speculos-up/package.json @@ -0,0 +1,95 @@ +{ + "name": "@metamask/speculos-up", + "version": "0.1.0", + "description": "Download and manage the Speculos Ledger emulator binary", + "keywords": [ + "emulator", + "hardware-wallet", + "ledger", + "metamask", + "speculos" + ], + "homepage": "https://github.com/MetaMask/accounts/tree/main/packages/speculos-up#readme", + "bugs": { + "url": "https://github.com/MetaMask/accounts/issues" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/MetaMask/accounts.git" + }, + "bin": { + "mm-speculos-up": "./dist/cli.mjs" + }, + "files": [ + "dist/", + "bundled/*.tar.gz", + "bundled/checksums.json" + ], + "sideEffects": false, + "main": "./dist/index.cjs", + "types": "./dist/index.d.cts", + "exports": { + ".": { + "import": { + "types": "./dist/index.d.mts", + "default": "./dist/index.mjs" + }, + "require": { + "types": "./dist/index.d.cts", + "default": "./dist/index.cjs" + } + }, + "./package.json": "./package.json" + }, + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + }, + "scripts": { + "build": "ts-bridge --project tsconfig.build.json --verbose --clean --no-references", + "build:all": "ts-bridge --project tsconfig.build.json --verbose --clean", + "build:clean": "yarn build --clean", + "build:docs": "typedoc", + "build:speculos:docker": "bash ./scripts/build-speculos-docker.sh", + "changelog:update": "../../scripts/update-changelog.sh @metamask/speculos-up", + "changelog:validate": "../../scripts/validate-changelog.sh @metamask/speculos-up", + "publish:preview": "yarn npm publish --tag preview", + "since-latest-release": "../../scripts/since-latest-release.sh", + "test": "yarn test:source && yarn test:types", + "test:clean": "jest --clearCache", + "test:source": "jest --reporters=jest-silent-reporter", + "test:types": "../../scripts/tsd-test.sh ./src", + "test:verbose": "jest --verbose", + "test:watch": "jest --watch" + }, + "dependencies": { + "tar": "^8.0.3" + }, + "devDependencies": { + "@lavamoat/allow-scripts": "^5.1.1", + "@lavamoat/preinstall-always-fail": "^3.0.2", + "@metamask/auto-changelog": "^7.1.0", + "@ts-bridge/cli": "^0.6.4", + "@types/jest": "^30.0.0", + "@types/node": "^26.6.11", + "deepmerge": "^4.3.1", + "depcheck": "^1.4.7", + "jest": "^30.5.2", + "jest-it-up": "^5.0.1", + "rimraf": "^6.1.4", + "ts-jest": "^29.4.15", + "ts-node": "^10.9.2", + "tsd": "^0.33.0", + "typedoc": "^0.28.20", + "typescript": "~5.9.3" + }, + "engines": { + "node": ">=22" + }, + "lavamoat": { + "allowScripts": { + "@lavamoat/preinstall-always-fail": false + } + } +} diff --git a/packages/speculos-up/scripts/build-speculos-docker.sh b/packages/speculos-up/scripts/build-speculos-docker.sh new file mode 100755 index 000000000..24ac1702a --- /dev/null +++ b/packages/speculos-up/scripts/build-speculos-docker.sh @@ -0,0 +1,202 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Build Linux Speculos release archives via Docker (macOS, Windows, or Linux hosts). +# PyInstaller cannot cross-compile: each arch runs in a matching linux/ container. +# +# Usage: ./scripts/build-speculos-docker.sh [version] [arch...] +# +# version Speculos pip version (default: 0.27.8) +# arch One or more of: amd64, arm64 (default: both) +# +# Produces in packages/speculos-up/dist-build/: +# speculos-v-linux-amd64.tar.gz +# speculos-v-linux-arm64.tar.gz + +DEFAULT_VERSION="0.27.8" +# PyInstaller is pinned to an exact version so release builds are reproducible +# and verifiable against bundled/checksums.json. speculos stays parameterized +# via VERSION by design. Bump the pin deliberately, then rebuild both +# architectures and update the bundled archives and checksums together. +PYINSTALLER_VERSION="6.14.1" +PYTHON_IMAGE="python:3.11-bookworm" +DEBIAN_IMAGE="debian:bookworm-slim" + +usage() { + cat <<'EOF' +Usage: ./scripts/build-speculos-docker.sh [version] [arch...] + +Build Linux ELF Speculos binaries with PyInstaller inside Docker. + +Arguments: + version Speculos pip version (default: 0.27.8) + arch amd64 and/or arm64 (default: both) + +Examples: + ./scripts/build-speculos-docker.sh + ./scripts/build-speculos-docker.sh 0.27.8 arm64 + ./scripts/build-speculos-docker.sh 0.27.8 amd64 arm64 + +Requires Docker. On Apple Silicon, linux/arm64 builds are fast; linux/amd64 uses emulation. +EOF +} + +if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then + usage + exit 0 +fi + +VERSION="${1:-$DEFAULT_VERSION}" +shift || true + +ARCHS=() +if [[ $# -eq 0 ]]; then + ARCHS=(amd64 arm64) +else + for arch in "$@"; do + case "${arch}" in + amd64 | arm64) + ARCHS+=("${arch}") + ;; + *) + echo "error: unknown arch '${arch}' (expected amd64 or arm64)" >&2 + exit 1 + ;; + esac + done +fi + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +DIST_DIR="${SCRIPT_DIR}/../dist-build" +mkdir -p "${DIST_DIR}" + +if ! command -v docker >/dev/null 2>&1; then + echo "error: docker is not installed or not on PATH" >&2 + exit 1 +fi + +if ! docker info >/dev/null 2>&1; then + echo "error: Docker daemon is not running" >&2 + exit 1 +fi + +docker_platform() { + case "$1" in + amd64) echo "linux/amd64" ;; + arm64) echo "linux/arm64" ;; + esac +} + +file_arch_pattern() { + case "$1" in + amd64) echo "x86-64" ;; + arm64) echo "ARM aarch64" ;; + esac +} + +build_arch() { + local arch="$1" + local platform file_arch image + platform="$(docker_platform "${arch}")" + file_arch="$(file_arch_pattern "${arch}")" + + # PyQt6 publishes pre-built wheels for x86_64 but not always aarch64. + # For arm64 use a Debian image where we install PyQt6 from system packages + # so pip never tries to build from source. + if [[ "${arch}" == "arm64" ]]; then + image="${DEBIAN_IMAGE}" + else + image="${PYTHON_IMAGE}" + fi + + echo "[build] speculos v${VERSION} linux-${arch} (${platform})" + + if [[ "${arch}" == "arm64" ]]; then + docker run --rm \ + --platform "${platform}" \ + -v "${DIST_DIR}:/out" \ + -w /out \ + -e "SPECULOS_VERSION=${VERSION}" \ + -e "TARGET_ARCH=${arch}" \ + -e "FILE_ARCH=${file_arch}" \ + -e "PYINSTALLER_VERSION=${PYINSTALLER_VERSION}" \ + "${image}" \ + bash -c ' +set -euo pipefail +export DEBIAN_FRONTEND=noninteractive +apt-get update -qq && apt-get install -qq -y --no-install-recommends \ + python3 python3-pip python3-venv python3-pyqt6 binutils file \ + libpython3.11-dev libgl1 libglib2.0-0 > /dev/null +python3 -m venv --system-site-packages /tmp/venv +source /tmp/venv/bin/activate +pip install --upgrade pip +pip install "pyinstaller==${PYINSTALLER_VERSION}" "speculos==${SPECULOS_VERSION}" --no-deps +pip install "construct>=2.10.56,<3.0.0" "flask>=2.0.0,<3.0.0" \ + "flask-restful>=0.3.9,<1.0" "flask-cors>=5.0.0,<7.0.0" \ + "jsonschema>=3.2.0,<5.0.0" "mnemonic>=0.19,<1.0" \ + "pillow>=13.0.0,<14.0.0" "pyelftools>=0.27,<1.0" \ + "requests>=2.25.1,<3.0.0" "ledgered>=0.14.0" "pygame>=2.6.1,<3.0.0" \ + backports.tarfile altgraph packaging setuptools pyinstaller-hooks-contrib +printf "from speculos.main import main\nmain()\n" > /tmp/speculos-entry.py +rm -rf build dist +mkdir -p build dist +# 0.27 moved imports into speculos/__init__.py, so it cannot be the entry script. +pyinstaller \ + --onefile \ + --name speculos \ + --distpath dist \ + --workpath build \ + --noupx \ + --collect-all speculos \ + /tmp/speculos-entry.py +file dist/speculos | tee /tmp/speculos-file.txt +grep -Fq "${FILE_ARCH}" /tmp/speculos-file.txt +./dist/speculos --help > /dev/null +ARCHIVE="/out/speculos-v${SPECULOS_VERSION}-linux-${TARGET_ARCH}.tar.gz" +tar -czf "${ARCHIVE}" -C dist speculos +ls -lh "${ARCHIVE}" +' + else + docker run --rm \ + --platform "${platform}" \ + -v "${DIST_DIR}:/out" \ + -w /out \ + -e "SPECULOS_VERSION=${VERSION}" \ + -e "TARGET_ARCH=${arch}" \ + -e "FILE_ARCH=${file_arch}" \ + -e "PYINSTALLER_VERSION=${PYINSTALLER_VERSION}" \ + "${image}" \ + bash -lc ' +set -euo pipefail +pip install --upgrade pip +pip install "pyinstaller==${PYINSTALLER_VERSION}" "speculos==${SPECULOS_VERSION}" backports.tarfile +printf "from speculos.main import main\nmain()\n" > /tmp/speculos-entry.py +rm -rf build dist +mkdir -p build dist +# 0.27 moved imports into speculos/__init__.py, so it cannot be the entry script. +pyinstaller \ + --onefile \ + --name speculos \ + --distpath dist \ + --workpath build \ + --noupx \ + --collect-all speculos \ + /tmp/speculos-entry.py +file dist/speculos | tee /tmp/speculos-file.txt +grep -Fq "${FILE_ARCH}" /tmp/speculos-file.txt +./dist/speculos --help > /dev/null +ARCHIVE="/out/speculos-v${SPECULOS_VERSION}-linux-${TARGET_ARCH}.tar.gz" +tar -czf "${ARCHIVE}" -C dist speculos +ls -lh "${ARCHIVE}" +' + fi + + echo "[build] Wrote ${DIST_DIR}/speculos-v${VERSION}-linux-${arch}.tar.gz" +} + +echo "[build] Output directory: ${DIST_DIR}" +for arch in "${ARCHS[@]}"; do + build_arch "${arch}" +done + +echo "[build] Done." diff --git a/packages/speculos-up/scripts/build-speculos.sh b/packages/speculos-up/scripts/build-speculos.sh new file mode 100755 index 000000000..186e9042a --- /dev/null +++ b/packages/speculos-up/scripts/build-speculos.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Build standalone speculos Linux binaries. +# +# On macOS (or any non-Linux host) this delegates to build-speculos-docker.sh +# so PyInstaller runs inside Linux containers for both amd64 and arm64. +# +# On Linux it builds natively for the host architecture only. +# +# Usage: ./scripts/build-speculos.sh [version] [arch...] +# +# version Speculos pip version (default: 0.27.8) +# arch amd64 and/or arm64 (macOS only; ignored on Linux) +# +# Produces in dist-build/: +# speculos-v-linux-.tar.gz + +VERSION="${1:-0.27.8}" +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" + +if [[ "$(uname -s)" != "Linux" ]]; then + echo "[build] Non-Linux host detected — delegating to Docker build" + exec "${SCRIPT_DIR}/build-speculos-docker.sh" "$@" +fi + +# --- Native Linux build (host architecture only) --- + +shift || true +if [[ $# -gt 0 ]]; then + echo "[build] Warning: arch arguments ignored on Linux (builds host arch only)" >&2 +fi + +DIST_DIR="${SCRIPT_DIR}/../dist-build" +HOST_ARCH="$(uname -m)" + +echo "[build] Building speculos v${VERSION} standalone binary (linux-${HOST_ARCH})" + +rm -rf "${DIST_DIR}" +mkdir -p "${DIST_DIR}" + +# PyInstaller is pinned to an exact version so release builds are reproducible +# and verifiable against bundled/checksums.json. speculos stays parameterized +# via VERSION by design. Bump the pin deliberately, then rebuild both +# architectures and update the bundled archives and checksums together. +PYINSTALLER_VERSION="6.14.1" + +python3 -m venv "${DIST_DIR}/venv" +source "${DIST_DIR}/venv/bin/activate" +pip install --quiet "speculos==${VERSION}" "pyinstaller==${PYINSTALLER_VERSION}" backports.tarfile + +# 0.27 moved imports into speculos/__init__.py, so it cannot be the entry script. +printf 'from speculos.main import main\nmain()\n' > "${DIST_DIR}/speculos-entry.py" + +pyinstaller \ + --onefile \ + --name speculos \ + --distpath "${DIST_DIR}" \ + --workpath "${DIST_DIR}/build" \ + --specpath "${DIST_DIR}" \ + --noupx \ + --collect-all speculos \ + "${DIST_DIR}/speculos-entry.py" + +echo "[build] Binary created at: ${DIST_DIR}/speculos" +ls -lh "${DIST_DIR}/speculos" +"${DIST_DIR}/speculos" --help > /dev/null + +TAR_NAME="speculos-v${VERSION}-linux-${HOST_ARCH}.tar.gz" +tar -czf "${DIST_DIR}/${TAR_NAME}" -C "${DIST_DIR}" speculos + +echo "[build] Archive created at: ${DIST_DIR}/${TAR_NAME}" + +deactivate diff --git a/packages/speculos-up/src/cli.ts b/packages/speculos-up/src/cli.ts new file mode 100644 index 000000000..fab629fc1 --- /dev/null +++ b/packages/speculos-up/src/cli.ts @@ -0,0 +1,11 @@ +#!/usr/bin/env node + +import { downloadAndInstall } from '.'; +import { say } from './utils'; + +downloadAndInstall().catch((error: unknown) => { + const message = error instanceof Error ? error.message : String(error); + say(`Error: ${message}`); + // eslint-disable-next-line no-restricted-globals + process.exit(1); +}); diff --git a/packages/speculos-up/src/download.test.ts b/packages/speculos-up/src/download.test.ts new file mode 100644 index 000000000..112800d4d --- /dev/null +++ b/packages/speculos-up/src/download.test.ts @@ -0,0 +1,286 @@ +import { execFile } from 'node:child_process'; +import { mkdtemp, readFile, rm } from 'node:fs/promises'; +import type { IncomingMessage } from 'node:http'; +import { createServer } from 'node:https'; +import type { Server } from 'node:https'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { assertHttpsUrl, downloadToFile, startDownload } from './download'; +import type { DownloadOptions } from './types'; + +describe('download', () => { + describe('assertHttpsUrl', () => { + it('accepts https URLs', () => { + expect(() => + assertHttpsUrl(new URL('https://github.com/example/archive.tar.gz')), + ).not.toThrow(); + }); + + it('rejects http URLs', () => { + expect(() => + assertHttpsUrl(new URL('http://github.com/example/archive.tar.gz')), + ).toThrow(/only https: URLs are allowed, got "http:"/u); + }); + + it('rejects other protocols', () => { + expect(() => + assertHttpsUrl(new URL('ftp://github.com/example/archive.tar.gz')), + ).toThrow(/got "ftp:"/u); + }); + + it('includes redirect context in the error when provided', () => { + expect(() => + assertHttpsUrl( + new URL('http://evil.example.com/archive.tar.gz'), + 'redirect target from https://github.com/example', + ), + ).toThrow(/redirect target from https:\/\/github\.com\/example/u); + }); + }); + + describe('startDownload', () => { + it('rejects http URLs without making a request', () => { + expect(() => + startDownload(new URL('http://github.com/example/archive.tar.gz')), + ).toThrow(/only https: URLs are allowed/u); + }); + + it('rejects other insecure protocols without making a request', () => { + expect(() => startDownload(new URL('file:///etc/passwd'))).toThrow( + /only https: URLs are allowed, got "file:"/u, + ); + }); + }); + + describe('downloadToFile', () => { + it('rejects http URLs without creating the destination file', async () => { + await expect( + downloadToFile( + new URL('http://github.com/example/archive.tar.gz'), + '/tmp/speculos-up-should-not-exist.tar.gz', + ), + ).rejects.toThrow(/only https: URLs are allowed/u); + }); + }); + + describe('redirect Location validation (via assertHttpsUrl)', () => { + // startDownload validates every redirect Location header with + // assertHttpsUrl before following it; a redirect that downgrades to + // http: is rejected with the same error. + it('rejects a redirect Location that downgrades to http', () => { + const redirectUrl = new URL( + '/evil.tar.gz', + new URL('https://github.com/example'), + ); + const httpRedirect = new URL( + `http://evil.example.com${redirectUrl.pathname}`, + ); + expect(() => + assertHttpsUrl( + httpRedirect, + `redirect target from ${redirectUrl.toString()}`, + ), + ).toThrow( + /Refusing to download from "http:\/\/evil\.example\.com\/evil\.tar\.gz" \(redirect target/u, + ); + }); + + it('accepts a redirect Location that stays on https', () => { + const redirectUrl = new URL( + 'https://objects.githubusercontent.com/example.tar.gz', + ); + expect(() => + assertHttpsUrl(redirectUrl, 'redirect target from https://github.com'), + ).not.toThrow(); + }); + }); + + describe('against a local HTTPS server', () => { + const archiveContent = 'archive-bytes'; + // The local test server uses a self-signed certificate; the download + // options carry `rejectUnauthorized: false` through to Node's HTTPS + // request so the handshake succeeds in tests. + const insecureTlsOptions = { + rejectUnauthorized: false, + } as unknown as DownloadOptions; + + let server: Server; + let serverUrl: string; + let certDir: string; + + const handler = ( + req: IncomingMessage, + res: import('node:http').ServerResponse, + ): void => { + if (req.url === '/archive.tar.gz') { + res.writeHead(200, { 'content-type': 'application/gzip' }); + res.end(archiveContent); + return; + } + if (req.url === '/redirect-to-archive') { + res.writeHead(302, { location: '/archive.tar.gz' }); + res.end(); + return; + } + if (req.url === '/redirect-to-http') { + const { port } = server.address() as { port: number }; + res.writeHead(302, { + location: `http://127.0.0.1:${port}/archive.tar.gz`, + }); + res.end(); + return; + } + if ((req.url ?? '').match(/^\/loop/u)) { + // Infinite redirect loop. + res.writeHead(302, { location: req.url }); + res.end(); + return; + } + res.writeHead(404); + res.end('not found'); + }; + + /** + * Collect the contents of a download stream. + * + * @param stream - The stream to read. + * @returns The concatenated stream contents. + */ + async function collectStream( + stream: AsyncIterable, + ): Promise { + let contents = ''; + for await (const chunk of stream) { + contents += chunk.toString(); + } + return contents; + } + + beforeAll(async () => { + certDir = await mkdtemp(join(tmpdir(), 'speculos-up-tls-')); + const keyPath = join(certDir, 'key.pem'); + const certPath = join(certDir, 'cert.pem'); + await new Promise((resolve, reject) => { + execFile( + 'openssl', + [ + 'req', + '-x509', + '-newkey', + 'rsa:2048', + '-keyout', + keyPath, + '-out', + certPath, + '-days', + '1', + '-nodes', + '-subj', + '/CN=localhost', + ], + (error: Error | null) => { + if (error) { + reject(error); + return; + } + resolve(); + }, + ); + }); + server = createServer( + { key: await readFile(keyPath), cert: await readFile(certPath) }, + handler, + ); + await new Promise((resolve) => { + server.listen(0, '127.0.0.1', () => { + resolve(); + }); + }); + const address = server.address(); + if (address === null || typeof address === 'string') { + throw new Error('Expected the test server to listen on a port.'); + } + serverUrl = `https://127.0.0.1:${String(address.port)}`; + }, 15000); + + afterAll(async () => { + await new Promise((resolve, reject) => { + server.close((error) => { + if (error) { + reject(error); + return; + } + resolve(); + }); + }); + await rm(certDir, { recursive: true, force: true }); + }); + + it('streams a successful response', async () => { + const stream = startDownload( + new URL(`${serverUrl}/archive.tar.gz`), + insecureTlsOptions, + ); + const response = await stream.response(); + expect(response.statusCode).toBe(200); + expect(await collectStream(stream)).toBe(archiveContent); + }, 10000); + + it('follows https redirects', async () => { + const stream = startDownload( + new URL(`${serverUrl}/redirect-to-archive`), + insecureTlsOptions, + ); + expect(await collectStream(stream)).toBe(archiveContent); + }, 10000); + + it('rejects a redirect Location that downgrades to http', async () => { + const stream = startDownload( + new URL(`${serverUrl}/redirect-to-http`), + insecureTlsOptions, + ); + await expect(collectStream(stream)).rejects.toThrow( + /only https: URLs are allowed/u, + ); + }, 10000); + + it('errors on non-2xx status codes', async () => { + const stream = startDownload( + new URL(`${serverUrl}/missing`), + insecureTlsOptions, + ); + await expect(collectStream(stream)).rejects.toThrow( + /failed\. Status Code: 404/u, + ); + }, 10000); + + it('errors when too many redirects are followed', async () => { + const stream = startDownload(new URL(`${serverUrl}/loop-1`), { + ...insecureTlsOptions, + maxRedirects: 1, + }); + await expect(collectStream(stream)).rejects.toThrow( + /Too many redirects/u, + ); + }, 10000); + + it('errors when the connection fails', async () => { + const stream = startDownload( + new URL('https://127.0.0.1:1/archive.tar.gz'), + insecureTlsOptions, + ); + await expect(collectStream(stream)).rejects.toThrow(/ECONNREFUSED/u); + }, 10000); + + it('downloads a URL to a file', async () => { + const destinationPath = join(certDir, 'downloaded.tar.gz'); + await downloadToFile( + new URL(`${serverUrl}/archive.tar.gz`), + destinationPath, + insecureTlsOptions, + ); + expect(await readFile(destinationPath, 'utf8')).toBe(archiveContent); + }, 10000); + }); +}); diff --git a/packages/speculos-up/src/download.ts b/packages/speculos-up/src/download.ts new file mode 100644 index 000000000..1bf4a1f09 --- /dev/null +++ b/packages/speculos-up/src/download.ts @@ -0,0 +1,152 @@ +// eslint-disable-next-line import-x/no-nodejs-modules +import { createWriteStream } from 'node:fs'; +// eslint-disable-next-line import-x/no-nodejs-modules +import { request as httpRequest } from 'node:http'; +// eslint-disable-next-line import-x/no-nodejs-modules +import type { IncomingMessage } from 'node:http'; +// eslint-disable-next-line import-x/no-nodejs-modules +import { request as httpsRequest } from 'node:https'; +// eslint-disable-next-line import-x/no-nodejs-modules +import { Stream } from 'node:stream'; +// eslint-disable-next-line import-x/no-nodejs-modules +import { pipeline } from 'node:stream/promises'; + +import type { DownloadOptions } from './types'; + +/** + * A PassThrough stream that emits a 'response' event when the HTTP(S) response is available. + */ +class DownloadStream extends Stream.PassThrough { + /** + * Returns a promise that resolves with the HTTP(S) IncomingMessage response. + * + * @returns The HTTP(S) response stream. + */ + async response(): Promise { + return new Promise((resolve, reject) => { + this.once('response', resolve); + this.once('error', reject); + }); + } +} + +/** + * Assert that a URL uses HTTPS. + * + * Downloads (including redirect targets) must use HTTPS so that archive + * contents and checksums cannot be tampered with in transit. + * + * @param url - The URL to check. + * @param context - Optional context describing where the URL came from, used + * in the error message. + * @throws If the URL does not use the `https:` protocol. + */ +export function assertHttpsUrl(url: URL, context?: string): void { + if (url.protocol !== 'https:') { + const origin = context ? ` (${context})` : ''; + throw new Error( + `Refusing to download from "${url.toString()}"${origin}: only https: URLs are allowed, got "${url.protocol}".`, + ); + } +} + +/** + * Start a download from the given URL. + * + * @param url - The HTTPS URL to download from. + * @param options - Download options. + * @param redirects - Current redirect count. + * @returns A stream of the download. + * @throws If the URL does not use the `https:` protocol. + */ +export function startDownload( + url: URL, + options: DownloadOptions = {}, + redirects: number = 0, +): DownloadStream { + assertHttpsUrl(url); + const MAX_REDIRECTS = options.maxRedirects ?? 5; + const request = url.protocol === 'http:' ? httpRequest : httpsRequest; + const stream = new DownloadStream(); + request(url.toString(), options, (response) => { + stream.once('close', () => { + response.destroy(); + }); + + const { statusCode, statusMessage, headers } = response; + if ( + statusCode && + statusCode >= 300 && + statusCode < 400 && + headers.location + ) { + if (redirects >= MAX_REDIRECTS) { + stream.emit('error', new Error('Too many redirects')); + response.destroy(); + return; + } + + let redirectUrl: URL; + try { + redirectUrl = new URL(headers.location, url); + assertHttpsUrl(redirectUrl, `redirect target from ${url.toString()}`); + } catch (error) { + stream.emit( + 'error', + error instanceof Error ? error : new Error(String(error)), + ); + response.destroy(); + return; + } + + pipeline( + startDownload(redirectUrl, options, redirects + 1).once( + 'response', + stream.emit.bind(stream, 'response'), + ), + stream, + ).catch(stream.emit.bind(stream, 'error')); + response.destroy(); + return; + } + + if (!statusCode || statusCode < 200 || statusCode >= 300) { + stream.emit( + 'error', + new Error( + `Request to ${url.toString()} failed. Status Code: ${statusCode} - ${statusMessage}`, + ), + ); + response.destroy(); + return; + } + + stream.emit('response', response); + response.once('error', stream.emit.bind(stream, 'error')); + pipeline(response, stream).catch(stream.emit.bind(stream, 'error')); + }) + .once('error', stream.emit.bind(stream, 'error')) + .end(); + return stream; +} + +/** + * Download a URL to a file on disk. + * + * @param url - The HTTPS URL to download from. + * @param destinationPath - The path of the file to write. + * @param options - Download options. + * @throws If the URL does not use the `https:` protocol, or if the download + * or write fails. + */ +export async function downloadToFile( + url: URL, + destinationPath: string, + options: DownloadOptions = {}, +): Promise { + assertHttpsUrl(url); + await pipeline( + startDownload(url, options), + createWriteStream(destinationPath), + ); +} diff --git a/packages/speculos-up/src/extract.test.ts b/packages/speculos-up/src/extract.test.ts new file mode 100644 index 000000000..48478713b --- /dev/null +++ b/packages/speculos-up/src/extract.test.ts @@ -0,0 +1,169 @@ +import { + mkdtemp, + readFile, + rm, + stat, + symlink, + link, + writeFile, +} from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { create as createTarArchive } from 'tar'; + +import { extractFromLocal } from './extract'; +import { Binary } from './types'; + +/** + * Create a temp directory for test fixtures. + * + * @param name - A name fragment for the directory. + * @returns The temp directory path. + */ +async function makeTempDir(name: string): Promise { + return mkdtemp(join(tmpdir(), `speculos-up-${name}-`)); +} + +/** + * Create a directory containing a speculos payload file and pack it into a + * tar.gz archive. + * + * @param archivePath - The path of the tar.gz archive to create. + * @param contents - The contents of the speculos file. + * @returns The source directory that was packed. + */ +async function packSpeculosArchive( + archivePath: string, + contents: string | Buffer, +): Promise { + const sourceDir = await makeTempDir('archive-src'); + await writeFile(join(sourceDir, Binary.Speculos), contents, { + mode: 0o755, + }); + await createTarArchive({ cwd: sourceDir, file: archivePath, gzip: true }, [ + '.', + ]); + return sourceDir; +} + +describe('extract', () => { + let tempDir: string; + + beforeAll(async () => { + tempDir = await makeTempDir('extract'); + }); + + afterAll(async () => { + await rm(tempDir, { recursive: true, force: true }); + }); + + describe('extractFromLocal', () => { + it('extracts a valid archive', async () => { + const archivePath = join(tempDir, 'valid.tar.gz'); + await packSpeculosArchive(archivePath, 'speculos-payload'); + const destination = join(tempDir, 'valid-dest'); + + const paths = await extractFromLocal( + archivePath, + [Binary.Speculos], + destination, + ); + + expect(paths).toStrictEqual([join(destination, Binary.Speculos)]); + expect(await readFile(join(destination, Binary.Speculos), 'utf8')).toBe( + 'speculos-payload', + ); + }, 10000); + + it('rejects archives containing a symlink entry', async () => { + const sourceDir = await makeTempDir('symlink-src'); + await writeFile(join(sourceDir, Binary.Speculos), 'payload', { + mode: 0o755, + }); + await symlink(Binary.Speculos, join(sourceDir, 'speculos-link')); + const archivePath = join(tempDir, 'symlink.tar.gz'); + await createTarArchive( + { cwd: sourceDir, file: archivePath, gzip: true }, + ['.'], + ); + const destination = join(tempDir, 'symlink-dest'); + + await expect( + extractFromLocal(archivePath, [Binary.Speculos], destination), + ).rejects.toThrow( + /Refusing to extract unsafe archive entry .*SymbolicLink/u, + ); + + // The temporary extraction directory must be cleaned up on failure. + await expect(stat(`${destination}.extracting`)).rejects.toThrow( + /ENOENT/u, + ); + await expect(stat(destination)).rejects.toThrow(/ENOENT/u); + }, 10000); + + it('rejects archives containing a hardlink entry', async () => { + const sourceDir = await makeTempDir('hardlink-src'); + await writeFile(join(sourceDir, Binary.Speculos), 'payload', { + mode: 0o755, + }); + await link( + join(sourceDir, Binary.Speculos), + join(sourceDir, 'speculos-hardlink'), + ); + const archivePath = join(tempDir, 'hardlink.tar.gz'); + await createTarArchive( + { cwd: sourceDir, file: archivePath, gzip: true }, + ['.'], + ); + const destination = join(tempDir, 'hardlink-dest'); + + await expect( + extractFromLocal(archivePath, [Binary.Speculos], destination), + ).rejects.toThrow(/Refusing to extract unsafe archive entry .*Link/u); + }, 10000); + + it('aborts archives that decompress beyond the configured size cap', async () => { + const archivePath = join(tempDir, 'oversized.tar.gz'); + // Highly compressible content: tiny on disk, large when decompressed. + await packSpeculosArchive(archivePath, Buffer.alloc(64 * 1024, 0x61)); + const destination = join(tempDir, 'oversized-dest'); + + await expect( + extractFromLocal(archivePath, [Binary.Speculos], destination, { + maxDecompressedBytes: 1024, + }), + ).rejects.toThrow(/exceeds the allowed maximum/u); + + await expect(stat(destination)).rejects.toThrow(/ENOENT/u); + }, 10000); + + it('rejects archives that are not gzip-compressed', async () => { + const sourceDir = await makeTempDir('plain-src'); + await writeFile(join(sourceDir, Binary.Speculos), 'payload'); + const archivePath = join(tempDir, 'plain.tar'); + // Deliberately create a plain (non-gzipped) tar archive. + await createTarArchive({ cwd: sourceDir, file: archivePath }, ['.']); + const destination = join(tempDir, 'plain-dest'); + + await expect( + extractFromLocal(archivePath, [Binary.Speculos], destination), + ).rejects.toThrow(/incorrect header check/u); + }, 10000); + + it('creates the destination directory even if the parent does not exist', async () => { + const archivePath = join(tempDir, 'nested.tar.gz'); + await packSpeculosArchive(archivePath, 'nested-payload'); + const destination = join(tempDir, 'nested', 'parent', 'dest'); + + const paths = await extractFromLocal( + archivePath, + [Binary.Speculos], + destination, + ); + + expect(paths).toStrictEqual([join(destination, Binary.Speculos)]); + const extractedStat = await stat(join(destination, Binary.Speculos)); + expect(extractedStat.isFile()).toBe(true); + }, 10000); + }); +}); diff --git a/packages/speculos-up/src/extract.ts b/packages/speculos-up/src/extract.ts new file mode 100644 index 000000000..1672d0239 --- /dev/null +++ b/packages/speculos-up/src/extract.ts @@ -0,0 +1,189 @@ +// eslint-disable-next-line import-x/no-nodejs-modules +import { createReadStream } from 'node:fs'; +// eslint-disable-next-line import-x/no-nodejs-modules +import { mkdir, rm, rename, stat } from 'node:fs/promises'; +// eslint-disable-next-line import-x/no-nodejs-modules +import { join } from 'node:path'; +// eslint-disable-next-line import-x/no-nodejs-modules +import type { Readable } from 'node:stream'; +// eslint-disable-next-line import-x/no-nodejs-modules +import { createGunzip } from 'node:zlib'; +import { extract as extractTar } from 'tar'; +import type { ReadEntry } from 'tar'; + +import type { Binary } from './types'; +import { CLEANUP_MAX_RETRIES, say } from './utils'; + +/** + * Default maximum decompressed size of an archive (1 GiB). Archives that + * decompress to more than this are aborted to protect against decompression + * bombs. + */ +export const DEFAULT_MAX_DECOMPRESSED_ARCHIVE_BYTES = 1024 * 1024 * 1024; // 1 GiB + +/** + * Options for extracting a local archive. + */ +export type ExtractOptions = { + /** + * Maximum decompressed size of the archive, in bytes. Extraction aborts + * with an error if the decompressed tar stream exceeds this size. + */ + maxDecompressedBytes?: number; +}; + +/** + * A tar entry that was rejected by the extraction filter. + */ +type UnsafeTarEntry = { + path: string; + type: string; +}; + +/** + * Check whether a tar entry type may be extracted. + * + * Only regular files and directories are allowed. Symlinks, hardlinks, + * device nodes, FIFOs, and anything else are rejected so a malicious archive + * cannot plant links or special files on disk. + * + * @param entryType - The tar entry type name. + * @returns True if the entry type is allowed. + */ +function isAllowedTarEntryType(entryType: string): boolean { + return [ + 'File', + 'OldFile', + 'ContiguousFile', + 'Directory', + 'GNUDumpDir', + ].includes(entryType); +} + +/** + * Extract a tar.gz stream into a directory, with hardened tar options: + * + * - `strict: true`, so tar warnings raise errors instead of being ignored. + * - An `onwarn` hook that turns any remaining warning into an error. + * - A filter that rejects symlink, hardlink, and other non-regular entries. + * - A decompressed-size cap that aborts extraction of oversized archives. + * + * @param source - The (compressed) archive stream. + * @param destinationDir - The directory to extract into. + * @param maxDecompressedBytes - The maximum allowed decompressed size. + * @throws If the archive is not valid gzip, exceeds the decompressed-size + * cap, contains unsafe entries, or tar reports warnings/errors. + */ +async function extractTarGzArchive( + source: Readable, + destinationDir: string, + maxDecompressedBytes: number, +): Promise { + let decompressedBytes = 0; + + const gunzip = createGunzip(); + // Forward source read errors into the gunzip stream so iteration rejects. + source.on('error', (error) => gunzip.destroy(error)); + source.pipe(gunzip); + + const decompressedChunks = (async function* (): AsyncGenerator { + try { + for await (const chunk of gunzip) { + decompressedBytes += chunk.length; + if (decompressedBytes > maxDecompressedBytes) { + throw new Error( + `Archive decompressed size exceeds the allowed maximum of ${maxDecompressedBytes} bytes.`, + ); + } + yield chunk; + } + } finally { + gunzip.destroy(); + source.destroy(); + } + })(); + + const unsafeEntries: UnsafeTarEntry[] = []; + await extractTar({ + cwd: destinationDir, + input: decompressedChunks, + strict: true, + onwarn: (code, message) => { + throw new Error(`tar extraction warning (${code}): ${message}`); + }, + filter: (entryPath: string, entry: ReadEntry): boolean => { + if (!isAllowedTarEntryType(entry.type)) { + unsafeEntries.push({ path: entryPath, type: entry.type }); + return false; + } + return true; + }, + }); + + const firstUnsafeEntry = unsafeEntries[0]; + if (firstUnsafeEntry !== undefined) { + throw new Error( + `Refusing to extract unsafe archive entry "${firstUnsafeEntry.path}" of type "${firstUnsafeEntry.type}": only regular files and directories are allowed.`, + ); + } +} + +/** + * Extract the speculos binary from a local tar.gz archive. + * + * @param archivePath - The absolute path to the tar.gz archive. + * @param binaries - The binaries to extract. + * @param dir - The destination directory. + * @param options - Extraction options. + * @returns The list of extracted binary paths. + * @throws If extraction fails, the archive contains unsafe entries, or the + * archive exceeds the decompressed-size cap. + */ +export async function extractFromLocal( + archivePath: string, + binaries: Binary[], + dir: string, + options: ExtractOptions = {}, +): Promise { + const tempDir = `${dir}.extracting`; + const rmOpts = { + recursive: true, + maxRetries: CLEANUP_MAX_RETRIES, + force: true, + }; + try { + await rm(tempDir, rmOpts); + await mkdir(tempDir, { recursive: true }); + + say('extracting bundled archive'); + await extractTarGzArchive( + createReadStream(archivePath), + tempDir, + options.maxDecompressedBytes ?? DEFAULT_MAX_DECOMPRESSED_ARCHIVE_BYTES, + ); + + const paths: string[] = []; + for (const binary of binaries) { + const extractedPath = join(tempDir, binary); + await stat(extractedPath); + paths.push(join(dir, binary)); + } + + await rm(dir, rmOpts); + await rename(tempDir, dir); + return paths; + } catch (error) { + const rmErrors = ( + await Promise.allSettled([rm(tempDir, rmOpts), rm(dir, rmOpts)]) + ) + .filter((result) => result.status === 'rejected') + .map((result) => result.reason); + + if (rmErrors.length) { + throw new Error( + `Extraction failed and cleanup also failed: ${rmErrors.map((reason) => (reason instanceof Error ? reason.message : String(reason))).join(', ')}`, + ); + } + throw error; + } +} diff --git a/packages/speculos-up/src/index.test.ts b/packages/speculos-up/src/index.test.ts new file mode 100644 index 000000000..27fa641cd --- /dev/null +++ b/packages/speculos-up/src/index.test.ts @@ -0,0 +1,582 @@ +import type { Dir } from 'node:fs'; +import { + copyFile, + mkdir, + mkdtemp, + opendir, + readFile, + readdir, + rm, + stat, + writeFile, +} from 'node:fs/promises'; +import { createRequire } from 'node:module'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { dirname } from 'node:path'; +import { create as createTarArchive } from 'tar'; + +import { + checkAndDownloadBinaries, + checkAndExtractLocalBinaries, + cleanCache, + downloadAndInstall, + getInstallDir, + getSpeculosBinaryPath, + installBinaries, + verifyBundledChecksum, +} from '.'; +import { downloadToFile } from './download'; +import { Binary } from './types'; +import { computeFileSha256 } from './utils'; +import * as utils from './utils'; + +jest.mock('./download', () => ({ + downloadToFile: jest.fn(), +})); + +const ARCHIVE_NAME = 'speculos-v0.27.8-linux-amd64.tar.gz'; + +/** + * Create a temp directory for test fixtures. + * + * @param name - A name fragment for the directory. + * @returns The temp directory path. + */ +async function makeTempDir(name: string): Promise { + return mkdtemp(join(tmpdir(), `speculos-up-${name}-`)); +} + +/** + * Create a package-like fixture directory with bundled/checksums.json. + * + * @param checksumsPath - The directory in which to create the fixture. + * @param checksums - The checksums map to write, or a raw malformed string. + */ +async function writeChecksumsFile( + checksumsPath: string, + checksums: Record | string, +): Promise { + await mkdir(join(checksumsPath, 'bundled'), { recursive: true }); + const contents = + typeof checksums === 'string' + ? checksums + : `${JSON.stringify(checksums, null, 2)}\n`; + await writeFile(join(checksumsPath, 'bundled', 'checksums.json'), contents); +} + +/** + * Create a tar.gz fixture containing a speculos payload file. + * + * @param archivePath - The path of the archive to create. + * @param payload - The payload contents, defaults to an executable script. + * @returns The SHA-256 checksum of the created archive. + */ +async function createArchiveFixture( + archivePath: string, + payload: string | Buffer = '#!/bin/sh\necho "speculos version"\n', +): Promise { + const sourceDir = await makeTempDir('fixture-src'); + try { + await writeFile(join(sourceDir, Binary.Speculos), payload, { + mode: 0o755, + }); + await mkdir(dirname(archivePath), { recursive: true }); + await createTarArchive({ cwd: sourceDir, file: archivePath, gzip: true }, [ + '.', + ]); + } finally { + await rm(sourceDir, { recursive: true, force: true }); + } + return computeFileSha256(archivePath); +} + +/** + * Read the entries of a directory handle and close it. + * + * @param dir - The directory handle. + * @returns The entry names. + */ +async function readDirEntries(dir: Dir): Promise { + const entries: string[] = []; + for await (const entry of dir) { + entries.push(entry.name); + } + return entries; +} + +describe('index security paths', () => { + let tempDir: string; + + beforeAll(async () => { + tempDir = await makeTempDir('index'); + }); + + afterAll(async () => { + await rm(tempDir, { recursive: true, force: true }); + }); + + describe('verifyBundledChecksum', () => { + it('returns true when the checksum matches', async () => { + const packageDir = join(tempDir, 'verify-ok'); + const archivePath = join(packageDir, 'bundled', ARCHIVE_NAME); + const checksum = await createArchiveFixture(archivePath); + await writeChecksumsFile(packageDir, { [ARCHIVE_NAME]: checksum }); + + expect(await verifyBundledChecksum(archivePath, packageDir)).toBe(true); + }); + + it('returns false when the checksum does not match', async () => { + const packageDir = join(tempDir, 'verify-mismatch'); + const archivePath = join(packageDir, 'bundled', ARCHIVE_NAME); + await createArchiveFixture(archivePath); + await writeChecksumsFile(packageDir, { + [ARCHIVE_NAME]: 'deadbeef', + }); + + expect(await verifyBundledChecksum(archivePath, packageDir)).toBe(false); + }); + + it('throws when no checksum is recorded for the archive', async () => { + const packageDir = join(tempDir, 'verify-missing-entry'); + const archivePath = join(packageDir, 'bundled', ARCHIVE_NAME); + await createArchiveFixture(archivePath); + await writeChecksumsFile(packageDir, { + 'some-other-archive.tar.gz': 'abc123', + }); + + await expect( + verifyBundledChecksum(archivePath, packageDir), + ).rejects.toThrow(/No checksum recorded/u); + }); + + it('throws when checksums.json is malformed', async () => { + const packageDir = join(tempDir, 'verify-malformed'); + const archivePath = join(packageDir, 'bundled', ARCHIVE_NAME); + await createArchiveFixture(archivePath); + await writeChecksumsFile(packageDir, '{ not valid json'); + + await expect( + verifyBundledChecksum(archivePath, packageDir), + ).rejects.toThrow(/not valid JSON/u); + }); + + it('throws when checksums.json is unreadable', async () => { + const packageDir = join(tempDir, 'verify-unreadable'); + const archivePath = join(packageDir, 'bundled', ARCHIVE_NAME); + await createArchiveFixture(archivePath); + // No checksums.json written at all. + + await expect( + verifyBundledChecksum(archivePath, packageDir), + ).rejects.toThrow(/Unable to read checksums file/u); + }); + + it('throws when checksums.json is not an object', async () => { + const packageDir = join(tempDir, 'verify-not-object'); + const archivePath = join(packageDir, 'bundled', ARCHIVE_NAME); + await createArchiveFixture(archivePath); + await writeChecksumsFile(packageDir, '["not", "an", "object"]'); + + await expect( + verifyBundledChecksum(archivePath, packageDir), + ).rejects.toThrow(/must contain a JSON object/u); + }); + }); + + describe('checkAndDownloadBinaries', () => { + const mockedDownloadToFile = jest.mocked(downloadToFile); + const downloadUrl = new URL( + `https://github.com/MetaMask/accounts/releases/download/speculos-v0.27.8/${ARCHIVE_NAME}`, + ); + + let packageDir: string; + let archivePath: string; + let cachePath: string; + let archiveChecksum: string; + + beforeEach(async () => { + packageDir = join( + tempDir, + `download-pkg-${Date.now()}-${Math.random().toString(36).slice(2)}`, + ); + await mkdir(join(packageDir, 'bundled'), { recursive: true }); + archivePath = join(packageDir, 'bundled', ARCHIVE_NAME); + archiveChecksum = await createArchiveFixture(archivePath); + await writeChecksumsFile(packageDir, { [ARCHIVE_NAME]: archiveChecksum }); + cachePath = join( + tempDir, + `download-cache-${Math.random().toString(36).slice(2)}`, + ); + mockedDownloadToFile.mockReset(); + }); + + it('downloads, verifies, and extracts when not cached', async () => { + const sourceArchive = archivePath; + mockedDownloadToFile.mockImplementation(async (_url, destination) => { + await copyFile(sourceArchive, destination); + }); + + const dir = await checkAndDownloadBinaries( + downloadUrl, + cachePath, + packageDir, + ); + const entries = await readDirEntries(dir); + + expect(mockedDownloadToFile).toHaveBeenCalledTimes(1); + expect(mockedDownloadToFile).toHaveBeenCalledWith( + downloadUrl, + `${cachePath}.download.tar.gz`, + ); + expect(entries).toContain(Binary.Speculos); + // The temporary downloaded archive must be removed. + await expect(stat(`${cachePath}.download.tar.gz`)).rejects.toThrow( + /ENOENT/u, + ); + }); + + it('rejects a downloaded archive whose checksum does not match', async () => { + await writeChecksumsFile(packageDir, { + [ARCHIVE_NAME]: 'deadbeef', + }); + mockedDownloadToFile.mockImplementation(async (_url, destination) => { + await copyFile(archivePath, destination); + }); + + await expect( + checkAndDownloadBinaries(downloadUrl, cachePath, packageDir), + ).rejects.toThrow(/Checksum mismatch for downloaded archive/u); + + // Nothing may be left behind: no temp archive, no cache directory. + await expect(stat(`${cachePath}.download.tar.gz`)).rejects.toThrow( + /ENOENT/u, + ); + await expect(stat(cachePath)).rejects.toThrow(/ENOENT/u); + }); + + it('refuses to download when no checksum is recorded for the archive', async () => { + await writeChecksumsFile(packageDir, { + 'another-archive.tar.gz': 'abc123', + }); + + await expect( + checkAndDownloadBinaries(downloadUrl, cachePath, packageDir), + ).rejects.toThrow(/No checksum recorded/u); + expect(mockedDownloadToFile).not.toHaveBeenCalled(); + }); + + it('refuses to download when checksums.json is unreadable', async () => { + await rm(join(packageDir, 'bundled', 'checksums.json'), { force: true }); + + await expect( + checkAndDownloadBinaries(downloadUrl, cachePath, packageDir), + ).rejects.toThrow(/Unable to read checksums file/u); + expect(mockedDownloadToFile).not.toHaveBeenCalled(); + }); + + it('uses the cache without downloading when the binary exists', async () => { + await mkdir(cachePath, { recursive: true }); + await writeFile(join(cachePath, Binary.Speculos), 'cached-payload', { + mode: 0o755, + }); + + const dir = await checkAndDownloadBinaries( + downloadUrl, + cachePath, + packageDir, + ); + const entries = await readDirEntries(dir); + + expect(entries).toContain(Binary.Speculos); + expect(mockedDownloadToFile).not.toHaveBeenCalled(); + }); + + it('repopulates an empty cache directory instead of treating it as installed', async () => { + await mkdir(cachePath, { recursive: true }); + mockedDownloadToFile.mockImplementation(async (_url, destination) => { + await copyFile(archivePath, destination); + }); + + const dir = await checkAndDownloadBinaries( + downloadUrl, + cachePath, + packageDir, + ); + const entries = await readDirEntries(dir); + + expect(mockedDownloadToFile).toHaveBeenCalledTimes(1); + expect(entries).toContain(Binary.Speculos); + }); + }); + + describe('checkAndExtractLocalBinaries', () => { + it('extracts into an empty cache directory instead of treating it as found', async () => { + const archivePath = join(tempDir, 'local-empty-cache.tar.gz'); + await createArchiveFixture(archivePath); + const cachePath = join( + tempDir, + `local-empty-cache-${Math.random().toString(36).slice(2)}`, + ); + // The cache directory exists but is empty — previously this was + // mistakenly treated as an installation. + await mkdir(cachePath, { recursive: true }); + + const dir = await checkAndExtractLocalBinaries(archivePath, cachePath); + const entries = await readDirEntries(dir); + + expect(entries).toContain(Binary.Speculos); + const binaryStat = await stat(join(cachePath, Binary.Speculos)); + expect(binaryStat.isFile()).toBe(true); + }); + + it('uses the cache without extracting when the binary exists', async () => { + const cachePath = join( + tempDir, + `local-hit-${Math.random().toString(36).slice(2)}`, + ); + await mkdir(cachePath, { recursive: true }); + await writeFile(join(cachePath, Binary.Speculos), 'cached-payload', { + mode: 0o755, + }); + + // The archive path is deliberately invalid: a cache hit must not + // even attempt to read it. + const dir = await checkAndExtractLocalBinaries( + join(tempDir, 'does-not-exist.tar.gz'), + cachePath, + ); + const entries = await readDirEntries(dir); + + expect(entries).toContain(Binary.Speculos); + }); + }); + + describe('installBinaries', () => { + it('symlinks (or copies) cached binaries into the bin directory', async () => { + const cachePath = join(tempDir, 'install-cache'); + await mkdir(cachePath, { recursive: true }); + await writeFile( + join(cachePath, Binary.Speculos), + '#!/bin/sh\necho "speculos 0.27.8"\n', + { mode: 0o755 }, + ); + const binDir = join(tempDir, 'install-bin'); + + await installBinaries(await opendir(cachePath), binDir, cachePath); + + const installedStat = await stat(join(binDir, Binary.Speculos)); + expect(installedStat.isFile() || installedStat.isSymbolicLink()).toBe( + true, + ); + }); + + it('resolves entry paths from sourceDir without requiring Dirent.parentPath', async () => { + // Entries are resolved against `sourceDir`; `Dirent.parentPath` is not + // used, so this must work with only Node 22+ APIs. + const sourceDir = join(tempDir, 'install-fallback-source'); + await mkdir(sourceDir, { recursive: true }); + const payload = '#!/bin/sh\necho "speculos 0.27.8"\n'; + await writeFile(join(sourceDir, Binary.Speculos), payload, { + mode: 0o755, + }); + const binDir = join(tempDir, 'install-fallback-bin'); + + const entries = [{ isFile: (): boolean => true, name: Binary.Speculos }]; + const syntheticDir = { + async *[Symbol.asyncIterator](): AsyncGenerator<{ + isFile: () => boolean; + name: string; + }> { + for (const entry of entries) { + yield entry; + } + }, + } as unknown as Dir; + + await installBinaries(syntheticDir, binDir, sourceDir); + + const installedPath = join(binDir, Binary.Speculos); + const installedStat = await stat(installedPath); + expect(installedStat.isFile() || installedStat.isSymbolicLink()).toBe( + true, + ); + // The installed entry must point at the file in `sourceDir`. + expect(await readFile(installedPath, 'utf8')).toBe(payload); + }); + }); + + describe('downloadAndInstall', () => { + it('installs from a warm cache using the bundled archive checksum', async () => { + const cacheDir = await makeTempDir('install-cache-dir'); + const cwdDir = await makeTempDir('install-cwd'); + // downloadAndInstall() installs into the same version-named + // directory that getSpeculosBinaryPath()/isSpeculosInstalled() + // check, so a warm cache there short-circuits the download. + const installDir = getInstallDir({ cacheDir }); + await mkdir(installDir, { recursive: true }); + await writeFile( + join(installDir, Binary.Speculos), + '#!/bin/sh\necho "speculos 0.27.8"\n', + { mode: 0o755 }, + ); + + const cwdSpy = jest.spyOn(process, 'cwd').mockReturnValue(cwdDir); + try { + const binaryPath = await downloadAndInstall({ cacheDir }); + expect(binaryPath).toBe(join(installDir, Binary.Speculos)); + expect(getSpeculosBinaryPath({ cacheDir })).toBe( + join(installDir, Binary.Speculos), + ); + + const installed = await readdir(join(cwdDir, 'node_modules', '.bin')); + expect(installed).toContain(Binary.Speculos); + } finally { + cwdSpy.mockRestore(); + await rm(cacheDir, { recursive: true, force: true }); + await rm(cwdDir, { recursive: true, force: true }); + } + }, 15000); + + it('fails closed when downloading a version with no checksum entry', async () => { + // No bundled archive exists for this version, so the remote path is + // taken; the archive has no entry in the real bundled/checksums.json + // and the download must be refused before any network request. + await expect( + downloadAndInstall({ + version: '99.99.99', + cacheDir: join(tempDir, 'never-created-cache'), + }), + ).rejects.toThrow(/No checksum recorded/u); + + await expect(stat(join(tempDir, 'never-created-cache'))).rejects.toThrow( + /ENOENT/u, + ); + expect(jest.mocked(downloadToFile).mock.calls).toHaveLength(0); + }, 15000); + }); + + describe('built artifact package directory resolution', () => { + const builtCjsPath = join(__dirname, '..', 'dist', 'index.cjs'); + + /** + * Check whether the package has been built. + * + * @returns Whether the built CJS entry point exists. + */ + function isBuiltArtifactAvailable(): boolean { + try { + createRequire(__filename).resolve(builtCjsPath); + return true; + } catch { + return false; + } + } + + // Regression guard for package-directory resolution: the published + // build must resolve `bundled/checksums.json`, otherwise every cold + // install throws "Unable to resolve the speculos-up package directory". + // The suite is skipped when the package has not been built so the source + // test run stays hermetic. + const describeWhenBuilt = isBuiltArtifactAvailable() + ? describe + : describe.skip; + + describeWhenBuilt('published CJS build', () => { + it('resolves the package directory from the CJS build', async () => { + // Import the built artifact rather than the source, so the actual + // published entry point is exercised. + const builtRequire = createRequire(__filename); + const artifact: typeof import('.') = builtRequire(builtCjsPath); + + // Version 99.99.99 has no bundled archive and no checksum entry, + // so the install fails closed during the checksum lookup, before + // any network request. Reaching that error proves the package + // directory (and therefore `bundled/checksums.json`) was resolved. + await expect( + artifact.downloadAndInstall({ + version: '99.99.99', + cacheDir: join(tempDir, 'built-cjs-cache'), + }), + ).rejects.toThrow(/No checksum recorded/u); + }, 15000); + }); + }); + + describe('cleanCache', () => { + it('deletes the default cache directory', async () => { + const cacheRoot = await makeTempDir('clean-root'); + const speculosRoot = join(cacheRoot, 'metamask', 'speculos-up'); + await mkdir(speculosRoot, { recursive: true }); + const utilsSpy = jest + .spyOn(utils, 'getDefaultCacheDir') + .mockReturnValue(speculosRoot); + + try { + await cleanCache(); + await expect(stat(speculosRoot)).rejects.toThrow(/ENOENT/u); + } finally { + utilsSpy.mockRestore(); + await rm(cacheRoot, { recursive: true, force: true }); + } + }); + + it('deletes a cache directory inside the cache root', async () => { + const cacheRoot = await makeTempDir('clean-inside-root'); + const speculosRoot = join(cacheRoot, 'metamask', 'speculos-up'); + const target = join(speculosRoot, 'some-hash'); + await mkdir(target, { recursive: true }); + await writeFile(join(target, 'speculos'), 'payload'); + const utilsSpy = jest + .spyOn(utils, 'getDefaultCacheDir') + .mockReturnValue(speculosRoot); + + try { + await cleanCache({ cacheDir: target }); + await expect(stat(target)).rejects.toThrow(/ENOENT/u); + } finally { + utilsSpy.mockRestore(); + await rm(cacheRoot, { recursive: true, force: true }); + } + }); + + it('refuses to delete a directory outside the cache root', async () => { + const cacheRoot = await makeTempDir('clean-outside-root'); + const speculosRoot = join(cacheRoot, 'metamask', 'speculos-up'); + const victim = join(cacheRoot, 'important-data'); + await mkdir(victim, { recursive: true }); + await writeFile(join(victim, 'do-not-delete.txt'), 'important'); + const utilsSpy = jest + .spyOn(utils, 'getDefaultCacheDir') + .mockReturnValue(speculosRoot); + + try { + await expect(cleanCache({ cacheDir: victim })).rejects.toThrow( + /outside the speculos-up cache root/u, + ); + // The directory must still exist. + expect(await stat(join(victim, 'do-not-delete.txt'))).toBeDefined(); + } finally { + utilsSpy.mockRestore(); + await rm(cacheRoot, { recursive: true, force: true }); + } + }); + + it('refuses to delete a directory reached via traversal outside the cache root', async () => { + const cacheRoot = await makeTempDir('clean-traversal-root'); + const speculosRoot = join(cacheRoot, 'metamask', 'speculos-up'); + const utilsSpy = jest + .spyOn(utils, 'getDefaultCacheDir') + .mockReturnValue(speculosRoot); + + try { + await expect( + cleanCache({ cacheDir: join(speculosRoot, '..', '..', 'elsewhere') }), + ).rejects.toThrow(/outside the speculos-up cache root/u); + } finally { + utilsSpy.mockRestore(); + await rm(cacheRoot, { recursive: true, force: true }); + } + }); + }); +}); diff --git a/packages/speculos-up/src/index.ts b/packages/speculos-up/src/index.ts new file mode 100644 index 000000000..4740d24f4 --- /dev/null +++ b/packages/speculos-up/src/index.ts @@ -0,0 +1,369 @@ +// eslint-disable-next-line import-x/no-nodejs-modules +import type { Dir } from 'node:fs'; +// eslint-disable-next-line import-x/no-nodejs-modules +import { + copyFile, + mkdir, + opendir, + rm, + symlink, + unlink, +} from 'node:fs/promises'; +// eslint-disable-next-line import-x/no-nodejs-modules +import { basename, dirname, join, relative } from 'node:path'; + +import { downloadToFile } from './download'; +import { extractFromLocal } from './extract'; +import type { SpeculosupOptions } from './types'; +import { Binary, Platform } from './types'; +import { + CLEANUP_MAX_RETRIES, + computeFileSha256, + getBinaryArchiveUrl, + getBinaryPath, + getBundledArchivePath, + getDefaultCacheDir, + getDefaultRepo, + getDefaultVersion, + getRequiredChecksum, + getVersion, + isCodedError, + isInstalled, + isPathWithin, + noop, + normalizeSystemArchitecture, + say, +} from './utils'; + +let cachedPackageDir: string | undefined; + +/** + * Resolve the package root directory containing bundled/ and dist/. + * Works in both CJS and ESM contexts. + * + * The package manifest is resolved because it keeps the same name + * (`package.json`) in both the CJS and ESM builds. Extensionless internal + * specifiers (such as `./utils`) do not resolve against the `.cjs`/`.mjs`-only + * output produced by the build, so they would fail in both builds. + * + * @returns The package root directory, or undefined if not resolvable. + */ +function resolvePackageDir(): string | undefined { + if (cachedPackageDir) { + return cachedPackageDir; + } + try { + // eslint-disable-next-line no-restricted-globals + const manifestPath = require.resolve('../package.json'); + cachedPackageDir = dirname(manifestPath); + return cachedPackageDir; + } catch { + return undefined; + } +} + +/** + * Verify the SHA-256 checksum of a bundled archive against checksums.json. + * + * Verification fails closed: if the checksums file is unreadable, malformed, + * or has no entry for the archive, an error is thrown rather than skipping + * verification. + * + * @param archivePath - The path to the archive file. + * @param packageDir - The package root directory. + * @returns True if the checksum matches, false if it does not. + * @throws If the checksums file is unreadable or malformed, or if no checksum + * is recorded for the archive. + */ +export async function verifyBundledChecksum( + archivePath: string, + packageDir: string, +): Promise { + const checksumsPath = join(packageDir, 'bundled', 'checksums.json'); + const archiveName = basename(archivePath); + const expected = await getRequiredChecksum(checksumsPath, archiveName); + const actual = await computeFileSha256(archivePath); + if (actual !== expected) { + say(`checksum mismatch: expected ${expected}, got ${actual}`); + return false; + } + say('bundled archive checksum verified'); + return true; +} + +/** + * Resolve the installation directory for a given version and architecture. + * + * @param options - Installation options. + * @returns The cache path for this version+arch. + */ +export function getInstallDir(options: SpeculosupOptions = {}): string { + const cacheDir = options.cacheDir ?? getDefaultCacheDir(); + const version = options.version ?? getDefaultVersion(); + const resolvedArch = options.arch ?? normalizeSystemArchitecture(); + const platform = options.platform ?? Platform.Linux; + return join( + cacheDir, + `speculos-${version}-${String(platform)}-${resolvedArch}`, + ); +} + +/** + * Get the path to the installed speculos binary. + * + * @param options - Installation options. + * @returns The absolute path to the speculos binary, or `null` if not installed. + */ +export function getSpeculosBinaryPath( + options: SpeculosupOptions = {}, +): string | null { + const installDir = getInstallDir(options); + if (!isInstalled(installDir)) { + return null; + } + return getBinaryPath(installDir); +} + +/** + * Check if speculos is installed. + * + * @param options - Installation options. + * @returns True if the managed binary exists. + */ +export function isSpeculosInstalled(options: SpeculosupOptions = {}): boolean { + const installDir = getInstallDir(options); + return isInstalled(installDir); +} + +/** + * Check if binaries are already in the cache. If not, download the archive + * from the given HTTPS URL, verify its SHA-256 checksum against the package's + * `bundled/checksums.json`, and only then extract it. + * + * The cache is only treated as valid if the expected binary file actually + * exists; an empty or partial cache directory is re-populated. + * + * @param url - The HTTPS URL of the tar.gz archive to download. + * @param cachePath - The cache directory. + * @param packageDir - The package root directory containing + * `bundled/checksums.json`. + * @returns A directory handle for the cached binaries. + * @throws If the checksums file is unreadable, malformed, or has no entry for + * the archive, if the downloaded archive's checksum does not match, or if the + * download or extraction fails. Verification fails closed in all those cases. + */ +export async function checkAndDownloadBinaries( + url: URL, + cachePath: string, + packageDir: string, +): Promise { + say('checking cache'); + if (isInstalled(cachePath)) { + say('found binaries in cache'); + return opendir(cachePath); + } + + say('binaries not in cache'); + say(`installing from ${url.toString()}`); + + const archiveName = basename(url.pathname); + const checksumsPath = join(packageDir, 'bundled', 'checksums.json'); + const expectedChecksum = await getRequiredChecksum( + checksumsPath, + archiveName, + ); + + await mkdir(dirname(cachePath), { recursive: true }); + const archivePath = `${cachePath}.download.tar.gz`; + await downloadToFile(url, archivePath); + try { + const actualChecksum = await computeFileSha256(archivePath); + if (actualChecksum !== expectedChecksum) { + throw new Error( + `Checksum mismatch for downloaded archive "${archiveName}": expected ${expectedChecksum}, got ${actualChecksum}`, + ); + } + say('downloaded archive checksum verified'); + await extractFromLocal(archivePath, [Binary.Speculos], cachePath); + } finally { + await rm(archivePath, { + recursive: true, + force: true, + maxRetries: CLEANUP_MAX_RETRIES, + }).catch(noop); + } + return opendir(cachePath); +} + +/** + * Check if binaries are already in the cache. If not, extract from a local archive. + * + * The cache is only treated as valid if the expected binary file actually + * exists; an empty or partial cache directory is re-populated. + * + * @param archivePath - The absolute path to the local tar.gz archive. + * @param cachePath - The cache directory. + * @returns A directory handle for the cached binaries. + * @throws If extraction fails. + */ +export async function checkAndExtractLocalBinaries( + archivePath: string, + cachePath: string, +): Promise { + say('checking cache'); + if (isInstalled(cachePath)) { + say('found binaries in cache'); + return opendir(cachePath); + } + + say('binaries not in cache'); + say('extracting from bundled archive'); + await extractFromLocal(archivePath, [Binary.Speculos], cachePath); + return opendir(cachePath); +} + +/** + * Install the downloaded binaries by creating symlinks or copying files. + * + * @param downloadedBinaries - The directory containing the binaries. + * @param binDir - The target directory for installation. + * @param sourceDir - The directory the binaries were downloaded and + * extracted into. + */ +export async function installBinaries( + downloadedBinaries: Dir, + binDir: string, + sourceDir: string, +): Promise { + for await (const file of downloadedBinaries) { + if (!file.isFile()) { + continue; + } + // Resolve each entry against `sourceDir` — the directory the entries were + // read from — instead of `Dirent.parentPath`, which is only populated on + // newer runtimes. This relies solely on long-supported APIs (Node 22+). + const sourcePath = join(sourceDir, file.name); + const installPath = join(binDir, relative(sourceDir, sourcePath)); + + const relativeSource = relative(dirname(installPath), sourcePath); + + await mkdir(binDir, { recursive: true }); + + await unlink(installPath).catch(noop); + try { + await symlink(relativeSource, installPath); + } catch (linkError) { + if ( + !( + isCodedError(linkError) && ['EPERM', 'EXDEV'].includes(linkError.code) + ) + ) { + throw linkError; + } + await copyFile(sourcePath, installPath); + } + say(`installed - ${getVersion(installPath)}`); + } +} + +/** + * Download and install the Speculos binary. + * + * If a bundled archive exists for the target platform and architecture and + * its checksum verifies, it is used directly. Otherwise the archive is + * downloaded over HTTPS from the release URL and its SHA-256 checksum is + * verified against the package's `bundled/checksums.json` before extraction. + * + * Binaries are installed into the version-named directory returned by + * `getInstallDir()` — the same directory that `getSpeculosBinaryPath()` and + * `isSpeculosInstalled()` check — and symlinked into `node_modules/.bin`. + * + * @param options - Installation options. + * @returns The path to the installed speculos binary. + * @throws If the system architecture is unsupported, the checksums file is + * unreadable, malformed, or missing an entry, a checksum does not match, or + * the download or extraction fails. + */ +export async function downloadAndInstall( + options: SpeculosupOptions = {}, +): Promise { + const version = options.version ?? getDefaultVersion(); + const repo = options.repo ?? getDefaultRepo(); + const platform = options.platform ?? Platform.Linux; + const targetArch = options.arch ?? normalizeSystemArchitecture(); + + say(`fetching speculos v${version} for ${String(platform)} ${targetArch}`); + + // Install into the readable, version-named directory that + // getSpeculosBinaryPath()/isSpeculosInstalled() look in, so a successful + // install is immediately visible to callers. + const installDir = getInstallDir(options); + + const binDir = join( + // eslint-disable-next-line no-restricted-globals + process.cwd(), + 'node_modules', + '.bin', + ); + + const packageDir = resolvePackageDir(); + const bundledArchive = packageDir + ? getBundledArchivePath(version, platform, targetArch, packageDir) + : null; + let downloadedBinaries: Dir; + + if ( + bundledArchive && + packageDir && + (await verifyBundledChecksum(bundledArchive, packageDir)) + ) { + say('using bundled binary'); + downloadedBinaries = await checkAndExtractLocalBinaries( + bundledArchive, + installDir, + ); + } else { + if (!packageDir) { + throw new Error( + 'Unable to resolve the speculos-up package directory; cannot verify checksums for remote downloads.', + ); + } + const archiveUrl = getBinaryArchiveUrl(repo, version, platform, targetArch); + const url = new URL(archiveUrl); + downloadedBinaries = await checkAndDownloadBinaries( + url, + installDir, + packageDir, + ); + } + + await installBinaries(downloadedBinaries, binDir, installDir); + + say('done!'); + + return getBinaryPath(installDir); +} + +/** + * Remove a cached speculos installation. + * + * The cache directory to remove must be the default cache directory itself or + * a path inside it; anything else is refused, so a caller-supplied path can + * never cause an arbitrary directory to be recursively deleted. + * + * @param options - Installation options. + * @throws If the resolved cache directory is outside the expected cache root. + */ +export async function cleanCache( + options: SpeculosupOptions = {}, +): Promise { + const cacheRoot = getDefaultCacheDir(); + const cacheDir = options.cacheDir ?? cacheRoot; + if (!isPathWithin(cacheRoot, cacheDir)) { + throw new Error( + `Refusing to delete "${cacheDir}" because it is outside the speculos-up cache root "${cacheRoot}".`, + ); + } + await rm(cacheDir, { recursive: true, force: true }); + say('cache cleaned'); +} diff --git a/packages/speculos-up/src/speculos-up.test.ts b/packages/speculos-up/src/speculos-up.test.ts new file mode 100644 index 000000000..f85da776d --- /dev/null +++ b/packages/speculos-up/src/speculos-up.test.ts @@ -0,0 +1,343 @@ +import { createHash } from 'node:crypto'; +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { getInstallDir, getSpeculosBinaryPath, isSpeculosInstalled } from '.'; +import { Architecture, Platform } from './types'; +import { + computeFileSha256, + getDefaultCacheDir, + getDefaultVersion, + getDefaultRepo, + getBinaryArchiveUrl, + getBundledArchivePath, + getRequiredChecksum, + getVersion, + isPathWithin, + loadChecksumsFile, + normalizeSystemArchitecture, +} from './utils'; + +/** + * Run a callback with XDG_CACHE_HOME temporarily overridden. + * + * @param value - The temporary value for XDG_CACHE_HOME. + * @param callback - The callback to run. + * @returns The callback's return value. + */ +function withXdgCacheHome(value: string, callback: () => void): void { + // eslint-disable-next-line n/no-process-env + const previous = process.env.XDG_CACHE_HOME; + // eslint-disable-next-line n/no-process-env + process.env.XDG_CACHE_HOME = value; + try { + return callback(); + } finally { + // eslint-disable-next-line n/no-process-env + process.env.XDG_CACHE_HOME = previous; + } +} + +describe('speculos-up', () => { + describe('getDefaultVersion', () => { + it('returns a version string', () => { + const version = getDefaultVersion(); + expect(version).toMatch(/^\d+\.\d+\.\d+$/u); + }); + }); + + describe('getDefaultRepo', () => { + it('returns MetaMask/accounts', () => { + expect(getDefaultRepo()).toBe('MetaMask/accounts'); + }); + }); + + describe('normalizeSystemArchitecture', () => { + it('returns Arm64 for arm64 input', () => { + expect(normalizeSystemArchitecture('arm64')).toBe(Architecture.Arm64); + }); + + it('returns Arm64 for aarch64 input', () => { + expect(normalizeSystemArchitecture('aarch64')).toBe(Architecture.Arm64); + }); + + it('returns Amd64 for x64 input', () => { + expect(normalizeSystemArchitecture('x64')).toBe(Architecture.Amd64); + }); + + it('returns Amd64 for amd64 input', () => { + expect(normalizeSystemArchitecture('amd64')).toBe(Architecture.Amd64); + }); + + it.each(['arm', 'armv7l', 'ia32', 'ppc64', 's390x', 'unknown'])( + 'throws for unsupported architecture %s', + (architecture) => { + expect(() => normalizeSystemArchitecture(architecture)).toThrow( + `Unsupported system architecture "${architecture}"`, + ); + }, + ); + }); + + describe('getDefaultCacheDir', () => { + it('returns a path containing speculos-up', () => { + expect(getDefaultCacheDir()).toContain('speculos-up'); + }); + + it('honors an absolute XDG_CACHE_HOME', () => { + withXdgCacheHome('/tmp/xdg-cache', () => { + expect(getDefaultCacheDir()).toBe( + '/tmp/xdg-cache/metamask/speculos-up', + ); + }); + }); + + it('ignores a relative XDG_CACHE_HOME', () => { + withXdgCacheHome('relative/cache', () => { + expect(getDefaultCacheDir()).toContain('.cache'); + }); + }); + }); + + describe('getBinaryArchiveUrl', () => { + it('generates the correct URL', () => { + const url = getBinaryArchiveUrl( + 'MetaMask/accounts', + '0.27.8', + Platform.Linux, + 'amd64', + ); + expect(url).toBe( + 'https://github.com/MetaMask/accounts/releases/download/speculos-v0.27.8/speculos-v0.27.8-linux-amd64.tar.gz', + ); + }); + + it('always generates an https URL', () => { + const url = getBinaryArchiveUrl( + 'some/repo', + '1.0.0', + Platform.Linux, + 'arm64', + ); + expect(url.startsWith('https://')).toBe(true); + }); + }); + + describe('computeFileSha256', () => { + it('computes the SHA-256 checksum of a file', async () => { + const tempDir = await mkdtemp(join(tmpdir(), 'speculos-up-sha-')); + try { + const filePath = join(tempDir, 'file.txt'); + await writeFile(filePath, 'hello'); + const expected = createHash('sha256').update('hello').digest('hex'); + expect(await computeFileSha256(filePath)).toBe(expected); + } finally { + await rm(tempDir, { recursive: true, force: true }); + } + }); + + it('throws when the file does not exist', async () => { + await expect( + computeFileSha256('/nonexistent/speculos-up/file.txt'), + ).rejects.toThrow(/ENOENT/u); + }); + }); + + describe('loadChecksumsFile', () => { + it('loads a valid checksums file', async () => { + const tempDir = await mkdtemp(join(tmpdir(), 'speculos-up-cs-')); + try { + const checksumsPath = join(tempDir, 'checksums.json'); + await writeFile(checksumsPath, '{"archive.tar.gz": "abc123"}'); + expect(await loadChecksumsFile(checksumsPath)).toStrictEqual({ + 'archive.tar.gz': 'abc123', + }); + } finally { + await rm(tempDir, { recursive: true, force: true }); + } + }); + + it('throws when the file is missing', async () => { + await expect( + loadChecksumsFile('/nonexistent/speculos-up/checksums.json'), + ).rejects.toThrow(/Unable to read checksums file/u); + }); + + it('throws when the file is not valid JSON', async () => { + const tempDir = await mkdtemp(join(tmpdir(), 'speculos-up-cs-')); + try { + const checksumsPath = join(tempDir, 'checksums.json'); + await writeFile(checksumsPath, '{ oops'); + await expect(loadChecksumsFile(checksumsPath)).rejects.toThrow( + /not valid JSON/u, + ); + } finally { + await rm(tempDir, { recursive: true, force: true }); + } + }); + + it('throws when the JSON is not an object', async () => { + const tempDir = await mkdtemp(join(tmpdir(), 'speculos-up-cs-')); + try { + const checksumsPath = join(tempDir, 'checksums.json'); + await writeFile(checksumsPath, '["array"]'); + await expect(loadChecksumsFile(checksumsPath)).rejects.toThrow( + /must contain a JSON object/u, + ); + } finally { + await rm(tempDir, { recursive: true, force: true }); + } + }); + + it('throws when a checksum value is not a string', async () => { + const tempDir = await mkdtemp(join(tmpdir(), 'speculos-up-cs-')); + try { + const checksumsPath = join(tempDir, 'checksums.json'); + await writeFile(checksumsPath, '{"archive.tar.gz": 42}'); + await expect(loadChecksumsFile(checksumsPath)).rejects.toThrow( + /invalid checksum for "archive\.tar\.gz"/u, + ); + } finally { + await rm(tempDir, { recursive: true, force: true }); + } + }); + }); + + describe('getRequiredChecksum', () => { + it('returns the checksum for a known archive', async () => { + const tempDir = await mkdtemp(join(tmpdir(), 'speculos-up-req-')); + try { + const checksumsPath = join(tempDir, 'checksums.json'); + await writeFile(checksumsPath, '{"archive.tar.gz": "abc123"}'); + expect(await getRequiredChecksum(checksumsPath, 'archive.tar.gz')).toBe( + 'abc123', + ); + } finally { + await rm(tempDir, { recursive: true, force: true }); + } + }); + + it('throws when no checksum is recorded for the archive', async () => { + const tempDir = await mkdtemp(join(tmpdir(), 'speculos-up-req-')); + try { + const checksumsPath = join(tempDir, 'checksums.json'); + await writeFile(checksumsPath, '{"other.tar.gz": "abc123"}'); + await expect( + getRequiredChecksum(checksumsPath, 'archive.tar.gz'), + ).rejects.toThrow( + /No checksum recorded for "archive\.tar\.gz".*refusing to install/u, + ); + } finally { + await rm(tempDir, { recursive: true, force: true }); + } + }); + }); + + describe('getVersion', () => { + it('wraps errors when the binary cannot be executed', async () => { + const tempDir = await mkdtemp(join(tmpdir(), 'speculos-up-ver-')); + try { + const filePath = join(tempDir, 'speculos'); + await writeFile(filePath, 'not executable', { mode: 0o644 }); + expect(() => getVersion(filePath)).toThrow( + /Failed to get version for/u, + ); + } finally { + await rm(tempDir, { recursive: true, force: true }); + } + }); + }); + + describe('isPathWithin', () => { + it('accepts the root itself', () => { + expect(isPathWithin('/tmp/cache', '/tmp/cache')).toBe(true); + }); + + it('accepts paths inside the root', () => { + expect(isPathWithin('/tmp/cache', '/tmp/cache/child/grandchild')).toBe( + true, + ); + }); + + it('rejects sibling paths', () => { + expect(isPathWithin('/tmp/cache', '/tmp/cache-evil')).toBe(false); + }); + + it('rejects paths outside the root', () => { + expect(isPathWithin('/tmp/cache', '/tmp/elsewhere')).toBe(false); + }); + + it('rejects traversal attempts', () => { + expect(isPathWithin('/tmp/cache', '/tmp/cache/../../etc')).toBe(false); + }); + + it('rejects completely unrelated absolute paths', () => { + expect(isPathWithin('/tmp/cache', '/etc/passwd')).toBe(false); + }); + }); + + describe('getBundledArchivePath', () => { + it('returns a path for a bundled archive that exists', () => { + const packageDir = join(__dirname, '..'); + const result = getBundledArchivePath( + '0.27.8', + Platform.Linux, + Architecture.Amd64, + packageDir, + ); + expect(result).toMatch( + /bundled\/speculos-v0\.27\.8-linux-amd64\.tar\.gz$/u, + ); + }); + + it('returns null for a version that has no bundle', () => { + const packageDir = join(__dirname, '..'); + const result = getBundledArchivePath( + '99.99.99', + Platform.Linux, + Architecture.Amd64, + packageDir, + ); + expect(result).toBeNull(); + }); + }); + + describe('getInstallDir', () => { + it('includes version, platform, and arch', () => { + const dir = getInstallDir(); + expect(dir).toContain('speculos-0.27.8'); + expect(dir).toContain('linux'); + }); + + it('uses custom cache dir', () => { + const dir = getInstallDir({ + cacheDir: '/tmp/test', + arch: Architecture.Amd64, + }); + expect(dir).toBe('/tmp/test/speculos-0.27.8-linux-amd64'); + }); + + it('uses custom version and arch', () => { + const dir = getInstallDir({ version: '1.0.0', arch: Architecture.Arm64 }); + expect(dir).toContain('speculos-1.0.0-linux-arm64'); + }); + }); + + describe('getSpeculosBinaryPath', () => { + it('returns null when the managed binary is not installed', () => { + const options = { cacheDir: '/tmp/nonexistent-speculos-up-test' }; + expect(isSpeculosInstalled(options)).toBe(false); + expect(getSpeculosBinaryPath(options)).toBeNull(); + }); + }); + + describe('isSpeculosInstalled', () => { + it('returns false for non-existent path', () => { + const result = isSpeculosInstalled({ + cacheDir: '/tmp/nonexistent-speculos-up-test', + }); + expect(result).toBe(false); + }); + }); +}); diff --git a/packages/speculos-up/src/types.ts b/packages/speculos-up/src/types.ts new file mode 100644 index 000000000..c208272b3 --- /dev/null +++ b/packages/speculos-up/src/types.ts @@ -0,0 +1,31 @@ +export enum Architecture { + Amd64 = 'amd64', + Arm64 = 'arm64', +} + +export enum Platform { + Linux = 'linux', +} + +export enum Binary { + Speculos = 'speculos', +} + +export type DownloadOptions = { + method?: 'GET' | 'HEAD'; + headers?: Record; + maxRedirects?: number; +}; + +export type SpeculosupOptions = { + /** Speculos version to install. */ + version?: string; + /** GitHub repository hosting releases. */ + repo?: string; + /** Custom cache directory. */ + cacheDir?: string; + /** Target platform. */ + platform?: Platform; + /** Target architecture. */ + arch?: Architecture; +}; diff --git a/packages/speculos-up/src/utils.ts b/packages/speculos-up/src/utils.ts new file mode 100644 index 000000000..25ec7aef3 --- /dev/null +++ b/packages/speculos-up/src/utils.ts @@ -0,0 +1,332 @@ +// eslint-disable-next-line import-x/no-nodejs-modules +import { execFileSync } from 'node:child_process'; +// eslint-disable-next-line import-x/no-nodejs-modules +import { createHash } from 'node:crypto'; +// eslint-disable-next-line import-x/no-nodejs-modules +import { existsSync } from 'node:fs'; +// eslint-disable-next-line import-x/no-nodejs-modules +import { readFile } from 'node:fs/promises'; +// eslint-disable-next-line import-x/no-nodejs-modules +import { arch } from 'node:os'; +// eslint-disable-next-line import-x/no-nodejs-modules +import { homedir } from 'node:os'; +// eslint-disable-next-line import-x/no-nodejs-modules +import { isAbsolute, join, relative, resolve, sep } from 'node:path'; + +import { Architecture } from './types'; +import type { Platform } from './types'; + +const DEFAULT_VERSION = '0.27.8'; +const DEFAULT_REPO = 'MetaMask/accounts'; + +/** + * Maximum number of retries for best-effort filesystem cleanup operations + * (for example, removing a partially extracted or downloaded archive). + */ +export const CLEANUP_MAX_RETRIES = 3; + +/** + * Architecture strings that are normalized to {@link Architecture.Amd64}. + */ +const AMD64_ARCHITECTURES = new Set(['x64', 'amd64']); + +/** + * Architecture strings that are normalized to {@link Architecture.Arm64}. + */ +const ARM64_ARCHITECTURES = new Set(['arm64', 'aarch64']); + +/** + * No-op function. + * + * @returns undefined. + */ +export const noop = (): undefined => undefined; + +/** + * Get the default Speculos version. + * + * @returns The version string. + */ +export function getDefaultVersion(): string { + return DEFAULT_VERSION; +} + +/** + * Get the default GitHub repo hosting speculos releases. + * + * @returns The repo string. + */ +export function getDefaultRepo(): string { + return DEFAULT_REPO; +} + +/** + * Normalize the system architecture. + * + * Only known 64-bit architectures are supported: `x64`/`amd64` map to + * {@link Architecture.Amd64}, and `arm64`/`aarch64` map to + * {@link Architecture.Arm64}. Anything else (for example `arm`, `armv7l`, + * `ia32`, or `ppc64`) is unsupported, because no Speculos binaries are + * published for it. + * + * @param architecture - The architecture string. + * @returns The normalized architecture. + * @throws If the architecture is not supported. + */ +export function normalizeSystemArchitecture( + architecture: string = arch(), +): Architecture { + if (AMD64_ARCHITECTURES.has(architecture)) { + return Architecture.Amd64; + } + if (ARM64_ARCHITECTURES.has(architecture)) { + return Architecture.Arm64; + } + throw new Error( + `Unsupported system architecture "${architecture}". Supported architectures are x64/amd64 and arm64/aarch64.`, + ); +} + +/** + * Get the default cache directory. + * + * Honors the `XDG_CACHE_HOME` environment variable when it is set to an + * absolute path; otherwise uses `~/.cache`. + * + * @returns The cache directory path. + */ +export function getDefaultCacheDir(): string { + // eslint-disable-next-line no-restricted-globals + const envCacheDir = process.env.XDG_CACHE_HOME; + const cacheBase = + envCacheDir && isAbsolute(envCacheDir) + ? envCacheDir + : join(homedir(), '.cache'); + return join(cacheBase, 'metamask', 'speculos-up'); +} + +/** + * Log a message with the speculos-up prefix. + * + * @param message - The message to log. + */ +export function say(message: string): void { + console.log(`[speculos-up] ${message}`); +} + +/** + * Get the version of the binary at the given path. + * + * @param binPath - Path to the binary. + * @returns The version output, with a single trailing newline stripped. + */ +export function getVersion(binPath: string): string { + try { + const output = execFileSync(binPath, ['--version'], { + encoding: 'utf8', + }); + return output.endsWith('\n') ? output.slice(0, -1) : output; + } catch (error: unknown) { + const versionError = `Failed to get version for ${binPath}`; + if (error instanceof Error) { + error.message = `${versionError}\n\n${error.message}`; + throw error; + } + throw new Error(`${versionError}: ${String(error)}`); + } +} + +/** + * Check if an error has a code property. + * + * @param error - The error to check. + * @returns True if the error has a code property. + */ +export function isCodedError( + error: unknown, +): error is Error & { code: string } { + return ( + error instanceof Error && 'code' in error && typeof error.code === 'string' + ); +} + +/** + * Generate the URL for downloading the Speculos binary archive. + * + * @param repo - The GitHub repository. + * @param version - The version string. + * @param platform - The target platform. + * @param targetArch - The target architecture. + * @returns The download URL. + */ +export function getBinaryArchiveUrl( + repo: string, + version: string, + platform: Platform, + targetArch: string, +): string { + return `https://github.com/${repo}/releases/download/speculos-v${version}/speculos-v${version}-${String(platform)}-${targetArch}.tar.gz`; +} + +/** + * Get the path to the speculos binary in the given install directory. + * + * @param installDir - The directory where the binary was extracted. + * @returns The absolute path to the speculos binary. + */ +export function getBinaryPath(installDir: string): string { + return join(installDir, 'speculos'); +} + +/** + * Check if speculos is already installed at the given path. + * + * @param installDir - The install directory. + * @returns True if the binary exists. + */ +export function isInstalled(installDir: string): boolean { + return existsSync(getBinaryPath(installDir)); +} + +/** + * Get the path to a bundled speculos archive, if one exists for the given + * platform and architecture. + * + * Bundled archives are pre-packaged tar.gz files in the `bundled/` directory + * next to the compiled `dist/` output. They allow the binary to be used + * without a network download. + * + * @param version - The speculos version. + * @param platform - The target platform. + * @param targetArch - The target architecture. + * @param packageDir - The package root directory containing bundled/. + * @returns The absolute path to the bundled archive, or `null` if not found. + */ +export function getBundledArchivePath( + version: string, + platform: Platform, + targetArch: string, + packageDir: string, +): string | null { + const fileName = `speculos-v${version}-${String(platform)}-${targetArch}.tar.gz`; + const archivePath = join(packageDir, 'bundled', fileName); + return existsSync(archivePath) ? archivePath : null; +} + +/** + * Compute the SHA-256 checksum of a file. + * + * @param filePath - The path to the file. + * @returns The lowercase hex-encoded SHA-256 digest. + * @throws If the file cannot be read. + */ +export async function computeFileSha256(filePath: string): Promise { + const fileBuffer = await readFile(filePath); + return createHash('sha256').update(fileBuffer).digest('hex'); +} + +/** + * Get the error message from an unknown error value. + * + * @param error - The error value. + * @returns A human-readable message. + */ +function getErrorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +/** + * Load and validate a checksums file. + * + * The file must contain a JSON object mapping archive filenames to hex-encoded + * checksum strings. + * + * @param checksumsPath - The path to the checksums JSON file. + * @returns The parsed checksums map. + * @throws If the file is unreadable, not valid JSON, or has an invalid shape. + * Verification must fail closed in those cases. + */ +export async function loadChecksumsFile( + checksumsPath: string, +): Promise> { + let contents: string; + try { + contents = await readFile(checksumsPath, 'utf8'); + } catch (error) { + throw new Error( + `Unable to read checksums file "${checksumsPath}": ${getErrorMessage(error)}`, + ); + } + + let parsed: unknown; + try { + parsed = JSON.parse(contents); + } catch (error) { + throw new Error( + `Checksums file "${checksumsPath}" is not valid JSON: ${getErrorMessage(error)}`, + ); + } + + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) { + throw new Error( + `Checksums file "${checksumsPath}" must contain a JSON object mapping archive filenames to SHA-256 checksums.`, + ); + } + + const checksums: Record = {}; + for (const [fileName, checksum] of Object.entries(parsed)) { + if (typeof checksum !== 'string' || checksum.length === 0) { + throw new Error( + `Checksums file "${checksumsPath}" has an invalid checksum for "${fileName}": expected a non-empty string.`, + ); + } + checksums[fileName] = checksum; + } + return checksums; +} + +/** + * Get the required checksum for a file from a checksums file. + * + * @param checksumsPath - The path to the checksums JSON file. + * @param fileName - The archive filename to look up. + * @returns The expected checksum. + * @throws If the checksums file is unreadable or malformed, or if no checksum + * is recorded for the given filename. Verification must fail closed in those + * cases. + */ +export async function getRequiredChecksum( + checksumsPath: string, + fileName: string, +): Promise { + const checksums = await loadChecksumsFile(checksumsPath); + const expected = checksums[fileName]; + if (expected === undefined) { + throw new Error( + `No checksum recorded for "${fileName}" in "${checksumsPath}"; refusing to install an unverified archive.`, + ); + } + return expected; +} + +/** + * Check whether a path is equal to or nested inside another path. + * + * Both paths are resolved before comparison, so relative segments such as `..` + * are taken into account. + * + * @param rootPath - The root path. + * @param candidatePath - The path to check. + * @returns True if the candidate path is the root itself or inside it. + */ +export function isPathWithin(rootPath: string, candidatePath: string): boolean { + const relativePath = relative(resolve(rootPath), resolve(candidatePath)); + if (relativePath === '') { + return true; + } + return ( + relativePath !== '..' && + !relativePath.startsWith(`..${sep}`) && + !isAbsolute(relativePath) + ); +} diff --git a/packages/speculos-up/tsconfig.build.json b/packages/speculos-up/tsconfig.build.json new file mode 100644 index 000000000..7fffda54d --- /dev/null +++ b/packages/speculos-up/tsconfig.build.json @@ -0,0 +1,13 @@ +{ + "extends": "../../tsconfig.packages.build.json", + "compilerOptions": { + "baseUrl": "./", + "outDir": "dist", + "rootDir": "src", + "moduleResolution": "NodeNext", + "skipLibCheck": true, + "paths": {} + }, + "include": ["./src/**/*.ts"], + "exclude": ["./src/**/*.test.ts", "./src/**/*.test-d.ts"] +} diff --git a/packages/speculos-up/tsconfig.json b/packages/speculos-up/tsconfig.json new file mode 100644 index 000000000..0d2dc33a6 --- /dev/null +++ b/packages/speculos-up/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig.packages.json", + "compilerOptions": { + "baseUrl": "./", + "moduleResolution": "NodeNext", + "skipLibCheck": true + }, + "include": ["./src"], + "exclude": ["./dist/**/*"] +} diff --git a/tsconfig.build.json b/tsconfig.build.json index 92a9dba76..172048a83 100644 --- a/tsconfig.build.json +++ b/tsconfig.build.json @@ -18,6 +18,8 @@ { "path": "./packages/keyring-sdk/tsconfig.build.json" }, { "path": "./packages/keyring-snap-sdk/tsconfig.build.json" }, { "path": "./packages/keyring-utils/tsconfig.build.json" }, + { "path": "./packages/speculos-up/tsconfig.build.json" }, + { "path": "./packages/hw-emulator/tsconfig.build.json" }, { "path": "./packages/keyring-watch-only/tsconfig.build.json" } ], "files": [], diff --git a/tsconfig.json b/tsconfig.json index 846232da9..5864d9402 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -16,6 +16,8 @@ { "path": "./packages/keyring-sdk" }, { "path": "./packages/keyring-snap-sdk" }, { "path": "./packages/keyring-utils" }, + { "path": "./packages/speculos-up" }, + { "path": "./packages/hw-emulator" }, { "path": "./packages/keyring-watch-only" } ], "files": [], diff --git a/yarn.config.cjs b/yarn.config.cjs index ba5acfba5..7c75f80c5 100644 --- a/yarn.config.cjs +++ b/yarn.config.cjs @@ -23,7 +23,34 @@ const { inspect } = require('util'); * Only intended as temporary measures to faciliate upgrades and releases. * This should trend towards empty. */ -const ALLOWED_INCONSISTENT_DEPENDENCIES = {}; +const ALLOWED_INCONSISTENT_DEPENDENCIES = { + // hw-emulator and speculos-up intentionally track latest ahead of the rest of + // the monorepo. Reconcile when the other packages move to the same majors. + '@ethereumjs/common': ['^10.1.3'], + '@ethereumjs/rlp': ['^10.1.3'], + '@ethereumjs/tx': ['^10.1.3'], + '@ethereumjs/util': ['^10.1.3'], + '@keystonehq/bc-ur-registry-eth': ['^0.23.2'], + '@lavamoat/allow-scripts': ['^5.1.1'], + '@lavamoat/preinstall-always-fail': ['^3.0.2'], + '@metamask/auto-changelog': ['^7.1.0'], + '@metamask/eth-sig-util': ['^10.0.1'], + '@ts-bridge/cli': ['^0.6.4'], + '@types/jest': ['^30.0.0'], + '@types/node': ['^26.6.11'], + '@types/ws': ['^8.18.2'], + deepmerge: ['^4.3.1'], + 'ethereum-cryptography': ['^3.2.0'], + jest: ['^30.5.2'], + 'jest-it-up': ['^5.0.1'], + rimraf: ['^6.1.4'], + secp256k1: ['^5.0.2'], + 'ts-jest': ['^29.4.15'], + tsd: ['^0.33.0'], + typedoc: ['^0.28.20'], + typescript: ['~5.9.3'], + uuid: ['^11.1.1'], +}; /** * These packages are allowed to use a pinned (exact) version rather than a diff --git a/yarn.lock b/yarn.lock index f9e09e32d..bedc0a5a9 100644 --- a/yarn.lock +++ b/yarn.lock @@ -19,152 +19,158 @@ __metadata: languageName: node linkType: hard -"@ampproject/remapping@npm:^2.2.0": - version: 2.3.0 - resolution: "@ampproject/remapping@npm:2.3.0" +"@arcanis/slice-ansi@npm:^1.1.1": + version: 1.1.1 + resolution: "@arcanis/slice-ansi@npm:1.1.1" dependencies: - "@jridgewell/gen-mapping": "npm:^0.3.5" - "@jridgewell/trace-mapping": "npm:^0.3.24" - checksum: 10/f3451525379c68a73eb0a1e65247fbf28c0cccd126d93af21c75fceff77773d43c0d4a2d51978fb131aff25b5f2cb41a9fe48cc296e61ae65e679c4f6918b0ab + grapheme-splitter: "npm:^1.0.4" + checksum: 10/14ed60cb45750d386c64229ac7bab20e10eedc193503fa4decff764162d329d6d3363ed2cd3debec833186ee54affe4f824f6e8eff531295117fd1ebda200270 languageName: node linkType: hard -"@babel/code-frame@npm:^7.0.0, @babel/code-frame@npm:^7.12.13, @babel/code-frame@npm:^7.24.7, @babel/code-frame@npm:^7.26.2": - version: 7.26.2 - resolution: "@babel/code-frame@npm:7.26.2" +"@babel/code-frame@npm:^7.0.0, @babel/code-frame@npm:^7.12.13, @babel/code-frame@npm:^7.27.1, @babel/code-frame@npm:^7.29.7": + version: 7.29.7 + resolution: "@babel/code-frame@npm:7.29.7" dependencies: - "@babel/helper-validator-identifier": "npm:^7.25.9" + "@babel/helper-validator-identifier": "npm:^7.29.7" js-tokens: "npm:^4.0.0" - picocolors: "npm:^1.0.0" - checksum: 10/db2c2122af79d31ca916755331bb4bac96feb2b334cdaca5097a6b467fdd41963b89b14b6836a14f083de7ff887fc78fa1b3c10b14e743d33e12dbfe5ee3d223 + picocolors: "npm:^1.1.1" + checksum: 10/84da552e51a55795a50b3589116edb2f9e368a647d266380683775f18effd9acd4521b0246bebd0b049a7f32af1f87b1e8475d3bcb665f876bd04ade8da99697 languageName: node linkType: hard -"@babel/compat-data@npm:^7.25.2": - version: 7.25.4 - resolution: "@babel/compat-data@npm:7.25.4" - checksum: 10/d37a8936cc355a9ca3050102e03d179bdae26bd2e5c99a977637376c192b23637a039795f153c849437a086727628c9860e2c6af92d7151396e2362c09176337 +"@babel/compat-data@npm:^7.29.7": + version: 7.29.7 + resolution: "@babel/compat-data@npm:7.29.7" + checksum: 10/ad2272714087f68970977f6e2b53597a8503fc9c3028c4a91686474bd77a707dd00903cdde4b73788972016d1bad4dc3fa4e5ff38e1ed8f1c3bde1095352973a languageName: node linkType: hard -"@babel/core@npm:^7.11.6, @babel/core@npm:^7.12.3, @babel/core@npm:^7.23.2, @babel/core@npm:^7.23.9": - version: 7.25.2 - resolution: "@babel/core@npm:7.25.2" +"@babel/core@npm:^7.11.6, @babel/core@npm:^7.12.3, @babel/core@npm:^7.23.2, @babel/core@npm:^7.23.9, @babel/core@npm:^7.27.4": + version: 7.29.16 + resolution: "@babel/core@npm:7.29.16" dependencies: - "@ampproject/remapping": "npm:^2.2.0" - "@babel/code-frame": "npm:^7.24.7" - "@babel/generator": "npm:^7.25.0" - "@babel/helper-compilation-targets": "npm:^7.25.2" - "@babel/helper-module-transforms": "npm:^7.25.2" - "@babel/helpers": "npm:^7.25.0" - "@babel/parser": "npm:^7.25.0" - "@babel/template": "npm:^7.25.0" - "@babel/traverse": "npm:^7.25.2" - "@babel/types": "npm:^7.25.2" + "@babel/code-frame": "npm:^7.29.7" + "@babel/generator": "npm:^7.29.16" + "@babel/helper-compilation-targets": "npm:^7.29.13" + "@babel/helper-module-transforms": "npm:^7.29.16" + "@babel/helpers": "npm:^7.29.16" + "@babel/parser": "npm:^7.29.15" + "@babel/template": "npm:^7.29.7" + "@babel/traverse": "npm:^7.29.16" + "@babel/types": "npm:^7.29.15" + "@jridgewell/remapping": "npm:^2.3.5" convert-source-map: "npm:^2.0.0" debug: "npm:^4.1.0" gensync: "npm:^1.0.0-beta.2" json5: "npm:^2.2.3" semver: "npm:^6.3.1" - checksum: 10/0d6ec10ff430df66f654c089d6f7ef1d9bed0c318ac257ad5f0dfa0caa45666011828ae75f998bcdb279763e892b091b2925d0bc483299e61649d2c7a2245e33 + checksum: 10/9419824a1991c21049a30b112f425d9ed26e22bd75fe7c792f2a3cb9c48d2e1597f0fb48330dff282d692cb08157ebfb4ac3387b3c26e1e29c938746bbf19533 languageName: node linkType: hard -"@babel/generator@npm:^7.25.0, @babel/generator@npm:^7.26.9, @babel/generator@npm:^7.7.2": - version: 7.26.9 - resolution: "@babel/generator@npm:7.26.9" +"@babel/generator@npm:^7.27.5, @babel/generator@npm:^7.29.16, @babel/generator@npm:^7.7.2": + version: 7.29.16 + resolution: "@babel/generator@npm:7.29.16" dependencies: - "@babel/parser": "npm:^7.26.9" - "@babel/types": "npm:^7.26.9" - "@jridgewell/gen-mapping": "npm:^0.3.5" - "@jridgewell/trace-mapping": "npm:^0.3.25" + "@babel/parser": "npm:^7.29.15" + "@babel/types": "npm:^7.29.15" + "@jridgewell/gen-mapping": "npm:^0.3.12" + "@jridgewell/trace-mapping": "npm:^0.3.28" jsesc: "npm:^3.0.2" - checksum: 10/95075dd6158a49efcc71d7f2c5d20194fcf245348de7723ca35e37cd5800587f1d4de2be6c4ba87b5f5fbb967c052543c109eaab14b43f6a73eb05ccd9a5bb44 + checksum: 10/86580d5b63a963185447d32b209cf342c7df364013239f1369aa843e2622a4c0c676014cfa68db962205bcbbe36f2be4515145ca98a3633e3b44a92a587832dc languageName: node linkType: hard -"@babel/helper-compilation-targets@npm:^7.25.2": - version: 7.25.2 - resolution: "@babel/helper-compilation-targets@npm:7.25.2" +"@babel/helper-compilation-targets@npm:^7.29.13": + version: 7.29.13 + resolution: "@babel/helper-compilation-targets@npm:7.29.13" dependencies: - "@babel/compat-data": "npm:^7.25.2" - "@babel/helper-validator-option": "npm:^7.24.8" - browserslist: "npm:^4.23.1" + "@babel/compat-data": "npm:^7.29.7" + "@babel/helper-validator-option": "npm:^7.29.7" + browserslist: "npm:^4.24.0" lru-cache: "npm:^5.1.1" semver: "npm:^6.3.1" - checksum: 10/eccb2d75923d2d4d596f9ff64716e8664047c4192f1b44c7d5c07701d4a3498ac2587a72ddae1046e65a501bc630eb7df4557958b08ec2dcf5b4a264a052f111 + checksum: 10/19463d12a5e011df9784860c1fdb648b5754dde37653ff8deb6a47e86fac4eee8e051f8fe29ef8194763b3b7d8fb433bed389012f3af1fcf34d9b1b2149d2394 + languageName: node + linkType: hard + +"@babel/helper-globals@npm:^7.29.7": + version: 7.29.7 + resolution: "@babel/helper-globals@npm:7.29.7" + checksum: 10/e53203e87ae24a45f59639edea0c429bc3c63c6d74f1862fe60a35032d89478e7511d2f34855da0fcb65782668d72e59e93d1de5bc00121ba9bc1aa38f1f0ad3 languageName: node linkType: hard -"@babel/helper-module-imports@npm:^7.25.9": - version: 7.25.9 - resolution: "@babel/helper-module-imports@npm:7.25.9" +"@babel/helper-module-imports@npm:^7.29.7": + version: 7.29.7 + resolution: "@babel/helper-module-imports@npm:7.29.7" dependencies: - "@babel/traverse": "npm:^7.25.9" - "@babel/types": "npm:^7.25.9" - checksum: 10/e090be5dee94dda6cd769972231b21ddfae988acd76b703a480ac0c96f3334557d70a965bf41245d6ee43891e7571a8b400ccf2b2be5803351375d0f4e5bcf08 + "@babel/traverse": "npm:^7.29.7" + "@babel/types": "npm:^7.29.7" + checksum: 10/28ec6f7efd99588d6eebfb25c9f1ccc34cb0cdb0839c4c0f08b3ec0105ccaefbe7e8b4f651f3f55a4f5c4fcb1d979bd32a9b8ee23e3e62163ea22aaa7ee0dfa1 languageName: node linkType: hard -"@babel/helper-module-transforms@npm:^7.25.2": - version: 7.26.0 - resolution: "@babel/helper-module-transforms@npm:7.26.0" +"@babel/helper-module-transforms@npm:^7.29.16": + version: 7.29.16 + resolution: "@babel/helper-module-transforms@npm:7.29.16" dependencies: - "@babel/helper-module-imports": "npm:^7.25.9" - "@babel/helper-validator-identifier": "npm:^7.25.9" - "@babel/traverse": "npm:^7.25.9" + "@babel/helper-module-imports": "npm:^7.29.7" + "@babel/helper-validator-identifier": "npm:^7.29.7" + "@babel/traverse": "npm:^7.29.16" peerDependencies: "@babel/core": ^7.0.0 - checksum: 10/9841d2a62f61ad52b66a72d08264f23052d533afc4ce07aec2a6202adac0bfe43014c312f94feacb3291f4c5aafe681955610041ece2c276271adce3f570f2f5 + checksum: 10/50eeb2456a1d280427315b0e388cbe56c756be210cd79ea02287abad25e8675782720ece7ce9d3b7b941124c34a47a43ea8fc407d830d651004ac6d5f91becd8 languageName: node linkType: hard -"@babel/helper-plugin-utils@npm:^7.0.0, @babel/helper-plugin-utils@npm:^7.10.4, @babel/helper-plugin-utils@npm:^7.12.13, @babel/helper-plugin-utils@npm:^7.25.9, @babel/helper-plugin-utils@npm:^7.8.0": - version: 7.26.5 - resolution: "@babel/helper-plugin-utils@npm:7.26.5" - checksum: 10/1cc0fd8514da3bb249bed6c27227696ab5e84289749d7258098701cffc0c599b7f61ec40dd332f8613030564b79899d9826813c96f966330bcfc7145a8377857 +"@babel/helper-plugin-utils@npm:^7.0.0, @babel/helper-plugin-utils@npm:^7.10.4, @babel/helper-plugin-utils@npm:^7.12.13, @babel/helper-plugin-utils@npm:^7.14.5, @babel/helper-plugin-utils@npm:^7.29.7, @babel/helper-plugin-utils@npm:^7.8.0": + version: 7.29.7 + resolution: "@babel/helper-plugin-utils@npm:7.29.7" + checksum: 10/6d16929fe5c792bbc8e4d67e18d7c1be69d2f18992deaa3d94dc26541fec662e83cbeeaf7553c6867d068eb7aed4e0d5e3e137c1dd4d5bcfa286f8d772f1f457 languageName: node linkType: hard -"@babel/helper-string-parser@npm:^7.25.9": - version: 7.25.9 - resolution: "@babel/helper-string-parser@npm:7.25.9" - checksum: 10/c28656c52bd48e8c1d9f3e8e68ecafd09d949c57755b0d353739eb4eae7ba4f7e67e92e4036f1cd43378cc1397a2c943ed7bcaf5949b04ab48607def0258b775 +"@babel/helper-string-parser@npm:^7.29.15": + version: 7.29.15 + resolution: "@babel/helper-string-parser@npm:7.29.15" + checksum: 10/f47627415e209bbfd83f9a4b2273eec30e9a30e087f65421055c6d5bf74ae30be5283d7ab340202a86022f266a5e48535748614491f6444e3248255829050052 languageName: node linkType: hard -"@babel/helper-validator-identifier@npm:^7.25.9": - version: 7.25.9 - resolution: "@babel/helper-validator-identifier@npm:7.25.9" - checksum: 10/3f9b649be0c2fd457fa1957b694b4e69532a668866b8a0d81eabfa34ba16dbf3107b39e0e7144c55c3c652bf773ec816af8df4a61273a2bb4eb3145ca9cf478e +"@babel/helper-validator-identifier@npm:^7.29.7": + version: 7.29.7 + resolution: "@babel/helper-validator-identifier@npm:7.29.7" + checksum: 10/2efa42701eb05babf26dff3332109c9e5e1a3400a71fb9e68ee27af28235036a2a72c2494c04bdab3f909075f42a58b2e8271074372bc7f8e79ec02bd364d7a7 languageName: node linkType: hard -"@babel/helper-validator-option@npm:^7.24.8": - version: 7.25.9 - resolution: "@babel/helper-validator-option@npm:7.25.9" - checksum: 10/9491b2755948ebbdd68f87da907283698e663b5af2d2b1b02a2765761974b1120d5d8d49e9175b167f16f72748ffceec8c9cf62acfbee73f4904507b246e2b3d +"@babel/helper-validator-option@npm:^7.29.7": + version: 7.29.7 + resolution: "@babel/helper-validator-option@npm:7.29.7" + checksum: 10/aeb6aa966f59300d3cc2fea7c68e1dfd7ad011fc10e535c8e2b2de3094b27c859428dc7220f16420350f8b1cde99da120b673be04bcb0c2f37b56258c96bed58 languageName: node linkType: hard -"@babel/helpers@npm:^7.25.0": - version: 7.25.0 - resolution: "@babel/helpers@npm:7.25.0" +"@babel/helpers@npm:^7.29.16": + version: 7.29.16 + resolution: "@babel/helpers@npm:7.29.16" dependencies: - "@babel/template": "npm:^7.25.0" - "@babel/types": "npm:^7.25.0" - checksum: 10/4fcb8167eba9853e30b8b235b81b923ef7b707396b0e23d7a4fa3e811729506755576cb9ec736e8b92cf19e5a1ec61e83d182904d8e6a0953803c6bebc2e1592 + "@babel/template": "npm:^7.29.7" + "@babel/types": "npm:^7.29.15" + checksum: 10/a579bee616f746b68044e009124efd09be52fb1e742abed4fa28cba7fda67f40e12c11d3771edd0bc1f06ae38de3d00d70fafed53586bc7d9a17224ffe8c37bd languageName: node linkType: hard -"@babel/parser@npm:^7.1.0, @babel/parser@npm:^7.14.7, @babel/parser@npm:^7.23.0, @babel/parser@npm:^7.23.9, @babel/parser@npm:^7.24.7, @babel/parser@npm:^7.25.0, @babel/parser@npm:^7.26.9": - version: 7.26.9 - resolution: "@babel/parser@npm:7.26.9" +"@babel/parser@npm:^7.1.0, @babel/parser@npm:^7.14.7, @babel/parser@npm:^7.20.7, @babel/parser@npm:^7.23.0, @babel/parser@npm:^7.23.9, @babel/parser@npm:^7.24.7, @babel/parser@npm:^7.29.15, @babel/parser@npm:^7.29.7": + version: 7.29.15 + resolution: "@babel/parser@npm:7.29.15" dependencies: - "@babel/types": "npm:^7.26.9" + "@babel/types": "npm:^7.29.15" bin: parser: ./bin/babel-parser.js - checksum: 10/cb84fe3ba556d6a4360f3373cf7eb0901c46608c8d77330cc1ca021d60f5d6ebb4056a8e7f9dd0ef231923ef1fe69c87b11ce9e160d2252e089a20232a2b942b + checksum: 10/5d3866c3baaa4f21cdbf3eca12a293bc0d0f6916f8180ca6a3109a7813f600bc97746101f7283d83329e8977ce269af5f501ac2b4e1df6acfffa640c578d77cd languageName: node linkType: hard @@ -190,18 +196,40 @@ __metadata: languageName: node linkType: hard -"@babel/plugin-syntax-class-properties@npm:^7.8.3": - version: 7.10.4 - resolution: "@babel/plugin-syntax-class-properties@npm:7.10.4" +"@babel/plugin-syntax-class-properties@npm:^7.12.13": + version: 7.12.13 + resolution: "@babel/plugin-syntax-class-properties@npm:7.12.13" dependencies: - "@babel/helper-plugin-utils": "npm:^7.10.4" + "@babel/helper-plugin-utils": "npm:^7.12.13" + peerDependencies: + "@babel/core": ^7.0.0-0 + checksum: 10/24f34b196d6342f28d4bad303612d7ff566ab0a013ce89e775d98d6f832969462e7235f3e7eaf17678a533d4be0ba45d3ae34ab4e5a9dcbda5d98d49e5efa2fc + languageName: node + linkType: hard + +"@babel/plugin-syntax-class-static-block@npm:^7.14.5": + version: 7.14.5 + resolution: "@babel/plugin-syntax-class-static-block@npm:7.14.5" + dependencies: + "@babel/helper-plugin-utils": "npm:^7.14.5" + peerDependencies: + "@babel/core": ^7.0.0-0 + checksum: 10/3e80814b5b6d4fe17826093918680a351c2d34398a914ce6e55d8083d72a9bdde4fbaf6a2dcea0e23a03de26dc2917ae3efd603d27099e2b98380345703bf948 + languageName: node + linkType: hard + +"@babel/plugin-syntax-import-attributes@npm:^7.24.7": + version: 7.29.7 + resolution: "@babel/plugin-syntax-import-attributes@npm:7.29.7" + dependencies: + "@babel/helper-plugin-utils": "npm:^7.29.7" peerDependencies: "@babel/core": ^7.0.0-0 - checksum: 10/454db1392c5415abf0681a619e71c667df94f7c7587767016b804c4b84180ed4fc00cefcae677850fa356c991085ab61ae524c4d4bab95445cb4aa0a3af96017 + checksum: 10/9f47345d09aae16b7ab52ecaf541cde3e3ae1e57e3eb2d4088e062b29dfbd67db55d42d529840557583d66121e2a98788df7a455401cc6d635c8b7700a02efc9 languageName: node linkType: hard -"@babel/plugin-syntax-import-meta@npm:^7.8.3": +"@babel/plugin-syntax-import-meta@npm:^7.10.4": version: 7.10.4 resolution: "@babel/plugin-syntax-import-meta@npm:7.10.4" dependencies: @@ -223,18 +251,18 @@ __metadata: languageName: node linkType: hard -"@babel/plugin-syntax-jsx@npm:^7.7.2": - version: 7.25.9 - resolution: "@babel/plugin-syntax-jsx@npm:7.25.9" +"@babel/plugin-syntax-jsx@npm:^7.27.1, @babel/plugin-syntax-jsx@npm:^7.7.2": + version: 7.29.7 + resolution: "@babel/plugin-syntax-jsx@npm:7.29.7" dependencies: - "@babel/helper-plugin-utils": "npm:^7.25.9" + "@babel/helper-plugin-utils": "npm:^7.29.7" peerDependencies: "@babel/core": ^7.0.0-0 - checksum: 10/bb609d1ffb50b58f0c1bac8810d0e46a4f6c922aa171c458f3a19d66ee545d36e782d3bffbbc1fed0dc65a558bdce1caf5279316583c0fff5a2c1658982a8563 + checksum: 10/84150d27c553a1d3d921354437f6725ca1d63b49514c25591bfcaaafa6ea4d6c10715b66fe7245e4ad7ab7c6cf4b6e1de7373defd3df00877ab12638170d7772 languageName: node linkType: hard -"@babel/plugin-syntax-logical-assignment-operators@npm:^7.8.3": +"@babel/plugin-syntax-logical-assignment-operators@npm:^7.10.4": version: 7.10.4 resolution: "@babel/plugin-syntax-logical-assignment-operators@npm:7.10.4" dependencies: @@ -256,7 +284,7 @@ __metadata: languageName: node linkType: hard -"@babel/plugin-syntax-numeric-separator@npm:^7.8.3": +"@babel/plugin-syntax-numeric-separator@npm:^7.10.4": version: 7.10.4 resolution: "@babel/plugin-syntax-numeric-separator@npm:7.10.4" dependencies: @@ -300,61 +328,72 @@ __metadata: languageName: node linkType: hard -"@babel/plugin-syntax-top-level-await@npm:^7.8.3": - version: 7.12.13 - resolution: "@babel/plugin-syntax-top-level-await@npm:7.12.13" +"@babel/plugin-syntax-private-property-in-object@npm:^7.14.5": + version: 7.14.5 + resolution: "@babel/plugin-syntax-private-property-in-object@npm:7.14.5" dependencies: - "@babel/helper-plugin-utils": "npm:^7.12.13" + "@babel/helper-plugin-utils": "npm:^7.14.5" + peerDependencies: + "@babel/core": ^7.0.0-0 + checksum: 10/b317174783e6e96029b743ccff2a67d63d38756876e7e5d0ba53a322e38d9ca452c13354a57de1ad476b4c066dbae699e0ca157441da611117a47af88985ecda + languageName: node + linkType: hard + +"@babel/plugin-syntax-top-level-await@npm:^7.14.5": + version: 7.14.5 + resolution: "@babel/plugin-syntax-top-level-await@npm:7.14.5" + dependencies: + "@babel/helper-plugin-utils": "npm:^7.14.5" peerDependencies: "@babel/core": ^7.0.0-0 - checksum: 10/74cf8c8b8715ec0de6c55b96af4907cfa3bbf87dbaecdc4c30acac8c30d281d62c578001faf8f99e1884e1ccb933f5a919eb184c542b92fcef7bdefe64482c39 + checksum: 10/bbd1a56b095be7820029b209677b194db9b1d26691fe999856462e66b25b281f031f3dfd91b1619e9dcf95bebe336211833b854d0fb8780d618e35667c2d0d7e languageName: node linkType: hard -"@babel/plugin-syntax-typescript@npm:^7.7.2": - version: 7.25.9 - resolution: "@babel/plugin-syntax-typescript@npm:7.25.9" +"@babel/plugin-syntax-typescript@npm:^7.27.1, @babel/plugin-syntax-typescript@npm:^7.7.2": + version: 7.29.7 + resolution: "@babel/plugin-syntax-typescript@npm:7.29.7" dependencies: - "@babel/helper-plugin-utils": "npm:^7.25.9" + "@babel/helper-plugin-utils": "npm:^7.29.7" peerDependencies: "@babel/core": ^7.0.0-0 - checksum: 10/0e9821e8ba7d660c36c919654e4144a70546942ae184e85b8102f2322451eae102cbfadbcadd52ce077a2b44b400ee52394c616feab7b5b9f791b910e933fd33 + checksum: 10/ef454d2a7a6209dd4255361c072c94ab1293e7ad4b06e7e744d08bb308065d4d6544964eae9b2357c3b33d8d939f9e32d4aa95905bc464407cd8f7101dee4443 languageName: node linkType: hard -"@babel/template@npm:^7.25.0, @babel/template@npm:^7.26.9, @babel/template@npm:^7.3.3": - version: 7.26.9 - resolution: "@babel/template@npm:7.26.9" +"@babel/template@npm:^7.29.7, @babel/template@npm:^7.3.3": + version: 7.29.7 + resolution: "@babel/template@npm:7.29.7" dependencies: - "@babel/code-frame": "npm:^7.26.2" - "@babel/parser": "npm:^7.26.9" - "@babel/types": "npm:^7.26.9" - checksum: 10/240288cebac95b1cc1cb045ad143365643da0470e905e11731e63280e43480785bd259924f4aea83898ef68e9fa7c176f5f2d1e8b0a059b27966e8ca0b41a1b6 + "@babel/code-frame": "npm:^7.29.7" + "@babel/parser": "npm:^7.29.7" + "@babel/types": "npm:^7.29.7" + checksum: 10/da92f7a5b61e05d2fb3934a44f18cec6006ee3c595116c17a3b44cb9756ecd43205c7360dbfa326fa8f4d00aaeb9e777342a881070d11c2305e9c694bc3ca6ff languageName: node linkType: hard -"@babel/traverse@npm:^7.23.2, @babel/traverse@npm:^7.25.2, @babel/traverse@npm:^7.25.9": - version: 7.26.9 - resolution: "@babel/traverse@npm:7.26.9" +"@babel/traverse@npm:^7.23.2, @babel/traverse@npm:^7.29.16, @babel/traverse@npm:^7.29.7": + version: 7.29.16 + resolution: "@babel/traverse@npm:7.29.16" dependencies: - "@babel/code-frame": "npm:^7.26.2" - "@babel/generator": "npm:^7.26.9" - "@babel/parser": "npm:^7.26.9" - "@babel/template": "npm:^7.26.9" - "@babel/types": "npm:^7.26.9" + "@babel/code-frame": "npm:^7.29.7" + "@babel/generator": "npm:^7.29.16" + "@babel/helper-globals": "npm:^7.29.7" + "@babel/parser": "npm:^7.29.15" + "@babel/template": "npm:^7.29.7" + "@babel/types": "npm:^7.29.15" debug: "npm:^4.3.1" - globals: "npm:^11.1.0" - checksum: 10/c16a79522eafa0a7e40eb556bf1e8a3d50dbb0ff943a80f2c06cee2ec7ff87baa0c5d040a5cff574d9bcb3bed05e7d8c6f13b238a931c97267674b02c6cf45b4 + checksum: 10/85e9515d7f5cbf4cc3102078f2e67ccaf24f040463cf179dba0168109c454505c8c153516b1644c396b2b5d386ae7488f08c0c21e4c0c44729e58ada0d18c5e5 languageName: node linkType: hard -"@babel/types@npm:^7.0.0, @babel/types@npm:^7.23.0, @babel/types@npm:^7.25.0, @babel/types@npm:^7.25.2, @babel/types@npm:^7.25.9, @babel/types@npm:^7.26.9, @babel/types@npm:^7.3.0, @babel/types@npm:^7.3.3": - version: 7.26.9 - resolution: "@babel/types@npm:7.26.9" +"@babel/types@npm:^7.0.0, @babel/types@npm:^7.20.7, @babel/types@npm:^7.23.0, @babel/types@npm:^7.27.3, @babel/types@npm:^7.29.15, @babel/types@npm:^7.29.7, @babel/types@npm:^7.3.0, @babel/types@npm:^7.3.3": + version: 7.29.15 + resolution: "@babel/types@npm:7.29.15" dependencies: - "@babel/helper-string-parser": "npm:^7.25.9" - "@babel/helper-validator-identifier": "npm:^7.25.9" - checksum: 10/11b62ea7ed64ef7e39cc9b33852c1084064c3b970ae0eaa5db659241cfb776577d1e68cbff4de438bada885d3a827b52cc0f3746112d8e1bc672bb99a8eb5b56 + "@babel/helper-string-parser": "npm:^7.29.15" + "@babel/helper-validator-identifier": "npm:^7.29.7" + checksum: 10/8500f1961da3139738b1d2dc41e1da0ac38be815f819be456b3fac2424c62c385b966751359d5971f9dfcccf9dc08166cfa0668c0d97f027d4b895b3dc7f3799 languageName: node linkType: hard @@ -510,13 +549,13 @@ __metadata: languageName: node linkType: hard -"@ethereumjs/common@npm:^10.0.0": - version: 10.0.0 - resolution: "@ethereumjs/common@npm:10.0.0" +"@ethereumjs/common@npm:^10.0.0, @ethereumjs/common@npm:^10.1.3": + version: 10.1.3 + resolution: "@ethereumjs/common@npm:10.1.3" dependencies: - "@ethereumjs/util": "npm:^10.0.0" + "@ethereumjs/util": "npm:^10.1.3" eventemitter3: "npm:^5.0.1" - checksum: 10/fc56c436f2452867d41ee880d50bd7cad7188369657dd76c23a2d2171a945a53e11a4d61c4935838c3c1b9d800d2707e61fd74fe3c21800e9f0e0e0fa7581ab6 + checksum: 10/6791d02b724bb8a325cb1676a319668f5b9698e8cfe8663eecc754e692edf4de06f2dd9d9ba68a7d31182f09ed7e59399e348f04fd42c6a85a83ffbb141ceacc languageName: node linkType: hard @@ -539,12 +578,12 @@ __metadata: languageName: node linkType: hard -"@ethereumjs/rlp@npm:^10.0.0": - version: 10.0.0 - resolution: "@ethereumjs/rlp@npm:10.0.0" +"@ethereumjs/rlp@npm:^10.1.3": + version: 10.1.3 + resolution: "@ethereumjs/rlp@npm:10.1.3" bin: rlp: bin/rlp.cjs - checksum: 10/3232f40ecc8dcd440994194925f9b8e74bf8f5eb995f98db9715b924358485ad5f332d529776537cc57e0c3393d1f0955014edbaefffa6935d4919de5f47c47d + checksum: 10/133772dc63837ced485cd666feafc09402bd04195e6f854712f19ce6fb9d5a28a9515c57f12150d26a262aca8939f860dae69e42c3f934fec359d4800beef837 languageName: node linkType: hard @@ -583,15 +622,16 @@ __metadata: languageName: node linkType: hard -"@ethereumjs/tx@npm:^10.0.0": - version: 10.0.0 - resolution: "@ethereumjs/tx@npm:10.0.0" +"@ethereumjs/tx@npm:^10.0.0, @ethereumjs/tx@npm:^10.1.3": + version: 10.1.3 + resolution: "@ethereumjs/tx@npm:10.1.3" dependencies: - "@ethereumjs/common": "npm:^10.0.0" - "@ethereumjs/rlp": "npm:^10.0.0" - "@ethereumjs/util": "npm:^10.0.0" - ethereum-cryptography: "npm:^3.2.0" - checksum: 10/e8dcc31109b921a4e8abd09b735fcc6e26baee80715f55b1caf870189450ebf3b896690487ed22e7408db476080eef655aafdb3551af8cd126743ebf2c46dbb6 + "@ethereumjs/common": "npm:^10.1.3" + "@ethereumjs/rlp": "npm:^10.1.3" + "@ethereumjs/util": "npm:^10.1.3" + "@noble/curves": "npm:^2.0.1" + "@noble/hashes": "npm:^2.0.1" + checksum: 10/5b62923c7ca965de95d823ba314de0f9f935c22f18fd39750723cfcf079baf621bcc0870ecbec6087e5a8b02882f66810b2a7ebbd9291344bc1710f224d1e067 languageName: node linkType: hard @@ -619,7 +659,7 @@ __metadata: languageName: node linkType: hard -"@ethereumjs/util@npm:9.1.0, @ethereumjs/util@npm:^9.0.1, @ethereumjs/util@npm:^9.1.0": +"@ethereumjs/util@npm:9.1.0, @ethereumjs/util@npm:^9.0.1, @ethereumjs/util@npm:^9.0.3, @ethereumjs/util@npm:^9.1.0": version: 9.1.0 resolution: "@ethereumjs/util@npm:9.1.0" dependencies: @@ -629,13 +669,14 @@ __metadata: languageName: node linkType: hard -"@ethereumjs/util@npm:^10.0.0": - version: 10.0.0 - resolution: "@ethereumjs/util@npm:10.0.0" +"@ethereumjs/util@npm:^10.1.3": + version: 10.1.3 + resolution: "@ethereumjs/util@npm:10.1.3" dependencies: - "@ethereumjs/rlp": "npm:^10.0.0" - ethereum-cryptography: "npm:^3.2.0" - checksum: 10/9fa6f50a87978bcbcc8555762089b594dd5d28816dcbbfd24b226c929ee689eb860cb4e7d0385d3a3fcd83a146d8db42a9f17587818296d0964d5a3a1f9039a6 + "@ethereumjs/rlp": "npm:^10.1.3" + "@noble/curves": "npm:^2.0.1" + "@noble/hashes": "npm:^2.0.1" + checksum: 10/d2c0cde3b1c2b76fa26146402207bcb9d7af0dd4c0eed1d65452e6e115e67e8aecaad491531c067c86112a6c3001277594b81470444fdd28ddf12f309ee0da95 languageName: node linkType: hard @@ -887,6 +928,19 @@ __metadata: languageName: node linkType: hard +"@gerrit0/mini-shiki@npm:^3.23.0": + version: 3.23.0 + resolution: "@gerrit0/mini-shiki@npm:3.23.0" + dependencies: + "@shikijs/engine-oniguruma": "npm:^3.23.0" + "@shikijs/langs": "npm:^3.23.0" + "@shikijs/themes": "npm:^3.23.0" + "@shikijs/types": "npm:^3.23.0" + "@shikijs/vscode-textmate": "npm:^10.0.2" + checksum: 10/d44dac7c3f58ba136285b3c15c8a89eba120f7a493dddcf6178601ab8c0a5286da6a19515100297934288c41ae225f21013a4c395fe2f656b58f812dd13ccc1e + languageName: node + linkType: hard + "@humanfs/core@npm:^0.19.1": version: 0.19.1 resolution: "@humanfs/core@npm:0.19.1" @@ -990,6 +1044,13 @@ __metadata: languageName: node linkType: hard +"@isaacs/nonrecursive-glob-match@npm:^1.1.0": + version: 1.1.0 + resolution: "@isaacs/nonrecursive-glob-match@npm:1.1.0" + checksum: 10/ef0e63803b1621f67242e0947bbc316998fc67aabe902be2b7139a818f5350ebfd3a878d535615862acbf6fb0d7de30fdc258c64b910d58c97c7a486dad40dfd + languageName: node + linkType: hard + "@istanbuljs/load-nyc-config@npm:^1.0.0": version: 1.1.0 resolution: "@istanbuljs/load-nyc-config@npm:1.1.0" @@ -1010,6 +1071,20 @@ __metadata: languageName: node linkType: hard +"@jest/console@npm:30.5.2": + version: 30.5.2 + resolution: "@jest/console@npm:30.5.2" + dependencies: + "@jest/types": "npm:30.5.1" + "@types/node": "npm:*" + chalk: "npm:^4.1.2" + jest-message-util: "npm:30.5.1" + jest-util: "npm:30.5.1" + slash: "npm:^3.0.0" + checksum: 10/2dea07a84013f9642dbb07b88b6278057d5dab9e2dc172c905434e7917baffd4af5a0a63a5b45f03f9065171f6ed176091ac78019f6f2c06d95d78ecb98194bd + languageName: node + linkType: hard + "@jest/console@npm:^29.7.0": version: 29.7.0 resolution: "@jest/console@npm:29.7.0" @@ -1024,6 +1099,47 @@ __metadata: languageName: node linkType: hard +"@jest/core@npm:30.5.2": + version: 30.5.2 + resolution: "@jest/core@npm:30.5.2" + dependencies: + "@jest/console": "npm:30.5.2" + "@jest/pattern": "npm:30.5.0" + "@jest/reporters": "npm:30.5.2" + "@jest/test-result": "npm:30.5.2" + "@jest/transform": "npm:30.5.2" + "@jest/types": "npm:30.5.1" + "@types/node": "npm:*" + ansi-escapes: "npm:^4.3.2" + chalk: "npm:^4.1.2" + ci-info: "npm:^4.2.0" + exit-x: "npm:^0.2.2" + fast-json-stable-stringify: "npm:^2.1.0" + graceful-fs: "npm:^4.2.11" + jest-changed-files: "npm:30.5.1" + jest-config: "npm:30.5.2" + jest-haste-map: "npm:30.5.1" + jest-message-util: "npm:30.5.1" + jest-regex-util: "npm:30.5.0" + jest-resolve: "npm:30.5.1" + jest-resolve-dependencies: "npm:30.5.2" + jest-runner: "npm:30.5.2" + jest-runtime: "npm:30.5.2" + jest-snapshot: "npm:30.5.2" + jest-util: "npm:30.5.1" + jest-validate: "npm:30.5.1" + jest-watcher: "npm:30.5.2" + pretty-format: "npm:30.5.1" + slash: "npm:^3.0.0" + peerDependencies: + node-notifier: ^8.0.1 || ^9.0.0 || ^10.0.0 + peerDependenciesMeta: + node-notifier: + optional: true + checksum: 10/2a7b17651410feae891ca7aa54b017de45dcaf52d02b93dc68b77c2cc56f97b9a2eedd878d5ed1d1ef6aebcdc9f13d272ec19705077ab531a9a17a8fbe353dfa + languageName: node + linkType: hard + "@jest/core@npm:^29.7.0": version: 29.7.0 resolution: "@jest/core@npm:29.7.0" @@ -1065,6 +1181,25 @@ __metadata: languageName: node linkType: hard +"@jest/diff-sequences@npm:30.5.0": + version: 30.5.0 + resolution: "@jest/diff-sequences@npm:30.5.0" + checksum: 10/6fdba657e811790850c68beeef9a9d435b77733242c0ff94226cd210bbc11320a39a687bb3037089be7ffc6a2d98f5527d987327a2a18f83ebc87a8fe1e97e2a + languageName: node + linkType: hard + +"@jest/environment@npm:30.5.2": + version: 30.5.2 + resolution: "@jest/environment@npm:30.5.2" + dependencies: + "@jest/fake-timers": "npm:30.5.2" + "@jest/types": "npm:30.5.1" + "@types/node": "npm:*" + jest-mock: "npm:30.5.2" + checksum: 10/c033375dec4c6bacb4ad6ebb6602ace7d87d8c674e4f25aa729a33bc469306105d760b7d7d2a63363b039b364f7e85989e604123c20bc52a32eba302e16cdb9c + languageName: node + linkType: hard + "@jest/environment@npm:^29.7.0": version: 29.7.0 resolution: "@jest/environment@npm:29.7.0" @@ -1077,6 +1212,15 @@ __metadata: languageName: node linkType: hard +"@jest/expect-utils@npm:30.5.2": + version: 30.5.2 + resolution: "@jest/expect-utils@npm:30.5.2" + dependencies: + "@jest/get-type": "npm:30.5.0" + checksum: 10/ca45ae83d0901241e7b561164719c20daae7e23fb7433f7d7c6762d5f825e61dcce062a6191972b00ef72c6d49be6ce2c8a227aeb8777df8dbcca02177d08935 + languageName: node + linkType: hard + "@jest/expect-utils@npm:^29.7.0": version: 29.7.0 resolution: "@jest/expect-utils@npm:29.7.0" @@ -1086,6 +1230,16 @@ __metadata: languageName: node linkType: hard +"@jest/expect@npm:30.5.2": + version: 30.5.2 + resolution: "@jest/expect@npm:30.5.2" + dependencies: + expect: "npm:30.5.2" + jest-snapshot: "npm:30.5.2" + checksum: 10/5d05a885ce180ed007eed09dcb9308a78ea58f6a8924cc1cab0426512abb8ccfe7ed735e3a2307f425460dcd95b67692d2590cbbdebfa84049767b43ba72f2f7 + languageName: node + linkType: hard + "@jest/expect@npm:^29.7.0": version: 29.7.0 resolution: "@jest/expect@npm:29.7.0" @@ -1096,6 +1250,20 @@ __metadata: languageName: node linkType: hard +"@jest/fake-timers@npm:30.5.2": + version: 30.5.2 + resolution: "@jest/fake-timers@npm:30.5.2" + dependencies: + "@jest/types": "npm:30.5.1" + "@sinonjs/fake-timers": "npm:^15.4.0" + "@types/node": "npm:*" + jest-message-util: "npm:30.5.1" + jest-mock: "npm:30.5.2" + jest-util: "npm:30.5.1" + checksum: 10/53a8a093e4191f93c9184fb94820afb062c503dd362c9bd74c785b4c62aad3a10b6a0ab44f258c28125039bbcd5b102aa3006ee5ff39e6f053b903398f6785cc + languageName: node + linkType: hard + "@jest/fake-timers@npm:^29.7.0": version: 29.7.0 resolution: "@jest/fake-timers@npm:29.7.0" @@ -1110,6 +1278,25 @@ __metadata: languageName: node linkType: hard +"@jest/get-type@npm:30.5.0": + version: 30.5.0 + resolution: "@jest/get-type@npm:30.5.0" + checksum: 10/6b67e70f6c1cca6da153814542903b4c385447c7c5e029f8911402ca8a75fbd33a14cc0fff4c6ed7c6c629f6425fade605d6f32eb9516b52146a8640fd899773 + languageName: node + linkType: hard + +"@jest/globals@npm:30.5.2": + version: 30.5.2 + resolution: "@jest/globals@npm:30.5.2" + dependencies: + "@jest/environment": "npm:30.5.2" + "@jest/expect": "npm:30.5.2" + "@jest/types": "npm:30.5.1" + jest-mock: "npm:30.5.2" + checksum: 10/664efe47ae27baf20e1d99e71e44628c0c15b331f55eba66f158a14b51a6a93c20a1e8c190e681ec377d6e98442f3a4855191c599ad156a79cab8cc6c82fda9c + languageName: node + linkType: hard + "@jest/globals@npm:^29.7.0": version: 29.7.0 resolution: "@jest/globals@npm:29.7.0" @@ -1122,6 +1309,66 @@ __metadata: languageName: node linkType: hard +"@jest/pattern@npm:30.5.0": + version: 30.5.0 + resolution: "@jest/pattern@npm:30.5.0" + dependencies: + "@types/node": "npm:*" + jest-regex-util: "npm:30.5.0" + checksum: 10/3a4afb55901cb442ce15d70b46aa59f43c6f39055c92aafd8a3b7982df7a95a9403ed257da2a1585fe5f76df9dd45bdb44994d712994a3c6e6f3ff43e1f37c9b + languageName: node + linkType: hard + +"@jest/react-is-18@npm:react-is@^18.3.1": + version: 18.3.1 + resolution: "react-is@npm:18.3.1" + checksum: 10/d5f60c87d285af24b1e1e7eaeb123ec256c3c8bdea7061ab3932e3e14685708221bf234ec50b21e10dd07f008f1b966a2730a0ce4ff67905b3872ff2042aec22 + languageName: node + linkType: hard + +"@jest/react-is-19@npm:react-is@^19.2.5": + version: 19.3.1 + resolution: "react-is@npm:19.3.1" + checksum: 10/d763db896daf611bc15456abc356b1d4c5c2fa0a68a60c2c53c0199d39c951e0b6891437c649ee41b1b3614f59932e93075834a42a3a52dfcb0cac22289ab191 + languageName: node + linkType: hard + +"@jest/reporters@npm:30.5.2": + version: 30.5.2 + resolution: "@jest/reporters@npm:30.5.2" + dependencies: + "@bcoe/v8-coverage": "npm:^0.2.3" + "@jest/console": "npm:30.5.2" + "@jest/test-result": "npm:30.5.2" + "@jest/transform": "npm:30.5.2" + "@jest/types": "npm:30.5.1" + "@jridgewell/trace-mapping": "npm:^0.3.31" + "@types/node": "npm:*" + chalk: "npm:^4.1.2" + collect-v8-coverage: "npm:^1.0.2" + exit-x: "npm:^0.2.2" + glob: "npm:^13.0.6" + graceful-fs: "npm:^4.2.11" + istanbul-lib-coverage: "npm:^3.0.0" + istanbul-lib-instrument: "npm:^6.0.0" + istanbul-lib-report: "npm:^3.0.0" + istanbul-lib-source-maps: "npm:^5.0.0" + istanbul-reports: "npm:^3.1.3" + jest-message-util: "npm:30.5.1" + jest-util: "npm:30.5.1" + jest-worker: "npm:30.5.1" + slash: "npm:^3.0.0" + string-length: "npm:^4.0.2" + v8-to-istanbul: "npm:^9.0.1" + peerDependencies: + node-notifier: ^8.0.1 || ^9.0.0 || ^10.0.0 + peerDependenciesMeta: + node-notifier: + optional: true + checksum: 10/b5221fb70ae0a379fb8a4dcc593d38004655a5d5e6d20fccac5d717b143503af07c39a4f5007878270cde44373046b9857755151fa03efeb0d6859d3ad3dab81 + languageName: node + linkType: hard + "@jest/reporters@npm:^29.7.0": version: 29.7.0 resolution: "@jest/reporters@npm:29.7.0" @@ -1159,6 +1406,15 @@ __metadata: languageName: node linkType: hard +"@jest/schemas@npm:30.5.0": + version: 30.5.0 + resolution: "@jest/schemas@npm:30.5.0" + dependencies: + "@sinclair/typebox": "npm:^0.34.0" + checksum: 10/8b882db2f056f96f4ef82cafca6270cbc0ab3a6201cd76f43214bc17cc3e16df3e5a10ffc03e5667c2381c8141f7dd79f49d03cb85354b38c33c228c832408e5 + languageName: node + linkType: hard + "@jest/schemas@npm:^29.6.3": version: 29.6.3 resolution: "@jest/schemas@npm:29.6.3" @@ -1168,6 +1424,30 @@ __metadata: languageName: node linkType: hard +"@jest/snapshot-utils@npm:30.5.1": + version: 30.5.1 + resolution: "@jest/snapshot-utils@npm:30.5.1" + dependencies: + "@jest/types": "npm:30.5.1" + chalk: "npm:^4.1.2" + graceful-fs: "npm:^4.2.11" + natural-compare: "npm:^1.4.0" + checksum: 10/9244bb420a48b707697f5d577628f1ce3f151477687dfa7bf7eec788fac9c8eec260d37873bd1283619ad45508b8ea42e97895b49ab825c14572b93223adb7e0 + languageName: node + linkType: hard + +"@jest/source-map@npm:30.5.2": + version: 30.5.2 + resolution: "@jest/source-map@npm:30.5.2" + dependencies: + "@jridgewell/trace-mapping": "npm:^0.3.31" + callsites: "npm:^3.1.0" + convert-source-map: "npm:^2.0.0" + graceful-fs: "npm:^4.2.11" + checksum: 10/c0d76d8537cd167d2c7d43b486254dd2172bfd3c939996e2decf3e34c77cfa38536ddd2de6a315a88b9d08066b18c8324e2b19e6301cebc033ddb3a6b1f8bd0b + languageName: node + linkType: hard + "@jest/source-map@npm:^29.6.3": version: 29.6.3 resolution: "@jest/source-map@npm:29.6.3" @@ -1179,6 +1459,18 @@ __metadata: languageName: node linkType: hard +"@jest/test-result@npm:30.5.2": + version: 30.5.2 + resolution: "@jest/test-result@npm:30.5.2" + dependencies: + "@jest/console": "npm:30.5.2" + "@jest/types": "npm:30.5.1" + "@types/istanbul-lib-coverage": "npm:^2.0.6" + collect-v8-coverage: "npm:^1.0.2" + checksum: 10/a72b61ab6e23bf63d1eacb83ed5d0c756a8eebb41f0e4133098ecb0fc3e336f93019cac20924aa347cb25f92fefa0393d118205b57b18da4925ca1ffd1c7cd8f + languageName: node + linkType: hard + "@jest/test-result@npm:^29.7.0": version: 29.7.0 resolution: "@jest/test-result@npm:29.7.0" @@ -1191,6 +1483,18 @@ __metadata: languageName: node linkType: hard +"@jest/test-sequencer@npm:30.5.2": + version: 30.5.2 + resolution: "@jest/test-sequencer@npm:30.5.2" + dependencies: + "@jest/test-result": "npm:30.5.2" + graceful-fs: "npm:^4.2.11" + jest-haste-map: "npm:30.5.1" + slash: "npm:^3.0.0" + checksum: 10/f4696a7dcdc5b19e8c1f80701fc5fc3eee8b03ee516a3ccfa0192f73c0f7bd2c36b7c7e7e666afbe7b75a25744423dad7307cb3d5c8a243d438b627efd21afe8 + languageName: node + linkType: hard + "@jest/test-sequencer@npm:^29.7.0": version: 29.7.0 resolution: "@jest/test-sequencer@npm:29.7.0" @@ -1203,6 +1507,28 @@ __metadata: languageName: node linkType: hard +"@jest/transform@npm:30.5.2": + version: 30.5.2 + resolution: "@jest/transform@npm:30.5.2" + dependencies: + "@babel/core": "npm:^7.27.4" + "@jest/types": "npm:30.5.1" + "@jridgewell/trace-mapping": "npm:^0.3.31" + babel-plugin-istanbul: "npm:^8.0.0" + chalk: "npm:^4.1.2" + convert-source-map: "npm:^2.0.0" + fast-json-stable-stringify: "npm:^2.1.0" + graceful-fs: "npm:^4.2.11" + jest-haste-map: "npm:30.5.1" + jest-regex-util: "npm:30.5.0" + jest-util: "npm:30.5.1" + pirates: "npm:^4.0.7" + slash: "npm:^3.0.0" + write-file-atomic: "npm:^5.0.1" + checksum: 10/5b2d6ce6e0c96ddec62be35c7924f6cb6550340508b63299bb0b88bef822bf9ba43e10baba6b956a0102a664060cc06cb5ae294b6b333cd94ea177c8a22b36e7 + languageName: node + linkType: hard + "@jest/transform@npm:^29.7.0": version: 29.7.0 resolution: "@jest/transform@npm:29.7.0" @@ -1226,6 +1552,21 @@ __metadata: languageName: node linkType: hard +"@jest/types@npm:30.5.1": + version: 30.5.1 + resolution: "@jest/types@npm:30.5.1" + dependencies: + "@jest/pattern": "npm:30.5.0" + "@jest/schemas": "npm:30.5.0" + "@types/istanbul-lib-coverage": "npm:^2.0.6" + "@types/istanbul-reports": "npm:^3.0.4" + "@types/node": "npm:*" + "@types/yargs": "npm:^17.0.33" + chalk: "npm:^4.1.2" + checksum: 10/721d25d6a9f92d972feca03ec3b3a7200f7c1d12c30a91956fffc42516b80068291aa1e195f14dab8ffe56d73298edbe42a47e8924a1380ecf8acc0cc7a01e9d + languageName: node + linkType: hard + "@jest/types@npm:^26.6.2": version: 26.6.2 resolution: "@jest/types@npm:26.6.2" @@ -1253,14 +1594,23 @@ __metadata: languageName: node linkType: hard -"@jridgewell/gen-mapping@npm:^0.3.5": - version: 0.3.5 - resolution: "@jridgewell/gen-mapping@npm:0.3.5" +"@jridgewell/gen-mapping@npm:^0.3.12, @jridgewell/gen-mapping@npm:^0.3.5": + version: 0.3.13 + resolution: "@jridgewell/gen-mapping@npm:0.3.13" dependencies: - "@jridgewell/set-array": "npm:^1.2.1" - "@jridgewell/sourcemap-codec": "npm:^1.4.10" + "@jridgewell/sourcemap-codec": "npm:^1.5.0" + "@jridgewell/trace-mapping": "npm:^0.3.24" + checksum: 10/902f8261dcf450b4af7b93f9656918e02eec80a2169e155000cb2059f90113dd98f3ccf6efc6072cee1dd84cac48cade51da236972d942babc40e4c23da4d62a + languageName: node + linkType: hard + +"@jridgewell/remapping@npm:^2.3.5": + version: 2.3.5 + resolution: "@jridgewell/remapping@npm:2.3.5" + dependencies: + "@jridgewell/gen-mapping": "npm:^0.3.5" "@jridgewell/trace-mapping": "npm:^0.3.24" - checksum: 10/81587b3c4dd8e6c60252122937cea0c637486311f4ed208b52b62aae2e7a87598f63ec330e6cd0984af494bfb16d3f0d60d3b21d7e5b4aedd2602ff3fe9d32e2 + checksum: 10/c2bb01856e65b506d439455f28aceacf130d6c023d1d4e3b48705e88def3571753e1a887daa04b078b562316c92d26ce36408a60534bceca3f830aec88a339ad languageName: node linkType: hard @@ -1271,13 +1621,6 @@ __metadata: languageName: node linkType: hard -"@jridgewell/set-array@npm:^1.2.1": - version: 1.2.1 - resolution: "@jridgewell/set-array@npm:1.2.1" - checksum: 10/832e513a85a588f8ed4f27d1279420d8547743cc37fcad5a5a76fc74bb895b013dfe614d0eed9cb860048e6546b798f8f2652020b4b2ba0561b05caa8c654b10 - languageName: node - linkType: hard - "@jridgewell/sourcemap-codec@npm:^1.4.10, @jridgewell/sourcemap-codec@npm:^1.4.14, @jridgewell/sourcemap-codec@npm:^1.5.0": version: 1.5.0 resolution: "@jridgewell/sourcemap-codec@npm:1.5.0" @@ -1295,13 +1638,13 @@ __metadata: languageName: node linkType: hard -"@jridgewell/trace-mapping@npm:^0.3.12, @jridgewell/trace-mapping@npm:^0.3.18, @jridgewell/trace-mapping@npm:^0.3.24, @jridgewell/trace-mapping@npm:^0.3.25": - version: 0.3.25 - resolution: "@jridgewell/trace-mapping@npm:0.3.25" +"@jridgewell/trace-mapping@npm:^0.3.12, @jridgewell/trace-mapping@npm:^0.3.18, @jridgewell/trace-mapping@npm:^0.3.23, @jridgewell/trace-mapping@npm:^0.3.24, @jridgewell/trace-mapping@npm:^0.3.28, @jridgewell/trace-mapping@npm:^0.3.31": + version: 0.3.31 + resolution: "@jridgewell/trace-mapping@npm:0.3.31" dependencies: "@jridgewell/resolve-uri": "npm:^3.1.0" "@jridgewell/sourcemap-codec": "npm:^1.4.14" - checksum: 10/dced32160a44b49d531b80a4a2159dceab6b3ddf0c8e95a0deae4b0e894b172defa63d5ac52a19c2068e1fe7d31ea4ba931fbeec103233ecb4208953967120fc + checksum: 10/da0283270e691bdb5543806077548532791608e52386cfbbf3b9e8fb00457859d1bd01d512851161c886eb3a2f3ce6fd9bcf25db8edf3bddedd275bd4a88d606 languageName: node linkType: hard @@ -1339,6 +1682,18 @@ __metadata: languageName: node linkType: hard +"@keystonehq/bc-ur-registry-eth@npm:^0.23.2": + version: 0.23.2 + resolution: "@keystonehq/bc-ur-registry-eth@npm:0.23.2" + dependencies: + "@ethereumjs/util": "npm:^9.0.3" + "@keystonehq/bc-ur-registry": "npm:^0.7.0" + hdkey: "npm:^2.0.1" + uuid: "npm:^8.3.2" + checksum: 10/35e7ba1e8cd44ac925f1f0ce062e3bbb8090b4e958b7f5cfc23c805137fcc91439c618e01b7286e750f0f153fc00089833d5debd0bbd6872204da42334f11a0e + languageName: node + linkType: hard + "@keystonehq/bc-ur-registry@npm:^0.6.0": version: 0.6.4 resolution: "@keystonehq/bc-ur-registry@npm:0.6.4" @@ -1350,6 +1705,17 @@ __metadata: languageName: node linkType: hard +"@keystonehq/bc-ur-registry@npm:^0.7.0": + version: 0.7.1 + resolution: "@keystonehq/bc-ur-registry@npm:0.7.1" + dependencies: + "@ngraveio/bc-ur": "npm:^1.1.5" + bs58check: "npm:^2.1.2" + tslib: "npm:^2.3.0" + checksum: 10/6dd2a86ef83d385af93c1064097669baf06965cb051a123731109699eefc512ddf446a622c29e2afd3e559a5e5f98f1e7373e66179e7e027363111b450bc28f7 + languageName: node + linkType: hard + "@keystonehq/metamask-airgapped-keyring@npm:^0.15.2": version: 0.15.2 resolution: "@keystonehq/metamask-airgapped-keyring@npm:0.15.2" @@ -1366,37 +1732,37 @@ __metadata: languageName: node linkType: hard -"@lavamoat/aa@npm:^5.0.1": - version: 5.0.1 - resolution: "@lavamoat/aa@npm:5.0.1" +"@lavamoat/aa@npm:^5.0.2": + version: 5.0.2 + resolution: "@lavamoat/aa@npm:5.0.2" dependencies: resolve: "npm:1.22.12" bin: lavamoat-ls: src/cli.js - checksum: 10/a93db450b850dde46e5ae12383086bc85244c00c2e380fe04f5c59d1d064a6329c3d7eed3d3e15c926a72c6d72976716d2164fee8c8b00254b03a68ce9c9963f + checksum: 10/0f16880717cea1231cd664fe9c511550ded87801348a4a2b7ed884e770731216b7c2be5efcce1ebc7e384ce4f3d0a2b3691612090f04f26a36518508453c3734 languageName: node linkType: hard -"@lavamoat/allow-scripts@npm:^5.1.0": - version: 5.1.0 - resolution: "@lavamoat/allow-scripts@npm:5.1.0" +"@lavamoat/allow-scripts@npm:^5.1.0, @lavamoat/allow-scripts@npm:^5.1.1": + version: 5.1.1 + resolution: "@lavamoat/allow-scripts@npm:5.1.1" dependencies: - "@lavamoat/aa": "npm:^5.0.1" + "@lavamoat/aa": "npm:^5.0.2" "@npmcli/run-script": "npm:10.0.4" bin-links: "npm:4.0.4" npm-normalize-package-bin: "npm:3.0.1" type-fest: "npm:4.41.0" - yargs: "npm:17.7.3" + yargs: "npm:18.0.0" bin: allow-scripts: src/cli.js - checksum: 10/8667aad4c2505796744f7276df7eaa8f155523525c1554a62123f65d35cd6450ae1d73d62670eb1bd851c0fe62ca827d5c65058464682358cef79b72b5081966 + checksum: 10/d83ba6ebac54120386f5ff7c97f29053a055209e32c146294d09fc0b70dc9ec6f53c75b6787d134cf1a0003bc92c195e5b13854fe2755d2821481e24acb28811 languageName: node linkType: hard -"@lavamoat/preinstall-always-fail@npm:^3.0.1": - version: 3.0.1 - resolution: "@lavamoat/preinstall-always-fail@npm:3.0.1" - checksum: 10/8fd13f8279515d26c2334af1e1e93e5399ccce5a1120f5b9e2bdaa1fc2886e772530c5eed6169b65f1866baa67e1a7fefaca6bf8cd9e0709279c4b76f26de285 +"@lavamoat/preinstall-always-fail@npm:^3.0.1, @lavamoat/preinstall-always-fail@npm:^3.0.2": + version: 3.0.2 + resolution: "@lavamoat/preinstall-always-fail@npm:3.0.2" + checksum: 10/5ef0eacca60495898f30ff10c352a936c9302adf307c5efcd5e5a7cb2865a0d2ffe06edd121a49b27543f7dc2006f9331cf1a12a96c64151de2cb55eb948dff7 languageName: node linkType: hard @@ -1492,9 +1858,9 @@ __metadata: linkType: hard "@ledgerhq/errors@npm:^6.19.1": - version: 6.19.1 - resolution: "@ledgerhq/errors@npm:6.19.1" - checksum: 10/8265c6d73c314a4aabbe060ec29e2feebb4e904fe811bf7a9c53cde08e713dcbceded9d927ebb2f0ffc47a7b16524379d4a7e9aa3d61945b8a832be7cd5cf69b + version: 6.35.0 + resolution: "@ledgerhq/errors@npm:6.35.0" + checksum: 10/1bbc4a314d22aca480a5433c9d4b5aded9907c86073ac8678c3f6bb50b6627973f12a5f93040993bf313aed8e8db72ce67758f5ae7b51b5302d8a05cf8055a15 languageName: node linkType: hard @@ -1568,9 +1934,9 @@ __metadata: linkType: hard "@ledgerhq/logs@npm:^6.12.0": - version: 6.12.0 - resolution: "@ledgerhq/logs@npm:6.12.0" - checksum: 10/a0a01f5d6edb0c14e7a42d24ab67ce362219517f6a50d0572c917f4f7988a1e2e9363e3d0fb170fe267f054e1e30a111564de44276e01c538b258d902c546421 + version: 6.17.0 + resolution: "@ledgerhq/logs@npm:6.17.0" + checksum: 10/81332b4db29e1e76ee24f8d741d30152b5c0676e58feedebfde93c7ef4bd641813596d9402d734af779fe3cb6e28599b91b6e6f57ac0017d1231f7d2dad49404 languageName: node linkType: hard @@ -1706,15 +2072,15 @@ __metadata: linkType: hard "@metamask/approval-controller@npm:^9.0.1": - version: 9.0.2 - resolution: "@metamask/approval-controller@npm:9.0.2" + version: 9.0.1 + resolution: "@metamask/approval-controller@npm:9.0.1" dependencies: - "@metamask/base-controller": "npm:^9.1.0" - "@metamask/messenger": "npm:^1.2.0" + "@metamask/base-controller": "npm:^9.0.1" + "@metamask/messenger": "npm:^1.0.0" "@metamask/rpc-errors": "npm:^7.0.2" "@metamask/utils": "npm:^11.9.0" nanoid: "npm:^3.3.8" - checksum: 10/f27d75901a1a8367a8972b30ebb097a063282c8eb40f3188a6255ed1e043313085de6d5feb9300660366d4d93c822ebe6b37219978806db0492c4fed761d3c6a + checksum: 10/980e7ded7022a887c11693226922f9814d160c93fe5297380addafebe9b6e9191ba3acc7bf54775c8c8eeb7e07bcfcaaf79cc90361ff18fa04c1d449eab2ed33 languageName: node linkType: hard @@ -1741,6 +2107,31 @@ __metadata: languageName: node linkType: hard +"@metamask/auto-changelog@npm:^7.1.0": + version: 7.1.0 + resolution: "@metamask/auto-changelog@npm:7.1.0" + dependencies: + "@octokit/rest": "npm:^20.0.0" + "@yarnpkg/core": "npm:4.9.1" + "@yarnpkg/fslib": "npm:^3.1.5" + diff: "npm:^5.0.0" + execa: "npm:^8.0.1" + semver: "npm:^7.8.5" + yargs: "npm:^17.7.2" + peerDependencies: + oxfmt: ^0.45.0 + prettier: ">=3.0.0" + peerDependenciesMeta: + oxfmt: + optional: true + prettier: + optional: true + bin: + auto-changelog: dist/cli.js + checksum: 10/475ef3a198ae17abd81df68831c459e4c7e5322b5970821dc233d1fc607593f7b8e743c7be76aaf4d9b89d71a45c7e374b2a104126e0c5a6bae331ce8160741c + languageName: node + linkType: hard + "@metamask/base-controller@npm:^9.0.1, @metamask/base-controller@npm:^9.1.0": version: 9.1.0 resolution: "@metamask/base-controller@npm:9.1.0" @@ -1775,8 +2166,8 @@ __metadata: linkType: hard "@metamask/controller-utils@npm:^11.19.0": - version: 11.20.0 - resolution: "@metamask/controller-utils@npm:11.20.0" + version: 11.19.0 + resolution: "@metamask/controller-utils@npm:11.19.0" dependencies: "@metamask/eth-query": "npm:^4.0.0" "@metamask/ethjs-unit": "npm:^0.3.0" @@ -1791,7 +2182,7 @@ __metadata: lodash: "npm:^4.17.21" peerDependencies: "@babel/runtime": ^7.0.0 - checksum: 10/a2ba778d00508a606ef4657cd6591a89f8f54136b3dd41f4f96f8effa2e9ad20de347e3c554f643cb248a002a17b478f95eafd4e3b4c3eca4bb40ae2e6bf7fdc + checksum: 10/d66ff170a6c2fb5726aa34c94e4870d79e96737043d3450f87d34eec8b24209b27a09df9935aad9e3e5bb685ebb3ee2c918e6d4cfbeec497c2fa823a177fc227 languageName: node linkType: hard @@ -2058,7 +2449,7 @@ __metadata: languageName: unknown linkType: soft -"@metamask/eth-qr-keyring@workspace:packages/keyring-eth-qr": +"@metamask/eth-qr-keyring@npm:^3.0.2, @metamask/eth-qr-keyring@workspace:packages/keyring-eth-qr": version: 0.0.0-use.local resolution: "@metamask/eth-qr-keyring@workspace:packages/keyring-eth-qr" dependencies: @@ -2103,9 +2494,9 @@ __metadata: languageName: node linkType: hard -"@metamask/eth-sig-util@npm:^10.0.0": - version: 10.0.0 - resolution: "@metamask/eth-sig-util@npm:10.0.0" +"@metamask/eth-sig-util@npm:^10.0.0, @metamask/eth-sig-util@npm:^10.0.1": + version: 10.0.1 + resolution: "@metamask/eth-sig-util@npm:10.0.1" dependencies: "@ethereumjs/rlp": "npm:^5.0.2" "@ethereumjs/util": "npm:^9.1.0" @@ -2114,7 +2505,7 @@ __metadata: "@metamask/utils": "npm:^12.0.2" "@noble/ciphers": "npm:^1.3.0" ethereum-cryptography: "npm:^3.2.0" - checksum: 10/95a8fcee07297eed497246b16b81374f16f38c405be0c541cced9a3844df7895e5cede020fcb924b1843f12ccd7f7658477439e04900c3ce85aadd5f622e1bb2 + checksum: 10/0f3b3dff80e507f89ecba47150b17c9639f8de70dd535615db43a3e13f2f80e9c1c70bd26a4aa3e691f9ce04fa7572e4b4022bf5bdd2e4176477c5d6ded4aa3e languageName: node linkType: hard @@ -2257,6 +2648,52 @@ __metadata: languageName: node linkType: hard +"@metamask/hw-emulator@workspace:packages/hw-emulator": + version: 0.0.0-use.local + resolution: "@metamask/hw-emulator@workspace:packages/hw-emulator" + dependencies: + "@ethereumjs/common": "npm:^10.1.3" + "@ethereumjs/rlp": "npm:^10.1.3" + "@ethereumjs/tx": "npm:^10.1.3" + "@ethereumjs/util": "npm:^10.1.3" + "@keystonehq/bc-ur-registry-eth": "npm:^0.23.2" + "@lavamoat/allow-scripts": "npm:^5.1.1" + "@lavamoat/preinstall-always-fail": "npm:^3.0.2" + "@metamask/auto-changelog": "npm:^7.1.0" + "@metamask/eth-qr-keyring": "npm:^3.0.2" + "@metamask/eth-sig-util": "npm:^10.0.1" + "@metamask/utils": "npm:^11.11.0" + "@ngraveio/bc-ur": "npm:^1.1.13" + "@ts-bridge/cli": "npm:^0.6.4" + "@types/jest": "npm:^30.0.0" + "@types/node": "npm:^26.6.11" + "@types/secp256k1": "npm:^4.0.7" + "@types/ws": "npm:^8.18.2" + "@zxing/library": "npm:^0.23.0" + deepmerge: "npm:^4.3.1" + depcheck: "npm:^1.4.7" + ethereum-cryptography: "npm:^3.2.0" + hdkey: "npm:^2.1.0" + jest: "npm:^30.5.2" + jest-it-up: "npm:^5.0.1" + qrcode-generator: "npm:^2.0.4" + rimraf: "npm:^6.1.4" + secp256k1: "npm:^5.0.2" + ts-jest: "npm:^29.4.15" + ts-node: "npm:^10.9.2" + tsd: "npm:^0.33.0" + typedoc: "npm:^0.28.20" + typescript: "npm:~5.9.3" + uuid: "npm:^11.1.1" + ws: "npm:^8.23.1" + peerDependencies: + "@metamask/speculos-up": ^0.1.0 + peerDependenciesMeta: + "@metamask/speculos-up": + optional: true + languageName: unknown + linkType: soft + "@metamask/hw-wallet-sdk@npm:^1.0.0, @metamask/hw-wallet-sdk@workspace:packages/hw-wallet-sdk": version: 0.0.0-use.local resolution: "@metamask/hw-wallet-sdk@workspace:packages/hw-wallet-sdk" @@ -2794,9 +3231,9 @@ __metadata: linkType: hard "@metamask/safe-event-emitter@npm:^3.0.0, @metamask/safe-event-emitter@npm:^3.1.1": - version: 3.1.2 - resolution: "@metamask/safe-event-emitter@npm:3.1.2" - checksum: 10/8ef7579f9317eb5c94ecf3e6abb8d13b119af274b678805eac76abe4c0667bfdf539f385e552bb973e96333b71b77aa7c787cb3fce9cd5fb4b00f1dbbabf880d + version: 3.1.1 + resolution: "@metamask/safe-event-emitter@npm:3.1.1" + checksum: 10/e24db4d7c20764bfc5b025065f92518c805f0ffb1da4820078b8cff7dcae964c0f354cf053fcb7ac659de015d5ffdf21aae5e8d44e191ee8faa9066855f22653 languageName: node linkType: hard @@ -2811,9 +3248,9 @@ __metadata: linkType: hard "@metamask/slip44@npm:^4.4.0": - version: 4.5.0 - resolution: "@metamask/slip44@npm:4.5.0" - checksum: 10/8450d4f5afa98e8f57c67a39f12aa413888c423505f22c05a3dc181be223f7742db017f54a99852acc3826abe74b22bf7247bccd78b810e509321c075e67516f + version: 4.4.0 + resolution: "@metamask/slip44@npm:4.4.0" + checksum: 10/296ac7c578bd35792c7e3942a9a0b7d9d7af76cf98358b97403c1ed483faa3c2fe6c71b1c3f8c7719fbfcf9fc73e5fa8707c89ac277ee9ce6c8bc4c694b2059d languageName: node linkType: hard @@ -2935,6 +3372,32 @@ __metadata: languageName: node linkType: hard +"@metamask/speculos-up@workspace:packages/speculos-up": + version: 0.0.0-use.local + resolution: "@metamask/speculos-up@workspace:packages/speculos-up" + dependencies: + "@lavamoat/allow-scripts": "npm:^5.1.1" + "@lavamoat/preinstall-always-fail": "npm:^3.0.2" + "@metamask/auto-changelog": "npm:^7.1.0" + "@ts-bridge/cli": "npm:^0.6.4" + "@types/jest": "npm:^30.0.0" + "@types/node": "npm:^26.6.11" + deepmerge: "npm:^4.3.1" + depcheck: "npm:^1.4.7" + jest: "npm:^30.5.2" + jest-it-up: "npm:^5.0.1" + rimraf: "npm:^6.1.4" + tar: "npm:^8.0.3" + ts-jest: "npm:^29.4.15" + ts-node: "npm:^10.9.2" + tsd: "npm:^0.33.0" + typedoc: "npm:^0.28.20" + typescript: "npm:~5.9.3" + bin: + mm-speculos-up: ./dist/cli.mjs + languageName: unknown + linkType: soft + "@metamask/storage-service@npm:^1.0.1": version: 1.0.1 resolution: "@metamask/storage-service@npm:1.0.1" @@ -3044,7 +3507,7 @@ __metadata: languageName: node linkType: hard -"@ngraveio/bc-ur@npm:^1.1.5": +"@ngraveio/bc-ur@npm:^1.1.13, @ngraveio/bc-ur@npm:^1.1.5": version: 1.1.13 resolution: "@ngraveio/bc-ur@npm:1.1.13" dependencies: @@ -3102,6 +3565,15 @@ __metadata: languageName: node linkType: hard +"@noble/curves@npm:^2.0.1": + version: 2.4.0 + resolution: "@noble/curves@npm:2.4.0" + dependencies: + "@noble/hashes": "npm:2.4.0" + checksum: 10/9d9c592c500a6248068200ce46e1bde5e4df03c4162a528397f7a5f02c885a0408dc20d365e6224b63efef3fc3ea26fc1c9c8338d602fc78991feadb2e425968 + languageName: node + linkType: hard + "@noble/hashes@npm:1.3.2": version: 1.3.2 resolution: "@noble/hashes@npm:1.3.2" @@ -3123,6 +3595,13 @@ __metadata: languageName: node linkType: hard +"@noble/hashes@npm:2.4.0, @noble/hashes@npm:^2.0.1": + version: 2.4.0 + resolution: "@noble/hashes@npm:2.4.0" + checksum: 10/88d4cdd6cef00f412a39f65bda1d24cba2264c6cacdd1c6c48d7ed66fd9be865ffb7231024fb81177975c684b8a463879b89c5ae6960370b05a546c0fd8afa2c + languageName: node + linkType: hard + "@noble/hashes@npm:~1.3.2": version: 1.3.3 resolution: "@noble/hashes@npm:1.3.3" @@ -3543,8 +4022,142 @@ __metadata: languageName: node linkType: hard -"@pkgjs/parseargs@npm:^0.11.0": - version: 0.11.0 +"@parcel/watcher-android-arm64@npm:2.6.0": + version: 2.6.0 + resolution: "@parcel/watcher-android-arm64@npm:2.6.0" + conditions: os=android & cpu=arm64 + languageName: node + linkType: hard + +"@parcel/watcher-darwin-arm64@npm:2.6.0": + version: 2.6.0 + resolution: "@parcel/watcher-darwin-arm64@npm:2.6.0" + conditions: os=darwin & cpu=arm64 + languageName: node + linkType: hard + +"@parcel/watcher-darwin-x64@npm:2.6.0": + version: 2.6.0 + resolution: "@parcel/watcher-darwin-x64@npm:2.6.0" + conditions: os=darwin & cpu=x64 + languageName: node + linkType: hard + +"@parcel/watcher-freebsd-x64@npm:2.6.0": + version: 2.6.0 + resolution: "@parcel/watcher-freebsd-x64@npm:2.6.0" + conditions: os=freebsd & cpu=x64 + languageName: node + linkType: hard + +"@parcel/watcher-linux-arm-glibc@npm:2.6.0": + version: 2.6.0 + resolution: "@parcel/watcher-linux-arm-glibc@npm:2.6.0" + conditions: os=linux & cpu=arm & libc=glibc + languageName: node + linkType: hard + +"@parcel/watcher-linux-arm-musl@npm:2.6.0": + version: 2.6.0 + resolution: "@parcel/watcher-linux-arm-musl@npm:2.6.0" + conditions: os=linux & cpu=arm & libc=musl + languageName: node + linkType: hard + +"@parcel/watcher-linux-arm64-glibc@npm:2.6.0": + version: 2.6.0 + resolution: "@parcel/watcher-linux-arm64-glibc@npm:2.6.0" + conditions: os=linux & cpu=arm64 & libc=glibc + languageName: node + linkType: hard + +"@parcel/watcher-linux-arm64-musl@npm:2.6.0": + version: 2.6.0 + resolution: "@parcel/watcher-linux-arm64-musl@npm:2.6.0" + conditions: os=linux & cpu=arm64 & libc=musl + languageName: node + linkType: hard + +"@parcel/watcher-linux-x64-glibc@npm:2.6.0": + version: 2.6.0 + resolution: "@parcel/watcher-linux-x64-glibc@npm:2.6.0" + conditions: os=linux & cpu=x64 & libc=glibc + languageName: node + linkType: hard + +"@parcel/watcher-linux-x64-musl@npm:2.6.0": + version: 2.6.0 + resolution: "@parcel/watcher-linux-x64-musl@npm:2.6.0" + conditions: os=linux & cpu=x64 & libc=musl + languageName: node + linkType: hard + +"@parcel/watcher-win32-arm64@npm:2.6.0": + version: 2.6.0 + resolution: "@parcel/watcher-win32-arm64@npm:2.6.0" + conditions: os=win32 & cpu=arm64 + languageName: node + linkType: hard + +"@parcel/watcher-win32-x64@npm:2.6.0": + version: 2.6.0 + resolution: "@parcel/watcher-win32-x64@npm:2.6.0" + conditions: os=win32 & cpu=x64 + languageName: node + linkType: hard + +"@parcel/watcher@npm:^2.6.0": + version: 2.6.0 + resolution: "@parcel/watcher@npm:2.6.0" + dependencies: + "@parcel/watcher-android-arm64": "npm:2.6.0" + "@parcel/watcher-darwin-arm64": "npm:2.6.0" + "@parcel/watcher-darwin-x64": "npm:2.6.0" + "@parcel/watcher-freebsd-x64": "npm:2.6.0" + "@parcel/watcher-linux-arm-glibc": "npm:2.6.0" + "@parcel/watcher-linux-arm-musl": "npm:2.6.0" + "@parcel/watcher-linux-arm64-glibc": "npm:2.6.0" + "@parcel/watcher-linux-arm64-musl": "npm:2.6.0" + "@parcel/watcher-linux-x64-glibc": "npm:2.6.0" + "@parcel/watcher-linux-x64-musl": "npm:2.6.0" + "@parcel/watcher-win32-arm64": "npm:2.6.0" + "@parcel/watcher-win32-x64": "npm:2.6.0" + detect-libc: "npm:^2.0.3" + is-glob: "npm:^4.0.3" + node-addon-api: "npm:^7.0.0" + node-gyp: "npm:latest" + picomatch: "npm:^4.0.4" + dependenciesMeta: + "@parcel/watcher-android-arm64": + optional: true + "@parcel/watcher-darwin-arm64": + optional: true + "@parcel/watcher-darwin-x64": + optional: true + "@parcel/watcher-freebsd-x64": + optional: true + "@parcel/watcher-linux-arm-glibc": + optional: true + "@parcel/watcher-linux-arm-musl": + optional: true + "@parcel/watcher-linux-arm64-glibc": + optional: true + "@parcel/watcher-linux-arm64-musl": + optional: true + "@parcel/watcher-linux-x64-glibc": + optional: true + "@parcel/watcher-linux-x64-musl": + optional: true + "@parcel/watcher-win32-arm64": + optional: true + "@parcel/watcher-win32-x64": + optional: true + checksum: 10/0f5f8efcd963aa4c9a2edd8f542cb339075fc1d3dd5f09b1fbfdff82f2e0a6b7da29aa5e600710045eb8d9f0f92923e4ad1b1a38cbdcb455a3a40e5618cb11c3 + languageName: node + linkType: hard + +"@pkgjs/parseargs@npm:^0.11.0": + version: 0.11.0 resolution: "@pkgjs/parseargs@npm:0.11.0" checksum: 10/115e8ceeec6bc69dff2048b35c0ab4f8bbee12d8bb6c1f4af758604586d802b6e669dcb02dda61d078de42c2b4ddce41b3d9e726d7daa6b4b850f4adbf7333ff languageName: node @@ -3557,10 +4170,10 @@ __metadata: languageName: node linkType: hard -"@pkgr/core@npm:^0.2.9": - version: 0.2.9 - resolution: "@pkgr/core@npm:0.2.9" - checksum: 10/bb2fb86977d63f836f8f5b09015d74e6af6488f7a411dcd2bfdca79d76b5a681a9112f41c45bdf88a9069f049718efc6f3900d7f1de66a2ec966068308ae517f +"@pkgr/core@npm:^0.3.6": + version: 0.3.6 + resolution: "@pkgr/core@npm:0.3.6" + checksum: 10/29082aa13d36f13fc41cdc64cb1feb36b630de0d6ebde84e2ff68e3d7a7f1dce4462cca91f76176c46e50bbca6b1e7f1fd9cf907af12d5d70da83bc981ca4ccf languageName: node linkType: hard @@ -3724,6 +4337,51 @@ __metadata: languageName: node linkType: hard +"@shikijs/engine-oniguruma@npm:^3.23.0": + version: 3.23.0 + resolution: "@shikijs/engine-oniguruma@npm:3.23.0" + dependencies: + "@shikijs/types": "npm:3.23.0" + "@shikijs/vscode-textmate": "npm:^10.0.2" + checksum: 10/edd8983be86f6b055793813e80ecf31c3cefdd896f3742797ae03f2cbb9f467ac736c4b152d4a5c42dbd17da17d24ff798a15d37bcf6205d7f8cd8f44e2a11e0 + languageName: node + linkType: hard + +"@shikijs/langs@npm:^3.23.0": + version: 3.23.0 + resolution: "@shikijs/langs@npm:3.23.0" + dependencies: + "@shikijs/types": "npm:3.23.0" + checksum: 10/115b1afb9eb4eb300eb68b146e442f7e6d196878798c5b9d75dd53a6ef1e1c3b27e325353a10973e3fa47d88630e937b8a3cf3b37b6eef80bf2aec3d51657bb3 + languageName: node + linkType: hard + +"@shikijs/themes@npm:^3.23.0": + version: 3.23.0 + resolution: "@shikijs/themes@npm:3.23.0" + dependencies: + "@shikijs/types": "npm:3.23.0" + checksum: 10/741987380445b788aea6cc1e03492bc06950f1a0461edf45083bd226889c5ba78c7ed1af9724afacab7d6471777f0c0e8871577183dfb2cfbceb255663374835 + languageName: node + linkType: hard + +"@shikijs/types@npm:3.23.0, @shikijs/types@npm:^3.23.0": + version: 3.23.0 + resolution: "@shikijs/types@npm:3.23.0" + dependencies: + "@shikijs/vscode-textmate": "npm:^10.0.2" + "@types/hast": "npm:^3.0.4" + checksum: 10/18b5703d445d53dd6782a3e2c7332009302c6c046f301d9cd99f1a26b9c8329b3e502b096894bffac61f78835c533827bab2ce78a39666ab87b78f8d7ca11f7b + languageName: node + linkType: hard + +"@shikijs/vscode-textmate@npm:^10.0.2": + version: 10.1.0 + resolution: "@shikijs/vscode-textmate@npm:10.1.0" + checksum: 10/7cf3d9c4c17979d680e670a985cd3e166a1e9960e6d648c3dc60299812040639a90b1dc9e7ab43bd24057a2913a122133fafde3d2cadeff515ebedca18a53fcd + languageName: node + linkType: hard + "@sinclair/typebox@npm:^0.27.8": version: 0.27.8 resolution: "@sinclair/typebox@npm:0.27.8" @@ -3738,6 +4396,20 @@ __metadata: languageName: node linkType: hard +"@sinclair/typebox@npm:^0.34.0": + version: 0.34.52 + resolution: "@sinclair/typebox@npm:0.34.52" + checksum: 10/693a7ab6c8935cbb6e89698bd75ac465038ecfff8b8ad22c50ad6d93a049b0e7cfe4d759200d0401707c5679d6f7a3791fd6dee139bcbb250fa3aae3c17e8bd1 + languageName: node + linkType: hard + +"@sindresorhus/is@npm:^4.0.0": + version: 4.6.0 + resolution: "@sindresorhus/is@npm:4.6.0" + checksum: 10/e7f36ed72abfcd5e0355f7423a72918b9748bb1ef370a59f3e5ad8d40b728b85d63b272f65f63eec1faf417cda89dcb0aeebe94015647b6054659c1442fe5ce0 + languageName: node + linkType: hard + "@sinonjs/commons@npm:^3.0.0, @sinonjs/commons@npm:^3.0.1": version: 3.0.1 resolution: "@sinonjs/commons@npm:3.0.1" @@ -3765,6 +4437,15 @@ __metadata: languageName: node linkType: hard +"@sinonjs/fake-timers@npm:^15.4.0": + version: 15.5.0 + resolution: "@sinonjs/fake-timers@npm:15.5.0" + dependencies: + "@sinonjs/commons": "npm:^3.0.1" + checksum: 10/eb4ab1ae5d7430c5442d1ebac21cbfa8a4b942f7dda1ed53c85800177fb434f58ff7946865cdf30937588b5d2b32b6b06e9f0212cf3d0e07902c9be53c4a28a8 + languageName: node + linkType: hard + "@sinonjs/samsam@npm:^8.0.1": version: 8.0.2 resolution: "@sinonjs/samsam@npm:8.0.2" @@ -4407,6 +5088,15 @@ __metadata: languageName: node linkType: hard +"@szmarczak/http-timer@npm:^4.0.5": + version: 4.0.6 + resolution: "@szmarczak/http-timer@npm:4.0.6" + dependencies: + defer-to-connect: "npm:^2.0.0" + checksum: 10/c29df3bcec6fc3bdec2b17981d89d9c9fc9bd7d0c9bcfe92821dc533f4440bc890ccde79971838b4ceed1921d456973c4180d7175ee1d0023ad0562240a58d95 + languageName: node + linkType: hard + "@tootallnate/once@npm:2": version: 2.0.0 resolution: "@tootallnate/once@npm:2.0.0" @@ -4698,9 +5388,9 @@ __metadata: languageName: node linkType: hard -"@ts-bridge/cli@npm:^0.6.3": - version: 0.6.3 - resolution: "@ts-bridge/cli@npm:0.6.3" +"@ts-bridge/cli@npm:^0.6.3, @ts-bridge/cli@npm:^0.6.4": + version: 0.6.4 + resolution: "@ts-bridge/cli@npm:0.6.4" dependencies: "@ts-bridge/resolver": "npm:^0.2.0" chalk: "npm:^5.3.0" @@ -4711,7 +5401,7 @@ __metadata: bin: ts-bridge: ./dist/index.js tsbridge: ./dist/index.js - checksum: 10/01cba56ff0f097ca0ef15b79cff80a6be07b7f237e7153f63f7a9acf911583d0a410385fa1711d7b14e3a5e95fed63310b6a743700e7ecc0dd3a2d97a0df75b3 + checksum: 10/257ee0cacec71c1b3cc018825088e06b4bd554ba5fe95bdb98c4c82edd6cd4bcff1054d351e6c7cdfdd3bd2145a055b5d14fa453a6ece761645e42b48b88e9a0 languageName: node linkType: hard @@ -4750,6 +5440,13 @@ __metadata: languageName: node linkType: hard +"@tsd/typescript@npm:^5.9.2": + version: 5.9.3 + resolution: "@tsd/typescript@npm:5.9.3" + checksum: 10/978a50d1b6151c1264600089279bf018bfa1c5e3058a4f6f2c38c5b72eff453c24fe66d2b1b24ff33671306aa2a0c3933af77479e24b8d498f959cd3bbe34738 + languageName: node + linkType: hard + "@tsd/typescript@npm:~5.4.3": version: 5.4.5 resolution: "@tsd/typescript@npm:5.4.5" @@ -4757,16 +5454,16 @@ __metadata: languageName: node linkType: hard -"@types/babel__core@npm:^7.1.14": - version: 7.1.19 - resolution: "@types/babel__core@npm:7.1.19" +"@types/babel__core@npm:^7.1.14, @types/babel__core@npm:^7.20.5": + version: 7.20.5 + resolution: "@types/babel__core@npm:7.20.5" dependencies: - "@babel/parser": "npm:^7.1.0" - "@babel/types": "npm:^7.0.0" + "@babel/parser": "npm:^7.20.7" + "@babel/types": "npm:^7.20.7" "@types/babel__generator": "npm:*" "@types/babel__template": "npm:*" "@types/babel__traverse": "npm:*" - checksum: 10/cd6850227184f078ffd412696c13393257e5808232cf993e0f19dc081cbeac6c9058eaf9b36797069c3f68857c16e0262a9ab4eb43fb0eb2edb70c563eaa6eed + checksum: 10/c32838d280b5ab59d62557f9e331d3831f8e547ee10b4f85cb78753d97d521270cebfc73ce501e9fb27fe71884d1ba75e18658692c2f4117543f0fc4e3e118b3 languageName: node linkType: hard @@ -4816,6 +5513,18 @@ __metadata: languageName: node linkType: hard +"@types/cacheable-request@npm:^6.0.1": + version: 6.0.3 + resolution: "@types/cacheable-request@npm:6.0.3" + dependencies: + "@types/http-cache-semantics": "npm:*" + "@types/keyv": "npm:^3.1.4" + "@types/node": "npm:*" + "@types/responselike": "npm:^1.0.0" + checksum: 10/159f9fdb2a1b7175eef453ae2ced5ea04c0d2b9610cc9ccd9f9abb066d36dacb1f37acd879ace10ad7cbb649490723feb396fb7307004c9670be29636304b988 + languageName: node + linkType: hard + "@types/color-name@npm:^1.1.1": version: 1.1.1 resolution: "@types/color-name@npm:1.1.1" @@ -4846,6 +5555,13 @@ __metadata: languageName: node linkType: hard +"@types/emscripten@npm:^1.39.6": + version: 1.41.6 + resolution: "@types/emscripten@npm:1.41.6" + checksum: 10/d497bd30d078dec05f0e2860a242091201532dd343d532459fc9bbdaea9c0e8bf0c5c515e5b2b0a3bfa886c3e4d83183c7e8091005ca0592b30c0d49f2526f28 + languageName: node + linkType: hard + "@types/eslint@npm:^7.2.13": version: 7.29.0 resolution: "@types/eslint@npm:7.29.0" @@ -4882,6 +5598,15 @@ __metadata: languageName: node linkType: hard +"@types/hast@npm:^3.0.4": + version: 3.0.5 + resolution: "@types/hast@npm:3.0.5" + dependencies: + "@types/unist": "npm:*" + checksum: 10/864a274e6e5ce0662de3bf984d804aea1f0e64eb4d5ffed27d9e832ee0002e76dfa18f1812a96b7cc24e2a9f40125ff2e47f73f7ab90c815840047c197d89635 + languageName: node + linkType: hard + "@types/hdkey@npm:^2.0.1": version: 2.0.3 resolution: "@types/hdkey@npm:2.0.3" @@ -4891,10 +5616,17 @@ __metadata: languageName: node linkType: hard -"@types/istanbul-lib-coverage@npm:*, @types/istanbul-lib-coverage@npm:^2.0.0, @types/istanbul-lib-coverage@npm:^2.0.1": - version: 2.0.3 - resolution: "@types/istanbul-lib-coverage@npm:2.0.3" - checksum: 10/0650cba4be8f464bee89b9de0b71a5ea3b5cc676ce24e1196b5d6a51542ce9e613ae4549bf19756bb33dbbbb32b47931040266100062bfb197c597d73e341eb0 +"@types/http-cache-semantics@npm:*": + version: 4.2.0 + resolution: "@types/http-cache-semantics@npm:4.2.0" + checksum: 10/01ea0dc9c1852267f5f9a0190846ac158707994b8e325bca190385ec97aa773d4a99cd333e22e838bde3c9aba59e2b5a6ac399b494c203587c6d8f28d21d6326 + languageName: node + linkType: hard + +"@types/istanbul-lib-coverage@npm:*, @types/istanbul-lib-coverage@npm:^2.0.0, @types/istanbul-lib-coverage@npm:^2.0.1, @types/istanbul-lib-coverage@npm:^2.0.6": + version: 2.0.6 + resolution: "@types/istanbul-lib-coverage@npm:2.0.6" + checksum: 10/3feac423fd3e5449485afac999dcfcb3d44a37c830af898b689fadc65d26526460bedb889db278e0d4d815a670331796494d073a10ee6e3a6526301fe7415778 languageName: node linkType: hard @@ -4907,12 +5639,12 @@ __metadata: languageName: node linkType: hard -"@types/istanbul-reports@npm:^3.0.0": - version: 3.0.0 - resolution: "@types/istanbul-reports@npm:3.0.0" +"@types/istanbul-reports@npm:^3.0.0, @types/istanbul-reports@npm:^3.0.4": + version: 3.0.4 + resolution: "@types/istanbul-reports@npm:3.0.4" dependencies: "@types/istanbul-lib-report": "npm:*" - checksum: 10/286a18cff19c4dac4321b9ea406a3560faf577fb2a4df5abf9d577fa81ba831c9baa7d40d03f1daf7fe613d468546b731c00b844b72fad9834c583311a35bb7b + checksum: 10/93eb18835770b3431f68ae9ac1ca91741ab85f7606f310a34b3586b5a34450ec038c3eed7ab19266635499594de52ff73723a54a72a75b9f7d6a956f01edee95 languageName: node linkType: hard @@ -4926,6 +5658,16 @@ __metadata: languageName: node linkType: hard +"@types/jest@npm:^30.0.0": + version: 30.0.0 + resolution: "@types/jest@npm:30.0.0" + dependencies: + expect: "npm:^30.0.0" + pretty-format: "npm:^30.0.0" + checksum: 10/cdeaa924c68b5233d9ff92861a89e7042df2b0f197633729bcf3a31e65bd4e9426e751c5665b5ac2de0b222b33f100a5502da22aefce3d2c62931c715e88f209 + languageName: node + linkType: hard + "@types/jsdom@npm:^20.0.0": version: 20.0.1 resolution: "@types/jsdom@npm:20.0.1" @@ -4944,6 +5686,15 @@ __metadata: languageName: node linkType: hard +"@types/keyv@npm:^3.1.4": + version: 3.1.4 + resolution: "@types/keyv@npm:3.1.4" + dependencies: + "@types/node": "npm:*" + checksum: 10/e009a2bfb50e90ca9b7c6e8f648f8464067271fd99116f881073fa6fa76dc8d0133181dd65e6614d5fb1220d671d67b0124aef7d97dc02d7e342ab143a47779d + languageName: node + linkType: hard + "@types/lodash@npm:^4.14.191, @types/lodash@npm:^4.17.20, @types/lodash@npm:^4.17.27": version: 4.17.27 resolution: "@types/lodash@npm:4.17.27" @@ -4982,6 +5733,31 @@ __metadata: languageName: node linkType: hard +"@types/node@npm:*, @types/node@npm:>=13.7.0, @types/node@npm:^26.6.11": + version: 26.6.11 + resolution: "@types/node@npm:26.6.11" + dependencies: + undici-types: "npm:~8.9.0" + checksum: 10/684887f6f6d1fec32605d9707a11614ededc482b270708d7da0aad6ef2a8641d3aad52c060178450373f88d770743cd43f0d43f9d977da6813b020639e800f58 + languageName: node + linkType: hard + +"@types/node@npm:11.11.6": + version: 11.11.6 + resolution: "@types/node@npm:11.11.6" + checksum: 10/3b0be5fe7104dc24d34271cb043149dab55317356bc20d7f3871dc9cb60954dc77ffc6b0531b00c3de32a748c207db769b925f17dbe03565f8a4a5001acbf367 + languageName: node + linkType: hard + +"@types/node@npm:22.7.5": + version: 22.7.5 + resolution: "@types/node@npm:22.7.5" + dependencies: + undici-types: "npm:~6.19.2" + checksum: 10/e8ba102f8c1aa7623787d625389be68d64e54fcbb76d41f6c2c64e8cf4c9f4a2370e7ef5e5f1732f3c57529d3d26afdcb2edc0101c5e413a79081449825c57ac + languageName: node + linkType: hard + "@types/node@npm:^20.19.0": version: 20.19.43 resolution: "@types/node@npm:20.19.43" @@ -5023,19 +5799,28 @@ __metadata: languageName: node linkType: hard -"@types/secp256k1@npm:^4.0.1": - version: 4.0.6 - resolution: "@types/secp256k1@npm:4.0.6" +"@types/responselike@npm:^1.0.0": + version: 1.0.3 + resolution: "@types/responselike@npm:1.0.3" dependencies: "@types/node": "npm:*" - checksum: 10/211f823be990b55612e604d620acf0dc3bc942d3836bdd8da604269effabc86d98161e5947487b4e4e128f9180fc1682daae2f89ea7a4d9648fdfe52fba365fc + checksum: 10/6ac4b35723429b11b117e813c7acc42c3af8b5554caaf1fc750404c1ae59f9b7376bc69b9e9e194a5a97357a597c2228b7173d317320f0360d617b6425212f58 languageName: node linkType: hard -"@types/semver@npm:^7, @types/semver@npm:^7.3.6": - version: 7.7.1 - resolution: "@types/semver@npm:7.7.1" - checksum: 10/8f09e7e6ca3ded67d78ba7a8f7535c8d9cf8ced83c52e7f3ac3c281fe8c689c3fe475d199d94390dc04fc681d51f2358b430bb7b2e21c62de24f2bee2c719068 +"@types/secp256k1@npm:^4.0.1, @types/secp256k1@npm:^4.0.7": + version: 4.0.7 + resolution: "@types/secp256k1@npm:4.0.7" + dependencies: + "@types/node": "npm:*" + checksum: 10/bcf7adbd953d2cb829ae98a3cd2f8eeb1e2316f4f6de720ee3863da90bd98899c08fa8c42748e8701cad16ede0898df69a6e7f22660d1fb3cb276d5c771069db + languageName: node + linkType: hard + +"@types/semver@npm:^7, @types/semver@npm:^7.1.0, @types/semver@npm:^7.3.6": + version: 7.8.0 + resolution: "@types/semver@npm:7.8.0" + checksum: 10/bbb33a88cdbc72759cf6b2750f1a28468f4470a61a1543061f494c21a53ad53bb85976e5282d79c811579e7073db0ecb6643ee0bcbf0466e8b5b3cb57ea97de0 languageName: node linkType: hard @@ -5055,10 +5840,10 @@ __metadata: languageName: node linkType: hard -"@types/stack-utils@npm:^2.0.0": - version: 2.0.0 - resolution: "@types/stack-utils@npm:2.0.0" - checksum: 10/b3fbae25b073116977ecb5c67d22f14567b51a7792403b0bf46e5de8f29bde3bd4ec1626afb22065495ca7f1c699c8bd66720050c94b8f8f9bcefbee79d161fd +"@types/stack-utils@npm:^2.0.0, @types/stack-utils@npm:^2.0.3": + version: 2.0.3 + resolution: "@types/stack-utils@npm:2.0.3" + checksum: 10/72576cc1522090fe497337c2b99d9838e320659ac57fa5560fcbdcbafcf5d0216c6b3a0a8a4ee4fdb3b1f5e3420aa4f6223ab57b82fef3578bec3206425c6cf5 languageName: node linkType: hard @@ -5069,6 +5854,20 @@ __metadata: languageName: node linkType: hard +"@types/treeify@npm:^1.0.0": + version: 1.0.3 + resolution: "@types/treeify@npm:1.0.3" + checksum: 10/777e579b30a916a781e7cbad2b7a76bc5473ff7bfe7167dd6de47f80f4386df5bf3d0dc34170afb75d52e75f6ed61cc109abf2324e093c1f9ecd4e79fec58d0c + languageName: node + linkType: hard + +"@types/unist@npm:*": + version: 3.0.3 + resolution: "@types/unist@npm:3.0.3" + checksum: 10/96e6453da9e075aaef1dc22482463898198acdc1eeb99b465e65e34303e2ec1e3b1ed4469a9118275ec284dc98019f63c3f5d49422f0e4ac707e5ab90fb3b71a + languageName: node + linkType: hard + "@types/uuid@npm:^9.0.8": version: 9.0.8 resolution: "@types/uuid@npm:9.0.8" @@ -5097,12 +5896,12 @@ __metadata: languageName: node linkType: hard -"@types/ws@npm:^8.18.1": - version: 8.18.1 - resolution: "@types/ws@npm:8.18.1" +"@types/ws@npm:^8.18.1, @types/ws@npm:^8.18.2": + version: 8.18.2 + resolution: "@types/ws@npm:8.18.2" dependencies: "@types/node": "npm:*" - checksum: 10/1ce05e3174dcacf28dae0e9b854ef1c9a12da44c7ed73617ab6897c5cbe4fccbb155a20be5508ae9a7dde2f83bd80f5cf3baa386b934fc4b40889ec963e94f3a + checksum: 10/7d87483731222387ba7d49a752b7eca6c29baeb3439d9c0a2ebe57b06bad0ce868cd850f4794c81aa93a90b2a35d7673c9b0362e7b940aace446144c17a894c2 languageName: node linkType: hard @@ -5122,12 +5921,12 @@ __metadata: languageName: node linkType: hard -"@types/yargs@npm:^17.0.8": - version: 17.0.11 - resolution: "@types/yargs@npm:17.0.11" +"@types/yargs@npm:^17.0.33, @types/yargs@npm:^17.0.8": + version: 17.0.35 + resolution: "@types/yargs@npm:17.0.35" dependencies: "@types/yargs-parser": "npm:*" - checksum: 10/91e52a7f767151ed7dc9cac82ee7e3b51aa6d0d8c9356cdf1e2c35a9483e71e012f0246b04e8222b09181ea3c7e1d24c1c78b6f1b0484fa3cb47b0ab25d14f75 + checksum: 10/47bcd4476a4194ea11617ea71cba8a1eddf5505fc39c44336c1a08d452a0de4486aedbc13f47a017c8efbcb5a8aa358d976880663732ebcbc6dbcbbecadb0581 languageName: node linkType: hard @@ -5266,6 +6065,160 @@ __metadata: languageName: node linkType: hard +"@ungap/structured-clone@npm:^1.3.0": + version: 1.4.0 + resolution: "@ungap/structured-clone@npm:1.4.0" + checksum: 10/dee21ff372783fa1d4defba14ffdaf5133a27804032261a61293fa75331d1e6c8d137d95e00f5f19a53e580d689f9c8608542f9fc854cd0706bd395a0b55f5b1 + languageName: node + linkType: hard + +"@unrs/resolver-binding-android-arm-eabi@npm:1.13.0": + version: 1.13.0 + resolution: "@unrs/resolver-binding-android-arm-eabi@npm:1.13.0" + conditions: os=android & cpu=arm + languageName: node + linkType: hard + +"@unrs/resolver-binding-android-arm64@npm:1.13.0": + version: 1.13.0 + resolution: "@unrs/resolver-binding-android-arm64@npm:1.13.0" + conditions: os=android & cpu=arm64 + languageName: node + linkType: hard + +"@unrs/resolver-binding-darwin-arm64@npm:1.13.0": + version: 1.13.0 + resolution: "@unrs/resolver-binding-darwin-arm64@npm:1.13.0" + conditions: os=darwin & cpu=arm64 + languageName: node + linkType: hard + +"@unrs/resolver-binding-darwin-x64@npm:1.13.0": + version: 1.13.0 + resolution: "@unrs/resolver-binding-darwin-x64@npm:1.13.0" + conditions: os=darwin & cpu=x64 + languageName: node + linkType: hard + +"@unrs/resolver-binding-freebsd-x64@npm:1.13.0": + version: 1.13.0 + resolution: "@unrs/resolver-binding-freebsd-x64@npm:1.13.0" + conditions: os=freebsd & cpu=x64 + languageName: node + linkType: hard + +"@unrs/resolver-binding-linux-arm-gnueabihf@npm:1.13.0": + version: 1.13.0 + resolution: "@unrs/resolver-binding-linux-arm-gnueabihf@npm:1.13.0" + conditions: os=linux & cpu=arm + languageName: node + linkType: hard + +"@unrs/resolver-binding-linux-arm-musleabihf@npm:1.13.0": + version: 1.13.0 + resolution: "@unrs/resolver-binding-linux-arm-musleabihf@npm:1.13.0" + conditions: os=linux & cpu=arm + languageName: node + linkType: hard + +"@unrs/resolver-binding-linux-arm64-gnu@npm:1.13.0": + version: 1.13.0 + resolution: "@unrs/resolver-binding-linux-arm64-gnu@npm:1.13.0" + conditions: os=linux & cpu=arm64 & libc=glibc + languageName: node + linkType: hard + +"@unrs/resolver-binding-linux-arm64-musl@npm:1.13.0": + version: 1.13.0 + resolution: "@unrs/resolver-binding-linux-arm64-musl@npm:1.13.0" + conditions: os=linux & cpu=arm64 & libc=musl + languageName: node + linkType: hard + +"@unrs/resolver-binding-linux-loong64-gnu@npm:1.13.0": + version: 1.13.0 + resolution: "@unrs/resolver-binding-linux-loong64-gnu@npm:1.13.0" + conditions: os=linux & cpu=loong64 & libc=glibc + languageName: node + linkType: hard + +"@unrs/resolver-binding-linux-loong64-musl@npm:1.13.0": + version: 1.13.0 + resolution: "@unrs/resolver-binding-linux-loong64-musl@npm:1.13.0" + conditions: os=linux & cpu=loong64 & libc=musl + languageName: node + linkType: hard + +"@unrs/resolver-binding-linux-ppc64-gnu@npm:1.13.0": + version: 1.13.0 + resolution: "@unrs/resolver-binding-linux-ppc64-gnu@npm:1.13.0" + conditions: os=linux & cpu=ppc64 & libc=glibc + languageName: node + linkType: hard + +"@unrs/resolver-binding-linux-riscv64-gnu@npm:1.13.0": + version: 1.13.0 + resolution: "@unrs/resolver-binding-linux-riscv64-gnu@npm:1.13.0" + conditions: os=linux & cpu=riscv64 & libc=glibc + languageName: node + linkType: hard + +"@unrs/resolver-binding-linux-riscv64-musl@npm:1.13.0": + version: 1.13.0 + resolution: "@unrs/resolver-binding-linux-riscv64-musl@npm:1.13.0" + conditions: os=linux & cpu=riscv64 & libc=musl + languageName: node + linkType: hard + +"@unrs/resolver-binding-linux-s390x-gnu@npm:1.13.0": + version: 1.13.0 + resolution: "@unrs/resolver-binding-linux-s390x-gnu@npm:1.13.0" + conditions: os=linux & cpu=s390x & libc=glibc + languageName: node + linkType: hard + +"@unrs/resolver-binding-linux-x64-gnu@npm:1.13.0": + version: 1.13.0 + resolution: "@unrs/resolver-binding-linux-x64-gnu@npm:1.13.0" + conditions: os=linux & cpu=x64 & libc=glibc + languageName: node + linkType: hard + +"@unrs/resolver-binding-linux-x64-musl@npm:1.13.0": + version: 1.13.0 + resolution: "@unrs/resolver-binding-linux-x64-musl@npm:1.13.0" + conditions: os=linux & cpu=x64 & libc=musl + languageName: node + linkType: hard + +"@unrs/resolver-binding-openharmony-arm64@npm:1.13.0": + version: 1.13.0 + resolution: "@unrs/resolver-binding-openharmony-arm64@npm:1.13.0" + conditions: os=openharmony & cpu=arm64 + languageName: node + linkType: hard + +"@unrs/resolver-binding-win32-arm64-msvc@npm:1.13.0": + version: 1.13.0 + resolution: "@unrs/resolver-binding-win32-arm64-msvc@npm:1.13.0" + conditions: os=win32 & cpu=arm64 + languageName: node + linkType: hard + +"@unrs/resolver-binding-win32-ia32-msvc@npm:1.13.0": + version: 1.13.0 + resolution: "@unrs/resolver-binding-win32-ia32-msvc@npm:1.13.0" + conditions: os=win32 & cpu=ia32 + languageName: node + linkType: hard + +"@unrs/resolver-binding-win32-x64-msvc@npm:1.13.0": + version: 1.13.0 + resolution: "@unrs/resolver-binding-win32-x64-msvc@npm:1.13.0" + conditions: os=win32 & cpu=x64 + languageName: node + linkType: hard + "@vue/compiler-core@npm:3.4.38": version: 3.4.38 resolution: "@vue/compiler-core@npm:3.4.38" @@ -5351,6 +6304,90 @@ __metadata: languageName: node linkType: hard +"@yarnpkg/core@npm:4.9.1": + version: 4.9.1 + resolution: "@yarnpkg/core@npm:4.9.1" + dependencies: + "@arcanis/slice-ansi": "npm:^1.1.1" + "@types/semver": "npm:^7.1.0" + "@types/treeify": "npm:^1.0.0" + "@yarnpkg/fslib": "npm:^3.1.5" + "@yarnpkg/libzip": "npm:^3.2.2" + "@yarnpkg/parsers": "npm:^3.1.0" + "@yarnpkg/shell": "npm:^4.1.3" + camelcase: "npm:^5.3.1" + chalk: "npm:^4.1.2" + ci-info: "npm:^4.0.0" + clipanion: "npm:^4.0.0-rc.2" + cross-spawn: "npm:^7.0.3" + diff: "npm:^5.1.0" + dotenv: "npm:^16.3.1" + es-toolkit: "npm:^1.39.7" + fast-glob: "npm:^3.2.2" + got: "npm:^11.7.0" + hpagent: "npm:^1.2.0" + micromatch: "npm:^4.0.2" + p-limit: "npm:^2.2.0" + semver: "npm:^7.8.5" + strip-ansi: "npm:^6.0.0" + tar: "npm:^7.5.3" + tinylogic: "npm:^2.0.0" + treeify: "npm:^1.1.0" + tslib: "npm:^2.4.0" + checksum: 10/d8aaa8670b82efbb0a92e4df92f5fd67143c66408d9fa28607725b534e80bc6647b627df4798672575bb818bc603a14ff8f7dcd1020c8d79efef4291e874ef67 + languageName: node + linkType: hard + +"@yarnpkg/fslib@npm:^3.1.3, @yarnpkg/fslib@npm:^3.1.5": + version: 3.1.5 + resolution: "@yarnpkg/fslib@npm:3.1.5" + dependencies: + tslib: "npm:^2.4.0" + checksum: 10/67b4850cdfbf0c11460302d997c0eacab46246cc8c7718a045beca346c494163e15768e2d20ab719ff6a98adbe7eaa9efcecdfd5cb0b8539f84a96449ac7ceaa + languageName: node + linkType: hard + +"@yarnpkg/libzip@npm:^3.2.2": + version: 3.2.2 + resolution: "@yarnpkg/libzip@npm:3.2.2" + dependencies: + "@types/emscripten": "npm:^1.39.6" + "@yarnpkg/fslib": "npm:^3.1.3" + tslib: "npm:^2.4.0" + peerDependencies: + "@yarnpkg/fslib": ^3.1.3 + checksum: 10/b6548be0a421e2390b74fd767d5f90e6da34a84af3ca28389b86d7f9e7602663f01347b5081cb93f8821877cae3ed48d2cb1cb8c35a4a4f7fc3d00109c85af0f + languageName: node + linkType: hard + +"@yarnpkg/parsers@npm:^3.1.0": + version: 3.1.0 + resolution: "@yarnpkg/parsers@npm:3.1.0" + dependencies: + js-yaml: "npm:^4.3.0" + tslib: "npm:^2.4.0" + checksum: 10/8b2aee239e4798df8dc8c7bf9093a6905b32f9e91c5a2176a77a045baf429bb96e4b1fdbb2548dbf5ba320284a2725c020b7160493cb022a37547a7d0f5d700f + languageName: node + linkType: hard + +"@yarnpkg/shell@npm:^4.1.3": + version: 4.1.4 + resolution: "@yarnpkg/shell@npm:4.1.4" + dependencies: + "@yarnpkg/fslib": "npm:^3.1.5" + "@yarnpkg/parsers": "npm:^3.1.0" + chalk: "npm:^4.1.2" + clipanion: "npm:^4.0.0-rc.2" + cross-spawn: "npm:^7.0.3" + fast-glob: "npm:^3.2.2" + micromatch: "npm:^4.0.2" + tslib: "npm:^2.4.0" + bin: + shell: ./lib/cli.js + checksum: 10/a10f975945770dd7cec7c341bab0694aeecd1826e56faebbf650a1405d700a993e6d4bb203e8df2c07cd0cc1b95ac11c6bd5b8b6912d7b13722eae790e5426f2 + languageName: node + linkType: hard + "@yarnpkg/types@npm:^4.0.0": version: 4.0.1 resolution: "@yarnpkg/types@npm:4.0.1" @@ -5360,6 +6397,26 @@ __metadata: languageName: node linkType: hard +"@zxing/library@npm:^0.23.0": + version: 0.23.0 + resolution: "@zxing/library@npm:0.23.0" + dependencies: + "@zxing/text-encoding": "npm:~0.9.0" + ts-custom-error: "npm:^3.3.1" + dependenciesMeta: + "@zxing/text-encoding": + optional: true + checksum: 10/f33d9a4975c9f30fa6b2c711e1e36c49e37ce50e534eeed8789acf4fd08979252c8921c2733396dd77d5d9789405b587d117f5b91b296793e09e75b002b72f3b + languageName: node + linkType: hard + +"@zxing/text-encoding@npm:~0.9.0": + version: 0.9.0 + resolution: "@zxing/text-encoding@npm:0.9.0" + checksum: 10/268e4ef64b8eaa32b990240bdfd1f7b3e2b501a6ed866a565f7c9747f04ac884fbe0537fe12bb05d9241b98fb111270c0fd0023ef0a02d23a6619b4589e98f6b + languageName: node + linkType: hard + "abab@npm:^2.0.6": version: 2.0.6 resolution: "abab@npm:2.0.6" @@ -5505,12 +6562,12 @@ __metadata: languageName: node linkType: hard -"ansi-escapes@npm:^4.2.1": - version: 4.3.1 - resolution: "ansi-escapes@npm:4.3.1" +"ansi-escapes@npm:^4.2.1, ansi-escapes@npm:^4.3.2": + version: 4.3.2 + resolution: "ansi-escapes@npm:4.3.2" dependencies: - type-fest: "npm:^0.11.0" - checksum: 10/964adff8777113109cc08e2e053af948a49137c52e86e427dc3cbfb515d0363763a731b96a0ef573531db3f788e1b45322d3cf13a7f4db9029a0f5ba17e9a14a + type-fest: "npm:^0.21.3" + checksum: 10/8661034456193ffeda0c15c8c564a9636b0c04094b7f78bd01517929c17c504090a60f7a75f949f5af91289c264d3e1001d91492c1bd58efc8e100500ce04de2 languageName: node linkType: hard @@ -5521,10 +6578,10 @@ __metadata: languageName: node linkType: hard -"ansi-regex@npm:^6.0.1": - version: 6.0.1 - resolution: "ansi-regex@npm:6.0.1" - checksum: 10/1ff8b7667cded1de4fa2c9ae283e979fc87036864317da86a2e546725f96406746411d0d85e87a2d12fa5abd715d90006de7fa4fa0477c92321ad3b4c7d4e169 +"ansi-regex@npm:^6.2.2": + version: 6.6.0 + resolution: "ansi-regex@npm:6.6.0" + checksum: 10/101ea2a09dd4ab8a2329764a727280c76f38211c95156abd902a15de0a06939d02ca03075c873ff823459ff083a46e4a3c5aba66c7a4394eddfdddfc933e6fdc languageName: node linkType: hard @@ -5545,21 +6602,21 @@ __metadata: languageName: node linkType: hard -"ansi-styles@npm:^5.0.0": +"ansi-styles@npm:^5.0.0, ansi-styles@npm:^5.2.0": version: 5.2.0 resolution: "ansi-styles@npm:5.2.0" checksum: 10/d7f4e97ce0623aea6bc0d90dcd28881ee04cba06c570b97fd3391bd7a268eedfd9d5e2dd4fdcbdd82b8105df5faf6f24aaedc08eaf3da898e702db5948f63469 languageName: node linkType: hard -"ansi-styles@npm:^6.1.0": - version: 6.2.1 - resolution: "ansi-styles@npm:6.2.1" - checksum: 10/70fdf883b704d17a5dfc9cde206e698c16bcd74e7f196ab821511651aee4f9f76c9514bdfa6ca3a27b5e49138b89cb222a28caf3afe4567570139577f991df32 +"ansi-styles@npm:^6.1.0, ansi-styles@npm:^6.2.1": + version: 6.2.3 + resolution: "ansi-styles@npm:6.2.3" + checksum: 10/c49dad7639f3e48859bd51824c93b9eb0db628afc243c51c3dd2410c4a15ede1a83881c6c7341aa2b159c4f90c11befb38f2ba848c07c66c9f9de4bcd7cb9f30 languageName: node linkType: hard -"anymatch@npm:^3.0.3": +"anymatch@npm:^3.0.3, anymatch@npm:^3.1.3": version: 3.1.3 resolution: "anymatch@npm:3.1.3" dependencies: @@ -5694,13 +6751,6 @@ __metadata: languageName: node linkType: hard -"async@npm:^3.2.3": - version: 3.2.6 - resolution: "async@npm:3.2.6" - checksum: 10/cb6e0561a3c01c4b56a799cc8bab6ea5fef45f069ab32500b6e19508db270ef2dffa55e5aed5865c5526e9907b1f8be61b27530823b411ffafb5e1538c86c368 - languageName: node - linkType: hard - "asynckit@npm:^0.4.0": version: 0.4.0 resolution: "asynckit@npm:0.4.0" @@ -5736,6 +6786,23 @@ __metadata: languageName: node linkType: hard +"babel-jest@npm:30.5.2": + version: 30.5.2 + resolution: "babel-jest@npm:30.5.2" + dependencies: + "@jest/transform": "npm:30.5.2" + "@types/babel__core": "npm:^7.20.5" + babel-plugin-istanbul: "npm:^8.0.0" + babel-preset-jest: "npm:30.5.0" + chalk: "npm:^4.1.2" + graceful-fs: "npm:^4.2.11" + slash: "npm:^3.0.0" + peerDependencies: + "@babel/core": ^7.11.0 || ^8.0.0-0 + checksum: 10/52d08ac1a3130e94127e51892e3df8d61df647d0e6e66fdb24ac3c3ad5fb2466bf33d905f034a42056cf61e283874c1ef8c140e4e30728ad2da7ffc80b751473 + languageName: node + linkType: hard + "babel-jest@npm:^29.7.0": version: 29.7.0 resolution: "babel-jest@npm:29.7.0" @@ -5766,6 +6833,28 @@ __metadata: languageName: node linkType: hard +"babel-plugin-istanbul@npm:^8.0.0": + version: 8.0.2 + resolution: "babel-plugin-istanbul@npm:8.0.2" + dependencies: + "@babel/helper-plugin-utils": "npm:^7.0.0" + "@istanbuljs/load-nyc-config": "npm:^1.0.0" + "@istanbuljs/schema": "npm:^0.1.3" + istanbul-lib-instrument: "npm:^6.0.2" + test-exclude: "npm:^7.0.1" + checksum: 10/b2bd017e4001caca7c82d50a1a832f5d7b692f07eb62feae8fb17af026468bffb918284a3f5bc8d98ec2b2b1f8bb4c253e6bb9a1a07431f26bf308ab5202fb05 + languageName: node + linkType: hard + +"babel-plugin-jest-hoist@npm:30.5.0": + version: 30.5.0 + resolution: "babel-plugin-jest-hoist@npm:30.5.0" + dependencies: + "@types/babel__core": "npm:^7.20.5" + checksum: 10/e92ea04044909d0596c46742b2b0df1fc8cb91601768adb83de5b25d948ca88d979023e855499aa52a975411c2fabbaf0601d946f4227548f962a0fac23f7258 + languageName: node + linkType: hard + "babel-plugin-jest-hoist@npm:^29.6.3": version: 29.6.3 resolution: "babel-plugin-jest-hoist@npm:29.6.3" @@ -5778,25 +6867,40 @@ __metadata: languageName: node linkType: hard -"babel-preset-current-node-syntax@npm:^1.0.0": - version: 1.0.1 - resolution: "babel-preset-current-node-syntax@npm:1.0.1" +"babel-preset-current-node-syntax@npm:^1.0.0, babel-preset-current-node-syntax@npm:^1.2.0": + version: 1.2.0 + resolution: "babel-preset-current-node-syntax@npm:1.2.0" dependencies: "@babel/plugin-syntax-async-generators": "npm:^7.8.4" "@babel/plugin-syntax-bigint": "npm:^7.8.3" - "@babel/plugin-syntax-class-properties": "npm:^7.8.3" - "@babel/plugin-syntax-import-meta": "npm:^7.8.3" + "@babel/plugin-syntax-class-properties": "npm:^7.12.13" + "@babel/plugin-syntax-class-static-block": "npm:^7.14.5" + "@babel/plugin-syntax-import-attributes": "npm:^7.24.7" + "@babel/plugin-syntax-import-meta": "npm:^7.10.4" "@babel/plugin-syntax-json-strings": "npm:^7.8.3" - "@babel/plugin-syntax-logical-assignment-operators": "npm:^7.8.3" + "@babel/plugin-syntax-logical-assignment-operators": "npm:^7.10.4" "@babel/plugin-syntax-nullish-coalescing-operator": "npm:^7.8.3" - "@babel/plugin-syntax-numeric-separator": "npm:^7.8.3" + "@babel/plugin-syntax-numeric-separator": "npm:^7.10.4" "@babel/plugin-syntax-object-rest-spread": "npm:^7.8.3" "@babel/plugin-syntax-optional-catch-binding": "npm:^7.8.3" "@babel/plugin-syntax-optional-chaining": "npm:^7.8.3" - "@babel/plugin-syntax-top-level-await": "npm:^7.8.3" + "@babel/plugin-syntax-private-property-in-object": "npm:^7.14.5" + "@babel/plugin-syntax-top-level-await": "npm:^7.14.5" peerDependencies: - "@babel/core": ^7.0.0 - checksum: 10/94561959cb12bfa80867c9eeeace7c3d48d61707d33e55b4c3fdbe82fc745913eb2dbfafca62aef297421b38aadcb58550e5943f50fbcebbeefd70ce2bed4b74 + "@babel/core": ^7.0.0 || ^8.0.0-0 + checksum: 10/3608fa671cfa46364ea6ec704b8fcdd7514b7b70e6ec09b1199e13ae73ed346c51d5ce2cb6d4d5b295f6a3f2cad1fdeec2308aa9e037002dd7c929194cc838ea + languageName: node + linkType: hard + +"babel-preset-jest@npm:30.5.0": + version: 30.5.0 + resolution: "babel-preset-jest@npm:30.5.0" + dependencies: + babel-plugin-jest-hoist: "npm:30.5.0" + babel-preset-current-node-syntax: "npm:^1.2.0" + peerDependencies: + "@babel/core": ^7.11.0 || ^8.0.0-beta.1 || ^8.0.0 + checksum: 10/3bbac1f6adf0e56338c8897b17a15846cea81436335aa39de3e2bc3e39cc5483dcc755bdcdd0a6f980bda91bee3e9cce5c0f5e52c2f7084f0d3d3189a60c9834 languageName: node linkType: hard @@ -5895,18 +6999,18 @@ __metadata: linkType: hard "base-x@npm:^3.0.2": - version: 3.0.11 - resolution: "base-x@npm:3.0.11" + version: 3.0.10 + resolution: "base-x@npm:3.0.10" dependencies: safe-buffer: "npm:^5.0.1" - checksum: 10/c2e3c443fd07cb9b9d3e179a9e9c581daa31881005841fe8d6a834e534505890fedf03465ccf14512da60e3f7be00fe66167806b159ba076d2c03952ae7460c4 + checksum: 10/52307739559e81d9980889de2359cb4f816cc0eb9a463028fa3ab239ab913d9044a1b47b4520f98e68453df32a457b8ba58b8d0ee7e757fc3fb971f3fa7a1482 languageName: node linkType: hard "base-x@npm:^5.0.0": - version: 5.0.1 - resolution: "base-x@npm:5.0.1" - checksum: 10/6e4f847ef842e0a71c6b6020a6ec482a2a5e727f5a98534dbfd5d5a4e8afbc0d1bdf1fd57174b3f0455d107f10a932c3c7710bec07e2878f80178607f8f605c8 + version: 5.0.0 + resolution: "base-x@npm:5.0.0" + checksum: 10/fa82bc9a963f7a765a3287ba632661669fe553d06ee0d4d4e282640335bff30ec685e3c3b1714e265f697b234facd02a310f1e2465db88f4f1a448e6267fbc65 languageName: node linkType: hard @@ -5932,11 +7036,11 @@ __metadata: linkType: hard "baseline-browser-mapping@npm:^2.11.37": - version: 2.11.39 - resolution: "baseline-browser-mapping@npm:2.11.39" + version: 2.11.41 + resolution: "baseline-browser-mapping@npm:2.11.41" bin: baseline-browser-mapping: dist/cli.cjs - checksum: 10/6ddb8e18d66afb7b5956b2d7619782ded6fd94885761d6d3f367040a0865296b51500434d8490da1a149f52ebfd690db0928a8c6a42dfa5a56e8bd97839d2247 + checksum: 10/c15c0fb24285f5427c6c2fa3009ce31987efa97d03f6f90dc34cd4a56f5bc3798a22d7ec636ba118f0bb4e360b34cf917b9381b2fc393babfa1c5e504861f8c6 languageName: node linkType: hard @@ -6067,8 +7171,8 @@ __metadata: linkType: hard "body-parser@npm:~1.20.3": - version: 1.20.9 - resolution: "body-parser@npm:1.20.9" + version: 1.20.4 + resolution: "body-parser@npm:1.20.4" dependencies: bytes: "npm:~3.1.2" content-type: "npm:~1.0.5" @@ -6078,25 +7182,25 @@ __metadata: http-errors: "npm:~2.0.1" iconv-lite: "npm:~0.4.24" on-finished: "npm:~2.4.1" - qs: "npm:~6.16.0" + qs: "npm:~6.14.0" raw-body: "npm:~2.5.3" type-is: "npm:~1.6.18" unpipe: "npm:~1.0.0" - checksum: 10/e9ccf7a920205d674a83cdfae0e83ed3cfe32af668706034e9832a8bf3b80f06fbc18a7c26759611f72d334311683a4b1ff73661690038a352e8c3b4a424b709 + checksum: 10/ff67e28d3f426707be8697a75fdf8d564dc50c341b41f054264d8ab6e2924e519c7ce8acc9d0de05328fdc41e1d9f3f200aec9c1cfb1867d6b676a410d97c689 languageName: node linkType: hard "brace-expansion@npm:^1.1.7": - version: 1.1.21 - resolution: "brace-expansion@npm:1.1.21" + version: 1.1.11 + resolution: "brace-expansion@npm:1.1.11" dependencies: balanced-match: "npm:^1.0.0" concat-map: "npm:0.0.1" - checksum: 10/6c0ed34107cb3bd3f44c01d90ec8c01baa3ed75b7755617e2e5797b5908bbf20b313edf575612b200a783b84c7d1826aec2f7a2f03de9905bbfae5dc3dea6a95 + checksum: 10/faf34a7bb0c3fcf4b59c7808bc5d2a96a40988addf2e7e09dfbb67a2251800e0d14cd2bfc1aa79174f2f5095c54ff27f46fb1289fe2d77dac755b5eb3434cc07 languageName: node linkType: hard -"brace-expansion@npm:^2.0.1, brace-expansion@npm:^2.0.2": +"brace-expansion@npm:^2.0.1": version: 2.1.7 resolution: "brace-expansion@npm:2.1.7" dependencies: @@ -6105,12 +7209,12 @@ __metadata: languageName: node linkType: hard -"brace-expansion@npm:^5.0.8": - version: 5.0.12 - resolution: "brace-expansion@npm:5.0.12" +"brace-expansion@npm:^5.0.12, brace-expansion@npm:^5.0.8": + version: 5.1.2 + resolution: "brace-expansion@npm:5.1.2" dependencies: balanced-match: "npm:^4.0.2" - checksum: 10/65b550f1836e3b43f512f12afbc3be96616eee5c353e16d70181b7dffec8c08beabffb51d69a3bbdb27d675840725cbab025fda9d10716b5cda7dd864dc7bc4a + checksum: 10/cd8109849fc4a8688a8f99fba0fe461f1f0f821bfb534ea7c74f6068b46521d1bd2bbdd10d59b1a23e2ce1e14def98498518e790efad2534c37e862d522dfd71 languageName: node linkType: hard @@ -6144,7 +7248,7 @@ __metadata: languageName: node linkType: hard -"browserslist@npm:^4.23.1": +"browserslist@npm:^4.24.0": version: 4.29.6 resolution: "browserslist@npm:4.29.6" dependencies: @@ -6207,12 +7311,12 @@ __metadata: languageName: node linkType: hard -"bser@npm:2.1.1": - version: 2.1.1 - resolution: "bser@npm:2.1.1" +"bser@npm:2.1.2": + version: 2.1.2 + resolution: "bser@npm:2.1.2" dependencies: node-int64: "npm:^0.4.0" - checksum: 10/edba1b65bae682450be4117b695997972bd9a3c4dfee029cab5bcb72ae5393a79a8f909b8bc77957eb0deec1c7168670f18f4d5c556f46cdd3bca5f3b3a8d020 + checksum: 10/f4948fb8aa78927aace6da4b9047f716be955142949a0163634872a16c65d9ffe9907d2e99622587d3d44cc459542d1b209047c27f195e6d97d4a4fdc11c2dad languageName: node linkType: hard @@ -6292,6 +7396,28 @@ __metadata: languageName: node linkType: hard +"cacheable-lookup@npm:^5.0.3": + version: 5.0.4 + resolution: "cacheable-lookup@npm:5.0.4" + checksum: 10/618a8b3eea314060e74cb3285a6154e8343c244a34235acf91cfe626ee0705c24e3cd11e4b1a7b3900bd749ee203ae65afe13adf610c8ab173e99d4a208faf75 + languageName: node + linkType: hard + +"cacheable-request@npm:^7.0.2": + version: 7.0.4 + resolution: "cacheable-request@npm:7.0.4" + dependencies: + clone-response: "npm:^1.0.2" + get-stream: "npm:^5.1.0" + http-cache-semantics: "npm:^4.0.0" + keyv: "npm:^4.0.0" + lowercase-keys: "npm:^2.0.0" + normalize-url: "npm:^6.0.1" + responselike: "npm:^2.0.0" + checksum: 10/0f4f2001260ecca78b9f64fc8245e6b5a5dcde24ea53006daab71f5e0e1338095aa1512ec099c4f9895a9e5acfac9da423cb7c079e131485891e9214aca46c41 + languageName: node + linkType: hard + "call-bind-apply-helpers@npm:^1.0.1, call-bind-apply-helpers@npm:^1.0.2": version: 1.0.2 resolution: "call-bind-apply-helpers@npm:1.0.2" @@ -6331,7 +7457,7 @@ __metadata: languageName: node linkType: hard -"callsites@npm:^3.0.0": +"callsites@npm:^3.0.0, callsites@npm:^3.1.0": version: 3.1.0 resolution: "callsites@npm:3.1.0" checksum: 10/072d17b6abb459c2ba96598918b55868af677154bec7e73d222ef95a8fdb9bbf7dae96a8421085cdad8cd190d86653b5b6dc55a4484f2e5b2e27d5e0c3fc15b3 @@ -6364,9 +7490,9 @@ __metadata: linkType: hard "caniuse-lite@npm:^1.0.30001826": - version: 1.0.30001827 - resolution: "caniuse-lite@npm:1.0.30001827" - checksum: 10/4aed17531cf81db2da612214b7f26932e68435ef2a5747df9bad47bbb648ab498b44c0f32021c6d0bdd4fc98f3a6e9a076ff19e6bb91279b9462008e903fe56c + version: 1.0.30001829 + resolution: "caniuse-lite@npm:1.0.30001829" + checksum: 10/102183cc412ca790397dcd929f11c37b4b16d51dbaffee5e8d918dd72d6f3837146bbdb3835e249ff0f27c846cd986e37ad08d3fe8a61f3aa935bda165b9900d languageName: node linkType: hard @@ -6396,7 +7522,7 @@ __metadata: languageName: node linkType: hard -"chalk@npm:^4.0.0, chalk@npm:^4.0.2, chalk@npm:^4.1.0, chalk@npm:^4.1.2": +"chalk@npm:^4.0.0, chalk@npm:^4.1.0, chalk@npm:^4.1.2": version: 4.1.2 resolution: "chalk@npm:4.1.2" dependencies: @@ -6448,14 +7574,20 @@ __metadata: languageName: node linkType: hard +"ci-info@npm:^4.0.0, ci-info@npm:^4.2.0": + version: 4.5.0 + resolution: "ci-info@npm:4.5.0" + checksum: 10/7c2878b08b0d4ae0782eb8be6463710f18c0dc956dfa8f2011e4a84263a7c01496b982885bc683a455831b5244d4d4555e152b691ace73a1670cba6e98c2a76e + languageName: node + linkType: hard + "cipher-base@npm:^1.0.0, cipher-base@npm:^1.0.1, cipher-base@npm:^1.0.3": - version: 1.0.7 - resolution: "cipher-base@npm:1.0.7" + version: 1.0.4 + resolution: "cipher-base@npm:1.0.4" dependencies: - inherits: "npm:^2.0.4" - safe-buffer: "npm:^5.2.1" - to-buffer: "npm:^1.2.2" - checksum: 10/9501d2241b7968aaae74fc3db1d6a69a804e0b14117a8fd5d811edf351fcd39a1807bfd98e090a799cfe98b183fbf2e01ebb57f1239080850db07b68dcd9ba02 + inherits: "npm:^2.0.1" + safe-buffer: "npm:^5.0.1" + checksum: 10/3d5d6652ca499c3f7c5d7fdc2932a357ec1e5aa84f2ad766d850efd42e89753c97b795c3a104a8e7ae35b4e293f5363926913de3bf8181af37067d9d541ca0db languageName: node linkType: hard @@ -6466,6 +7598,13 @@ __metadata: languageName: node linkType: hard +"cjs-module-lexer@npm:^2.2.0": + version: 2.3.0 + resolution: "cjs-module-lexer@npm:2.3.0" + checksum: 10/c882a20da372f793b3a4582d2d65107a3e8f1613320840f5ce0c3024b3b60af9709099dc48e61056810014d3f248d1efa25af839876c923a3911735e9ad97b6d + languageName: node + linkType: hard + "clean-stack@npm:^2.0.0": version: 2.2.0 resolution: "clean-stack@npm:2.2.0" @@ -6473,6 +7612,17 @@ __metadata: languageName: node linkType: hard +"clipanion@npm:^4.0.0-rc.2": + version: 4.0.0-rc.4 + resolution: "clipanion@npm:4.0.0-rc.4" + dependencies: + typanion: "npm:^3.8.0" + peerDependencies: + typanion: "*" + checksum: 10/c3a94783318d91e6b35380a8aa4a6f166964082a51ff2df21a339266223aaab98f5986dd2c37ca7fd640ad1d233b3cd5b24aad64c51537b54ccc9c66ec070eeb + languageName: node + linkType: hard + "cliui@npm:^7.0.2": version: 7.0.4 resolution: "cliui@npm:7.0.4" @@ -6495,6 +7645,26 @@ __metadata: languageName: node linkType: hard +"cliui@npm:^9.0.1": + version: 9.0.1 + resolution: "cliui@npm:9.0.1" + dependencies: + string-width: "npm:^7.2.0" + strip-ansi: "npm:^7.1.0" + wrap-ansi: "npm:^9.0.0" + checksum: 10/df43d8d1c6e3254cbb64b1905310d5f6672c595496a3cbe76946c6d24777136886470686f2772ac9edfe547a74bb70e8017530b3554715aee119efd7752fc0d9 + languageName: node + linkType: hard + +"clone-response@npm:^1.0.2": + version: 1.0.3 + resolution: "clone-response@npm:1.0.3" + dependencies: + mimic-response: "npm:^1.0.0" + checksum: 10/4e671cac39b11c60aa8ba0a450657194a5d6504df51bca3fac5b3bd0145c4f8e8464898f87c8406b83232e3bc5cca555f51c1f9c8ac023969ebfbf7f6bdabb2e + languageName: node + linkType: hard + "cmd-shim@npm:^6.0.0": version: 6.0.1 resolution: "cmd-shim@npm:6.0.1" @@ -6516,10 +7686,10 @@ __metadata: languageName: node linkType: hard -"collect-v8-coverage@npm:^1.0.0": - version: 1.0.1 - resolution: "collect-v8-coverage@npm:1.0.1" - checksum: 10/85b26945ab9b8e15077f877a4a5bc91d836480c600bac4cd0a0e8be8515583fdfc393ccff049ff3e9f46cac39e5295af049209f3c484f30a028056cc5dd1fe8a +"collect-v8-coverage@npm:^1.0.0, collect-v8-coverage@npm:^1.0.2": + version: 1.0.3 + resolution: "collect-v8-coverage@npm:1.0.3" + checksum: 10/656443261fb7b79cf79e89cba4b55622b07c1d4976c630829d7c5c585c73cda1c2ff101f316bfb19bb9e2c58d724c7db1f70a21e213dcd14099227c5e6019860 languageName: node linkType: hard @@ -6571,6 +7741,13 @@ __metadata: languageName: node linkType: hard +"commander@npm:^15.0.0": + version: 15.1.0 + resolution: "commander@npm:15.1.0" + checksum: 10/31eb448f2ccccf9c193d33c201fd44d2f5311db3d53c8831f650a7df94fa97bf252c7ac6d9ba4a44fce0ac1b667bc09c58311dbc24a2e98384befe2e6b3ecadf + languageName: node + linkType: hard + "comment-parser@npm:1.4.1": version: 1.4.1 resolution: "comment-parser@npm:1.4.1" @@ -6701,7 +7878,7 @@ __metadata: languageName: node linkType: hard -"create-hmac@npm:^1.1.7": +"create-hmac@npm:^1.1.4, create-hmac@npm:^1.1.7": version: 1.1.7 resolution: "create-hmac@npm:1.1.7" dependencies: @@ -6863,15 +8040,24 @@ __metadata: languageName: node linkType: hard -"dedent@npm:^1.0.0": - version: 1.5.3 - resolution: "dedent@npm:1.5.3" +"decompress-response@npm:^6.0.0": + version: 6.0.0 + resolution: "decompress-response@npm:6.0.0" + dependencies: + mimic-response: "npm:^3.1.0" + checksum: 10/d377cf47e02d805e283866c3f50d3d21578b779731e8c5072d6ce8c13cc31493db1c2f6784da9d1d5250822120cefa44f1deab112d5981015f2e17444b763812 + languageName: node + linkType: hard + +"dedent@npm:^1.0.0, dedent@npm:^1.6.0": + version: 1.7.2 + resolution: "dedent@npm:1.7.2" peerDependencies: babel-plugin-macros: ^3.1.0 peerDependenciesMeta: babel-plugin-macros: optional: true - checksum: 10/e5277f6268f288649503125b781a7b7a2c9b22d011139688c0b3619fe40121e600eb1f077c891938d4b2428bdb6326cc3c77a763e4b1cc681bd9666ab1bad2a1 + checksum: 10/30b9062290dca72b0f5a6cd3667633448cef8cd0dec602eab61015741269ad49df90cabf0521f9a32d134ceab4e21aa7f097258c55cc3baadef94874686d6480 languageName: node linkType: hard @@ -6889,10 +8075,10 @@ __metadata: languageName: node linkType: hard -"deepmerge@npm:^4.2.2": - version: 4.2.2 - resolution: "deepmerge@npm:4.2.2" - checksum: 10/0e58ed14f530d08f9b996cfc3a41b0801691620235bc5e1883260e3ed1c1b4a1dfb59f865770e45d5dfb1d7ee108c4fc10c2f85e822989d4123490ea90be2545 +"deepmerge@npm:^4.2.2, deepmerge@npm:^4.3.1": + version: 4.3.1 + resolution: "deepmerge@npm:4.3.1" + checksum: 10/058d9e1b0ff1a154468bf3837aea436abcfea1ba1d165ddaaf48ca93765fdd01a30d33c36173da8fbbed951dd0a267602bc782fe288b0fc4b7e1e7091afc4529 languageName: node linkType: hard @@ -6913,6 +8099,13 @@ __metadata: languageName: node linkType: hard +"defer-to-connect@npm:^2.0.0": + version: 2.0.1 + resolution: "defer-to-connect@npm:2.0.1" + checksum: 10/8a9b50d2f25446c0bfefb55a48e90afd58f85b21bcf78e9207cd7b804354f6409032a1705c2491686e202e64fc05f147aa5aa45f9aa82627563f045937f5791b + languageName: node + linkType: hard + "define-data-property@npm:^1.0.1, define-data-property@npm:^1.1.4": version: 1.1.4 resolution: "define-data-property@npm:1.1.4" @@ -7045,7 +8238,14 @@ __metadata: languageName: node linkType: hard -"detect-newline@npm:^3.0.0": +"detect-libc@npm:^2.0.3": + version: 2.1.2 + resolution: "detect-libc@npm:2.1.2" + checksum: 10/b736c8d97d5d46164c0d1bed53eb4e6a3b1d8530d460211e2d52f1c552875e706c58a5376854e4e54f8b828c9cada58c855288c968522eb93ac7696d65970766 + languageName: node + linkType: hard + +"detect-newline@npm:^3.0.0, detect-newline@npm:^3.1.0": version: 3.1.0 resolution: "detect-newline@npm:3.1.0" checksum: 10/ae6cd429c41ad01b164c59ea36f264a2c479598e61cba7c99da24175a7ab80ddf066420f2bec9a1c57a6bead411b4655ff15ad7d281c000a89791f48cbe939e7 @@ -7073,10 +8273,10 @@ __metadata: languageName: node linkType: hard -"diff@npm:^5.0.0": - version: 5.0.0 - resolution: "diff@npm:5.0.0" - checksum: 10/4a179a75b17cbb420eb9145be913f9ddb34b47cb2ba4301e80ae745122826a468f02ca8f5e56945958de26ace594899c8381acb6659c88e7803ef078b53d690c +"diff@npm:^5.0.0, diff@npm:^5.1.0": + version: 5.2.2 + resolution: "diff@npm:5.2.2" + checksum: 10/8a885b38113d96138d87f6cb474ee959b7e9ab33c0c4cb1b07dcf019ec544945a2309d53d721532af020de4b3a58fb89f1026f64f42f9421aa9c3ae48a36998b languageName: node linkType: hard @@ -7114,6 +8314,13 @@ __metadata: languageName: node linkType: hard +"dotenv@npm:^16.3.1": + version: 16.6.1 + resolution: "dotenv@npm:16.6.1" + checksum: 10/1d1897144344447ffe62aa1a6d664f4cd2e0784e0aff787eeeec1940ded32f8e4b5b506d665134fc87157baa086fce07ec6383970a2b6d2e7985beaed6a4cc14 + languageName: node + linkType: hard + "dunder-proto@npm:^1.0.1": version: 1.0.1 resolution: "dunder-proto@npm:1.0.1" @@ -7148,25 +8355,14 @@ __metadata: languageName: node linkType: hard -"ejs@npm:^3.1.10": - version: 3.1.10 - resolution: "ejs@npm:3.1.10" - dependencies: - jake: "npm:^10.8.5" - bin: - ejs: bin/cli.js - checksum: 10/a9cb7d7cd13b7b1cd0be5c4788e44dd10d92f7285d2f65b942f33e127230c054f99a42db4d99f766d8dbc6c57e94799593ee66a14efd7c8dd70c4812bf6aa384 - languageName: node - linkType: hard - "electron-to-chromium@npm:^1.5.486": - version: 1.5.492 - resolution: "electron-to-chromium@npm:1.5.492" - checksum: 10/b4533c47e9b90ce7d8dac9e2dee2f885134e4652cb844f2412b193593d717640032f479f9f74e2b4a1b9165519561d8665b79749256fa757ed2b64e7e6f7c9d5 + version: 1.5.496 + resolution: "electron-to-chromium@npm:1.5.496" + checksum: 10/97b98ebcfb710e3e34c332c403af58e4faf8de8c511806bdf1e26a36ef72454ec3c8e7b47e8c4fb32f9e0a1b5a61210e1175054a50fca2f6330f0b4953bac55c languageName: node linkType: hard -"elliptic@npm:6.6.1, elliptic@npm:^6.4.0, elliptic@npm:^6.5.2, elliptic@npm:^6.5.4": +"elliptic@npm:6.6.1, elliptic@npm:^6.4.0, elliptic@npm:^6.5.2, elliptic@npm:^6.5.7": version: 6.6.1 resolution: "elliptic@npm:6.6.1" dependencies: @@ -7188,6 +8384,13 @@ __metadata: languageName: node linkType: hard +"emoji-regex@npm:^10.3.0": + version: 10.6.0 + resolution: "emoji-regex@npm:10.6.0" + checksum: 10/98cc0b0e1daed1ed25afbf69dcb921fee00f712f51aab93aa1547e4e4e8171725cc4f0098aaa645b4f611a19da11ec9f4623eb6ff2b72314b39a8f2ae7c12bf2 + languageName: node + linkType: hard + "emoji-regex@npm:^8.0.0": version: 8.0.0 resolution: "emoji-regex@npm:8.0.0" @@ -7218,6 +8421,15 @@ __metadata: languageName: node linkType: hard +"end-of-stream@npm:^1.1.0": + version: 1.4.5 + resolution: "end-of-stream@npm:1.4.5" + dependencies: + once: "npm:^1.4.0" + checksum: 10/1e0cfa6e7f49887544e03314f9dfc56a8cb6dde910cbb445983ecc2ff426fc05946df9d75d8a21a3a64f2cecfe1bf88f773952029f46756b2ed64a24e95b1fb8 + languageName: node + linkType: hard + "enhanced-resolve@npm:^5.15.0, enhanced-resolve@npm:^5.17.1": version: 5.20.1 resolution: "enhanced-resolve@npm:5.20.1" @@ -7272,6 +8484,13 @@ __metadata: languageName: node linkType: hard +"es-module-lexer@npm:^2.1.0": + version: 2.3.2 + resolution: "es-module-lexer@npm:2.3.2" + checksum: 10/065246d6e2b2dfea3287650b5800a30326771e0d9d238570e81371d7ae8d53db239bccb2166e272926bba44917da7c66dd7407a5214d17b0af5269005b1fec52 + languageName: node + linkType: hard + "es-object-atoms@npm:^1.0.0, es-object-atoms@npm:^1.1.1": version: 1.1.1 resolution: "es-object-atoms@npm:1.1.1" @@ -7293,6 +8512,16 @@ __metadata: languageName: node linkType: hard +"es-toolkit@npm:^1.39.7": + version: 1.53.2 + resolution: "es-toolkit@npm:1.53.2" + dependenciesMeta: + vitepress-plugin-sandpack@1.1.4: + unplugged: true + checksum: 10/a97323e731b1dfeb153674920134fb1ba0dd16d4981bd79823f0fcae372951f910a5f8bc2a6ac8f515e8525f462ed716c100b629276323005aa3e83243d87cc2 + languageName: node + linkType: hard + "escalade@npm:^3.1.1, escalade@npm:^3.2.0": version: 3.2.0 resolution: "escalade@npm:3.2.0" @@ -7964,6 +9193,13 @@ __metadata: languageName: node linkType: hard +"exit-x@npm:^0.2.2": + version: 0.2.2 + resolution: "exit-x@npm:0.2.2" + checksum: 10/ee043053e6c1e237adf5ad9c4faf9f085b606f64a4ff859e2b138fab63fe642711d00c9af452a9134c4c92c55f752e818bfabab78c24d345022db163f3137027 + languageName: node + linkType: hard + "exit@npm:^0.1.2": version: 0.1.2 resolution: "exit@npm:0.1.2" @@ -7980,6 +9216,20 @@ __metadata: languageName: node linkType: hard +"expect@npm:30.5.2, expect@npm:^30.0.0": + version: 30.5.2 + resolution: "expect@npm:30.5.2" + dependencies: + "@jest/expect-utils": "npm:30.5.2" + "@jest/get-type": "npm:30.5.0" + jest-matcher-utils: "npm:30.5.2" + jest-message-util: "npm:30.5.1" + jest-mock: "npm:30.5.2" + jest-util: "npm:30.5.1" + checksum: 10/92599f21f468172e4be9d6fadc6d373c5d838d1b5fdcc6fc72c9d3a83dafb6c4356bc4142b46622182b9450ab4f2978f19f701f2063ceffc9e02982386d296bf + languageName: node + linkType: hard + "expect@npm:^29.0.0, expect@npm:^29.7.0": version: 29.7.0 resolution: "expect@npm:29.7.0" @@ -8071,16 +9321,16 @@ __metadata: languageName: node linkType: hard -"fast-glob@npm:^3.2.9, fast-glob@npm:^3.3.0, fast-glob@npm:^3.3.2": - version: 3.3.2 - resolution: "fast-glob@npm:3.3.2" +"fast-glob@npm:^3.2.2, fast-glob@npm:^3.2.9, fast-glob@npm:^3.3.0, fast-glob@npm:^3.3.2": + version: 3.3.3 + resolution: "fast-glob@npm:3.3.3" dependencies: "@nodelib/fs.stat": "npm:^2.0.2" "@nodelib/fs.walk": "npm:^1.2.3" glob-parent: "npm:^5.1.2" merge2: "npm:^1.3.0" - micromatch: "npm:^4.0.4" - checksum: 10/222512e9315a0efca1276af9adb2127f02105d7288fa746145bf45e2716383fb79eb983c89601a72a399a56b7c18d38ce70457c5466218c5f13fad957cee16df + micromatch: "npm:^4.0.8" + checksum: 10/dcc6432b269762dd47381d8b8358bf964d8f4f60286ac6aa41c01ade70bda459ff2001b516690b96d5365f68a49242966112b5d5cc9cd82395fa8f9d017c90ad languageName: node linkType: hard @@ -8106,12 +9356,11 @@ __metadata: linkType: hard "fast-xml-builder@npm:^1.1.4": - version: 1.3.2 - resolution: "fast-xml-builder@npm:1.3.2" + version: 1.1.4 + resolution: "fast-xml-builder@npm:1.1.4" dependencies: - path-expression-matcher: "npm:^1.6.2" - xml-naming: "npm:^0.3.0" - checksum: 10/147cba62efaf1ef66598c2abb2cf816d44159fe2e24a4655a9c5e9e52ff972947d860eb24222bdb1470bf50c97f7671f67eab8d6310cc6e23201b6e021dfe731 + path-expression-matcher: "npm:^1.1.3" + checksum: 10/32937866aaf5a90e69d1f4ee6e15e875248d5b5d2afd70277e9e8323074de4980cef24575a591b8e43c29f405d5f12377b3bad3842dc412b0c5c17a3eaee4b6b languageName: node linkType: hard @@ -8137,12 +9386,12 @@ __metadata: languageName: node linkType: hard -"fb-watchman@npm:^2.0.0": - version: 2.0.1 - resolution: "fb-watchman@npm:2.0.1" +"fb-watchman@npm:^2.0.0, fb-watchman@npm:^2.0.2": + version: 2.0.4 + resolution: "fb-watchman@npm:2.0.4" dependencies: - bser: "npm:2.1.1" - checksum: 10/9a03efc7d41ce3ca3d799d63505a1f7312caddf4e7737d39f2165bfe4872cbd4b87eccc9e6c57229ea08f14b4d7187896da31a7270b8da7a4aaa8fba2d3d1c42 + bser: "npm:2.1.2" + checksum: 10/b2bf0f08518a9fe25e2ea5b27b15d73de030129c995629de2942520e9f9586bf19639b55a111b4b900fa94cd8ddb59d2ab234e5b05655d76479bca1f2ecebf0b languageName: node linkType: hard @@ -8183,15 +9432,6 @@ __metadata: languageName: node linkType: hard -"filelist@npm:^1.0.4": - version: 1.0.4 - resolution: "filelist@npm:1.0.4" - dependencies: - minimatch: "npm:^5.0.1" - checksum: 10/4b436fa944b1508b95cffdfc8176ae6947b92825483639ef1b9a89b27d82f3f8aa22b21eed471993f92709b431670d4e015b39c087d435a61e1bb04564cf51de - languageName: node - linkType: hard - "fill-range@npm:^7.1.1": version: 7.1.1 resolution: "fill-range@npm:7.1.1" @@ -8266,12 +9506,12 @@ __metadata: linkType: hard "follow-redirects@npm:^1.16.0": - version: 1.16.3 - resolution: "follow-redirects@npm:1.16.3" + version: 1.16.1 + resolution: "follow-redirects@npm:1.16.1" peerDependenciesMeta: debug: optional: true - checksum: 10/ac3b15f7d18c26be8b38fb314d271b8def49f710388eea76079721792ef1b828fdb6696cacc92962f54bcd2462479fdcf33497502dc20ed0a5a8be1afb092215 + checksum: 10/269c9f38e4bb413d7ab224fb5aa733118288a18e84d4d0a22821a850574624a55d45f2c6735fc09fc1cceedb6343a5539daf6d2dd70bce8980c8336d230a2f50 languageName: node linkType: hard @@ -8400,6 +9640,13 @@ __metadata: languageName: node linkType: hard +"get-east-asian-width@npm:^1.0.0": + version: 1.7.0 + resolution: "get-east-asian-width@npm:1.7.0" + checksum: 10/8d8d96b54d1cfb6510f1b6dce51c4a6000b4d122757780d519d0147d968a6f5401421dbeff2e6bd3dc742e9b502fbcdbb98a50bf7f62730a6a8d6749a632279c + languageName: node + linkType: hard + "get-intrinsic@npm:^1.2.4, get-intrinsic@npm:^1.2.5, get-intrinsic@npm:^1.2.6, get-intrinsic@npm:^1.3.0": version: 1.3.1 resolution: "get-intrinsic@npm:1.3.1" @@ -8452,6 +9699,15 @@ __metadata: languageName: node linkType: hard +"get-stream@npm:^5.1.0": + version: 5.2.0 + resolution: "get-stream@npm:5.2.0" + dependencies: + pump: "npm:^3.0.0" + checksum: 10/13a73148dca795e41421013da6e3ebff8ccb7fba4d2f023fd0c6da2c166ec4e789bec9774a73a7b49c08daf2cae552f8a3e914042ac23b5f59dd278cc8f9cbfb + languageName: node + linkType: hard + "get-stream@npm:^6.0.0": version: 6.0.1 resolution: "get-stream@npm:6.0.1" @@ -8500,7 +9756,7 @@ __metadata: languageName: node linkType: hard -"glob@npm:^10.2.2, glob@npm:^10.3.7": +"glob@npm:^10.2.2, glob@npm:^10.3.7, glob@npm:^10.4.1": version: 10.5.0 resolution: "glob@npm:10.5.0" dependencies: @@ -8516,7 +9772,7 @@ __metadata: languageName: node linkType: hard -"glob@npm:^13.0.0": +"glob@npm:^13.0.0, glob@npm:^13.0.6": version: 13.0.7 resolution: "glob@npm:13.0.7" dependencies: @@ -8527,6 +9783,17 @@ __metadata: languageName: node linkType: hard +"glob@npm:^14.0.3": + version: 14.0.7 + resolution: "glob@npm:14.0.7" + dependencies: + minimatch: "npm:^11.0.5" + minipass: "npm:^7.1.3" + path-scurry: "npm:^3.0.0" + checksum: 10/2cd2405519c1968bd7a623304ca94f5b64983ac2516fdede2613f1faa0dc9ff0472a5000863c73e77cf301dc316f5cc6b7abc65c0d2405a0ea287f3033598300 + languageName: node + linkType: hard + "glob@npm:^7.1.3, glob@npm:^7.1.4, glob@npm:^7.1.7": version: 7.2.3 resolution: "glob@npm:7.2.3" @@ -8542,15 +9809,15 @@ __metadata: linkType: hard "glob@npm:^8.0.1": - version: 8.1.0 - resolution: "glob@npm:8.1.0" + version: 8.0.3 + resolution: "glob@npm:8.0.3" dependencies: fs.realpath: "npm:^1.0.0" inflight: "npm:^1.0.4" inherits: "npm:2" minimatch: "npm:^5.0.1" once: "npm:^1.3.0" - checksum: 10/9aab1c75eb087c35dbc41d1f742e51d0507aa2b14c910d96fb8287107a10a22f4bbdce26fc0a3da4c69a20f7b26d62f1640b346a4f6e6becfff47f335bb1dc5e + checksum: 10/cd002c04010ffddba426376c3046466b923b5450f89a434e6a9df6bfec369a4e907afc436303d7fbc34366dcf37056dcc3bec41e41ce983ed8d78b6035ecc317 languageName: node linkType: hard @@ -8578,13 +9845,6 @@ __metadata: languageName: node linkType: hard -"globals@npm:^11.1.0": - version: 11.12.0 - resolution: "globals@npm:11.12.0" - checksum: 10/9f054fa38ff8de8fa356502eb9d2dae0c928217b8b5c8de1f09f5c9b6c8a96d8b9bd3afc49acbcd384a98a81fea713c859e1b09e214c60509517bb8fc2bc13c2 - languageName: node - linkType: hard - "globals@npm:^14.0.0": version: 14.0.0 resolution: "globals@npm:14.0.0" @@ -8633,17 +9893,61 @@ __metadata: languageName: node linkType: hard -"gopd@npm:^1.0.1, gopd@npm:^1.2.0": - version: 1.2.0 - resolution: "gopd@npm:1.2.0" - checksum: 10/94e296d69f92dc1c0768fcfeecfb3855582ab59a7c75e969d5f96ce50c3d201fd86d5a2857c22565764d5bb8a816c7b1e58f133ec318cd56274da36c5e3fb1a1 +"gopd@npm:^1.0.1, gopd@npm:^1.2.0": + version: 1.2.0 + resolution: "gopd@npm:1.2.0" + checksum: 10/94e296d69f92dc1c0768fcfeecfb3855582ab59a7c75e969d5f96ce50c3d201fd86d5a2857c22565764d5bb8a816c7b1e58f133ec318cd56274da36c5e3fb1a1 + languageName: node + linkType: hard + +"got@npm:^11.7.0": + version: 11.8.6 + resolution: "got@npm:11.8.6" + dependencies: + "@sindresorhus/is": "npm:^4.0.0" + "@szmarczak/http-timer": "npm:^4.0.5" + "@types/cacheable-request": "npm:^6.0.1" + "@types/responselike": "npm:^1.0.0" + cacheable-lookup: "npm:^5.0.3" + cacheable-request: "npm:^7.0.2" + decompress-response: "npm:^6.0.0" + http2-wrapper: "npm:^1.0.0-beta.5.2" + lowercase-keys: "npm:^2.0.0" + p-cancelable: "npm:^2.0.0" + responselike: "npm:^2.0.0" + checksum: 10/a30c74029d81bd5fe50dea1a0c970595d792c568e188ff8be254b5bc11e6158d1b014570772d4a30d0a97723e7dd34e7c8cc1a2f23018f60aece3070a7a5c2a5 + languageName: node + linkType: hard + +"graceful-fs@npm:^4.2.11, graceful-fs@npm:^4.2.4, graceful-fs@npm:^4.2.6, graceful-fs@npm:^4.2.9": + version: 4.2.12 + resolution: "graceful-fs@npm:4.2.12" + checksum: 10/80fdd8384a2bbc94cc32dca8b7fdf011c6bc11bb96c296c8329a3c3515010956921c5080c4bd2f1a1becdf7655e5fcc691afc63ebb0c1d3da5d6afe4a17d471f + languageName: node + linkType: hard + +"grapheme-splitter@npm:^1.0.4": + version: 1.0.4 + resolution: "grapheme-splitter@npm:1.0.4" + checksum: 10/fdb2f51fd430ce881e18e44c4934ad30e59736e46213f7ad35ea5970a9ebdf7d0fe56150d15cc98230d55d2fd48c73dc6781494c38d8cf2405718366c36adb88 languageName: node linkType: hard -"graceful-fs@npm:^4.2.4, graceful-fs@npm:^4.2.6, graceful-fs@npm:^4.2.9": - version: 4.2.11 - resolution: "graceful-fs@npm:4.2.11" - checksum: 10/bf152d0ed1dc159239db1ba1f74fdbc40cb02f626770dcd5815c427ce0688c2635a06ed69af364396da4636d0408fcf7d4afdf7881724c3307e46aff30ca49e2 +"handlebars@npm:^4.7.10": + version: 4.7.10 + resolution: "handlebars@npm:4.7.10" + dependencies: + minimist: "npm:^1.2.8" + neo-async: "npm:^2.6.2" + source-map: "npm:^0.6.1" + uglify-js: "npm:^3.1.4" + wordwrap: "npm:^1.0.0" + dependenciesMeta: + uglify-js: + optional: true + bin: + handlebars: bin/handlebars + checksum: 10/e7df9b9986594384de11ea27d2f9c694f90dca9ff768ac28851b4cf89f6268a3177ec50c9bb1601c8841f67bee25598b37bdcd53d1f7acd3744619f938ad1f53 languageName: node linkType: hard @@ -8790,6 +10094,13 @@ __metadata: languageName: node linkType: hard +"hpagent@npm:^1.2.0": + version: 1.2.0 + resolution: "hpagent@npm:1.2.0" + checksum: 10/bad186449da7e3456788a8cbae459fc6c0a855d5872a7f460c48ce4a613020d8d914839dad10047297099299c4f9e6c65a0eec3f5886af196c0a516e4ad8a845 + languageName: node + linkType: hard + "html-encoding-sniffer@npm:^3.0.0": version: 3.0.0 resolution: "html-encoding-sniffer@npm:3.0.0" @@ -8806,10 +10117,10 @@ __metadata: languageName: node linkType: hard -"http-cache-semantics@npm:^4.1.0": - version: 4.1.1 - resolution: "http-cache-semantics@npm:4.1.1" - checksum: 10/362d5ed66b12ceb9c0a328fb31200b590ab1b02f4a254a697dc796850cc4385603e75f53ec59f768b2dad3bfa1464bd229f7de278d2899a0e3beffc634b6683f +"http-cache-semantics@npm:^4.0.0, http-cache-semantics@npm:^4.1.0": + version: 4.3.0 + resolution: "http-cache-semantics@npm:4.3.0" + checksum: 10/3f7b17565d3a046f069ecfc220d790ccfbef4a94a486502c5d1a23c50d71880393175416845579487a91bfefca393614d16a99bd566d474807a4ebb1139da9cd languageName: node linkType: hard @@ -8837,6 +10148,16 @@ __metadata: languageName: node linkType: hard +"http2-wrapper@npm:^1.0.0-beta.5.2": + version: 1.0.3 + resolution: "http2-wrapper@npm:1.0.3" + dependencies: + quick-lru: "npm:^5.1.1" + resolve-alpn: "npm:^1.0.0" + checksum: 10/8097ee2699440c2e64bda52124990cc5b0fb347401c7797b1a0c1efd5a0f79a4ebaa68e8a6ac3e2dde5f09460c1602764da6da2412bad628ed0a3b0ae35e72d4 + languageName: node + linkType: hard + "https-proxy-agent@npm:^5.0.0, https-proxy-agent@npm:^5.0.1": version: 5.0.1 resolution: "https-proxy-agent@npm:5.0.1" @@ -8935,15 +10256,15 @@ __metadata: languageName: node linkType: hard -"import-local@npm:^3.0.2": - version: 3.0.2 - resolution: "import-local@npm:3.0.2" +"import-local@npm:^3.0.2, import-local@npm:^3.2.0": + version: 3.2.0 + resolution: "import-local@npm:3.2.0" dependencies: pkg-dir: "npm:^4.2.0" resolve-cwd: "npm:^3.0.0" bin: import-local-fixture: fixtures/cli.js - checksum: 10/c74d9f9484c878cda1de3434613c7ff72d5dadcf20e5482542232d7c2575b713ff88701d6675fcf09a3684cb23fb407c8b333b9cbc59438712723d058d8e976c + checksum: 10/0b0b0b412b2521739fbb85eeed834a3c34de9bc67e670b3d0b86248fc460d990a7b116ad056c084b87a693ef73d1f17268d6a5be626bb43c998a8b1c8a230004 languageName: node linkType: hard @@ -9026,10 +10347,13 @@ __metadata: languageName: node linkType: hard -"ip-address@npm:^10.1.1": - version: 10.7.6 - resolution: "ip-address@npm:10.7.6" - checksum: 10/16b2604753400f8eedb17d482f9cdbb6e8ca6dac31bcb6fa6984e6098091ac58acd92990cc4d09a9ee96936b6ab19fd60e5622f4add52bd7d2465969a04e2ca9 +"ip-address@npm:^9.0.5": + version: 9.0.5 + resolution: "ip-address@npm:9.0.5" + dependencies: + jsbn: "npm:1.1.0" + sprintf-js: "npm:^1.1.3" + checksum: 10/1ed81e06721af012306329b31f532b5e24e00cb537be18ddc905a84f19fe8f83a09a1699862bf3a1ec4b9dea93c55a3fa5faf8b5ea380431469df540f38b092c languageName: node linkType: hard @@ -9123,7 +10447,7 @@ __metadata: languageName: node linkType: hard -"is-generator-fn@npm:^2.0.0": +"is-generator-fn@npm:^2.0.0, is-generator-fn@npm:^2.1.0": version: 2.1.0 resolution: "is-generator-fn@npm:2.1.0" checksum: 10/a6ad5492cf9d1746f73b6744e0c43c0020510b59d56ddcb78a91cbc173f09b5e6beff53d75c9c5a29feb618bfef2bf458e025ecf3a57ad2268e2fb2569f56215 @@ -9335,7 +10659,7 @@ __metadata: languageName: node linkType: hard -"istanbul-lib-instrument@npm:^6.0.0": +"istanbul-lib-instrument@npm:^6.0.0, istanbul-lib-instrument@npm:^6.0.2": version: 6.0.3 resolution: "istanbul-lib-instrument@npm:6.0.3" dependencies: @@ -9370,6 +10694,17 @@ __metadata: languageName: node linkType: hard +"istanbul-lib-source-maps@npm:^5.0.0": + version: 5.0.6 + resolution: "istanbul-lib-source-maps@npm:5.0.6" + dependencies: + "@jridgewell/trace-mapping": "npm:^0.3.23" + debug: "npm:^4.1.1" + istanbul-lib-coverage: "npm:^3.0.0" + checksum: 10/569dd0a392ee3464b1fe1accbaef5cc26de3479eacb5b91d8c67ebb7b425d39fd02247d85649c3a0e9c29b600809fa60b5af5a281a75a89c01f385b1e24823a2 + languageName: node + linkType: hard + "istanbul-reports@npm:^3.1.3": version: 3.1.4 resolution: "istanbul-reports@npm:3.1.4" @@ -9393,17 +10728,14 @@ __metadata: languageName: node linkType: hard -"jake@npm:^10.8.5": - version: 10.9.2 - resolution: "jake@npm:10.9.2" +"jest-changed-files@npm:30.5.1": + version: 30.5.1 + resolution: "jest-changed-files@npm:30.5.1" dependencies: - async: "npm:^3.2.3" - chalk: "npm:^4.0.2" - filelist: "npm:^1.0.4" - minimatch: "npm:^3.1.2" - bin: - jake: bin/cli.js - checksum: 10/3be324708f99f031e0aec49ef8fd872eb4583cbe8a29a0c875f554f6ac638ee4ea5aa759bb63723fd54f77ca6d7db851eaa78353301734ed3700db9cb109a0cd + execa: "npm:^5.1.1" + jest-util: "npm:30.5.1" + p-limit: "npm:^3.1.0" + checksum: 10/e39d03d698b8f062c50b1efa06c46ad274202ed8b3a01fa84c712ee70b1698301cb047176e6b5e9c38e07a15237b9af91874c8e30fcd0107c64bd35b7d4738a5 languageName: node linkType: hard @@ -9418,6 +10750,34 @@ __metadata: languageName: node linkType: hard +"jest-circus@npm:30.5.2": + version: 30.5.2 + resolution: "jest-circus@npm:30.5.2" + dependencies: + "@jest/environment": "npm:30.5.2" + "@jest/expect": "npm:30.5.2" + "@jest/test-result": "npm:30.5.2" + "@jest/types": "npm:30.5.1" + "@types/node": "npm:*" + chalk: "npm:^4.1.2" + co: "npm:^4.6.0" + dedent: "npm:^1.6.0" + is-generator-fn: "npm:^2.1.0" + jest-each: "npm:30.5.2" + jest-matcher-utils: "npm:30.5.2" + jest-message-util: "npm:30.5.1" + jest-runtime: "npm:30.5.2" + jest-snapshot: "npm:30.5.2" + jest-util: "npm:30.5.1" + p-limit: "npm:^3.1.0" + pretty-format: "npm:30.5.1" + pure-rand: "npm:^7.0.0" + slash: "npm:^3.0.0" + stack-utils: "npm:^2.0.6" + checksum: 10/c203c9d5a18a70fb58ec402b538a8a47f01a73c050abdbca14fed15b2a3b3fe1d7efe166ec2450fecf032a4e016b371153489a0d8575ac0943e7ffbccf328462 + languageName: node + linkType: hard + "jest-circus@npm:^29.7.0": version: 29.7.0 resolution: "jest-circus@npm:29.7.0" @@ -9446,6 +10806,31 @@ __metadata: languageName: node linkType: hard +"jest-cli@npm:30.5.2": + version: 30.5.2 + resolution: "jest-cli@npm:30.5.2" + dependencies: + "@jest/core": "npm:30.5.2" + "@jest/test-result": "npm:30.5.2" + "@jest/types": "npm:30.5.1" + chalk: "npm:^4.1.2" + exit-x: "npm:^0.2.2" + import-local: "npm:^3.2.0" + jest-config: "npm:30.5.2" + jest-util: "npm:30.5.1" + jest-validate: "npm:30.5.1" + yargs: "npm:^17.7.2" + peerDependencies: + node-notifier: ^8.0.1 || ^9.0.0 || ^10.0.0 + peerDependenciesMeta: + node-notifier: + optional: true + bin: + jest: bin/jest.js + checksum: 10/0ad4941a840534caf0be7c13a1900270463b91c69de0ad25fa62e0f5a6b00dc76481bbcf7432d9219d37eff84a706f7dd86919f00d0e3cc3cfef7a086ba14972 + languageName: node + linkType: hard + "jest-cli@npm:^29.7.0": version: 29.7.0 resolution: "jest-cli@npm:29.7.0" @@ -9472,6 +10857,48 @@ __metadata: languageName: node linkType: hard +"jest-config@npm:30.5.2": + version: 30.5.2 + resolution: "jest-config@npm:30.5.2" + dependencies: + "@babel/core": "npm:^7.27.4" + "@jest/get-type": "npm:30.5.0" + "@jest/pattern": "npm:30.5.0" + "@jest/test-sequencer": "npm:30.5.2" + "@jest/types": "npm:30.5.1" + babel-jest: "npm:30.5.2" + chalk: "npm:^4.1.2" + ci-info: "npm:^4.2.0" + deepmerge: "npm:^4.3.1" + glob: "npm:^13.0.6" + graceful-fs: "npm:^4.2.11" + jest-circus: "npm:30.5.2" + jest-docblock: "npm:30.5.0" + jest-environment-node: "npm:30.5.2" + jest-regex-util: "npm:30.5.0" + jest-resolve: "npm:30.5.1" + jest-runner: "npm:30.5.2" + jest-util: "npm:30.5.1" + jest-validate: "npm:30.5.1" + parse-json: "npm:^5.2.0" + pretty-format: "npm:30.5.1" + slash: "npm:^3.0.0" + strip-json-comments: "npm:^3.1.1" + peerDependencies: + "@types/node": "*" + esbuild-register: ">=3.4.0" + ts-node: ">=9.0.0" + peerDependenciesMeta: + "@types/node": + optional: true + esbuild-register: + optional: true + ts-node: + optional: true + checksum: 10/3d8f20e6c8d42be7e5ba6df720f34039c8c0d0687b5a96f01c59a618075d295f1da0f36a22c49cf080db1b26c12c8d4618dcb9a51fe7df03692fc6232bc1a22c + languageName: node + linkType: hard + "jest-config@npm:^29.7.0": version: 29.7.0 resolution: "jest-config@npm:29.7.0" @@ -9510,6 +10937,18 @@ __metadata: languageName: node linkType: hard +"jest-diff@npm:30.5.2": + version: 30.5.2 + resolution: "jest-diff@npm:30.5.2" + dependencies: + "@jest/diff-sequences": "npm:30.5.0" + "@jest/get-type": "npm:30.5.0" + chalk: "npm:^4.1.2" + pretty-format: "npm:30.5.1" + checksum: 10/42c2f228f605438e2f6c128290365fce29914508fbb96a8bfda41000a2437d8de9718b77ad97d40e65d0e36ea05a4b06227137f669869e11f2fa08c92df5a4be + languageName: node + linkType: hard + "jest-diff@npm:^29.0.3, jest-diff@npm:^29.7.0": version: 29.7.0 resolution: "jest-diff@npm:29.7.0" @@ -9522,6 +10961,15 @@ __metadata: languageName: node linkType: hard +"jest-docblock@npm:30.5.0": + version: 30.5.0 + resolution: "jest-docblock@npm:30.5.0" + dependencies: + detect-newline: "npm:^3.1.0" + checksum: 10/892645b5ac2eb39fa237e59ed31e9bc90e4284f2a705b0ff3aca513caf9db3f9e95c9126b213a6cce67d0a94bb56f1be3b4a06e61f1a0e3b4486aaa5e20b6354 + languageName: node + linkType: hard + "jest-docblock@npm:^29.7.0": version: 29.7.0 resolution: "jest-docblock@npm:29.7.0" @@ -9531,6 +10979,20 @@ __metadata: languageName: node linkType: hard +"jest-each@npm:30.5.2": + version: 30.5.2 + resolution: "jest-each@npm:30.5.2" + dependencies: + "@jest/get-type": "npm:30.5.0" + "@jest/types": "npm:30.5.1" + chalk: "npm:^4.1.2" + jest-regex-util: "npm:30.5.0" + jest-util: "npm:30.5.1" + pretty-format: "npm:30.5.1" + checksum: 10/c5f1ee8707950f295709101757a9fd5ee21ac0ff5b827b6e04ce4a39a956a66e4d358487478050266f56ffe9697673fb2b5ae6665c1732435d44ea1f962eec60 + languageName: node + linkType: hard + "jest-each@npm:^29.7.0": version: 29.7.0 resolution: "jest-each@npm:29.7.0" @@ -9565,6 +11027,21 @@ __metadata: languageName: node linkType: hard +"jest-environment-node@npm:30.5.2": + version: 30.5.2 + resolution: "jest-environment-node@npm:30.5.2" + dependencies: + "@jest/environment": "npm:30.5.2" + "@jest/fake-timers": "npm:30.5.2" + "@jest/types": "npm:30.5.1" + "@types/node": "npm:*" + jest-mock: "npm:30.5.2" + jest-util: "npm:30.5.1" + jest-validate: "npm:30.5.1" + checksum: 10/6ddf88441fd085c3ea29b0b8dec4fc72974ac403fe114986b47d7831517aae0bded95e92b128c0d4a34bdacfa0101cb63a0c8d15c251937308b8266f1c76a9ba + languageName: node + linkType: hard + "jest-environment-node@npm:^29.7.0": version: 29.7.0 resolution: "jest-environment-node@npm:29.7.0" @@ -9586,6 +11063,25 @@ __metadata: languageName: node linkType: hard +"jest-haste-map@npm:30.5.1": + version: 30.5.1 + resolution: "jest-haste-map@npm:30.5.1" + dependencies: + "@jest/types": "npm:30.5.1" + "@parcel/watcher": "npm:^2.6.0" + "@types/node": "npm:*" + anymatch: "npm:^3.1.3" + fb-watchman: "npm:^2.0.2" + fdir: "npm:^6.5.0" + graceful-fs: "npm:^4.2.11" + jest-regex-util: "npm:30.5.0" + jest-util: "npm:30.5.1" + jest-worker: "npm:30.5.1" + picomatch: "npm:^4.0.3" + checksum: 10/0804f1436ca9d561716a16345722673050772d525337f24288950973c225cd5554ff5841c976f16e932edda7d53f5128f9413bac45dd5a7e94d895eed79636d3 + languageName: node + linkType: hard + "jest-haste-map@npm:^29.7.0": version: 29.7.0 resolution: "jest-haste-map@npm:29.7.0" @@ -9622,6 +11118,28 @@ __metadata: languageName: node linkType: hard +"jest-it-up@npm:^5.0.1": + version: 5.0.1 + resolution: "jest-it-up@npm:5.0.1" + dependencies: + commander: "npm:^15.0.0" + prompts: "npm:^2.4.0" + bin: + jest-it-up: bin/jest-it-up + checksum: 10/69e174cf11905da201316fb3faa7eaae62036d7a99a3f3f2d5eadc5cf05148733c8cfaadb59f2601f50a7e4287de7405e9258fb226bcbe2601859ca3c8970fe4 + languageName: node + linkType: hard + +"jest-leak-detector@npm:30.5.1": + version: 30.5.1 + resolution: "jest-leak-detector@npm:30.5.1" + dependencies: + "@jest/get-type": "npm:30.5.0" + pretty-format: "npm:30.5.1" + checksum: 10/1e35b3e30dda79d7583b8c62b487fc4e0a7ca2d25c7e2699a2aee830d6b440af2f059fdb8dda843dec094b90cbb030b0eb571e3d55effa3b14bb4dd550d59f7a + languageName: node + linkType: hard + "jest-leak-detector@npm:^29.7.0": version: 29.7.0 resolution: "jest-leak-detector@npm:29.7.0" @@ -9632,6 +11150,18 @@ __metadata: languageName: node linkType: hard +"jest-matcher-utils@npm:30.5.2": + version: 30.5.2 + resolution: "jest-matcher-utils@npm:30.5.2" + dependencies: + "@jest/get-type": "npm:30.5.0" + chalk: "npm:^4.1.2" + jest-diff: "npm:30.5.2" + pretty-format: "npm:30.5.1" + checksum: 10/c3a772f30d3cddb8bf32bad82cc87104dcfc853694fcd212fe2e0fadda3bedebb8a99cb8688f780e1118c12275395e90b27fd53f83c74560cc8eb2974e6a2463 + languageName: node + linkType: hard + "jest-matcher-utils@npm:^29.7.0": version: 29.7.0 resolution: "jest-matcher-utils@npm:29.7.0" @@ -9644,6 +11174,24 @@ __metadata: languageName: node linkType: hard +"jest-message-util@npm:30.5.1": + version: 30.5.1 + resolution: "jest-message-util@npm:30.5.1" + dependencies: + "@babel/code-frame": "npm:^7.27.1" + "@jest/types": "npm:30.5.1" + "@types/stack-utils": "npm:^2.0.3" + chalk: "npm:^4.1.2" + graceful-fs: "npm:^4.2.11" + jest-util: "npm:30.5.1" + picomatch: "npm:^4.0.3" + pretty-format: "npm:30.5.1" + slash: "npm:^3.0.0" + stack-utils: "npm:^2.0.6" + checksum: 10/bb25344137d71b2e36a24077b0391b78bce07731e70522e2e4f91deb1c0cc08d4e80371985c359e78e91201a7e76936e631aea4b6a0e5271f9fe1dd34f340e9b + languageName: node + linkType: hard + "jest-message-util@npm:^29.7.0": version: 29.7.0 resolution: "jest-message-util@npm:29.7.0" @@ -9661,6 +11209,18 @@ __metadata: languageName: node linkType: hard +"jest-mock@npm:30.5.2": + version: 30.5.2 + resolution: "jest-mock@npm:30.5.2" + dependencies: + "@jest/expect-utils": "npm:30.5.2" + "@jest/types": "npm:30.5.1" + "@types/node": "npm:*" + jest-util: "npm:30.5.1" + checksum: 10/4a605ae054b317afef942a886285c65afe30fb2de7f883d0fd889bbbe01da2cdd3cebbbdd5b6fba57a3309c80d32105d1418bb4893e6f3ccf4529b61d8bc62d2 + languageName: node + linkType: hard + "jest-mock@npm:^29.7.0": version: 29.7.0 resolution: "jest-mock@npm:29.7.0" @@ -9684,6 +11244,13 @@ __metadata: languageName: node linkType: hard +"jest-regex-util@npm:30.5.0": + version: 30.5.0 + resolution: "jest-regex-util@npm:30.5.0" + checksum: 10/2236cb0f3bc7f61690500d779afab57fbcb2a35925f416ab32e68e5c1efae6d916efa9c3ee49c94d4d0990e1316e6581a1545209b08715c848b919364e89e66f + languageName: node + linkType: hard + "jest-regex-util@npm:^29.6.3": version: 29.6.3 resolution: "jest-regex-util@npm:29.6.3" @@ -9691,6 +11258,16 @@ __metadata: languageName: node linkType: hard +"jest-resolve-dependencies@npm:30.5.2": + version: 30.5.2 + resolution: "jest-resolve-dependencies@npm:30.5.2" + dependencies: + jest-regex-util: "npm:30.5.0" + jest-snapshot: "npm:30.5.2" + checksum: 10/cc6fd7cc877bbcc38c4b3fa7ca0eaa07cc6d9356096cd1e9c23a5f2ec1b9b3ad6cdca9833c5f9316162d862fc30140d9ff9e8ffe594f76685bae1d1f105347f1 + languageName: node + linkType: hard + "jest-resolve-dependencies@npm:^29.7.0": version: 29.7.0 resolution: "jest-resolve-dependencies@npm:29.7.0" @@ -9701,6 +11278,21 @@ __metadata: languageName: node linkType: hard +"jest-resolve@npm:30.5.1": + version: 30.5.1 + resolution: "jest-resolve@npm:30.5.1" + dependencies: + chalk: "npm:^4.1.2" + graceful-fs: "npm:^4.2.11" + jest-haste-map: "npm:30.5.1" + jest-util: "npm:30.5.1" + jest-validate: "npm:30.5.1" + slash: "npm:^3.0.0" + unrs-resolver: "npm:^1.12.1" + checksum: 10/00c219e17fee4999569cd61f3971ee367add89d46734b8b18e3cf007c580e7477f2a30dc579201f65e9428971e4583627f8955bf0a0af4b2537b491186bb1323 + languageName: node + linkType: hard + "jest-resolve@npm:^29.7.0": version: 29.7.0 resolution: "jest-resolve@npm:29.7.0" @@ -9718,6 +11310,36 @@ __metadata: languageName: node linkType: hard +"jest-runner@npm:30.5.2": + version: 30.5.2 + resolution: "jest-runner@npm:30.5.2" + dependencies: + "@jest/console": "npm:30.5.2" + "@jest/environment": "npm:30.5.2" + "@jest/source-map": "npm:30.5.2" + "@jest/test-result": "npm:30.5.2" + "@jest/transform": "npm:30.5.2" + "@jest/types": "npm:30.5.1" + "@types/node": "npm:*" + chalk: "npm:^4.1.2" + emittery: "npm:^0.13.1" + exit-x: "npm:^0.2.2" + graceful-fs: "npm:^4.2.11" + jest-docblock: "npm:30.5.0" + jest-environment-node: "npm:30.5.2" + jest-haste-map: "npm:30.5.1" + jest-leak-detector: "npm:30.5.1" + jest-message-util: "npm:30.5.1" + jest-resolve: "npm:30.5.1" + jest-runtime: "npm:30.5.2" + jest-util: "npm:30.5.1" + jest-watcher: "npm:30.5.2" + jest-worker: "npm:30.5.1" + p-limit: "npm:^3.1.0" + checksum: 10/936c50973724d26daa8eb4152e7a5e853dc60a6ff22f14239b9f53349787a81e9e075232bcecaa8062ae27f0de603dce79894da8095d178538c28bf51da3ed89 + languageName: node + linkType: hard + "jest-runner@npm:^29.7.0": version: 29.7.0 resolution: "jest-runner@npm:29.7.0" @@ -9747,6 +11369,37 @@ __metadata: languageName: node linkType: hard +"jest-runtime@npm:30.5.2": + version: 30.5.2 + resolution: "jest-runtime@npm:30.5.2" + dependencies: + "@jest/environment": "npm:30.5.2" + "@jest/fake-timers": "npm:30.5.2" + "@jest/globals": "npm:30.5.2" + "@jest/source-map": "npm:30.5.2" + "@jest/test-result": "npm:30.5.2" + "@jest/transform": "npm:30.5.2" + "@jest/types": "npm:30.5.1" + "@types/node": "npm:*" + chalk: "npm:^4.1.2" + cjs-module-lexer: "npm:^2.2.0" + collect-v8-coverage: "npm:^1.0.2" + es-module-lexer: "npm:^2.1.0" + glob: "npm:^13.0.6" + graceful-fs: "npm:^4.2.11" + jest-haste-map: "npm:30.5.1" + jest-message-util: "npm:30.5.1" + jest-mock: "npm:30.5.2" + jest-regex-util: "npm:30.5.0" + jest-resolve: "npm:30.5.1" + jest-snapshot: "npm:30.5.2" + jest-util: "npm:30.5.1" + slash: "npm:^3.0.0" + strip-bom: "npm:^4.0.0" + checksum: 10/d44355c4157bddca99e924a98f48fdc158c07ff1539b2231f2f593fae2a22ce31ae22845b9f5cd2b15a2f5f39870ed7313a99b096420f02b15984de833566287 + languageName: node + linkType: hard + "jest-runtime@npm:^29.7.0": version: 29.7.0 resolution: "jest-runtime@npm:29.7.0" @@ -9787,6 +11440,35 @@ __metadata: languageName: node linkType: hard +"jest-snapshot@npm:30.5.2": + version: 30.5.2 + resolution: "jest-snapshot@npm:30.5.2" + dependencies: + "@babel/core": "npm:^7.27.4" + "@babel/generator": "npm:^7.27.5" + "@babel/plugin-syntax-jsx": "npm:^7.27.1" + "@babel/plugin-syntax-typescript": "npm:^7.27.1" + "@babel/types": "npm:^7.27.3" + "@jest/expect-utils": "npm:30.5.2" + "@jest/get-type": "npm:30.5.0" + "@jest/snapshot-utils": "npm:30.5.1" + "@jest/transform": "npm:30.5.2" + "@jest/types": "npm:30.5.1" + babel-preset-current-node-syntax: "npm:^1.2.0" + chalk: "npm:^4.1.2" + expect: "npm:30.5.2" + graceful-fs: "npm:^4.2.11" + jest-diff: "npm:30.5.2" + jest-matcher-utils: "npm:30.5.2" + jest-message-util: "npm:30.5.1" + jest-util: "npm:30.5.1" + pretty-format: "npm:30.5.1" + semver: "npm:^7.7.2" + synckit: "npm:^0.11.8" + checksum: 10/64be725cd1171c940831c30cef6f349a9b5e331d064ee6454607e59da98d2a4141cb66eb5d208346e775f8ca3c199114f8fb1853218b9112a2b37cd7d572a648 + languageName: node + linkType: hard + "jest-snapshot@npm:^29.7.0": version: 29.7.0 resolution: "jest-snapshot@npm:29.7.0" @@ -9815,6 +11497,20 @@ __metadata: languageName: node linkType: hard +"jest-util@npm:30.5.1": + version: 30.5.1 + resolution: "jest-util@npm:30.5.1" + dependencies: + "@jest/types": "npm:30.5.1" + "@types/node": "npm:*" + chalk: "npm:^4.1.2" + ci-info: "npm:^4.2.0" + graceful-fs: "npm:^4.2.11" + picomatch: "npm:^4.0.3" + checksum: 10/87e7fa2be0c90b1c28ab7747688c02544f7622b628f12f1c9fe5b23e70dd0f04cb2d41cb122d64f16c22427f94a2443d2374d8ea113839c9c33ab9c4555c480c + languageName: node + linkType: hard + "jest-util@npm:^26.0.0": version: 26.6.2 resolution: "jest-util@npm:26.6.2" @@ -9829,7 +11525,7 @@ __metadata: languageName: node linkType: hard -"jest-util@npm:^29.0.0, jest-util@npm:^29.7.0": +"jest-util@npm:^29.7.0": version: 29.7.0 resolution: "jest-util@npm:29.7.0" dependencies: @@ -9843,6 +11539,20 @@ __metadata: languageName: node linkType: hard +"jest-validate@npm:30.5.1": + version: 30.5.1 + resolution: "jest-validate@npm:30.5.1" + dependencies: + "@jest/get-type": "npm:30.5.0" + "@jest/types": "npm:30.5.1" + camelcase: "npm:^6.3.0" + chalk: "npm:^4.1.2" + leven: "npm:^3.1.0" + pretty-format: "npm:30.5.1" + checksum: 10/a78ce1fee1b7f445c394efb283190446b454118b458fd835025b555a79f62cd2f0840ce1619ef0259753382e4dbb534d8107071a978c8d845928abdbb6d599d3 + languageName: node + linkType: hard + "jest-validate@npm:^29.7.0": version: 29.7.0 resolution: "jest-validate@npm:29.7.0" @@ -9857,6 +11567,22 @@ __metadata: languageName: node linkType: hard +"jest-watcher@npm:30.5.2": + version: 30.5.2 + resolution: "jest-watcher@npm:30.5.2" + dependencies: + "@jest/test-result": "npm:30.5.2" + "@jest/types": "npm:30.5.1" + "@types/node": "npm:*" + ansi-escapes: "npm:^4.3.2" + chalk: "npm:^4.1.2" + emittery: "npm:^0.13.1" + jest-util: "npm:30.5.1" + string-length: "npm:^4.0.2" + checksum: 10/aec43f7cf8db5e640a2a3f63676da77cd55d8b6bbc7cc0b563a03fc6c263bd1ec88eba02f0cdd639dfe4114f516c7c55911984e20570325eb77cc22cdb720871 + languageName: node + linkType: hard + "jest-watcher@npm:^29.7.0": version: 29.7.0 resolution: "jest-watcher@npm:29.7.0" @@ -9873,6 +11599,19 @@ __metadata: languageName: node linkType: hard +"jest-worker@npm:30.5.1": + version: 30.5.1 + resolution: "jest-worker@npm:30.5.1" + dependencies: + "@types/node": "npm:*" + "@ungap/structured-clone": "npm:^1.3.0" + jest-util: "npm:30.5.1" + merge-stream: "npm:^2.0.0" + supports-color: "npm:^8.1.1" + checksum: 10/cff8638859f661a7f43ce56e9901ba8c42a3ac909ee3fedd254ede78fd93c034ca1e57f4f74f520d4d663b52cb3432e614362d52dc698e1a09778a235ce1af58 + languageName: node + linkType: hard + "jest-worker@npm:^29.7.0": version: 29.7.0 resolution: "jest-worker@npm:29.7.0" @@ -9904,6 +11643,25 @@ __metadata: languageName: node linkType: hard +"jest@npm:^30.5.2": + version: 30.5.2 + resolution: "jest@npm:30.5.2" + dependencies: + "@jest/core": "npm:30.5.2" + "@jest/types": "npm:30.5.1" + import-local: "npm:^3.2.0" + jest-cli: "npm:30.5.2" + peerDependencies: + node-notifier: ^8.0.1 || ^9.0.0 || ^10.0.0 + peerDependenciesMeta: + node-notifier: + optional: true + bin: + jest: bin/jest.js + checksum: 10/687b2f290e25093c061878a1ca861ea8b6552dd3542c01b04764f84294bfd8697f716abe106a0f8ea3a6fb85c567f569e567e1cd1ca4d0a0f1e54b3291ce67c2 + languageName: node + linkType: hard + "js-sha3@npm:0.8.0": version: 0.8.0 resolution: "js-sha3@npm:0.8.0" @@ -9926,18 +11684,18 @@ __metadata: linkType: hard "js-yaml@npm:^3.13.1, js-yaml@npm:^3.14.1": - version: 3.15.2 - resolution: "js-yaml@npm:3.15.2" + version: 3.14.1 + resolution: "js-yaml@npm:3.14.1" dependencies: argparse: "npm:^1.0.7" esprima: "npm:^4.0.0" bin: js-yaml: bin/js-yaml.js - checksum: 10/320b5471c1b7309a15d9c0068ba273e2da7382a369038a9746c92ef649087c3d6d2a5c676810154efb4eb2ca9584179c8ae14e2fc2e4bd558d964e6bf4fafd3d + checksum: 10/9e22d80b4d0105b9899135365f746d47466ed53ef4223c529b3c0f7a39907743fdbd3c4379f94f1106f02755b5e90b2faaf84801a891135544e1ea475d1a1379 languageName: node linkType: hard -"js-yaml@npm:^4.1.1": +"js-yaml@npm:^4.1.1, js-yaml@npm:^4.3.0": version: 4.3.2 resolution: "js-yaml@npm:4.3.2" dependencies: @@ -9955,6 +11713,13 @@ __metadata: languageName: node linkType: hard +"jsbn@npm:1.1.0": + version: 1.1.0 + resolution: "jsbn@npm:1.1.0" + checksum: 10/bebe7ae829bbd586ce8cbe83501dd8cb8c282c8902a8aeeed0a073a89dc37e8103b1244f3c6acd60278bcbfe12d93a3f83c9ac396868a3b3bbc3c5e5e3b648ef + languageName: node + linkType: hard + "jsdoc-type-pratt-parser@npm:~4.1.0": version: 4.1.0 resolution: "jsdoc-type-pratt-parser@npm:4.1.0" @@ -10094,7 +11859,7 @@ __metadata: languageName: node linkType: hard -"keyv@npm:^4.5.4": +"keyv@npm:^4.0.0, keyv@npm:^4.5.4": version: 4.5.4 resolution: "keyv@npm:4.5.4" dependencies: @@ -10148,6 +11913,15 @@ __metadata: languageName: node linkType: hard +"linkify-it@npm:^5.0.2": + version: 5.0.2 + resolution: "linkify-it@npm:5.0.2" + dependencies: + uc.micro: "npm:^2.0.0" + checksum: 10/1d23387319c15f2c3d41cdada0fc2edac73afb6083e967ee051afc826f7d8d9f920e287fb7c32679b4516f60e6450853dee2b4339d7d2f313222e4b9e5be1476 + languageName: node + linkType: hard + "locate-path@npm:^5.0.0": version: 5.0.0 resolution: "locate-path@npm:5.0.0" @@ -10229,6 +12003,13 @@ __metadata: languageName: node linkType: hard +"lowercase-keys@npm:^2.0.0": + version: 2.0.0 + resolution: "lowercase-keys@npm:2.0.0" + checksum: 10/1c233d2da35056e8c49fae8097ee061b8c799b2f02e33c2bf32f9913c7de8fb481ab04dab7df35e94156c800f5f34e99acbf32b21781d87c3aa43ef7b748b79e + languageName: node + linkType: hard + "lru-cache@npm:^10.0.1, lru-cache@npm:^10.2.0": version: 10.4.3 resolution: "lru-cache@npm:10.4.3" @@ -10354,6 +12135,22 @@ __metadata: languageName: node linkType: hard +"markdown-it@npm:^14.3.0": + version: 14.3.3 + resolution: "markdown-it@npm:14.3.3" + dependencies: + argparse: "npm:^2.0.1" + entities: "npm:^4.5.0" + linkify-it: "npm:^5.0.2" + mdurl: "npm:^2.0.0" + punycode.js: "npm:^2.3.1" + uc.micro: "npm:^2.1.0" + bin: + markdown-it: bin/markdown-it.mjs + checksum: 10/ab96ec39766d59ed234304ef01108a13793b735dc1032a00f5bd89a20fb030f8c9305ac7b76f1f59a10257a4e456cdffd5f7c568e6ef9d99fe7f1fe2074395df + languageName: node + linkType: hard + "marked@npm:^12.0.1": version: 12.0.2 resolution: "marked@npm:12.0.2" @@ -10390,6 +12187,13 @@ __metadata: languageName: node linkType: hard +"mdurl@npm:^2.0.0": + version: 2.1.0 + resolution: "mdurl@npm:2.1.0" + checksum: 10/b7db2c0aa0479e11c5454b8a6ae055326bd9180b83e58696f89e862b84a0f5c7c80e497be650f205c0807b4567f6ee3e09238a76c8f1217f1fd750a1f6f2146d + languageName: node + linkType: hard + "media-typer@npm:0.3.0": version: 0.3.0 resolution: "media-typer@npm:0.3.0" @@ -10452,7 +12256,7 @@ __metadata: languageName: node linkType: hard -"micromatch@npm:^4.0.2, micromatch@npm:^4.0.4": +"micromatch@npm:^4.0.2, micromatch@npm:^4.0.4, micromatch@npm:^4.0.8": version: 4.0.8 resolution: "micromatch@npm:4.0.8" dependencies: @@ -10501,6 +12305,20 @@ __metadata: languageName: node linkType: hard +"mimic-response@npm:^1.0.0": + version: 1.0.1 + resolution: "mimic-response@npm:1.0.1" + checksum: 10/034c78753b0e622bc03c983663b1cdf66d03861050e0c8606563d149bc2b02d63f62ce4d32be4ab50d0553ae0ffe647fc34d1f5281184c6e1e8cf4d85e8d9823 + languageName: node + linkType: hard + +"mimic-response@npm:^3.1.0": + version: 3.1.0 + resolution: "mimic-response@npm:3.1.0" + checksum: 10/7e719047612411fe071332a7498cf0448bbe43c485c0d780046c76633a771b223ff49bd00267be122cedebb897037fdb527df72335d0d0f74724604ca70b37ad + languageName: node + linkType: hard + "min-indent@npm:^1.0.0": version: 1.0.1 resolution: "min-indent@npm:1.0.1" @@ -10522,7 +12340,7 @@ __metadata: languageName: node linkType: hard -"minimatch@npm:^10.2.2": +"minimatch@npm:^10.2.2, minimatch@npm:^10.2.5": version: 10.2.6 resolution: "minimatch@npm:10.2.6" dependencies: @@ -10531,7 +12349,17 @@ __metadata: languageName: node linkType: hard -"minimatch@npm:^3.0.4, minimatch@npm:^3.1.1, minimatch@npm:^3.1.2, minimatch@npm:^3.1.5": +"minimatch@npm:^11.0.5": + version: 11.0.10 + resolution: "minimatch@npm:11.0.10" + dependencies: + "@isaacs/nonrecursive-glob-match": "npm:^1.1.0" + brace-expansion: "npm:^5.0.12" + checksum: 10/1729832b0d6d1b0b66949f994d69d129d12c90f695bab5470a6cd9127f9ee5bd88ed85b7dc00774c66c5926491eeaa4000f11b28ecf754ecffbb24cab0c0c81b + languageName: node + linkType: hard + +"minimatch@npm:^3.0.4, minimatch@npm:^3.1.1, minimatch@npm:^3.1.5": version: 3.1.5 resolution: "minimatch@npm:3.1.5" dependencies: @@ -10541,29 +12369,29 @@ __metadata: linkType: hard "minimatch@npm:^5.0.1": - version: 5.1.9 - resolution: "minimatch@npm:5.1.9" + version: 5.1.0 + resolution: "minimatch@npm:5.1.0" dependencies: brace-expansion: "npm:^2.0.1" - checksum: 10/23b4feb64dcb77ba93b70a72be551eb2e2677ac02178cf1ed3d38836cc4cd84802d90b77f60ef87f2bac64d270d2d8eba242e428f0554ea4e36bfdb7e9d25d0c + checksum: 10/3bcc271af1e5e95260fb9acd859628db9567a27ff1fe45b42fcf9b37f17dddbc5a23a614108755a6e076a5109969cabdc0b266ae6929fab12e679ec0f07f65ec languageName: node linkType: hard "minimatch@npm:^7.4.6": - version: 7.4.9 - resolution: "minimatch@npm:7.4.9" + version: 7.4.6 + resolution: "minimatch@npm:7.4.6" dependencies: - brace-expansion: "npm:^2.0.2" - checksum: 10/9bc60b593dafb71d68b1a671a0c1a4bb9a71ef2f8daa8ed4b8b6199bb2d522163fb2e94d82ca40518eaa3b00218f587ad7ab2ed40e56e4c57a8bddb6c2bd1d27 + brace-expansion: "npm:^2.0.1" + checksum: 10/0046ba1161ac6414bde1b07c440792ebcdb2ed93e6714c85c73974332b709b7e692801550bc9da22028a8613407b3f13861e17dd0dd44f4babdeacd44950430b languageName: node linkType: hard "minimatch@npm:^9.0.3, minimatch@npm:^9.0.4": - version: 9.0.9 - resolution: "minimatch@npm:9.0.9" + version: 9.0.5 + resolution: "minimatch@npm:9.0.5" dependencies: - brace-expansion: "npm:^2.0.2" - checksum: 10/b91fad937deaffb68a45a2cb731ff3cff1c3baf9b6469c879477ed16f15c8f4ce39d63a3f75c2455107c2fdff0f3ab597d97dc09e2e93b883aafcf926ef0c8f9 + brace-expansion: "npm:^2.0.1" + checksum: 10/dd6a8927b063aca6d910b119e1f2df6d2ce7d36eab91de83167dd136bb85e1ebff97b0d3de1cb08bd1f7e018ca170b4962479fefab5b2a69e2ae12cb2edc8348 languageName: node linkType: hard @@ -10578,6 +12406,13 @@ __metadata: languageName: node linkType: hard +"minimist@npm:^1.2.8": + version: 1.2.8 + resolution: "minimist@npm:1.2.8" + checksum: 10/908491b6cc15a6c440ba5b22780a0ba89b9810e1aea684e253e43c4e3b8d56ec1dcdd7ea96dde119c29df59c936cde16062159eae4225c691e19c70b432b6e6f + languageName: node + linkType: hard + "minipass-collect@npm:^1.0.2": version: 1.0.2 resolution: "minipass-collect@npm:1.0.2" @@ -10709,12 +12544,19 @@ __metadata: languageName: node linkType: hard -"nanoid@npm:^3.3.10, nanoid@npm:^3.3.18, nanoid@npm:^3.3.8": - version: 3.3.19 - resolution: "nanoid@npm:3.3.19" +"nanoid@npm:^3.3.10, nanoid@npm:^3.3.7, nanoid@npm:^3.3.8": + version: 3.3.11 + resolution: "nanoid@npm:3.3.11" bin: nanoid: bin/nanoid.cjs - checksum: 10/a330adb28dad63eccb0a0c95a2a61353e84b7e067061fff94167803d94be8eef0f7b75cf2da1bece06e8b7afb892abbe52cf0ec33298c817a083eedccd7656e4 + checksum: 10/73b5afe5975a307aaa3c95dfe3334c52cdf9ae71518176895229b8d65ab0d1c0417dd081426134eb7571c055720428ea5d57c645138161e7d10df80815527c48 + languageName: node + linkType: hard + +"napi-postinstall@npm:npm-empty-package@^1.0.0": + version: 1.0.0 + resolution: "npm-empty-package@npm:1.0.0" + checksum: 10/a8c1a51365b2edbe4ac6532f60f19a994293c88dca891f69cd8d744fc6ab462c34caec258f00da1c35b46900cef5a6308f4a0cddccfb08955cae5e75c46e2afb languageName: node linkType: hard @@ -10732,6 +12574,13 @@ __metadata: languageName: node linkType: hard +"neo-async@npm:^2.6.2": + version: 2.6.2 + resolution: "neo-async@npm:2.6.2" + checksum: 10/1a7948fea86f2b33ec766bc899c88796a51ba76a4afc9026764aedc6e7cde692a09067031e4a1bf6db4f978ccd99e7f5b6c03fe47ad9865c3d4f99050d67e002 + languageName: node + linkType: hard + "nise@npm:^6.1.1": version: 6.1.1 resolution: "nise@npm:6.1.1" @@ -10759,7 +12608,25 @@ __metadata: resolution: "node-addon-api@npm:3.2.1" dependencies: node-gyp: "npm:latest" - checksum: 10/681b52dfa3e15b0a8e5cf283cc0d8cd5fd2a57c559ae670fcfd20544cbb32f75de7648674110defcd17ab2c76ebef630aa7d2d2f930bc7a8cc439b20fe233518 + checksum: 10/681b52dfa3e15b0a8e5cf283cc0d8cd5fd2a57c559ae670fcfd20544cbb32f75de7648674110defcd17ab2c76ebef630aa7d2d2f930bc7a8cc439b20fe233518 + languageName: node + linkType: hard + +"node-addon-api@npm:^5.0.0": + version: 5.1.0 + resolution: "node-addon-api@npm:5.1.0" + dependencies: + node-gyp: "npm:latest" + checksum: 10/595f59ffb4630564f587c502119cbd980d302e482781021f3b479f5fc7e41cf8f2f7280fdc2795f32d148e4f3259bd15043c52d4a3442796aa6f1ae97b959636 + languageName: node + linkType: hard + +"node-addon-api@npm:^7.0.0": + version: 7.1.1 + resolution: "node-addon-api@npm:7.1.1" + dependencies: + node-gyp: "npm:latest" + checksum: 10/ee1e1ed6284a2f8cd1d59ac6175ecbabf8978dcf570345e9a8095a9d0a2b9ced591074ae77f9009287b00c402352b38aa9322a34f2199cdc9f567b842a636b94 languageName: node linkType: hard @@ -10845,9 +12712,9 @@ __metadata: linkType: hard "node-releases@npm:^2.0.64": - version: 2.0.65 - resolution: "node-releases@npm:2.0.65" - checksum: 10/43c287f35cc102bc3c527ea2cecc6f71aad2ffd08f828a3e18aa267bf82b5ed201b9563907c148ea15fbe69760f82e32b713daa222c1aa2b1f3a621d58448b9f + version: 2.0.66 + resolution: "node-releases@npm:2.0.66" + checksum: 10/516a65213330de98294b9bf2eb9a5a054dce1245af9e1293de7c90221742247d4fe1b0abeb2d9d63259cd65147ba03992a1d8bac082b7658961e0d28c117ca70 languageName: node linkType: hard @@ -10915,6 +12782,13 @@ __metadata: languageName: node linkType: hard +"normalize-url@npm:^6.0.1": + version: 6.1.0 + resolution: "normalize-url@npm:6.1.0" + checksum: 10/5ae699402c9d5ffa330adc348fcd6fc6e6a155ab7c811b96e30b7ecab60ceef821d8f86443869671dda71bbc47f4b9625739c82ad247e883e9aefe875bfb8659 + languageName: node + linkType: hard + "npm-install-checks@npm:^6.0.0": version: 6.3.0 resolution: "npm-install-checks@npm:6.3.0" @@ -11079,7 +12953,7 @@ __metadata: languageName: node linkType: hard -"once@npm:^1.3.0, once@npm:^1.4.0": +"once@npm:^1.3.0, once@npm:^1.3.1, once@npm:^1.4.0": version: 1.4.0 resolution: "once@npm:1.4.0" dependencies: @@ -11201,6 +13075,13 @@ __metadata: languageName: node linkType: hard +"p-cancelable@npm:^2.0.0": + version: 2.1.1 + resolution: "p-cancelable@npm:2.1.1" + checksum: 10/7f1b64db17fc54acf359167d62898115dcf2a64bf6b3b038e4faf36fc059e5ed762fb9624df8ed04b25bee8de3ab8d72dea9879a2a960cd12e23c420a4aca6ed + languageName: node + linkType: hard + "p-limit@npm:^2.2.0": version: 2.3.0 resolution: "p-limit@npm:2.3.0" @@ -11253,10 +13134,10 @@ __metadata: languageName: node linkType: hard -"package-json-from-dist@npm:^1.0.0": - version: 1.0.0 - resolution: "package-json-from-dist@npm:1.0.0" - checksum: 10/ac706ec856a5a03f5261e4e48fa974f24feb044d51f84f8332e2af0af04fbdbdd5bbbfb9cbbe354190409bc8307c83a9e38c6672c3c8855f709afb0006a009ea +"package-json-from-dist@npm:^1.0.0, package-json-from-dist@npm:^1.0.1": + version: 1.0.1 + resolution: "package-json-from-dist@npm:1.0.1" + checksum: 10/58ee9538f2f762988433da00e26acc788036914d57c71c246bf0be1b60cdbd77dd60b6a3e1a30465f0b248aeb80079e0b34cb6050b1dfa18c06953bb1cbc7602 languageName: node linkType: hard @@ -11327,7 +13208,7 @@ __metadata: languageName: node linkType: hard -"path-expression-matcher@npm:^1.2.0, path-expression-matcher@npm:^1.6.2": +"path-expression-matcher@npm:^1.1.3, path-expression-matcher@npm:^1.2.0": version: 1.6.2 resolution: "path-expression-matcher@npm:1.6.2" checksum: 10/d7786b170933dd82ed897144daed7d54dbe2e7b7d8684182ee9bf51a966cc92548788e2f49280922202a0186409008d816aefa37ed4650e4038184181a73c4bd @@ -11382,10 +13263,20 @@ __metadata: languageName: node linkType: hard +"path-scurry@npm:^3.0.0": + version: 3.0.3 + resolution: "path-scurry@npm:3.0.3" + dependencies: + lru-cache: "npm:^11.0.0" + minipass: "npm:^7.1.2" + checksum: 10/abbed2962f9e3e666c644d8b23d8250bd6a29140e55236f126f95c1d193bab5f949b1bb910712c4cec57ae4d438af7e66daacb119af297f00e44b9e5d77bb6b2 + languageName: node + linkType: hard + "path-to-regexp@npm:^8.1.0": - version: 8.4.2 - resolution: "path-to-regexp@npm:8.4.2" - checksum: 10/70fd2cbce0b962cbcf4d312af07818bfce2bae11c09cf3bd86be99c0e30168238a1a7b02b18b452e73f075897df04597d30d63e56da7be41eecfc37998693389 + version: 8.1.0 + resolution: "path-to-regexp@npm:8.1.0" + checksum: 10/5016a27153d99d3da6a7769a3f34eb4a35538d23a9b4044f517960978876af4d23146f0421e9714be0449f61ffffb04941ffcb7e6bd7c69cf6d891238becd587 languageName: node linkType: hard @@ -11404,20 +13295,19 @@ __metadata: linkType: hard "pbkdf2@npm:^3.0.17, pbkdf2@npm:^3.0.9": - version: 3.1.6 - resolution: "pbkdf2@npm:3.1.6" + version: 3.1.2 + resolution: "pbkdf2@npm:3.1.2" dependencies: - create-hash: "npm:^1.2.0" - create-hmac: "npm:^1.1.7" - ripemd160: "npm:^2.0.3" - safe-buffer: "npm:^5.2.1" - sha.js: "npm:^2.4.12" - to-buffer: "npm:^1.2.2" - checksum: 10/489af0d7b0c25da78517c45e3f2f02804e2131d7cc9d0393d086ac53c07b852248eb92c1011613a87984191647a254ae2928888df042484d79f7b359c417f6ea + create-hash: "npm:^1.1.2" + create-hmac: "npm:^1.1.4" + ripemd160: "npm:^2.0.1" + safe-buffer: "npm:^5.0.1" + sha.js: "npm:^2.4.8" + checksum: 10/40bdf30df1c9bb1ae41ec50c11e480cf0d36484b7c7933bf55e4451d1d0e3f09589df70935c56e7fccc5702779a0d7b842d012be8c08a187b44eb24d55bb9460 languageName: node linkType: hard -"picocolors@npm:^1.0.0, picocolors@npm:^1.1.1": +"picocolors@npm:^1.0.1, picocolors@npm:^1.1.1": version: 1.1.1 resolution: "picocolors@npm:1.1.1" checksum: 10/e1cf46bf84886c79055fdfa9dcb3e4711ad259949e3565154b004b260cd356c5d54b31a1437ce9782624bf766272fe6b0154f5f0c744fb7af5d454d2b60db045 @@ -11425,23 +13315,23 @@ __metadata: linkType: hard "picomatch@npm:^2.0.4, picomatch@npm:^2.2.1, picomatch@npm:^2.2.3, picomatch@npm:^2.3.1": - version: 2.3.2 - resolution: "picomatch@npm:2.3.2" - checksum: 10/b788ef8148a2415b9dec12f0bb350ae6a5830f8f1950e472abc2f5225494debf7d1b75eb031df0ceaea9e8ec3e7bad599e8dbf3c60d61b42be429ba41bff4426 + version: 2.3.1 + resolution: "picomatch@npm:2.3.1" + checksum: 10/60c2595003b05e4535394d1da94850f5372c9427ca4413b71210f437f7b2ca091dbd611c45e8b37d10036fa8eade25c1b8951654f9d3973bfa66a2ff4d3b08bc languageName: node linkType: hard -"picomatch@npm:^4.0.2, picomatch@npm:^4.0.4": +"picomatch@npm:^4.0.2, picomatch@npm:^4.0.3, picomatch@npm:^4.0.4": version: 4.0.7 resolution: "picomatch@npm:4.0.7" checksum: 10/66e1df34bc39c72fa3756be4069f7887ea3e35e94bba1c3f6167763007698cb04b8a0a365161d186fda6e9571a2d3efb606b2966eb6a7dea6252911224dc2f48 languageName: node linkType: hard -"pirates@npm:^4.0.4": - version: 4.0.5 - resolution: "pirates@npm:4.0.5" - checksum: 10/3728bae0cf6c18c3d25f5449ee8c5bc1a6a83bca688abe0e1654ce8c069bfd408170397cef133ed9ec8b0faeb4093c5c728d0e72ab7b3385256cd87008c40364 +"pirates@npm:^4.0.4, pirates@npm:^4.0.7": + version: 4.0.7 + resolution: "pirates@npm:4.0.7" + checksum: 10/2427f371366081ae42feb58214f04805d6b41d6b84d74480ebcc9e0ddbd7105a139f7c653daeaf83ad8a1a77214cf07f64178e76de048128fec501eab3305a96 languageName: node linkType: hard @@ -11487,13 +13377,13 @@ __metadata: linkType: hard "postcss@npm:^8.4.40": - version: 8.5.28 - resolution: "postcss@npm:8.5.28" + version: 8.4.41 + resolution: "postcss@npm:8.4.41" dependencies: - nanoid: "npm:^3.3.18" - picocolors: "npm:^1.1.1" - source-map-js: "npm:^1.2.1" - checksum: 10/c34814c1da499f370cd3b02a085a2d866989a966629b7bd4025f4a2a10d538a2ec83dc3181e1008550edb4cf44e49a0c40ec82332b08d9600877e6841240ad05 + nanoid: "npm:^3.3.7" + picocolors: "npm:^1.0.1" + source-map-js: "npm:^1.2.0" + checksum: 10/6e6176c2407eff60493ca60a706c6b7def20a722c3adda94ea1ece38345eb99964191336fd62b62652279cec6938e79e0b1e1d477142c8d3516e7a725a74ee37 languageName: node linkType: hard @@ -11537,6 +13427,18 @@ __metadata: languageName: node linkType: hard +"pretty-format@npm:30.5.1, pretty-format@npm:^30.0.0": + version: 30.5.1 + resolution: "pretty-format@npm:30.5.1" + dependencies: + "@jest/react-is-18": "npm:react-is@^18.3.1" + "@jest/react-is-19": "npm:react-is@^19.2.5" + "@jest/schemas": "npm:30.5.0" + ansi-styles: "npm:^5.2.0" + checksum: 10/bf86d7eb192ef2a456ded06fbe5d387c92b09dc4473331dbc7130e79128fd90f66c662717df8a52431060c1ddb8288a0a78858e9c203974de1b8d1107054b6e8 + languageName: node + linkType: hard + "pretty-format@npm:^29.0.0, pretty-format@npm:^29.7.0": version: 29.7.0 resolution: "pretty-format@npm:29.7.0" @@ -11593,7 +13495,7 @@ __metadata: languageName: node linkType: hard -"prompts@npm:^2.0.1, prompts@npm:^2.4.2": +"prompts@npm:^2.0.1, prompts@npm:^2.4.0, prompts@npm:^2.4.2": version: 2.4.2 resolution: "prompts@npm:2.4.2" dependencies: @@ -11623,12 +13525,12 @@ __metadata: linkType: hard "proxy-addr@npm:~2.0.7": - version: 2.0.8 - resolution: "proxy-addr@npm:2.0.8" + version: 2.0.7 + resolution: "proxy-addr@npm:2.0.7" dependencies: forwarded: "npm:0.2.0" ipaddr.js: "npm:1.9.1" - checksum: 10/6922b732c5625a9ba174c053bf3a750a80c87f19b7c62919f88ff01834eb80e2467834cfa72fc48b3a7ed6b3d18daadf773f6efb21db1c5fcc76d784509fcf1f + checksum: 10/f24a0c80af0e75d31e3451398670d73406ec642914da11a2965b80b1898ca6f66a0e3e091a11a4327079b2b268795f6fa06691923fef91887215c3d0e8ea3f68 languageName: node linkType: hard @@ -11646,6 +13548,23 @@ __metadata: languageName: node linkType: hard +"pump@npm:^3.0.0": + version: 3.0.4 + resolution: "pump@npm:3.0.4" + dependencies: + end-of-stream: "npm:^1.1.0" + once: "npm:^1.3.1" + checksum: 10/d043c3e710c56ffd280711e98a94e863ab334f79ea43cee0fb70e1349b2355ffd2ff287c7522e4c960a247699d5b7825f00fa090b85d6179c973be13f78a6c49 + languageName: node + linkType: hard + +"punycode.js@npm:^2.3.1": + version: 2.3.1 + resolution: "punycode.js@npm:2.3.1" + checksum: 10/f0e946d1edf063f9e3d30a32ca86d8ff90ed13ca40dad9c75d37510a04473340cfc98db23a905cc1e517b1e9deb0f6021dce6f422ace235c60d3c9ac47c5a16a + languageName: node + linkType: hard + "punycode@npm:2.1.0": version: 2.1.0 resolution: "punycode@npm:2.1.0" @@ -11667,6 +13586,13 @@ __metadata: languageName: node linkType: hard +"pure-rand@npm:^7.0.0": + version: 7.0.1 + resolution: "pure-rand@npm:7.0.1" + checksum: 10/c61a576fda5032ec9763ecb000da4a8f19263b9e2f9ae9aa2759c8fbd9dc6b192b2ce78391ebd41abb394a5fedb7bcc4b03c9e6141ac8ab20882dd5717698b80 + languageName: node + linkType: hard + "purify-ts@npm:2.1.0": version: 2.1.0 resolution: "purify-ts@npm:2.1.0" @@ -11685,6 +13611,13 @@ __metadata: languageName: node linkType: hard +"qrcode-generator@npm:^2.0.4": + version: 2.0.4 + resolution: "qrcode-generator@npm:2.0.4" + checksum: 10/c488558bca2869d8837300da299a9653030dbb486ce6113153585b117fa0ab6822a03c8312cc794d41c2e3f8353dc64b950e8a3ffe90f89022593c4e7060cd53 + languageName: node + linkType: hard + "qs@npm:~6.14.0": version: 6.14.2 resolution: "qs@npm:6.14.2" @@ -11694,16 +13627,6 @@ __metadata: languageName: node linkType: hard -"qs@npm:~6.16.0": - version: 6.16.2 - resolution: "qs@npm:6.16.2" - dependencies: - es-define-property: "npm:^1.0.1" - side-channel: "npm:^1.1.1" - checksum: 10/8ff10fd394a0a0f7b2c98d17b44da6982ded922d5a4ccda0c227a591090e360bf2ae3a1cd236b63797075ee7d37b2035b44e1b12979605741462c6dded265023 - languageName: node - linkType: hard - "querystringify@npm:^2.1.1": version: 2.2.0 resolution: "querystringify@npm:2.2.0" @@ -11732,6 +13655,13 @@ __metadata: languageName: node linkType: hard +"quick-lru@npm:^5.1.1": + version: 5.1.1 + resolution: "quick-lru@npm:5.1.1" + checksum: 10/a516faa25574be7947969883e6068dbe4aa19e8ef8e8e0fd96cddd6d36485e9106d85c0041a27153286b0770b381328f4072aa40d3b18a19f5f7d2b78b94b5ed + languageName: node + linkType: hard + "randombytes@npm:^2.0.1, randombytes@npm:^2.1.0": version: 2.1.0 resolution: "randombytes@npm:2.1.0" @@ -11923,6 +13853,13 @@ __metadata: languageName: node linkType: hard +"resolve-alpn@npm:^1.0.0": + version: 1.2.1 + resolution: "resolve-alpn@npm:1.2.1" + checksum: 10/744e87888f0b6fa0b256ab454ca0b9c0b80808715e2ef1f3672773665c92a941f6181194e30ccae4a8cd0adbe0d955d3f133102636d2ee0cca0119fec0bc9aec + languageName: node + linkType: hard + "resolve-cwd@npm:^3.0.0": version: 3.0.0 resolution: "resolve-cwd@npm:3.0.0" @@ -11998,6 +13935,15 @@ __metadata: languageName: node linkType: hard +"responselike@npm:^2.0.0": + version: 2.0.1 + resolution: "responselike@npm:2.0.1" + dependencies: + lowercase-keys: "npm:^2.0.0" + checksum: 10/b122535466e9c97b55e69c7f18e2be0ce3823c5d47ee8de0d9c0b114aa55741c6db8bfbfce3766a94d1272e61bfb1ebf0a15e9310ac5629fbb7446a861b4fd3a + languageName: node + linkType: hard + "retry@npm:^0.12.0": version: 0.12.0 resolution: "retry@npm:0.12.0" @@ -12041,7 +13987,19 @@ __metadata: languageName: node linkType: hard -"ripemd160@npm:^2.0.0, ripemd160@npm:^2.0.1, ripemd160@npm:^2.0.2, ripemd160@npm:^2.0.3": +"rimraf@npm:^6.1.4": + version: 6.1.4 + resolution: "rimraf@npm:6.1.4" + dependencies: + glob: "npm:^14.0.3" + package-json-from-dist: "npm:^1.0.1" + bin: + rimraf: dist/esm/bin.mjs + checksum: 10/0d32a62467513fd179fe92ac797334f57dfc20661ac997e80f7573a223fdb83d76b80db52d2911068b5101aefb175aaf31d1d5ac960b8ff1140d5cfc171f70c0 + languageName: node + linkType: hard + +"ripemd160@npm:^2.0.0, ripemd160@npm:^2.0.1, ripemd160@npm:^2.0.2": version: 2.0.3 resolution: "ripemd160@npm:2.0.3" dependencies: @@ -12175,14 +14133,26 @@ __metadata: linkType: hard "secp256k1@npm:^4.0.0, secp256k1@npm:^4.0.1": - version: 4.0.3 - resolution: "secp256k1@npm:4.0.3" + version: 4.0.5 + resolution: "secp256k1@npm:4.0.5" dependencies: - elliptic: "npm:^6.5.4" - node-addon-api: "npm:^2.0.0" + elliptic: "npm:^6.5.7" + node-addon-api: "npm:^5.0.0" + node-gyp: "npm:latest" + node-gyp-build: "npm:^4.2.0" + checksum: 10/16b6131d521ca345959469cf6720f55b2ffec83d6989a2ae80975d6dfa3815b29a8ff80b30ce8089532999544f64bc070c2933f701721800a88b9e0e6d4814a1 + languageName: node + linkType: hard + +"secp256k1@npm:^5.0.2": + version: 5.0.2 + resolution: "secp256k1@npm:5.0.2" + dependencies: + elliptic: "npm:^6.5.7" + node-addon-api: "npm:^5.0.0" node-gyp: "npm:latest" node-gyp-build: "npm:^4.2.0" - checksum: 10/8b45820cd90fd2f95cc8fdb9bf8a71e572de09f2311911ae461a951ffa9e30c99186a129d0f1afeb380dd67eca0c10493f8a7513c39063fda015e99995088e3b + checksum: 10/edae3fb213a149c15559a8a74ea0d04e256d154f92ef9eb3cf3ba17425bc517a702abbd02c286d81b76210dd2176bac30cca0b792ce14a89cbbe87a6c46b35b5 languageName: node linkType: hard @@ -12308,16 +14278,15 @@ __metadata: languageName: node linkType: hard -"sha.js@npm:^2.3.6, sha.js@npm:^2.4.0, sha.js@npm:^2.4.11, sha.js@npm:^2.4.12, sha.js@npm:^2.4.8": - version: 2.4.12 - resolution: "sha.js@npm:2.4.12" +"sha.js@npm:^2.3.6, sha.js@npm:^2.4.0, sha.js@npm:^2.4.11, sha.js@npm:^2.4.8": + version: 2.4.11 + resolution: "sha.js@npm:2.4.11" dependencies: - inherits: "npm:^2.0.4" - safe-buffer: "npm:^5.2.1" - to-buffer: "npm:^1.2.0" + inherits: "npm:^2.0.1" + safe-buffer: "npm:^5.0.1" bin: - sha.js: bin.js - checksum: 10/39c0993592c2ab34eb2daae2199a2a1d502713765aecb611fd97c0c4ab7cd53e902d628e1962aaf384bafd28f55951fef46dcc78799069ce41d74b03aa13b5a7 + sha.js: ./bin.js + checksum: 10/d833bfa3e0a67579a6ce6e1bc95571f05246e0a441dd8c76e3057972f2a3e098465687a4369b07e83a0375a88703577f71b5b2e966809e67ebc340dbedb478c7 languageName: node linkType: hard @@ -12391,7 +14360,7 @@ __metadata: languageName: node linkType: hard -"side-channel@npm:^1.1.0, side-channel@npm:^1.1.1": +"side-channel@npm:^1.1.0": version: 1.1.1 resolution: "side-channel@npm:1.1.1" dependencies: @@ -12483,12 +14452,12 @@ __metadata: linkType: hard "socks@npm:^2.6.2, socks@npm:^2.8.3": - version: 2.8.11 - resolution: "socks@npm:2.8.11" + version: 2.8.3 + resolution: "socks@npm:2.8.3" dependencies: - ip-address: "npm:^10.1.1" + ip-address: "npm:^9.0.5" smart-buffer: "npm:^4.2.0" - checksum: 10/6e04a51e3c56561007abeed6e7424586726a774082b91cb4c69defcbd9b286e160dac8bc07830b31b8ff8ad972e916de0f8212873cc65dd70ae99344d507c2b8 + checksum: 10/ffcb622c22481dfcd7589aae71fbfd71ca34334064d181df64bf8b7feaeee19706aba4cffd1de35cc7bbaeeaa0af96be2d7f40fcbc7bc0ab69533a7ae9ffc4fb languageName: node linkType: hard @@ -12526,7 +14495,7 @@ __metadata: languageName: node linkType: hard -"source-map-js@npm:^1.2.0, source-map-js@npm:^1.2.1": +"source-map-js@npm:^1.2.0": version: 1.2.2 resolution: "source-map-js@npm:1.2.2" checksum: 10/4807c894bb6280c8b84886159b96080e3996f42c6e8015e647881edfd4f955f6024ceebb8bb40d33ce8b106e24b2e29c133575e1c60c01c8aae57a05fdf17761 @@ -12594,6 +14563,13 @@ __metadata: languageName: node linkType: hard +"sprintf-js@npm:^1.1.3": + version: 1.1.3 + resolution: "sprintf-js@npm:1.1.3" + checksum: 10/e7587128c423f7e43cc625fe2f87e6affdf5ca51c1cc468e910d8aaca46bb44a7fbcfa552f787b1d3987f7043aeb4527d1b99559e6621e01b42b3f45e5a24cbb + languageName: node + linkType: hard + "sprintf-js@npm:~1.0.2": version: 1.0.3 resolution: "sprintf-js@npm:1.0.3" @@ -12617,12 +14593,12 @@ __metadata: languageName: node linkType: hard -"stack-utils@npm:^2.0.3": - version: 2.0.5 - resolution: "stack-utils@npm:2.0.5" +"stack-utils@npm:^2.0.3, stack-utils@npm:^2.0.6": + version: 2.0.6 + resolution: "stack-utils@npm:2.0.6" dependencies: escape-string-regexp: "npm:^2.0.0" - checksum: 10/a6d64e5dd24d321289ebefdff2e210ece75fdf20dbcdb702b86da1f7b730743fae3e9337adae4a5cc00d4970d748ff758387df3ea7c71c45b466c43c7359bc00 + checksum: 10/cdc988acbc99075b4b036ac6014e5f1e9afa7e564482b687da6384eee6a1909d7eaffde85b0a17ffbe186c5247faf6c2b7544e802109f63b72c7be69b13151bb languageName: node linkType: hard @@ -12658,13 +14634,13 @@ __metadata: languageName: node linkType: hard -"string-length@npm:^4.0.1": - version: 4.0.1 - resolution: "string-length@npm:4.0.1" +"string-length@npm:^4.0.1, string-length@npm:^4.0.2": + version: 4.0.2 + resolution: "string-length@npm:4.0.2" dependencies: char-regex: "npm:^1.0.2" strip-ansi: "npm:^6.0.0" - checksum: 10/7bd3191668ddafa6f574a8b17a1bd1b085737d64ceefa51f72cdd19c45a730422cd70d984eee7584d6e5b5c84b6318633c6d6a720a4bfd7c58769985fa77573e + checksum: 10/ce85533ef5113fcb7e522bcf9e62cb33871aa99b3729cec5595f4447f660b0cefd542ca6df4150c97a677d58b0cb727a3fe09ac1de94071d05526c73579bf505 languageName: node linkType: hard @@ -12690,6 +14666,17 @@ __metadata: languageName: node linkType: hard +"string-width@npm:^7.0.0, string-width@npm:^7.2.0": + version: 7.2.0 + resolution: "string-width@npm:7.2.0" + dependencies: + emoji-regex: "npm:^10.3.0" + get-east-asian-width: "npm:^1.0.0" + strip-ansi: "npm:^7.1.0" + checksum: 10/42f9e82f61314904a81393f6ef75b832c39f39761797250de68c041d8ba4df2ef80db49ab6cd3a292923a6f0f409b8c9980d120f7d32c820b4a8a84a2598a295 + languageName: node + linkType: hard + "string_decoder@npm:^1.1.1, string_decoder@npm:^1.3.0": version: 1.3.0 resolution: "string_decoder@npm:1.3.0" @@ -12717,12 +14704,12 @@ __metadata: languageName: node linkType: hard -"strip-ansi@npm:^7.0.1": - version: 7.1.0 - resolution: "strip-ansi@npm:7.1.0" +"strip-ansi@npm:^7.0.1, strip-ansi@npm:^7.1.0": + version: 7.2.0 + resolution: "strip-ansi@npm:7.2.0" dependencies: - ansi-regex: "npm:^6.0.1" - checksum: 10/475f53e9c44375d6e72807284024ac5d668ee1d06010740dec0b9744f2ddf47de8d7151f80e5f6190fc8f384e802fdf9504b76a7e9020c9faee7103623338be2 + ansi-regex: "npm:^6.2.2" + checksum: 10/96da3bc6d73cfba1218625a3d66cf7d37a69bf0920d8735b28f9eeaafcdb6c1fe8440e1ae9eb1ba0ca355dbe8702da872e105e2e939fa93e7851b3cb5dd7d316 languageName: node linkType: hard @@ -12788,7 +14775,7 @@ __metadata: languageName: node linkType: hard -"supports-color@npm:^8.0.0": +"supports-color@npm:^8.0.0, supports-color@npm:^8.1.1": version: 8.1.1 resolution: "supports-color@npm:8.1.1" dependencies: @@ -12831,12 +14818,12 @@ __metadata: languageName: node linkType: hard -"synckit@npm:^0.11.12": - version: 0.11.12 - resolution: "synckit@npm:0.11.12" +"synckit@npm:^0.11.12, synckit@npm:^0.11.8": + version: 0.11.13 + resolution: "synckit@npm:0.11.13" dependencies: - "@pkgr/core": "npm:^0.2.9" - checksum: 10/2f51978bfed81aaf0b093f596709a72c49b17909020f42b43c5549f9c0fe18b1fe29f82e41ef771172d729b32e9ce82900a85d2b87fa14d59f886d4df8d7a329 + "@pkgr/core": "npm:^0.3.6" + checksum: 10/188544a829dbd38abd144281960835c1f8027aaa495b7c40d39ebf0c1c63a4a41c0edc42818b7ada9b5c0c15fba2f625b472220d128798fe98f9181fed84e6a2 languageName: node linkType: hard @@ -12858,16 +14845,23 @@ __metadata: languageName: node linkType: hard -"tar@npm:^7.5.16": - version: 7.5.22 - resolution: "tar@npm:7.5.22" +"tar@npm:^7.5.16, tar@npm:^7.5.3": + version: 7.5.24 + resolution: "tar@npm:7.5.24" dependencies: "@isaacs/fs-minipass": "npm:^4.0.0" chownr: "npm:^3.0.0" minipass: "npm:^7.1.2" minizlib: "npm:^3.1.0" yallist: "npm:^5.0.0" - checksum: 10/129606384b3c895f422aaca48bf316357be6dc7aa35c1066c3f06c28acfff0be5b356e1b0a0be7c53a7a8945534ac06cec6d8e296d170d8a09c8bff67b29300e + checksum: 10/9156541c8e99f5bc491aa7fbf5fa778095c774353cc610c9caa65845b3b911000aa3d781a10e649dd57869b6a93270504cac26ec81e58b05b5b2ea828dd8d1db + languageName: node + linkType: hard + +"tar@npm:^8.0.3": + version: 8.0.3 + resolution: "tar@npm:8.0.3" + checksum: 10/55c098ab9bc2786c7488f1075a071c3b11b7e44aef2ad70247dfd6bb1c04542f78415084c8a07b2b595c481cfde3951bdd027701861816c3bf16dc7278eeee6e languageName: node linkType: hard @@ -12882,6 +14876,17 @@ __metadata: languageName: node linkType: hard +"test-exclude@npm:^7.0.1": + version: 7.0.2 + resolution: "test-exclude@npm:7.0.2" + dependencies: + "@istanbuljs/schema": "npm:^0.1.2" + glob: "npm:^10.4.1" + minimatch: "npm:^10.2.2" + checksum: 10/45920af7556a58333c75c3d5011b4087f7ac41366319fb0f6ccc4ac8d0e9d2c81442d7ebf6efd13813dcf18c135eda3c52e4ad3e00407a3ee041d8dec6bfd753 + languageName: node + linkType: hard + "text-decoder@npm:^1.1.0": version: 1.1.1 resolution: "text-decoder@npm:1.1.1" @@ -12892,8 +14897,8 @@ __metadata: linkType: hard "tiny-secp256k1@npm:^1.1.6": - version: 1.1.7 - resolution: "tiny-secp256k1@npm:1.1.7" + version: 1.1.6 + resolution: "tiny-secp256k1@npm:1.1.6" dependencies: bindings: "npm:^1.3.0" bn.js: "npm:^4.11.8" @@ -12901,7 +14906,7 @@ __metadata: elliptic: "npm:^6.4.0" nan: "npm:^2.13.2" node-gyp: "npm:latest" - checksum: 10/588393c36df18b2819787fc91616e1fcb930509307eecc460ad45c7011f99f900eea28493a36eb203c3933ae76f737e6a1b978fa0b8a391fcc5dd7b64d57c572 + checksum: 10/e25b45ba3e95a332d21556617f2049f7ef065c737dd979e197856f35ef0bd9ee5608872f0068e5cddf0b50919b43b8eaca86bdea560f623e63ec5c560934ca9b languageName: node linkType: hard @@ -12915,6 +14920,13 @@ __metadata: languageName: node linkType: hard +"tinylogic@npm:^2.0.0": + version: 2.0.0 + resolution: "tinylogic@npm:2.0.0" + checksum: 10/6467b1ed9b602dae035726ee3faf2682bddffb5389b42fdb4daf13878037420ed9981a572ca7db467bd26c4ab00fb4eefe654f24e35984ec017fb5e83081db97 + languageName: node + linkType: hard + "tinypool@npm:^2.2.0": version: 2.2.0 resolution: "tinypool@npm:2.2.0" @@ -12929,7 +14941,7 @@ __metadata: languageName: node linkType: hard -"to-buffer@npm:^1.2.0, to-buffer@npm:^1.2.1, to-buffer@npm:^1.2.2": +"to-buffer@npm:^1.2.1": version: 1.2.2 resolution: "to-buffer@npm:1.2.2" dependencies: @@ -12991,6 +15003,13 @@ __metadata: languageName: node linkType: hard +"treeify@npm:^1.1.0": + version: 1.1.0 + resolution: "treeify@npm:1.1.0" + checksum: 10/5241976a751168fb9894a12d031299f1f6337b7f2cbd3eff22ee86e6777620352a69a1cab0d4709251317ff307eeda0dc45918850974fc44f4c7fc50e623b990 + languageName: node + linkType: hard + "trim-newlines@npm:^3.0.0": version: 3.0.1 resolution: "trim-newlines@npm:3.0.1" @@ -13007,6 +15026,13 @@ __metadata: languageName: node linkType: hard +"ts-custom-error@npm:^3.3.1": + version: 3.3.1 + resolution: "ts-custom-error@npm:3.3.1" + checksum: 10/92e3a2c426bf6049579aeb889b6f9787e0cfb6bb715a1457e2571708be7fe739662ca9eb2a8c61b72a2d32189645f4fbcf1a370087e030d922e9e2a7b7c1c994 + languageName: node + linkType: hard + "ts-declaration-location@npm:^1.0.6": version: 1.0.7 resolution: "ts-declaration-location@npm:1.0.7" @@ -13018,26 +15044,27 @@ __metadata: languageName: node linkType: hard -"ts-jest@npm:^29.0.5": - version: 29.2.5 - resolution: "ts-jest@npm:29.2.5" +"ts-jest@npm:^29.0.5, ts-jest@npm:^29.4.15": + version: 29.4.15 + resolution: "ts-jest@npm:29.4.15" dependencies: bs-logger: "npm:^0.2.6" - ejs: "npm:^3.1.10" fast-json-stable-stringify: "npm:^2.1.0" - jest-util: "npm:^29.0.0" + handlebars: "npm:^4.7.10" json5: "npm:^2.2.3" lodash.memoize: "npm:^4.1.2" make-error: "npm:^1.3.6" - semver: "npm:^7.6.3" + semver: "npm:^7.8.5" + type-fest: "npm:^4.41.0" yargs-parser: "npm:^21.1.1" peerDependencies: - "@babel/core": ">=7.0.0-beta.0 <8" - "@jest/transform": ^29.0.0 - "@jest/types": ^29.0.0 - babel-jest: ^29.0.0 - jest: ^29.0.0 - typescript: ">=4.3 <6" + "@babel/core": ">=7.0.0-beta.0 <9" + "@jest/transform": ^29.0.0 || ^30.0.0 + "@jest/types": ^29.0.0 || ^30.0.0 + babel-jest: ^29.0.0 || ^30.0.0 + jest: ^29.0.0 || ^30.0.0 + jest-util: ^29.0.0 || ^30.0.0 + typescript: ">=4.3 <7" peerDependenciesMeta: "@babel/core": optional: true @@ -13049,9 +15076,11 @@ __metadata: optional: true esbuild: optional: true + jest-util: + optional: true bin: ts-jest: cli.js - checksum: 10/f89e562816861ec4510840a6b439be6145f688b999679328de8080dc8e66481325fc5879519b662163e33b7578f35243071c38beb761af34e5fe58e3e326a958 + checksum: 10/762c9a5d2f93bbaf7143807410256b50c22c47e0a16599757330391a85fc7cba9b7a7c8b9bdef4760852b71ed866d03e5942aa343cda23e479261c0e7954b524 languageName: node linkType: hard @@ -13117,6 +15146,23 @@ __metadata: languageName: node linkType: hard +"tsd@npm:^0.33.0": + version: 0.33.0 + resolution: "tsd@npm:0.33.0" + dependencies: + "@tsd/typescript": "npm:^5.9.2" + eslint-formatter-pretty: "npm:^4.1.0" + globby: "npm:^11.0.1" + jest-diff: "npm:^29.0.3" + meow: "npm:^9.0.0" + path-exists: "npm:^4.0.0" + read-pkg-up: "npm:^7.0.0" + bin: + tsd: dist/cli.js + checksum: 10/a093a3e67e42ea42265c066c07f2021346c84780fbc4338edc96da6f239ee5595c132d87ae05e218fc5f794a64f89c624b7f2b171bc4ded43183bf1fded6190f + languageName: node + linkType: hard + "tslib@npm:2.7.0": version: 2.7.0 resolution: "tslib@npm:2.7.0" @@ -13152,6 +15198,13 @@ __metadata: languageName: node linkType: hard +"typanion@npm:^3.8.0": + version: 3.14.0 + resolution: "typanion@npm:3.14.0" + checksum: 10/5e88d9e6121ff0ec543f572152fdd1b70e9cca35406d79013ec8e08defa8ef96de5fec9e98da3afbd1eb4426b9e8e8fe423163d0b482e34a40103cab1ef29abd + languageName: node + linkType: hard + "type-check@npm:^0.4.0, type-check@npm:~0.4.0": version: 0.4.0 resolution: "type-check@npm:0.4.0" @@ -13175,20 +15228,13 @@ __metadata: languageName: node linkType: hard -"type-fest@npm:4.41.0": +"type-fest@npm:4.41.0, type-fest@npm:^4.41.0": version: 4.41.0 resolution: "type-fest@npm:4.41.0" checksum: 10/617ace794ac0893c2986912d28b3065ad1afb484cad59297835a0807dc63286c39e8675d65f7de08fafa339afcb8fe06a36e9a188b9857756ae1e92ee8bda212 languageName: node linkType: hard -"type-fest@npm:^0.11.0": - version: 0.11.0 - resolution: "type-fest@npm:0.11.0" - checksum: 10/2d60de8588b876719396abdce0fcf282a0b6290259300f6334f655e99229398ea165e6cabd118961201da8ce4b87d7f50fd5628fb466c346fdc00f68f3548fec - languageName: node - linkType: hard - "type-fest@npm:^0.18.0": version: 0.18.1 resolution: "type-fest@npm:0.18.1" @@ -13196,6 +15242,13 @@ __metadata: languageName: node linkType: hard +"type-fest@npm:^0.21.3": + version: 0.21.3 + resolution: "type-fest@npm:0.21.3" + checksum: 10/f4254070d9c3d83a6e573bcb95173008d73474ceadbbf620dd32d273940ca18734dff39c2b2480282df9afe5d1675ebed5499a00d791758748ea81f61a38961f + languageName: node + linkType: hard + "type-fest@npm:^0.6.0": version: 0.6.0 resolution: "type-fest@npm:0.6.0" @@ -13254,6 +15307,23 @@ __metadata: languageName: node linkType: hard +"typedoc@npm:^0.28.20": + version: 0.28.20 + resolution: "typedoc@npm:0.28.20" + dependencies: + "@gerrit0/mini-shiki": "npm:^3.23.0" + lunr: "npm:^2.3.9" + markdown-it: "npm:^14.3.0" + minimatch: "npm:^10.2.5" + yaml: "npm:^2.9.0" + peerDependencies: + typescript: 5.0.x || 5.1.x || 5.2.x || 5.3.x || 5.4.x || 5.5.x || 5.6.x || 5.7.x || 5.8.x || 5.9.x || 6.0.x + bin: + typedoc: bin/typedoc + checksum: 10/947172bc1bd85333aab1c6fb9dfe925e9184fcca6c6cd7310588e7d2135efcd4c412dcf9eb495c34522d3efdc793c2bc9e58d7ea06b1f917abffb7494ae04ec7 + languageName: node + linkType: hard + "typeforce@npm:^1.18.0": version: 1.18.0 resolution: "typeforce@npm:1.18.0" @@ -13286,6 +15356,16 @@ __metadata: languageName: node linkType: hard +"typescript@npm:~5.9.3": + version: 5.9.3 + resolution: "typescript@npm:5.9.3" + bin: + tsc: bin/tsc + tsserver: bin/tsserver + checksum: 10/c089d9d3da2729fd4ac517f9b0e0485914c4b3c26f80dc0cffcb5de1719a17951e92425d55db59515c1a7ddab65808466debb864d0d56dcf43f27007d0709594 + languageName: node + linkType: hard + "typescript@patch:typescript@npm%3A~5.8.3#optional!builtin": version: 5.8.3 resolution: "typescript@patch:typescript@npm%3A5.8.3#optional!builtin::version=5.8.3&hash=5786d5" @@ -13296,6 +15376,16 @@ __metadata: languageName: node linkType: hard +"typescript@patch:typescript@npm%3A~5.9.3#optional!builtin": + version: 5.9.3 + resolution: "typescript@patch:typescript@npm%3A5.9.3#optional!builtin::version=5.9.3&hash=5786d5" + bin: + tsc: bin/tsc + tsserver: bin/tsserver + checksum: 10/696e1b017bc2635f4e0c94eb4435357701008e2f272f553d06e35b494b8ddc60aa221145e286c28ace0c89ee32827a28c2040e3a69bdc108b1a5dc8fb40b72e3 + languageName: node + linkType: hard + "ua-is-frozen@npm:^0.1.2": version: 0.1.2 resolution: "ua-is-frozen@npm:0.1.2" @@ -13318,6 +15408,22 @@ __metadata: languageName: node linkType: hard +"uc.micro@npm:^2.0.0, uc.micro@npm:^2.1.0": + version: 2.1.0 + resolution: "uc.micro@npm:2.1.0" + checksum: 10/37197358242eb9afe367502d4638ac8c5838b78792ab218eafe48287b0ed28aaca268ec0392cc5729f6c90266744de32c06ae938549aee041fc93b0f9672d6b2 + languageName: node + linkType: hard + +"uglify-js@npm:^3.1.4": + version: 3.19.3 + resolution: "uglify-js@npm:3.19.3" + bin: + uglifyjs: bin/uglifyjs + checksum: 10/6b9639c1985d24580b01bb0ab68e78de310d38eeba7db45bec7850ab4093d8ee464d80ccfaceda9c68d1c366efbee28573b52f95e69ac792354c145acd380b11 + languageName: node + linkType: hard + "uint8array-tools@npm:^0.0.8": version: 0.0.8 resolution: "uint8array-tools@npm:0.0.8" @@ -13332,6 +15438,13 @@ __metadata: languageName: node linkType: hard +"undici-types@npm:~6.19.2": + version: 6.19.8 + resolution: "undici-types@npm:6.19.8" + checksum: 10/cf0b48ed4fc99baf56584afa91aaffa5010c268b8842f62e02f752df209e3dea138b372a60a963b3b2576ed932f32329ce7ddb9cb5f27a6c83040d8cd74b7a70 + languageName: node + linkType: hard + "undici-types@npm:~6.21.0": version: 6.21.0 resolution: "undici-types@npm:6.21.0" @@ -13339,6 +15452,13 @@ __metadata: languageName: node linkType: hard +"undici-types@npm:~8.9.0": + version: 8.9.0 + resolution: "undici-types@npm:8.9.0" + checksum: 10/8785591929de2b71d281c684e915c4a8c41becc225adbf42a3e89148f8b384724a21533494c30a1cbb85b4cbccd088d020788ff4f2d605013eb2863cd47a1639 + languageName: node + linkType: hard + "undici@npm:^6.25.0": version: 6.29.1 resolution: "undici@npm:6.29.1" @@ -13385,6 +15505,79 @@ __metadata: languageName: node linkType: hard +"unrs-resolver@npm:^1.12.1": + version: 1.13.0 + resolution: "unrs-resolver@npm:1.13.0" + dependencies: + "@unrs/resolver-binding-android-arm-eabi": "npm:1.13.0" + "@unrs/resolver-binding-android-arm64": "npm:1.13.0" + "@unrs/resolver-binding-darwin-arm64": "npm:1.13.0" + "@unrs/resolver-binding-darwin-x64": "npm:1.13.0" + "@unrs/resolver-binding-freebsd-x64": "npm:1.13.0" + "@unrs/resolver-binding-linux-arm-gnueabihf": "npm:1.13.0" + "@unrs/resolver-binding-linux-arm-musleabihf": "npm:1.13.0" + "@unrs/resolver-binding-linux-arm64-gnu": "npm:1.13.0" + "@unrs/resolver-binding-linux-arm64-musl": "npm:1.13.0" + "@unrs/resolver-binding-linux-loong64-gnu": "npm:1.13.0" + "@unrs/resolver-binding-linux-loong64-musl": "npm:1.13.0" + "@unrs/resolver-binding-linux-ppc64-gnu": "npm:1.13.0" + "@unrs/resolver-binding-linux-riscv64-gnu": "npm:1.13.0" + "@unrs/resolver-binding-linux-riscv64-musl": "npm:1.13.0" + "@unrs/resolver-binding-linux-s390x-gnu": "npm:1.13.0" + "@unrs/resolver-binding-linux-x64-gnu": "npm:1.13.0" + "@unrs/resolver-binding-linux-x64-musl": "npm:1.13.0" + "@unrs/resolver-binding-openharmony-arm64": "npm:1.13.0" + "@unrs/resolver-binding-win32-arm64-msvc": "npm:1.13.0" + "@unrs/resolver-binding-win32-ia32-msvc": "npm:1.13.0" + "@unrs/resolver-binding-win32-x64-msvc": "npm:1.13.0" + napi-postinstall: "npm:^0.3.7" + dependenciesMeta: + "@unrs/resolver-binding-android-arm-eabi": + optional: true + "@unrs/resolver-binding-android-arm64": + optional: true + "@unrs/resolver-binding-darwin-arm64": + optional: true + "@unrs/resolver-binding-darwin-x64": + optional: true + "@unrs/resolver-binding-freebsd-x64": + optional: true + "@unrs/resolver-binding-linux-arm-gnueabihf": + optional: true + "@unrs/resolver-binding-linux-arm-musleabihf": + optional: true + "@unrs/resolver-binding-linux-arm64-gnu": + optional: true + "@unrs/resolver-binding-linux-arm64-musl": + optional: true + "@unrs/resolver-binding-linux-loong64-gnu": + optional: true + "@unrs/resolver-binding-linux-loong64-musl": + optional: true + "@unrs/resolver-binding-linux-ppc64-gnu": + optional: true + "@unrs/resolver-binding-linux-riscv64-gnu": + optional: true + "@unrs/resolver-binding-linux-riscv64-musl": + optional: true + "@unrs/resolver-binding-linux-s390x-gnu": + optional: true + "@unrs/resolver-binding-linux-x64-gnu": + optional: true + "@unrs/resolver-binding-linux-x64-musl": + optional: true + "@unrs/resolver-binding-openharmony-arm64": + optional: true + "@unrs/resolver-binding-win32-arm64-msvc": + optional: true + "@unrs/resolver-binding-win32-ia32-msvc": + optional: true + "@unrs/resolver-binding-win32-x64-msvc": + optional: true + checksum: 10/b398a818af9f2b3847df9a7bd1a9fa074be1f3c99ac263a6b453abd49dab0a29cc60525c966a2913061e448cfde52efeb3d877aea142232194d641050065aa35 + languageName: node + linkType: hard + "update-browserslist-db@npm:^1.4.0": version: 1.4.0 resolution: "update-browserslist-db@npm:1.4.0" @@ -13747,6 +15940,13 @@ __metadata: languageName: node linkType: hard +"wordwrap@npm:^1.0.0": + version: 1.0.0 + resolution: "wordwrap@npm:1.0.0" + checksum: 10/497d40beb2bdb08e6d38754faa17ce20b0bf1306327f80cb777927edb23f461ee1f6bc659b3c3c93f26b08e1cf4b46acc5bae8fda1f0be3b5ab9a1a0211034cd + languageName: node + linkType: hard + "wrap-ansi-cjs@npm:wrap-ansi@^7.0.0, wrap-ansi@npm:^7.0.0": version: 7.0.0 resolution: "wrap-ansi@npm:7.0.0" @@ -13769,6 +15969,17 @@ __metadata: languageName: node linkType: hard +"wrap-ansi@npm:^9.0.0": + version: 9.0.2 + resolution: "wrap-ansi@npm:9.0.2" + dependencies: + ansi-styles: "npm:^6.2.1" + string-width: "npm:^7.0.0" + strip-ansi: "npm:^7.1.0" + checksum: 10/f3907e1ea9717404ca53a338fa5a017c2121550c3a5305180e2bc08c03e21aa45068df55b0d7676bf57be1880ba51a84458c17241ebedea485fafa9ef16b4024 + languageName: node + linkType: hard + "wrappy@npm:1": version: 1.0.2 resolution: "wrappy@npm:1.0.2" @@ -13786,7 +15997,7 @@ __metadata: languageName: node linkType: hard -"write-file-atomic@npm:^5.0.0": +"write-file-atomic@npm:^5.0.0, write-file-atomic@npm:^5.0.1": version: 5.0.1 resolution: "write-file-atomic@npm:5.0.1" dependencies: @@ -13796,9 +16007,9 @@ __metadata: languageName: node linkType: hard -"ws@npm:^8.11.0, ws@npm:^8.13.0, ws@npm:^8.18.0, ws@npm:^8.22.0": - version: 8.22.0 - resolution: "ws@npm:8.22.0" +"ws@npm:^8.11.0, ws@npm:^8.13.0, ws@npm:^8.18.0, ws@npm:^8.22.0, ws@npm:^8.23.1": + version: 8.23.1 + resolution: "ws@npm:8.23.1" peerDependencies: bufferutil: ^4.0.1 utf-8-validate: ">=5.0.2" @@ -13807,7 +16018,7 @@ __metadata: optional: true utf-8-validate: optional: true - checksum: 10/ed771c2766bdb5724a66872f60ffc1a39f06e1a5bc8849f453c273e97c91a40ed5a224f06dc0e22f44b4a9e03938bf746fc5938d6887433cc0f4c416237d3b10 + checksum: 10/298cbfe36403a85d5bba2fc1dbf389c32d30b206450bfebd27ae3d2b3f137d5d67c35615e8cc027391ce7238669f0883bce32c8489c7c2f7fe724c38023d66c2 languageName: node linkType: hard @@ -13827,13 +16038,6 @@ __metadata: languageName: node linkType: hard -"xml-naming@npm:^0.3.0": - version: 0.3.0 - resolution: "xml-naming@npm:0.3.0" - checksum: 10/1a09c3f14747bf243d4bbcfdb9917c40e9cbb4b6464f2b9fe6927976770dfa38eedfe94190b5b6db470f22429fd4bda688b1831ca36a769a6745ccb9bb595150 - languageName: node - linkType: hard - "xmlchars@npm:^2.2.0": version: 2.2.0 resolution: "xmlchars@npm:2.2.0" @@ -13901,13 +16105,13 @@ __metadata: linkType: hard "yaml@npm:^1.10.0": - version: 1.10.3 - resolution: "yaml@npm:1.10.3" - checksum: 10/e2ef2feb92c708138f016c69777a0f1e45f6d3c5e7cbcda30807a98a37eda2e008bd4fa57352b043c65245a4c799d0c99d1f9b3425de40e70929e26d2ea38215 + version: 1.10.2 + resolution: "yaml@npm:1.10.2" + checksum: 10/e088b37b4d4885b70b50c9fa1b7e54bd2e27f5c87205f9deaffd1fb293ab263d9c964feadb9817a7b129a5bf30a06582cb08750f810568ecc14f3cdbabb79cb3 languageName: node linkType: hard -"yaml@npm:^2.2.2": +"yaml@npm:^2.2.2, yaml@npm:^2.9.0": version: 2.9.1 resolution: "yaml@npm:2.9.1" bin: @@ -13930,18 +16134,24 @@ __metadata: languageName: node linkType: hard -"yargs@npm:17.7.3, yargs@npm:^17.0.1, yargs@npm:^17.3.1, yargs@npm:^17.7.1, yargs@npm:^17.7.2": - version: 17.7.3 - resolution: "yargs@npm:17.7.3" +"yargs-parser@npm:^22.0.0": + version: 22.0.0 + resolution: "yargs-parser@npm:22.0.0" + checksum: 10/f13c42bad6ebed1a587a72f2db5694f5fa772bcaf409a701691d13cf74eb5adfcf61a2611de08807e319b829d3e5e6e1578b16ebe174cae8e8be3bf7b8e7a19e + languageName: node + linkType: hard + +"yargs@npm:18.0.0": + version: 18.0.0 + resolution: "yargs@npm:18.0.0" dependencies: - cliui: "npm:^8.0.1" + cliui: "npm:^9.0.1" escalade: "npm:^3.1.1" get-caller-file: "npm:^2.0.5" - require-directory: "npm:^2.1.1" - string-width: "npm:^4.2.3" + string-width: "npm:^7.2.0" y18n: "npm:^5.0.5" - yargs-parser: "npm:^21.1.1" - checksum: 10/a3826798c03b159e139d0580a3b2733953889a9a1bac8e4e1ca7a1a249b55315b213c323a6a1dbdb305f6e59496a9eaa810742c87e34abcf1a0584d8f59212a1 + yargs-parser: "npm:^22.0.0" + checksum: 10/5af36234871390386b31cac99f00e79fcbc2ead858a61b30a8ca381c5fde5df8af0b407c36b000d3f774bcbe4aec5833f2f1c915f6ddc49ce97b78176b651801 languageName: node linkType: hard @@ -13960,6 +16170,21 @@ __metadata: languageName: node linkType: hard +"yargs@npm:^17.0.1, yargs@npm:^17.3.1, yargs@npm:^17.7.1, yargs@npm:^17.7.2": + version: 17.7.3 + resolution: "yargs@npm:17.7.3" + dependencies: + cliui: "npm:^8.0.1" + escalade: "npm:^3.1.1" + get-caller-file: "npm:^2.0.5" + require-directory: "npm:^2.1.1" + string-width: "npm:^4.2.3" + y18n: "npm:^5.0.5" + yargs-parser: "npm:^21.1.1" + checksum: 10/a3826798c03b159e139d0580a3b2733953889a9a1bac8e4e1ca7a1a249b55315b213c323a6a1dbdb305f6e59496a9eaa810742c87e34abcf1a0584d8f59212a1 + languageName: node + linkType: hard + "yn@npm:3.1.1": version: 3.1.1 resolution: "yn@npm:3.1.1"