@onekeyfe/hd-core 1.2.8-alpha.1 → 1.2.8-alpha.100

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +27 -0
  2. package/__tests__/DeviceCommands.test.ts +66 -13
  3. package/__tests__/btc-derive-context-hash.test.ts +200 -0
  4. package/__tests__/core-error-output.test.ts +34 -3
  5. package/__tests__/device-lifecycle-events.test.ts +73 -24
  6. package/__tests__/device-pool-state.test.ts +50 -0
  7. package/__tests__/logBlockEvent.test.ts +43 -0
  8. package/__tests__/protocol-v2-bootloader-mode.test.ts +43 -2
  9. package/__tests__/protocol-v2.test.ts +0 -47
  10. package/__tests__/refresh-device-state.test.ts +19 -17
  11. package/__tests__/sol-sign-offchain-message.test.ts +0 -8
  12. package/__tests__/zcash-sign-pczt.test.ts +212 -0
  13. package/dist/api/FirmwareUpdateV4.d.ts.map +1 -1
  14. package/dist/api/GetDeviceState.d.ts.map +1 -1
  15. package/dist/api/btc/BTCDeriveContextHash.d.ts +16 -0
  16. package/dist/api/btc/BTCDeriveContextHash.d.ts.map +1 -0
  17. package/dist/api/index.d.ts +3 -0
  18. package/dist/api/index.d.ts.map +1 -1
  19. package/dist/api/protocol-v2/DeviceReboot.d.ts.map +1 -1
  20. package/dist/api/zcash/ZcashGetAddress.d.ts +12 -0
  21. package/dist/api/zcash/ZcashGetAddress.d.ts.map +1 -0
  22. package/dist/api/zcash/ZcashSignPczt.d.ts +17 -0
  23. package/dist/api/zcash/ZcashSignPczt.d.ts.map +1 -0
  24. package/dist/core/index.d.ts +0 -1
  25. package/dist/core/index.d.ts.map +1 -1
  26. package/dist/device/Device.d.ts +2 -0
  27. package/dist/device/Device.d.ts.map +1 -1
  28. package/dist/device/DeviceCommands.d.ts +4 -4
  29. package/dist/device/DeviceCommands.d.ts.map +1 -1
  30. package/dist/device/DevicePool.d.ts.map +1 -1
  31. package/dist/events/logBlockEvent.d.ts.map +1 -1
  32. package/dist/index.d.ts +51 -5
  33. package/dist/index.js +488 -30
  34. package/dist/inject.d.ts.map +1 -1
  35. package/dist/types/api/btcDeriveContextHash.d.ts +10 -0
  36. package/dist/types/api/btcDeriveContextHash.d.ts.map +1 -0
  37. package/dist/types/api/export.d.ts +3 -0
  38. package/dist/types/api/export.d.ts.map +1 -1
  39. package/dist/types/api/index.d.ts +6 -0
  40. package/dist/types/api/index.d.ts.map +1 -1
  41. package/dist/types/api/zcashGetAddress.d.ts +22 -0
  42. package/dist/types/api/zcashGetAddress.d.ts.map +1 -0
  43. package/dist/types/api/zcashSignPczt.d.ts +9 -0
  44. package/dist/types/api/zcashSignPczt.d.ts.map +1 -0
  45. package/dist/types/params.d.ts +1 -0
  46. package/dist/types/params.d.ts.map +1 -1
  47. package/dist/utils/patch.d.ts +1 -1
  48. package/dist/utils/patch.d.ts.map +1 -1
  49. package/package.json +4 -4
  50. package/src/api/FirmwareUpdateV4.ts +8 -25
  51. package/src/api/GetDeviceState.ts +2 -5
  52. package/src/api/btc/BTCDeriveContextHash.ts +90 -0
  53. package/src/api/index.ts +3 -0
  54. package/src/api/protocol-v2/DeviceReboot.ts +2 -0
  55. package/src/api/zcash/ZcashGetAddress.ts +121 -0
  56. package/src/api/zcash/ZcashSignPczt.ts +153 -0
  57. package/src/core/index.ts +3 -7
  58. package/src/data/messages/messages-protocol-v2.json +138 -1
  59. package/src/data/messages/messages.json +51 -0
  60. package/src/device/Device.ts +11 -1
  61. package/src/device/DeviceCommands.ts +15 -1
  62. package/src/device/DevicePool.ts +12 -2
  63. package/src/events/core.ts +2 -2
  64. package/src/events/logBlockEvent.ts +6 -2
  65. package/src/inject.ts +6 -0
  66. package/src/types/api/btcDeriveContextHash.ts +15 -0
  67. package/src/types/api/export.ts +3 -0
  68. package/src/types/api/index.ts +10 -0
  69. package/src/types/api/zcashGetAddress.ts +36 -0
  70. package/src/types/api/zcashSignPczt.ts +18 -0
  71. package/src/types/params.ts +1 -1
package/README.md CHANGED
@@ -29,4 +29,31 @@ import Core from '@onekeyfe/hd-core';
29
29
  Documentation is available [Hardware SDK Getting Started](https://developer.onekey.so/en/hardware-sdk/getting-started)
30
30
 
31
31
  ## Examples
32
+
33
+ ### Babylon context hash
34
+
35
+ `btcDeriveContextHash(connectId, deviceId, params)` requires Classic 1s firmware
36
+ 3.21.0 or later and Protocol V1. It uses the existing wallet session and device
37
+ confirmation flow. Other device families and Protocol V2 are not supported.
38
+
39
+ ```typescript
40
+ const result = await HardwareSDK.btcDeriveContextHash(connectId, deviceId, {
41
+ path: "m/84'/0'/0'/0/0", // The currently selected Bitcoin key, not the IKM path.
42
+ appName: 'babylon-btc-vault',
43
+ context: 'deadbeef',
44
+ network: 'bitcoin-mainnet',
45
+ });
46
+ // result.payload.secret is a 32-byte value encoded as 64 lowercase hex characters.
47
+ ```
48
+
49
+ `appName` must contain 1–64 ASCII lowercase letters, digits or hyphens. `context`
50
+ must be lowercase hex without `0x`, containing 1–1024 decoded bytes. `network` is
51
+ required: `bitcoin-mainnet`, `bitcoin-testnet` (testnet3/testnet4), `bitcoin-signet`,
52
+ or `bitcoin-regtest`. The SDK infers the Bitcoin input script type from `path` and
53
+ encodes `appName` as ASCII bytes; the device performs the derivation internally.
54
+ Device rejection and unsupported firmware errors propagate through the normal
55
+ SDK response. Treat the returned secret as sensitive and do not log or persist it.
56
+
57
+ See the [Babylon specification](https://github.com/babylonlabs-io/babylon-toolkit/blob/main/docs/specs/derive-context-hash.md).
58
+
32
59
  // TODO: add example url
@@ -130,19 +130,6 @@ describe('DeviceCommands failure mapping', () => {
130
130
  );
131
131
  });
132
132
 
133
- it('preserves the Protocol V2 peer-removed pairing error code', async () => {
134
- const commands = createCommands();
135
- const transportError = Object.assign(new Error('Peer removed pairing information'), {
136
- errorCode: HardwareErrorCode.BlePeerRemovedPairingInformation,
137
- });
138
- commands.mainId = 'main-id';
139
- commands.transport = {
140
- call: jest.fn().mockRejectedValue(transportError),
141
- } as any;
142
-
143
- await expect(commands._commonCall('DeviceInfoGet', {})).rejects.toBe(transportError);
144
- });
145
-
146
133
  it('logs canonical DeviceStatus response fields without exposing the device ID', async () => {
147
134
  const commands = createCommands();
148
135
  const log = getLogger(LoggerNames.DeviceCommands);
@@ -414,6 +401,27 @@ describe('DeviceCommands failure mapping', () => {
414
401
  ).rejects.toMatchObject({ errorCode: HardwareErrorCode.DeviceBusy });
415
402
  });
416
403
 
404
+ it('maps commands rejected during a Protocol V2 firmware update to DeviceBusy', async () => {
405
+ const commands = createCommands();
406
+ const message = 'Requested command not allowed while a firmware update is in progress';
407
+
408
+ await expect(
409
+ commands._filterCommonTypes(
410
+ {
411
+ type: 'Failure',
412
+ message: { code: 'Failure_ProcessError', message },
413
+ } as any,
414
+ 'ProtocolInfoRequest'
415
+ )
416
+ ).rejects.toMatchObject({
417
+ errorCode: HardwareErrorCode.DeviceBusy,
418
+ params: {
419
+ failureCode: 'Failure_ProcessError',
420
+ firmwareMessage: message,
421
+ },
422
+ });
423
+ });
424
+
417
425
  it('maps the current AskPin passphrase-disabled response without relying on a subcode', async () => {
418
426
  const commands = createCommands();
419
427
 
@@ -551,6 +559,51 @@ describe('DeviceCommands failure mapping', () => {
551
559
  }
552
560
  );
553
561
 
562
+ it('maps the Protocol V2 seed-session busy response to DeviceBusy', async () => {
563
+ const commands = createCommands();
564
+
565
+ await expect(
566
+ commands._filterCommonTypes(
567
+ {
568
+ type: 'Failure',
569
+ message: {
570
+ code: 'Failure_ProcessError',
571
+ subcode: DeviceSessionErrorCode.DeviceSessionError_UserCancelled,
572
+ message: 'PIN cancelled',
573
+ },
574
+ } as any,
575
+ 'SignTx'
576
+ )
577
+ ).rejects.toMatchObject({
578
+ errorCode: HardwareErrorCode.DeviceBusy,
579
+ params: {
580
+ failureCode: 'Failure_ProcessError',
581
+ subcode: DeviceSessionErrorCode.DeviceSessionError_UserCancelled,
582
+ firmwareMessage: 'PIN cancelled',
583
+ },
584
+ });
585
+ });
586
+
587
+ it('keeps the same Protocol V2 response as ActionCancelled for DeviceSession calls', async () => {
588
+ const commands = createCommands();
589
+
590
+ await expect(
591
+ commands._filterCommonTypes(
592
+ {
593
+ type: 'Failure',
594
+ message: {
595
+ code: 'Failure_ProcessError',
596
+ subcode: DeviceSessionErrorCode.DeviceSessionError_UserCancelled,
597
+ message: 'PIN cancelled',
598
+ },
599
+ } as any,
600
+ 'DeviceSessionAskPin'
601
+ )
602
+ ).rejects.toMatchObject({
603
+ errorCode: HardwareErrorCode.ActionCancelled,
604
+ });
605
+ });
606
+
554
607
  it('does not use the legacy cancellation-message fallback for Protocol V1', async () => {
555
608
  const commands = createCommands();
556
609
  (commands.device.isProtocolV2 as jest.Mock).mockReturnValue(false);
@@ -0,0 +1,200 @@
1
+ import { EDeviceType, EFirmwareType, HardwareErrorCode } from '@onekeyfe/hd-shared';
2
+
3
+ import BTCDeriveContextHash from '../src/api/btc/BTCDeriveContextHash';
4
+ import { findMethod } from '../src/api/utils';
5
+ import { getLogBlockLabel, getSafeLogPayload } from '../src/events/logBlockEvent';
6
+ import { createCoreApi } from '../src/inject';
7
+ import { Device } from '../src/device/Device';
8
+
9
+ import type { DeviceFirmwareRange } from '../src/types';
10
+
11
+ jest.mock('../src/data/config', () => ({
12
+ getSDKVersion: jest.fn(() => '1.0.0'),
13
+ DEFAULT_DOMAIN: 'https://jssdk.onekey.so/1.0.0/',
14
+ }));
15
+
16
+ const createMethod = (overrides: Record<string, unknown> = {}) =>
17
+ new BTCDeriveContextHash({
18
+ id: 1,
19
+ payload: {
20
+ method: 'btcDeriveContextHash',
21
+ path: "m/84'/0'/0'/0/0",
22
+ appName: 'test-app',
23
+ context: 'deadbeef',
24
+ network: 'bitcoin-mainnet',
25
+ ...overrides,
26
+ },
27
+ });
28
+
29
+ describe('btcDeriveContextHash', () => {
30
+ test('forwards the public API call through the existing dispatcher', async () => {
31
+ const call = jest
32
+ .fn()
33
+ .mockResolvedValue({ success: true, payload: { secret: '00'.repeat(32) } });
34
+ const api = createCoreApi(call);
35
+ const params = {
36
+ path: "m/84'/0'/0'/0/0",
37
+ appName: 'test-app',
38
+ context: 'deadbeef',
39
+ network: 'bitcoin-mainnet' as const,
40
+ };
41
+ await api.btcDeriveContextHash('connect-id', 'device-id', params);
42
+ expect(call).toHaveBeenCalledWith({
43
+ ...params,
44
+ connectId: 'connect-id',
45
+ deviceId: 'device-id',
46
+ method: 'btcDeriveContextHash',
47
+ });
48
+ });
49
+
50
+ test.each([
51
+ ['bitcoin-mainnet', 'BITCOIN_MAINNET'],
52
+ ['bitcoin-testnet', 'BITCOIN_TESTNET'],
53
+ ['bitcoin-signet', 'BITCOIN_SIGNET'],
54
+ ['bitcoin-regtest', 'BITCOIN_REGTEST'],
55
+ ])('maps %s and returns the device result', async (network, wireNetwork) => {
56
+ const method = createMethod({ network });
57
+ method.init();
58
+ const response = { secret: '00'.repeat(32) };
59
+ const typedCall = jest.fn().mockResolvedValue({ message: response });
60
+ method.device = { commands: { typedCall } } as unknown as Device;
61
+
62
+ await expect(method.run()).resolves.toBe(response);
63
+ expect(typedCall).toHaveBeenCalledWith(
64
+ 'BabylonDeriveContextHash',
65
+ 'BabylonDerivedContextHash',
66
+ {
67
+ address_n: [2147483732, 2147483648, 2147483648, 0, 0],
68
+ script_type: 'SPENDWITNESS',
69
+ app_name: '746573742d617070',
70
+ context: 'deadbeef',
71
+ network: wireNetwork,
72
+ }
73
+ );
74
+ });
75
+
76
+ test.each([
77
+ ["m/44'/0'/0'/0/0", 'SPENDADDRESS'],
78
+ ["m/49'/0'/0'/0/0", 'SPENDP2SHWITNESS'],
79
+ [[2147483734, 2147483648, 2147483648, 0, 0], 'SPENDTAPROOT'],
80
+ ])('uses the selected path script type for %s', (path, scriptType) => {
81
+ const method = createMethod({ path });
82
+ method.init();
83
+ expect(method.params.script_type).toBe(scriptType);
84
+ });
85
+
86
+ test('accepts the maximum app name and context sizes', () => {
87
+ const method = createMethod({ appName: 'a'.repeat(64), context: 'ab'.repeat(1024) });
88
+ expect(() => method.init()).not.toThrow();
89
+ expect(method.params.context).toHaveLength(2048);
90
+ });
91
+
92
+ test.each([
93
+ { appName: '' },
94
+ { appName: 'a'.repeat(65) },
95
+ { appName: 'Test-App' },
96
+ { appName: 'test_app' },
97
+ { appName: '你好' },
98
+ { appName: null },
99
+ { context: '' },
100
+ { context: 'abc' },
101
+ { context: 'DEADBEEF' },
102
+ { context: '0xdeadbeef' },
103
+ { context: 'gg' },
104
+ { context: 'ab'.repeat(1025) },
105
+ { context: null },
106
+ { network: '' },
107
+ { network: 'litecoin' },
108
+ { network: 'toString' },
109
+ { network: 1 },
110
+ { path: 'm' },
111
+ { path: "m/84x'/0'/0'/0/0" },
112
+ { path: "m/2147483648'/0'/0'/0/0" },
113
+ { path: [2147483732, 2147483648, 2147483648, 0, 0.5] },
114
+ { path: [2147483732, 2147483648, 2147483648, 0, 4294967296] },
115
+ ])('rejects invalid inputs before a device call: %j', overrides => {
116
+ expect(() => createMethod(overrides).init()).toThrow(
117
+ expect.objectContaining({ errorCode: HardwareErrorCode.CallMethodInvalidParameter })
118
+ );
119
+ });
120
+
121
+ test('rejects sparse numeric paths before a device call', () => {
122
+ const sparsePath = [2147483732, 2147483648, 2147483648, 0, 5];
123
+ delete sparsePath[3];
124
+
125
+ [Array<number>(3), sparsePath].forEach(path => {
126
+ expect(() => createMethod({ path }).init()).toThrow(
127
+ expect.objectContaining({ errorCode: HardwareErrorCode.CallMethodInvalidParameter })
128
+ );
129
+ });
130
+ });
131
+
132
+ test('registers the public method and restricts it to supported firmware and protocol', () => {
133
+ const method = findMethod({ id: 1, payload: { ...createMethod().payload } });
134
+ method.init();
135
+ expect(method).toBeInstanceOf(BTCDeriveContextHash);
136
+ expect(method.strictCheckDeviceSupport).toBe(true);
137
+ expect(() => method.assertProtocolSupported('V2', EFirmwareType.Universal)).toThrow(
138
+ expect.objectContaining({ errorCode: HardwareErrorCode.DeviceNotSupportMethod })
139
+ );
140
+ });
141
+
142
+ test.each([EDeviceType.Classic1s, EDeviceType.ClassicPure])(
143
+ 'resolves the firmware requirement for %s through the device support check',
144
+ deviceType => {
145
+ const method = createMethod();
146
+ const device = Object.create(Device.prototype) as Device;
147
+ device.getCurrentDeviceType = jest.fn(() => deviceType);
148
+ const range: DeviceFirmwareRange = method.getVersionRange();
149
+
150
+ expect(device.getCurrentMethodVersionRange(type => range[type])).toEqual({ min: '3.21.0' });
151
+ expect(() => method.assertProtocolSupported('V1', EFirmwareType.Universal)).not.toThrow();
152
+ }
153
+ );
154
+
155
+ test.each([EDeviceType.Classic, EDeviceType.Mini, EDeviceType.Touch, EDeviceType.Pro])(
156
+ 'keeps %s outside the supported firmware range',
157
+ deviceType => {
158
+ const method = createMethod();
159
+ const device = Object.create(Device.prototype) as Device;
160
+ device.getCurrentDeviceType = jest.fn(() => deviceType);
161
+ const range: DeviceFirmwareRange = method.getVersionRange();
162
+
163
+ expect(device.getCurrentMethodVersionRange(type => range[type])).toBeUndefined();
164
+ }
165
+ );
166
+
167
+ test('propagates device rejection without returning a secret', async () => {
168
+ const method = createMethod();
169
+ method.init();
170
+ const error = new Error('User rejected');
171
+ method.device = {
172
+ commands: { typedCall: jest.fn().mockRejectedValue(error) },
173
+ } as unknown as Device;
174
+ await expect(method.run()).rejects.toBe(error);
175
+ });
176
+
177
+ test.each([undefined, '00', '00'.repeat(33)])(
178
+ 'rejects malformed device responses',
179
+ async secret => {
180
+ const method = createMethod();
181
+ method.init();
182
+ method.device = {
183
+ commands: { typedCall: jest.fn().mockResolvedValue({ message: { secret } }) },
184
+ } as unknown as Device;
185
+ await expect(method.run()).rejects.toMatchObject({
186
+ errorCode: HardwareErrorCode.CallMethodError,
187
+ });
188
+ }
189
+ );
190
+
191
+ test('blocks API request and response payloads in logs', () => {
192
+ const request = { payload: { method: 'btcDeriveContextHash' } };
193
+ const label = getLogBlockLabel(request);
194
+ expect(label).toBe('btcDeriveContextHash');
195
+ expect(getSafeLogPayload({ payload: { secret: '00'.repeat(32) } }, label)).toEqual({
196
+ method: 'btcDeriveContextHash',
197
+ payload: '[REDACTED]',
198
+ });
199
+ });
200
+ });
@@ -3,7 +3,7 @@ import { ERRORS, HardwareErrorCode } from '@onekeyfe/hd-shared';
3
3
  import { initConnector, initCore } from '../src/core';
4
4
  import { DataManager } from '../src/data-manager';
5
5
  import TransportManager from '../src/data-manager/TransportManager';
6
- import { IFRAME } from '../src/events';
6
+ import { IFRAME, createErrorMessage } from '../src/events';
7
7
  import SearchDevices from '../src/api/SearchDevices';
8
8
  import { DeviceList } from '../src/device/DeviceList';
9
9
  import { Device } from '../src/device/Device';
@@ -28,6 +28,23 @@ describe('Core 错误输出边界', () => {
28
28
  jest.restoreAllMocks();
29
29
  });
30
30
 
31
+ test('entry-point errors preserve USB recovery context across JSON serialization', () => {
32
+ const params = {
33
+ operation: 'open',
34
+ nativeErrorName: 'SecurityError',
35
+ nativeErrorMessage: 'Access denied',
36
+ };
37
+ const error = ERRORS.TypedError(
38
+ HardwareErrorCode.BridgeNeedsPermission,
39
+ 'Access denied',
40
+ params
41
+ );
42
+ expect(JSON.parse(JSON.stringify(createErrorMessage(error)))).toEqual({
43
+ success: false,
44
+ payload: { code: HardwareErrorCode.BridgeNeedsPermission, error: 'Access denied', params },
45
+ });
46
+ });
47
+
31
48
  test.each([
32
49
  ['webusb', false],
33
50
  ['desktop-webusb', false],
@@ -108,14 +125,28 @@ describe('Core 错误输出边界', () => {
108
125
  HardwareErrorCode.BleDeviceBondedCanceled,
109
126
  HardwareErrorCode.BleDeviceDisconnected,
110
127
  HardwareErrorCode.PollingTimeout,
128
+ HardwareErrorCode.BlePoweredOff,
129
+ HardwareErrorCode.BleUnsupported,
130
+ HardwareErrorCode.BridgeNeedsPermission,
131
+ HardwareErrorCode.WebUsbDeviceAccessError,
111
132
  ])(
112
- 'preserves terminal BLE error %s in the public response without polling again',
133
+ 'preserves terminal transport error %s in the public response without polling again',
113
134
  async errorCode => {
114
- jest.spyOn(DataManager, 'getSettings').mockReturnValue('react-native' as never);
135
+ jest
136
+ .spyOn(DataManager, 'getSettings')
137
+ .mockReturnValue(
138
+ [
139
+ HardwareErrorCode.BridgeNeedsPermission,
140
+ HardwareErrorCode.WebUsbDeviceAccessError,
141
+ ].includes(errorCode)
142
+ ? ('desktop-webusb' as never)
143
+ : ('react-native' as never)
144
+ );
115
145
  const error = ERRORS.TypedError(errorCode);
116
146
  const acquire = jest.fn().mockRejectedValue(error);
117
147
  jest.spyOn(TransportManager, 'getTransport').mockReturnValue({
118
148
  acquire,
149
+ enumerate: jest.fn().mockResolvedValue([{ path: 'ble-pairing-test' }]),
119
150
  release: jest.fn().mockResolvedValue(true),
120
151
  stop: jest.fn().mockResolvedValue(undefined),
121
152
  } as never);
@@ -10,7 +10,6 @@ import {
10
10
  isMissingDetectedProtocolV2Error,
11
11
  isRetryableBleConnectionError,
12
12
  isRetryableBleProtocolV2ProbeError,
13
- isTerminalBleStaleBondError,
14
13
  resolveBleConnectProtocol,
15
14
  } from '../src/core';
16
15
  import { DataManager } from '../src/data-manager';
@@ -364,11 +363,11 @@ describe('public device lifecycle events', () => {
364
363
 
365
364
  test('clears the cleanup barrier when its deadline expires', async () => {
366
365
  const realSetTimeout = setTimeout;
367
- jest
368
- .spyOn(global, 'setTimeout')
369
- .mockImplementation((callback, delay, ...args) =>
370
- realSetTimeout(callback, delay === 5_000 ? 0 : delay, ...args)
371
- );
366
+ const cleanupDeadline = createDeferred<() => void>();
367
+ jest.spyOn(global, 'setTimeout').mockImplementation((callback, delay, ...args) => {
368
+ if (delay === 5_000) cleanupDeadline.resolve(() => callback(...args));
369
+ return realSetTimeout(callback, delay, ...args);
370
+ });
372
371
  {
373
372
  jest.spyOn(DataManager, 'getSettings').mockReturnValue('react-native' as never);
374
373
  const acquire = jest.spyOn(Device.prototype, 'acquire').mockResolvedValue(undefined);
@@ -382,13 +381,15 @@ describe('public device lifecycle events', () => {
382
381
  type: IFRAME.CALL,
383
382
  payload: { method: 'getDeviceState', connectId: 'draining-device', connectProtocol: 'V2' },
384
383
  } as CoreMessage);
385
- setImmediate(() => cancel(context, 'draining-device'));
384
+ const expireCleanupDeadline = await cleanupDeadline.promise;
385
+ cancel(context, 'draining-device');
386
+ expireCleanupDeadline();
386
387
  await expect(result).resolves.toBeDefined();
387
- gate.resolve();
388
388
  await new Promise(resolve => {
389
389
  setImmediate(resolve);
390
390
  });
391
391
  expect(context.getPrePendingCallPromise('draining-device')).toBeUndefined();
392
+ gate.resolve();
392
393
  }
393
394
  });
394
395
 
@@ -611,7 +612,6 @@ describe('public device lifecycle events', () => {
611
612
  test.each([
612
613
  [HardwareErrorCode.RuntimeError, true],
613
614
  [HardwareErrorCode.BleDeviceBondError, false],
614
- [HardwareErrorCode.BlePeerRemovedPairingInformation, false],
615
615
  ] as const)(
616
616
  'retries a Protocol V2 probe mismatch with error code %s: %s',
617
617
  (errorCode, expected) => {
@@ -631,8 +631,6 @@ describe('public device lifecycle events', () => {
631
631
  [HardwareErrorCode.BleTimeoutError, true],
632
632
  [HardwareErrorCode.PollingTimeout, false],
633
633
  [HardwareErrorCode.BleDeviceBondError, false],
634
- [HardwareErrorCode.BlePeerRemovedPairingInformation, false],
635
- [HardwareErrorCode.BleBondInvalid, false],
636
634
  ] as const)('retries a BLE connection error with error code %s: %s', (errorCode, expected) => {
637
635
  const method = { payload: { connectProtocol: 'V2' } } as never;
638
636
  const error = {
@@ -685,19 +683,6 @@ describe('public device lifecycle events', () => {
685
683
  }
686
684
  );
687
685
 
688
- test.each([
689
- [HardwareErrorCode.BleDeviceBondError, true],
690
- [HardwareErrorCode.BlePeerRemovedPairingInformation, true],
691
- [HardwareErrorCode.BleBondInvalid, true],
692
- [HardwareErrorCode.DeviceNotFound, false],
693
- ] as const)('treats BLE stale-bond error code %s as terminal: %s', (errorCode, expected) => {
694
- const error = {
695
- errorCode,
696
- };
697
-
698
- expect(isTerminalBleStaleBondError(error)).toBe(expected);
699
- });
700
-
701
686
  test.each([
702
687
  [HardwareErrorCode.DeviceCheckDeviceIdError, true],
703
688
  [HardwareErrorCode.DeviceNotFound, false],
@@ -729,6 +714,48 @@ describe('public device lifecycle events', () => {
729
714
  expect(() => JSON.stringify(disconnectMessage?.payload.device)).not.toThrow();
730
715
  });
731
716
 
717
+ test.each(['V1', 'V2'] as const)(
718
+ 'preserves the %s connection identity for a transport disconnect after wipe',
719
+ protocol => {
720
+ jest.spyOn(DataManager, 'getSettings').mockReturnValue('webusb' as never);
721
+ core = initCore();
722
+ initConnector();
723
+ const messages: CoreMessage[] = [];
724
+ core.on(CORE_EVENT, message => messages.push(message));
725
+ const device = createInitializedDevice(protocol);
726
+ const connectId = device.getConnectId();
727
+ DevicePool.devicesCache[connectId] = device;
728
+
729
+ device.invalidateAfterWipe();
730
+ expect(device.toMessageObject()).toBeNull();
731
+ DevicePool.emitter.emit(DEVICE.CONNECT, device);
732
+ expect(messages.some(message => message.type === DEVICE.CONNECT)).toBe(false);
733
+ DevicePool.emitter.emit(TRANSPORT_EVENT.DEVICE_DISCONNECT, { connectId });
734
+
735
+ const disconnects = messages.filter(message => message.type === DEVICE.DISCONNECT);
736
+ expect(disconnects).toHaveLength(1);
737
+ expect(disconnects[0].payload.device).toMatchObject({
738
+ connectId,
739
+ serialNo: 'SERIAL-001',
740
+ deviceId: 'wallet-device-id',
741
+ });
742
+ expect(() => JSON.stringify(disconnects[0].payload.device)).not.toThrow();
743
+
744
+ device.features = {
745
+ ...createInitializedDevice(protocol).features,
746
+ deviceId: 'new-device-id',
747
+ initialized: false,
748
+ mode: 'notInitialized',
749
+ } as never;
750
+ DevicePool.emitter.emit(TRANSPORT_EVENT.DEVICE_DISCONNECT, { connectId });
751
+ const nextDisconnects = messages.filter(message => message.type === DEVICE.DISCONNECT);
752
+ expect(nextDisconnects[1].payload.device).toMatchObject({
753
+ deviceId: 'new-device-id',
754
+ mode: 'notInitialized',
755
+ });
756
+ }
757
+ );
758
+
732
759
  test('treats an acquired BLE device as reusable until the transport disconnects', async () => {
733
760
  jest.spyOn(DataManager, 'getSettings').mockReturnValue('desktop-web-ble' as never);
734
761
  const device = createInitializedDevice('V2');
@@ -1014,6 +1041,28 @@ describe('public device lifecycle events', () => {
1014
1041
  expect(device.wasInterruptedByUser()).toBe(false);
1015
1042
  });
1016
1043
 
1044
+ test.each(['V1', 'V2'] as const)(
1045
+ 'retires a failed USB %s session before the next user attempt',
1046
+ async protocol => {
1047
+ jest.spyOn(DataManager, 'getSettings').mockReturnValue('desktop-webusb' as never);
1048
+ const device = createInitializedDevice(protocol);
1049
+ device.originalDescriptor = { ...device.originalDescriptor, session: device.mainId };
1050
+ const disconnect = jest.fn().mockResolvedValue(undefined);
1051
+ const release = jest.fn().mockResolvedValue(undefined);
1052
+ device.deviceConnector = { disconnect, release } as never;
1053
+ device.commands = { disposed: false, dispose: jest.fn() } as never;
1054
+ (device as unknown as { deviceAcquired: boolean }).deviceAcquired = true;
1055
+ const error = ERRORS.TypedError(HardwareErrorCode.WebUsbDeviceAccessError);
1056
+ await expect(device.run(() => Promise.reject(error))).rejects.toBe(error);
1057
+ await new Promise(resolve => {
1058
+ setImmediate(resolve);
1059
+ });
1060
+ expect(disconnect).toHaveBeenCalledWith(device.mainId);
1061
+ expect(release).toHaveBeenCalledTimes(1);
1062
+ expect(device.hasDeviceAcquire()).toBe(false);
1063
+ }
1064
+ );
1065
+
1017
1066
  test('waits for the canceled run to finish releasing before cancellation completes', async () => {
1018
1067
  jest.spyOn(DataManager, 'getSettings').mockReturnValue('react-native' as never);
1019
1068
  const device = createInitializedDevice('V2');
@@ -85,6 +85,56 @@ describe('DevicePool state lifecycle', () => {
85
85
  expect(result.deviceList).toEqual([device]);
86
86
  });
87
87
 
88
+ test.each([
89
+ ['V1', undefined],
90
+ ['V1', 'wipe-path'],
91
+ ['V2', undefined],
92
+ ['V2', 'wipe-path'],
93
+ ] as const)('rediscovers a wiped %s device with connect id %s', async (protocol, connectId) => {
94
+ const descriptor = { path: 'wipe-path', protocolType: protocol } as never;
95
+ const device = Device.fromDescriptor(descriptor);
96
+ device.features = {
97
+ protocol,
98
+ deviceType: protocol === 'V2' ? 'pro2' : 'classic',
99
+ deviceId: 'old-device-id',
100
+ serialNo: 'wipe-path',
101
+ initialized: true,
102
+ mode: 'normal',
103
+ } as never;
104
+ DevicePool.devicesCache = { 'wipe-path': device };
105
+ device.invalidateAfterWipe();
106
+ expect(device.toMessageObject()).toBeNull();
107
+ const connect = jest.spyOn(device, 'connect').mockResolvedValue(true);
108
+ const initialize = jest.spyOn(device, 'initialize').mockImplementation(() => {
109
+ device.features = {
110
+ protocol,
111
+ deviceType: protocol === 'V2' ? 'pro2' : 'classic',
112
+ deviceId: 'new-device-id',
113
+ serialNo: 'wipe-path',
114
+ initialized: false,
115
+ mode: 'notInitialized',
116
+ } as never;
117
+ return Promise.resolve();
118
+ });
119
+ const release = jest.spyOn(device, 'release').mockResolvedValue(undefined);
120
+
121
+ try {
122
+ const result = await DevicePool.getDevices([descriptor], connectId);
123
+ expect(initialize).toHaveBeenCalledTimes(1);
124
+ expect(connect).toHaveBeenCalledTimes(1);
125
+ expect(release).toHaveBeenCalledTimes(1);
126
+ expect(result.deviceList[0].toMessageObject()).toMatchObject({
127
+ deviceId: 'new-device-id',
128
+ mode: 'notInitialized',
129
+ features: { initialized: false },
130
+ });
131
+ await DevicePool.getDevices([descriptor], connectId);
132
+ expect(initialize).toHaveBeenCalledTimes(1);
133
+ } finally {
134
+ jest.restoreAllMocks();
135
+ }
136
+ });
137
+
88
138
  test('keeps a discovered device when its Protocol V2 label cannot be read', async () => {
89
139
  const labelError = new Error('settings unavailable');
90
140
  const getDeviceState = jest
@@ -5,6 +5,7 @@ import {
5
5
  getLogBlockLabel,
6
6
  getSafeLogPayload,
7
7
  } from '../src/events';
8
+ import { getLog, initLog, setLoggerPostMessage } from '../src/utils/logger';
8
9
 
9
10
  describe('getLogBlockLabel', () => {
10
11
  it('keeps existing sensitive UI response blocking', () => {
@@ -96,4 +97,46 @@ describe('getLogBlockLabel', () => {
96
97
  it('does not classify events without an API method as method calls', () => {
97
98
  expect(getLogBlockLabel({ event: 'DEVICE_EVENT', type: 'device-connect' })).toBeUndefined();
98
99
  });
100
+
101
+ it.each(['zcashGetAddress', 'zcashGetUnifiedAddress', 'zcashSignPczt'])(
102
+ 'keeps %s wallet data out of logger caches and events with debug disabled',
103
+ method => {
104
+ const postMessage = jest.fn();
105
+ const prefix = `sensitive-zcash-${method}`;
106
+ const logger = initLog(prefix, false);
107
+ setLoggerPostMessage(postMessage);
108
+ const request = {
109
+ event: 'iframe-call',
110
+ payload: { method, pczt: 'synthetic-pczt-marker', includeUfvk: true },
111
+ };
112
+ const response = {
113
+ success: true,
114
+ payload: [
115
+ {
116
+ ufvk: 'synthetic-viewing-key-marker',
117
+ seedFingerprint: 'synthetic-fingerprint-marker',
118
+ pczt: 'synthetic-signed-pczt-marker',
119
+ },
120
+ ],
121
+ };
122
+ const blockLabel = getLogBlockLabel(request);
123
+
124
+ expect(blockLabel).toBe(method);
125
+ expect(getLogBlockLabel(request.payload)).toBe(method);
126
+ logger.debug('request:', getSafeLogPayload(request, blockLabel));
127
+ logger.debug('response:', getSafeLogPayload(response, blockLabel));
128
+
129
+ const cached = getLog().filter(entry => entry.prefix === prefix);
130
+ expect(cached.map(entry => entry.message[1])).toEqual([
131
+ { method, payload: '[REDACTED]' },
132
+ { method, payload: '[REDACTED]' },
133
+ ]);
134
+ expect(postMessage).toHaveBeenCalledTimes(2);
135
+ for (const output of [JSON.stringify(cached), JSON.stringify(postMessage.mock.calls)]) {
136
+ expect(output).not.toContain('synthetic-');
137
+ expect(output).toContain('[REDACTED]');
138
+ }
139
+ expect(response.payload[0].ufvk).toBe('synthetic-viewing-key-marker');
140
+ }
141
+ );
99
142
  });