diff --git a/.github/workflows/ci-tests.yml b/.github/workflows/ci-tests.yml index 9189d625..959eb25e 100644 --- a/.github/workflows/ci-tests.yml +++ b/.github/workflows/ci-tests.yml @@ -33,10 +33,10 @@ jobs: sudo apt-get update -y sudo apt-get install -y libusb-1.0.0 libudev-dev - - name: Set up Node.js 18 + - name: Set up Node.js 22 uses: actions/setup-node@v4 with: - node-version: '18' + node-version: '22' - name: Build code run: | @@ -46,3 +46,4 @@ jobs: - name: Run tests run: | yarn test:unit + yarn test:types diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 81df3ed4..dd568b19 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -30,10 +30,10 @@ jobs: sudo apt-get update -y sudo apt-get install -y libusb-1.0.0 libudev-dev - - name: Set up Node.js 18 + - name: Set up Node.js 22 uses: actions/setup-node@v4 with: - node-version: '18' + node-version: '22' registry-url: https://registry.npmjs.org - name: Build code diff --git a/README.md b/README.md index 0dee16ab..ba185cad 100644 --- a/README.md +++ b/README.md @@ -13,3 +13,348 @@ This package provides a basic client library to communicate with the Oasis apps We recommend using the npmjs package in order to receive updates/fixes. ![Example](docs/example.png) + +## Migrating to the Device Management Kit + +Ledger deprecated LedgerJS (`@ledgerhq/hw-transport` and the `@ledgerhq/hw-transport-*` packages) in favour of the +[Device Management Kit](https://github.com/LedgerHQ/device-sdk-ts) (DMK). Since 2.0.0, `OasisApp` accepts a +`DMKTransport` from [`@zondax/ledger-js`](https://github.com/Zondax/ledger-js), which adapts a DMK session to the +transport interface this package uses. + +### Upgrading to 2.0.0 + +Upgrading and migrating are separate steps: 2.0.0 still accepts your existing transport. + +- **LedgerJS transports still work, but are deprecated.** `new OasisApp(transport)` is struck through in editors and + logs a one-time `console.warn`. The next major version accepts only `DMKTransport`. +- **Node.js 20 or newer.** `@zondax/ledger-js` declares `engines.node >=20`, which yarn classic enforces on install. +- **The exported `Transport` type is narrower.** `@ledgerhq/hw-transport` is no longer a dependency, so this package's + `Transport` is now an alias of `LedgerTransport`, which only has `send` and `decorateAppAPIMethods`. Passing a + LedgerJS transport still typechecks. Calling `close()`, `exchange()` or `on()` through this package's type, or + through `app.transport` on a bare `OasisApp` annotation, does not: import `Transport` from `@ledgerhq/hw-transport`, + or annotate with your transport's type, as in `OasisApp` (inference does this for you on + `new OasisApp(transport)`). Note that `TransportWebUSB.create()` returns the base `Transport`, not + `TransportWebUSB`. + +### From `@ledgerhq/hw-transport-webusb` + +In the browser, the DMK talks to the device over WebHID instead of WebUSB. + +```sh +yarn add @ledgerhq/device-management-kit @ledgerhq/device-transport-kit-web-hid rxjs @zondax/ledger-js@2.1.0 +``` + +`rxjs` is a peer dependency of the DMK. `@zondax/ledger-js` already comes with this package, but you import +`DMKTransport` from it, so depend on it directly, at the exact version this package pins (`2.1.0`), to keep a single +copy in your tree: a `DMKTransport` from a second copy fails the `instanceof` check and is treated as a legacy +transport. + +Before: + +```ts +import TransportWebUSB from "@ledgerhq/hw-transport-webusb"; +import OasisApp from "@oasisprotocol/ledger"; + +const transport = await TransportWebUSB.create(); +try { + const app = new OasisApp(transport); + // ... +} finally { + await transport.close(); +} +``` + +After: + +```ts +import { DeviceManagementKitBuilder } from "@ledgerhq/device-management-kit"; +import { webHidTransportFactory } from "@ledgerhq/device-transport-kit-web-hid"; +import OasisApp from "@oasisprotocol/ledger"; +import { DMKTransport } from "@zondax/ledger-js"; +import { firstValueFrom } from "rxjs"; + +// Build once and reuse it. +const dmk = new DeviceManagementKitBuilder().addTransport(webHidTransportFactory).build(); + +// Run this from a user gesture, such as a click handler: it opens the browser's device picker. +const device = await firstValueFrom(dmk.startDiscovering({})); +const sessionId = await dmk.connect({ + device, + // See "Disable the session refresher" below. + sessionRefresherOptions: { isRefresherDisabled: true }, +}); +try { + const app = new OasisApp(new DMKTransport(dmk, sessionId)); + // ... +} finally { + await dmk.disconnect({ sessionId }); +} +``` + +| `@ledgerhq/hw-transport-webusb` | Device Management Kit | +| --- | --- | +| `TransportWebUSB.isSupported()` | `dmk.isEnvironmentSupported()` (synchronous) | +| `TransportWebUSB.create()` | `dmk.startDiscovering({})`, then `dmk.connect({ device, ... })` | +| `new OasisApp(transport)` | `new OasisApp(new DMKTransport(dmk, sessionId))` | +| `transport.close()` | `dmk.disconnect({ sessionId })` | +| picker cancelled: rejects with `No device selected.` | rejects with a DMK error whose `_tag` is `NoAccessibleDeviceError` | + +Things that behave differently: + +- **Users grant access again.** Browsers keep WebUSB and WebHID permissions apart, so a device allowed for WebUSB has + to be picked once more. Both APIs are only available in Chromium-based browsers. +- **The picker opens every time.** `TransportWebUSB.create()` silently reuses a device the user already granted; + `startDiscovering` always prompts. `dmk.listenToAvailableDevices({})` lists the already-granted devices, so you can + connect to one of those without prompting. +- **Disable the session refresher.** By default the DMK polls the device every second, on the same queue + `DMKTransport` sends on, so a poll can land between two chunks of a signing request. Pass + `sessionRefresherOptions: { isRefresherDisabled: true }` to `connect`, as in the example. +- **One call at a time, as before.** Starting a second `OasisApp` call while one is in flight rejects with + `DMKTransportLockedError`, which carries the same `id` (`TransportLocked`) as the LedgerJS error. +- **Device errors are unchanged.** Status words still come back as `return_code` and `error_message`, so + `successOrThrow` and existing return-code handling keep working. Connection problems surface as DMK errors, which + you identify by `_tag` rather than by message. + +### Method by method + +Once you have an `app`, the calls themselves do not change: every method keeps its name, arguments, response fields +and status codes. Only the lines that open and close the connection differ, so each example below is a diff from the +`hw-transport-webusb` version to the DMK version, reusing `dmk` and `device` from the example above. + +Paths are arrays of numbers. For ed25519, use the ADR 8 path `[44, 474, index]` (or the legacy +`[44, 474, 0, 0, index]`); every component is hardened for you. For secp256k1, use the BIP-44 path +`[44, 60, 0, 0, index]` with unhardened values; the first three components are hardened for you. A malformed path +throws an `Error` rather than returning a `return_code`. + +| Method | On the device | Returns, besides `return_code` and `error_message` | +| --- | --- | --- | +| [`getVersion()`](#getversion) | nothing to confirm | `major`, `minor`, `patch`, `test_mode`, `device_locked`, `target_id` | +| [`appInfo()`](#appinfo) | nothing to confirm | `appName`, `appVersion`, `flagLen`, `flagsValue`, `flag_recovery`, `flag_signed_mcu_code`, `flag_onboarded`, `flag_pin_validated` | +| [`deviceInfo()`](#deviceinfo) | nothing to confirm; dashboard only | `targetId`, `seVersion`, `flag`, `mcuVersion` | +| [`publicKey(path)`](#publickey) | nothing to confirm | `pk` | +| [`getAddressAndPubKey_ed25519(path)`](#getaddressandpubkey_ed25519) | nothing to confirm | `bech32_address`, `pk` | +| [`showAddressAndPubKey_ed25519(path)`](#showaddressandpubkey_ed25519) | user confirms the address | `bech32_address`, `pk` | +| [`getAddressAndPubKey_secp256k1(path)`](#getaddressandpubkey_secp256k1) | nothing to confirm | `hex_address`, `pk` | +| [`showAddressAndPubKey_secp256k1(path)`](#showaddressandpubkey_secp256k1) | user confirms the address | `hex_address`, `pk` | +| [`sign(path, context, message)`](#sign) | user reviews and approves | `signature` | +| [`signRtEd25519(path, meta, message)`](#signrted25519) | user reviews and approves | `signature` | +| [`signRtSecp256k1(path, meta, message)`](#signrtsecp256k1) | user reviews and approves | `signature` | + +For the methods that wait for the user (`show*` and `sign*`): + +- **There is no timeout by default.** Neither the DMK nor `DMKTransport` aborts an exchange unless you pass + `abortTimeout`, as in `new DMKTransport(dmk, sessionId, { abortTimeout })`. If you do, leave the user time to read + the screen. +- **Rejecting on the device** comes back as `return_code` `0x6986`, as before. + +#### `getVersion` + +The Oasis app's version, and whether it runs in test mode or the device is locked. + +```diff +-const transport = await TransportWebUSB.create(); +-const app = new OasisApp(transport); ++const sessionId = await dmk.connect({ device, sessionRefresherOptions: { isRefresherDisabled: true } }); ++const app = new OasisApp(new DMKTransport(dmk, sessionId)); + try { + const { major, minor, patch, test_mode, device_locked } = successOrThrow(await app.getVersion()); + } finally { +- await transport.close(); ++ await dmk.disconnect({ sessionId }); + } +``` + +#### `appInfo` + +The name and version of the app open on the device. Check it before anything else, to tell the user to open the +Oasis app. + +```diff +-const transport = await TransportWebUSB.create(); +-const app = new OasisApp(transport); ++const sessionId = await dmk.connect({ device, sessionRefresherOptions: { isRefresherDisabled: true } }); ++const app = new OasisApp(new DMKTransport(dmk, sessionId)); + try { + const { appName, appVersion } = successOrThrow(await app.appInfo()); + if (appName !== "Oasis") throw new Error("Open the Oasis app on the device"); + } finally { +- await transport.close(); ++ await dmk.disconnect({ sessionId }); + } +``` + +#### `deviceInfo` + +The secure element and MCU firmware versions. The device only answers this from the dashboard: while an app is +open, the Oasis app included, it returns `return_code` `0x6e00` and `successOrThrow` throws. + +```diff +-const transport = await TransportWebUSB.create(); +-const app = new OasisApp(transport); ++const sessionId = await dmk.connect({ device, sessionRefresherOptions: { isRefresherDisabled: true } }); ++const app = new OasisApp(new DMKTransport(dmk, sessionId)); + try { + const { seVersion, mcuVersion } = successOrThrow(await app.deviceInfo()); + } finally { +- await transport.close(); ++ await dmk.disconnect({ sessionId }); + } +``` + +#### `publicKey` + +The 32-byte ed25519 public key for a path, without showing anything on the device. + +```diff +-const transport = await TransportWebUSB.create(); +-const app = new OasisApp(transport); ++const sessionId = await dmk.connect({ device, sessionRefresherOptions: { isRefresherDisabled: true } }); ++const app = new OasisApp(new DMKTransport(dmk, sessionId)); + try { + const { pk } = successOrThrow(await app.publicKey([44, 474, 0])); + } finally { +- await transport.close(); ++ await dmk.disconnect({ sessionId }); + } +``` + +#### `getAddressAndPubKey_ed25519` + +The bech32 address (`oasis1...`) and 32-byte ed25519 public key for a path, without showing anything on the device. + +```diff +-const transport = await TransportWebUSB.create(); +-const app = new OasisApp(transport); ++const sessionId = await dmk.connect({ device, sessionRefresherOptions: { isRefresherDisabled: true } }); ++const app = new OasisApp(new DMKTransport(dmk, sessionId)); + try { + const { bech32_address, pk } = successOrThrow(await app.getAddressAndPubKey_ed25519([44, 474, 0])); + } finally { +- await transport.close(); ++ await dmk.disconnect({ sessionId }); + } +``` + +#### `showAddressAndPubKey_ed25519` + +Same response as `getAddressAndPubKey_ed25519`, but the device shows the address and waits for the user to confirm +it. + +```diff +-const transport = await TransportWebUSB.create(); +-const app = new OasisApp(transport); ++const sessionId = await dmk.connect({ device, sessionRefresherOptions: { isRefresherDisabled: true } }); ++const app = new OasisApp(new DMKTransport(dmk, sessionId)); + try { + const { bech32_address } = successOrThrow(await app.showAddressAndPubKey_ed25519([44, 474, 0])); + } finally { +- await transport.close(); ++ await dmk.disconnect({ sessionId }); + } +``` + +#### `getAddressAndPubKey_secp256k1` + +The address (40 hex characters, no `0x` prefix) and 33-byte compressed secp256k1 public key for a BIP-44 path, +without showing anything on the device. + +```diff +-const transport = await TransportWebUSB.create(); +-const app = new OasisApp(transport); ++const sessionId = await dmk.connect({ device, sessionRefresherOptions: { isRefresherDisabled: true } }); ++const app = new OasisApp(new DMKTransport(dmk, sessionId)); + try { + const { hex_address, pk } = successOrThrow(await app.getAddressAndPubKey_secp256k1([44, 60, 0, 0, 0])); + } finally { +- await transport.close(); ++ await dmk.disconnect({ sessionId }); + } +``` + +#### `showAddressAndPubKey_secp256k1` + +Same response as `getAddressAndPubKey_secp256k1`, but the device shows the address and waits for the user to +confirm it. + +```diff +-const transport = await TransportWebUSB.create(); +-const app = new OasisApp(transport); ++const sessionId = await dmk.connect({ device, sessionRefresherOptions: { isRefresherDisabled: true } }); ++const app = new OasisApp(new DMKTransport(dmk, sessionId)); + try { + const { hex_address } = successOrThrow(await app.showAddressAndPubKey_secp256k1([44, 60, 0, 0, 0])); + } finally { +- await transport.close(); ++ await dmk.disconnect({ sessionId }); + } +``` + +#### `sign` + +Signs a consensus transaction with ed25519. `context` is the signature context, +`oasis-core/consensus: tx for chain `, and `message` is the CBOR-encoded transaction. The device shows +the transaction and waits for the user to approve it. The signature is 64 bytes. + +```diff +-const transport = await TransportWebUSB.create(); +-const app = new OasisApp(transport); ++const sessionId = await dmk.connect({ device, sessionRefresherOptions: { isRefresherDisabled: true } }); ++const app = new OasisApp(new DMKTransport(dmk, sessionId)); + try { + const { signature } = successOrThrow(await app.sign([44, 474, 0], context, message)); + } finally { +- await transport.close(); ++ await dmk.disconnect({ sessionId }); + } +``` + +#### `signRtEd25519` + +Signs a runtime (ParaTime) transaction with ed25519. `meta` is a CBOR map with `runtime_id` and `chain_context`, and +`message` is the CBOR-encoded runtime transaction. The device shows the transaction and waits for the user to approve +it. The signature is 64 bytes. + +```diff +-const transport = await TransportWebUSB.create(); +-const app = new OasisApp(transport); ++const sessionId = await dmk.connect({ device, sessionRefresherOptions: { isRefresherDisabled: true } }); ++const app = new OasisApp(new DMKTransport(dmk, sessionId)); + try { + const { signature } = successOrThrow(await app.signRtEd25519([44, 474, 0], meta, message)); + } finally { +- await transport.close(); ++ await dmk.disconnect({ sessionId }); + } +``` + +#### `signRtSecp256k1` + +Same as `signRtEd25519`, for a secp256k1 account on a BIP-44 path. The signature is `r || s || v`: drop the last +byte to verify it as a plain ECDSA signature. + +```diff +-const transport = await TransportWebUSB.create(); +-const app = new OasisApp(transport); ++const sessionId = await dmk.connect({ device, sessionRefresherOptions: { isRefresherDisabled: true } }); ++const app = new OasisApp(new DMKTransport(dmk, sessionId)); + try { + const { signature } = successOrThrow(await app.signRtSecp256k1([44, 60, 0, 0, 0], meta, message)); + } finally { +- await transport.close(); ++ await dmk.disconnect({ sessionId }); + } +``` + +### Other environments + +| LedgerJS | DMK transport kit | +| --- | --- | +| `@ledgerhq/hw-transport-node-hid` | `@ledgerhq/device-transport-kit-node-hid` (`nodeHidTransportFactory`) | +| `@ledgerhq/hw-transport-web-ble` | `@ledgerhq/device-transport-kit-web-ble` (`webBleTransportFactory`) | +| `@ledgerhq/react-native-hw-transport-ble` | `@ledgerhq/device-transport-kit-react-native-ble` (`RNBleTransportFactory`) | + +Outside the browser there is no picker: find the device with `dmk.listenToAvailableDevices({})`. + +If no kit exists for your platform (a Capacitor or Ionic app, for example), `addTransport` accepts any DMK +`TransportFactory`, so you can write one. Until then, your LedgerJS transport keeps working in 2.x, with the +deprecation warning. diff --git a/package.json b/package.json index 2aa64eef..ec343560 100644 --- a/package.json +++ b/package.json @@ -27,7 +27,7 @@ "homepage": "https://github.com/oasisprotocol/ledger-js", "dependencies": { "@babel/runtime": "^7.9.2", - "@ledgerhq/hw-transport": "^6.1.0" + "@zondax/ledger-js": "2.1.0" }, "devDependencies": { "@babel/cli": "^7.11.6", @@ -60,6 +60,7 @@ "build-types": "tsc -p ./tsconfig.json", "certificate": "openssl req -nodes -new -x509 -keyout certs/server.key -out certs/server.cert; openssl x509 -in certs/server.cert -out certs/cert.pem -outform PEM", "test:unit": "jest -c jest.config.unit.js --runInBand", + "test:types": "yarn build-types && tsc -p tests/types/tsconfig.json", "test:integration": "jest -c jest.config.integration.js --runInBand --detectOpenHandles" }, "moduleDirectories": [ diff --git a/src/index.js b/src/index.js index 864e2df4..1643ed29 100644 --- a/src/index.js +++ b/src/index.js @@ -15,6 +15,7 @@ * limitations under the License. ******************************************************************************* */ +import { DMKTransport } from "@zondax/ledger-js"; import { publicKeyv1, serializePathBip44v1, serializePathv1, signSendChunkv1 } from "./helperV1"; import { APP_KEY, @@ -27,6 +28,10 @@ import { P1_VALUES, } from "./common"; +// Once per process rather than once per app: wallets construct an app per request, and a +// warning on every construction would bury everything else in their logs. +let legacyTransportWarned = false; + function processGetAddrEd25519Response(response) { const errorCodeData = response.slice(-2); const returnCode = errorCodeData[0] * 256 + errorCodeData[1]; @@ -68,12 +73,57 @@ export function successOrThrow(response) { return /** @type { T } */ (response); } +/** + * Generic in the transport so `app.transport` keeps the caller's own type rather than + * collapsing to the structural one. Construct with a hw-transport `Transport` and + * `app.transport.close()` still typechecks, because `T` is inferred as that class; pass + * a DMK transport and its own members survive the same way. + * + * @template {import('./types').LedgerTransport} [T=import('./types').LedgerTransport] + */ export default class OasisApp { - /** @param {import('./types').Transport} transport */ + /** + * Constructs the app over a Device Management Kit session. + * + * @overload + * @param {T extends import("@zondax/ledger-js").DMKTransport ? T : never} transport A `DMKTransport` from + * `@zondax/ledger-js`, bound to a connected DMK session. + * @param {string} [scrambleKey] + */ + /** + * Constructs the app over any transport that can send an APDU. + * + * @deprecated Pass a `DMKTransport` from `@zondax/ledger-js` instead. Ledger deprecated + * `@ledgerhq/hw-transport` in favour of the Device Management Kit, and this overload -- which + * also admits hand-rolled transports -- is removed in the next major version. Using it logs a + * one-time warning. See "Migrating to the Device Management Kit" in the README. + * + * `DMKTransport` has private members, so only a real instance selects the overload above: an + * hw-transport `Transport` or a plain object implementing the two methods lands here. + * + * @overload + * @param {T} transport + * @param {string} [scrambleKey] + */ + /** + * @param {T} transport + * @param {string} [scrambleKey] + */ constructor(transport, scrambleKey = APP_KEY) { if (!transport) { throw new Error("Transport has not been defined"); } + // A deprecation notice, not a security check: a structural or cross-copy transport can + // defeat instanceof, and the transport runs in the caller's own process anyway. + if (!(transport instanceof DMKTransport) && !legacyTransportWarned) { + legacyTransportWarned = true; + // eslint-disable-next-line no-console + console.warn( + "[@oasisprotocol/ledger] Passing a transport other than DMKTransport to OasisApp is deprecated and will " + + "be rejected in the next major version. Ledger deprecated @ledgerhq/hw-transport in favour of the " + + "Device Management Kit; see https://github.com/oasisprotocol/ledger-js#migrating-to-the-device-management-kit", + ); + } /** @type {Awaited>} */ this.versionResponse = undefined; diff --git a/src/types.ts b/src/types.ts index bb7841b1..8bc1bcd3 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,8 +1,44 @@ -import type Transport from "@ledgerhq/hw-transport"; +/** + * The transport surface this package actually needs: `OasisApp` calls `send` and + * `decorateAppAPIMethods`, nothing else. + * + * Describing those two methods structurally, rather than naming `Transport` from + * `@ledgerhq/hw-transport`, lets the app accept either a legacy `Transport` or a + * `DMKTransport` built on Ledger's Device Management Kit, which replaces hw-transport + * ahead of the September 2026 cutoff. A hw-transport `Transport` satisfies it as-is, + * and describing it here is what lets that package leave our dependencies entirely. + * + * Passing anything other than a `DMKTransport` is deprecated, though: `OasisApp`'s + * constructor marks that overload `@deprecated` and logs a one-time warning, and the next + * major accepts only `DMKTransport`. + */ +export interface LedgerTransport { + send: ( + cla: number, + ins: number, + p1: number, + p2: number, + data?: Buffer, + statusList?: number[], + options?: { abortTimeoutMs?: number }, + ) => Promise; + decorateAppAPIMethods: (self: Record, methods: string[], scrambleKey: string) => void; +} -export type { Transport }; +/** + * @deprecated Renamed to {@link LedgerTransport}, and no longer `Transport` from + * `@ledgerhq/hw-transport` -- that package is being retired, so it is gone from this + * package's dependencies and its type can no longer be re-exported. + * + * The alias keeps `import type { Transport }` resolving, and a hw-transport `Transport` + * still satisfies it, so passing one is unaffected. What no longer typechecks is + * *reaching through* this type for a hw-transport member -- `close`, `exchange`, `on`. + * Import `Transport` from `@ledgerhq/hw-transport` directly if you need those, or + * annotate with the concrete transport class you construct. + */ +export type Transport = LedgerTransport; -// @ledgerhq/hw-transport has an awful TransportStatusError type +// Ledger transports throw this shape; keep it local so we do not depend on hw-transport types. export interface TransportStatusError extends Error { statusCode: number; statusText: "UNKNOWN_ERROR"; @@ -10,8 +46,12 @@ export interface TransportStatusError extends Error { export type DerivationPath = number[]; -export interface App { - transport: Transport; +/** + * Generic in the transport so `app.transport` keeps whatever was passed in, rather than + * collapsing to {@link LedgerTransport} and losing that transport's other members. + */ +export interface App { + transport: T; } export type Response = @@ -24,22 +64,3 @@ export type Response = }; export type AsyncResponse = Promise>; - -/** Ensures good inferred types */ -async function typeOnlyTest() { - const { default: OasisApp, successOrThrow } = await import('./index'); - const { default: TransportWebUSB } = await import('@ledgerhq/hw-transport-webusb'); - const app = new OasisApp(await TransportWebUSB.create()); - console.log(successOrThrow(await app.getVersion()).major.toFixed()); - console.log(successOrThrow(await app.appInfo()).appName.trim()); - console.log(successOrThrow(await app.deviceInfo()).mcuVersion.trim()); - console.log(successOrThrow(await app.publicKey([44])).pk.byteLength.toFixed()); - console.log(successOrThrow(await app.getAddressAndPubKey_ed25519([44])).bech32_address.trim()); - console.log(successOrThrow(await app.showAddressAndPubKey_ed25519([44])).bech32_address.trim()); - console.log(successOrThrow(await app.getAddressAndPubKey_secp256k1([44])).hex_address.trim()); - console.log(successOrThrow(await app.showAddressAndPubKey_secp256k1([44])).hex_address.trim()); - - const ctx = 'oasis-core/consensus' - const msg = Buffer.from('a') - console.log(successOrThrow(await app.sign([44], ctx, msg)).signature?.byteLength.toFixed()); -} diff --git a/tests/deprecation.spec.js b/tests/deprecation.spec.js new file mode 100644 index 00000000..c73bf54a --- /dev/null +++ b/tests/deprecation.spec.js @@ -0,0 +1,68 @@ +const README_ANCHOR = "https://github.com/oasisprotocol/ledger-js#migrating-to-the-device-management-kit"; + +function handRolledTransport() { + return { + send: () => Promise.resolve(Buffer.from([0x90, 0x00])), + decorateAppAPIMethods: () => {}, + }; +} + +// The "already warned" flag is module state, so each test loads its own copy of the package. +// DMKTransport is loaded in the same registry, or `instanceof` would compare different classes. +function loadFresh() { + let modules; + jest.isolateModules(() => { + modules = { + // eslint-disable-next-line global-require + OasisApp: require("../src/index").default, + // eslint-disable-next-line global-require + DMKTransport: require("@zondax/ledger-js").DMKTransport, + }; + }); + return modules; +} + +describe("legacy transport deprecation", () => { + let warn; + let OasisApp; + let DMKTransport; + + beforeEach(() => { + ({ OasisApp, DMKTransport } = loadFresh()); + warn = jest.spyOn(console, "warn").mockImplementation(() => {}); + }); + + afterEach(() => { + warn.mockRestore(); + }); + + test("warns when constructed over a non-DMK transport, pointing at the README", () => { + expect(() => new OasisApp(handRolledTransport())).not.toThrow(); + + expect(warn).toHaveBeenCalledTimes(1); + expect(warn).toHaveBeenCalledWith(expect.stringContaining("deprecated")); + expect(warn).toHaveBeenCalledWith(expect.stringContaining(README_ANCHOR)); + }); + + test("warns once per process, not once per app", () => { + expect(() => new OasisApp(handRolledTransport())).not.toThrow(); + expect(() => new OasisApp(handRolledTransport())).not.toThrow(); + + expect(warn).toHaveBeenCalledTimes(1); + }); + + test("stays silent over a DMKTransport", () => { + const dmk = { + sendApdu: () => Promise.resolve({ statusCode: Uint8Array.from([0x90, 0x00]), data: new Uint8Array() }), + }; + + expect(() => new OasisApp(new DMKTransport(dmk, "session-1"))).not.toThrow(); + + expect(warn).not.toHaveBeenCalled(); + }); + + test("still rejects a missing transport before warning", () => { + expect(() => new OasisApp(undefined)).toThrow("Transport has not been defined"); + expect(warn).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/types/inference.ts b/tests/types/inference.ts new file mode 100644 index 00000000..f6da2e10 --- /dev/null +++ b/tests/types/inference.ts @@ -0,0 +1,66 @@ +/** + * Type-only test: `yarn test:types` compiles this file and never runs it. + * + * It compiles against the emitted `dist/*.d.ts`, which is what consumers see, rather than `src`. + * Against the JS source, TypeScript does not carry the class template into construct signatures + * built from JSDoc `@overload`, so no transport can bind `T`; the emitted declarations are plain + * TypeScript and infer it from the argument. + * + * Each `@ts-expect-error` asserts something that must not compile. If it starts compiling, `tsc` + * fails with "Unused '@ts-expect-error' directive". + */ +import OasisApp, { successOrThrow } from "@oasisprotocol/ledger"; +import type { Transport } from "@oasisprotocol/ledger/dist/types"; +import TransportWebUSB from "@ledgerhq/hw-transport-webusb"; +import { DMKTransport } from "@zondax/ledger-js"; + +export async function transportInference() { + const usb = await TransportWebUSB.create(); + + // `T` is inferred from a hw-transport, so its own members survive. + const usbApp = new OasisApp(usb); + await usbApp.transport.close(); + // @ts-expect-error `T` is that transport, not `any`. + usbApp.transport.sendApdu(); + + // A DMK-only member survives the same way. + const dmk = { sendApdu: async () => ({ statusCode: new Uint8Array(), data: new Uint8Array() }) }; + const dmkApp = new OasisApp(new DMKTransport(dmk, "session")); + dmkApp.transport.setScrambleKey("x"); + // @ts-expect-error DMKTransport has no close. + await dmkApp.transport.close(); + + // A bare annotation falls back to the structural default. + const bare: OasisApp = new OasisApp(usb); + await bare.transport.send(0x05, 0x00, 0, 0); + // @ts-expect-error close is not on LedgerTransport. + await bare.transport.close(); + + // The fix for a bare annotation: name the transport type. + const annotated: OasisApp = new OasisApp(usb); + await annotated.transport.close(); + + // The deprecated alias still accepts a hw-transport... + const alias: Transport = usb; + // @ts-expect-error ...but reaching through it for a hw-transport member no longer typechecks. + await alias.close(); + + // @ts-expect-error A transport without `send` is rejected. + new OasisApp({ decorateAppAPIMethods: () => {} }); +} + +// Response types do not depend on the transport, so a bare `OasisApp` covers them. +export async function responseTypes(app: OasisApp) { + successOrThrow(await app.getVersion()).major.toFixed(); + successOrThrow(await app.appInfo()).appName.trim(); + successOrThrow(await app.deviceInfo()).mcuVersion.trim(); + successOrThrow(await app.publicKey([44])).pk.byteLength.toFixed(); + successOrThrow(await app.getAddressAndPubKey_ed25519([44])).bech32_address.trim(); + successOrThrow(await app.showAddressAndPubKey_ed25519([44])).bech32_address.trim(); + successOrThrow(await app.getAddressAndPubKey_secp256k1([44])).hex_address.trim(); + successOrThrow(await app.showAddressAndPubKey_secp256k1([44])).hex_address.trim(); + + const ctx = "oasis-core/consensus"; + const msg = Buffer.from("a"); + successOrThrow(await app.sign([44], ctx, msg)).signature?.byteLength.toFixed(); +} diff --git a/tests/types/tsconfig.json b/tests/types/tsconfig.json new file mode 100644 index 00000000..9f9f2588 --- /dev/null +++ b/tests/types/tsconfig.json @@ -0,0 +1,19 @@ +{ + "files": ["inference.ts"], + "compilerOptions": { + "noEmit": true, + "esModuleInterop": true, + "lib": ["esnext", "dom"], + "moduleResolution": "node", + "module": "esnext", + "target": "esnext", + "strict": true, + "skipLibCheck": true, + "baseUrl": ".", + // Resolve the package the way a consumer does, but to this checkout's build output. + "paths": { + "@oasisprotocol/ledger": ["../../dist/index"], + "@oasisprotocol/ledger/dist/*": ["../../dist/*"] + } + } +} diff --git a/yarn.lock b/yarn.lock index 8516f900..ea97014c 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1681,7 +1681,7 @@ "@ledgerhq/hw-transport" "^6.30.6" "@ledgerhq/logs" "^6.12.0" -"@ledgerhq/hw-transport@^6.1.0", "@ledgerhq/hw-transport@^6.30.6", "@ledgerhq/hw-transport@^6.31.4": +"@ledgerhq/hw-transport@^6.30.6", "@ledgerhq/hw-transport@^6.31.4": version "6.31.4" resolved "https://registry.yarnpkg.com/@ledgerhq/hw-transport/-/hw-transport-6.31.4.tgz#9b23a6de4a4caaa5c24b149c2dea8adde46f0eb1" integrity sha512-6c1ir/cXWJm5dCWdq55NPgCJ3UuKuuxRvf//Xs36Bq9BwkV2YaRQhZITAkads83l07NAdR16hkTWqqpwFMaI6A== @@ -1904,6 +1904,11 @@ resolved "https://registry.yarnpkg.com/@ungap/structured-clone/-/structured-clone-1.2.0.tgz#756641adb587851b5ccb3e095daf27ae581c8406" integrity sha512-zuVdFrMJiuCDQUMCzQaD6KL28MjnqqN8XnAqiEq9PNm/hCPTSGfrXCOfwj1ow4LFb/tNymJPwsNbVePc1xFqrQ== +"@zondax/ledger-js@2.1.0": + version "2.1.0" + resolved "https://registry.yarnpkg.com/@zondax/ledger-js/-/ledger-js-2.1.0.tgz#8da389903789578e0b70354ff6037b97b3db4093" + integrity sha512-tFaaJOtbfanOXCPDihTtLE0NfIXuovUrKjAPYgomKGtmhO0ftCp8mdrQNaUuygRFDK5UbNSidtx5hdAJk+sthQ== + acorn-jsx@^5.3.2: version "5.3.2" resolved "https://registry.yarnpkg.com/acorn-jsx/-/acorn-jsx-5.3.2.tgz#7ed5bb55908b3b2f1bc55c6af1653bada7f07937"