@onekeyfe/hd-core 1.2.0-alpha.16 → 1.2.0-alpha.18

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 (125) hide show
  1. package/__tests__/DeviceEventRegistration.test.ts +3 -0
  2. package/__tests__/deviceFeaturesUtils.test.ts +27 -0
  3. package/__tests__/evmLedgerLegacySafety.test.ts +3 -0
  4. package/__tests__/homescreen.test.ts +24 -0
  5. package/__tests__/kaspaSignTransaction.test.ts +591 -0
  6. package/__tests__/protocol-v2.test.ts +1006 -204
  7. package/__tests__/protocolV2FileWrite.test.ts +28 -3
  8. package/__tests__/protocolV2UiInteraction.test.ts +266 -0
  9. package/dist/api/BaseMethod.d.ts +4 -0
  10. package/dist/api/BaseMethod.d.ts.map +1 -1
  11. package/dist/api/FirmwareUpdateV4.d.ts +3 -3
  12. package/dist/api/FirmwareUpdateV4.d.ts.map +1 -1
  13. package/dist/api/GetDeviceInfo.d.ts.map +1 -1
  14. package/dist/api/GetPassphraseState.d.ts.map +1 -1
  15. package/dist/api/UploadPortfolio.d.ts.map +1 -1
  16. package/dist/api/device/DeviceCancel.d.ts.map +1 -1
  17. package/dist/api/device/DeviceChangePin.d.ts.map +1 -1
  18. package/dist/api/device/DeviceLock.d.ts.map +1 -1
  19. package/dist/api/device/DeviceUnlock.d.ts.map +1 -1
  20. package/dist/api/device/DeviceWipe.d.ts.map +1 -1
  21. package/dist/api/helpers/protocolV2FileWrite.d.ts +1 -0
  22. package/dist/api/helpers/protocolV2FileWrite.d.ts.map +1 -1
  23. package/dist/api/index.d.ts +1 -1
  24. package/dist/api/index.d.ts.map +1 -1
  25. package/dist/api/kaspa/KaspaSignTransaction.d.ts +5 -1
  26. package/dist/api/kaspa/KaspaSignTransaction.d.ts.map +1 -1
  27. package/dist/api/kaspa/helpers/TransferSerialize.d.ts.map +1 -1
  28. package/dist/api/protocol-v2/DeviceInfoGet.d.ts.map +1 -1
  29. package/dist/api/protocol-v2/DeviceSessionOpen.d.ts +28 -0
  30. package/dist/api/protocol-v2/DeviceSessionOpen.d.ts.map +1 -0
  31. package/dist/api/protocol-v2/DeviceSettingsPageShow.d.ts.map +1 -1
  32. package/dist/api/protocol-v2/DeviceSettingsSet.d.ts.map +1 -1
  33. package/dist/api/protocol-v2/DeviceStatusGet.d.ts.map +1 -1
  34. package/dist/api/protocol-v2/DeviceUploadWallpaper.d.ts.map +1 -1
  35. package/dist/core/deviceEventRegistration.d.ts +1 -0
  36. package/dist/core/deviceEventRegistration.d.ts.map +1 -1
  37. package/dist/core/index.d.ts.map +1 -1
  38. package/dist/device/Device.d.ts +3 -3
  39. package/dist/device/Device.d.ts.map +1 -1
  40. package/dist/device/DeviceCommands.d.ts +7 -5
  41. package/dist/device/DeviceCommands.d.ts.map +1 -1
  42. package/dist/device/DevicePool.d.ts +2 -2
  43. package/dist/device/DevicePool.d.ts.map +1 -1
  44. package/dist/deviceProfile/buildDeviceFeatures.d.ts +6 -2
  45. package/dist/deviceProfile/buildDeviceFeatures.d.ts.map +1 -1
  46. package/dist/deviceProfile/buildDeviceProfile.d.ts +3 -2
  47. package/dist/deviceProfile/buildDeviceProfile.d.ts.map +1 -1
  48. package/dist/events/device.d.ts +4 -0
  49. package/dist/events/device.d.ts.map +1 -1
  50. package/dist/events/ui-request.d.ts +18 -2
  51. package/dist/events/ui-request.d.ts.map +1 -1
  52. package/dist/index.d.ts +85 -15
  53. package/dist/index.js +1515 -554
  54. package/dist/protocols/protocol-v2/features.d.ts +6 -18
  55. package/dist/protocols/protocol-v2/features.d.ts.map +1 -1
  56. package/dist/protocols/protocol-v2/index.d.ts +1 -1
  57. package/dist/protocols/protocol-v2/index.d.ts.map +1 -1
  58. package/dist/protocols/protocol-v2/uiInteraction.d.ts +39 -0
  59. package/dist/protocols/protocol-v2/uiInteraction.d.ts.map +1 -0
  60. package/dist/protocols/protocol-v2/unlockRetry.d.ts +5 -3
  61. package/dist/protocols/protocol-v2/unlockRetry.d.ts.map +1 -1
  62. package/dist/protocols/protocol-v2/walletSession.d.ts +2 -1
  63. package/dist/protocols/protocol-v2/walletSession.d.ts.map +1 -1
  64. package/dist/types/api/getDeviceInfo.d.ts +2 -1
  65. package/dist/types/api/getDeviceInfo.d.ts.map +1 -1
  66. package/dist/types/api/index.d.ts +2 -2
  67. package/dist/types/api/index.d.ts.map +1 -1
  68. package/dist/types/api/kaspaSignTransaction.d.ts +27 -2
  69. package/dist/types/api/kaspaSignTransaction.d.ts.map +1 -1
  70. package/dist/types/api/protocolV2.d.ts +4 -2
  71. package/dist/types/api/protocolV2.d.ts.map +1 -1
  72. package/dist/types/device.d.ts +2 -1
  73. package/dist/types/device.d.ts.map +1 -1
  74. package/dist/utils/deviceFeaturesUtils.d.ts.map +1 -1
  75. package/dist/utils/homescreen.d.ts.map +1 -1
  76. package/dist/utils/patch.d.ts +1 -1
  77. package/dist/utils/patch.d.ts.map +1 -1
  78. package/package.json +4 -4
  79. package/src/api/BaseMethod.ts +10 -2
  80. package/src/api/FirmwareUpdateV4.ts +27 -73
  81. package/src/api/GetDeviceInfo.ts +9 -2
  82. package/src/api/GetPassphraseState.ts +5 -2
  83. package/src/api/UploadPortfolio.ts +2 -0
  84. package/src/api/device/DeviceCancel.ts +1 -0
  85. package/src/api/device/DeviceChangePin.ts +23 -0
  86. package/src/api/device/DeviceLock.ts +1 -0
  87. package/src/api/device/DeviceUnlock.ts +9 -0
  88. package/src/api/device/DeviceWipe.ts +18 -0
  89. package/src/api/helpers/protocolV2FileWrite.ts +35 -11
  90. package/src/api/index.ts +1 -1
  91. package/src/api/kaspa/KaspaSignTransaction.ts +341 -22
  92. package/src/api/kaspa/helpers/TransferSerialize.ts +14 -0
  93. package/src/api/protocol-v2/DeviceInfoGet.ts +0 -1
  94. package/src/api/protocol-v2/DeviceSessionOpen.ts +100 -0
  95. package/src/api/protocol-v2/DeviceSettingsPageShow.ts +9 -1
  96. package/src/api/protocol-v2/DeviceSettingsSet.ts +11 -1
  97. package/src/api/protocol-v2/DeviceStatusGet.ts +1 -0
  98. package/src/api/protocol-v2/DeviceUploadWallpaper.ts +2 -1
  99. package/src/core/deviceEventRegistration.ts +2 -0
  100. package/src/core/index.ts +36 -3
  101. package/src/data/messages/messages-protocol-v2.json +122 -23
  102. package/src/data/messages/messages.json +286 -1
  103. package/src/device/Device.ts +33 -41
  104. package/src/device/DeviceCommands.ts +22 -4
  105. package/src/device/DevicePool.ts +14 -6
  106. package/src/deviceProfile/buildDeviceFeatures.ts +21 -9
  107. package/src/deviceProfile/buildDeviceProfile.ts +27 -11
  108. package/src/events/device.ts +4 -0
  109. package/src/events/ui-request.ts +24 -2
  110. package/src/inject.ts +2 -2
  111. package/src/protocols/protocol-v2/features.ts +27 -20
  112. package/src/protocols/protocol-v2/index.ts +0 -1
  113. package/src/protocols/protocol-v2/uiInteraction.ts +209 -0
  114. package/src/protocols/protocol-v2/unlockRetry.ts +43 -3
  115. package/src/protocols/protocol-v2/walletSession.ts +122 -31
  116. package/src/types/api/getDeviceInfo.ts +6 -1
  117. package/src/types/api/index.ts +2 -2
  118. package/src/types/api/kaspaSignTransaction.ts +40 -2
  119. package/src/types/api/protocolV2.ts +5 -3
  120. package/src/types/device.ts +6 -1
  121. package/src/utils/deviceFeaturesUtils.ts +13 -0
  122. package/src/utils/homescreen.ts +10 -0
  123. package/dist/api/protocol-v2/DeviceSessionGet.d.ts +0 -6
  124. package/dist/api/protocol-v2/DeviceSessionGet.d.ts.map +0 -1
  125. package/src/api/protocol-v2/DeviceSessionGet.ts +0 -15
@@ -29,7 +29,11 @@ import type {
29
29
  GetDeviceInfoParams,
30
30
  } from '../types/api/getDeviceInfo';
31
31
  import type { Features, OnekeyFeatures } from '../types';
32
- import type { DeviceFirmwareImageInfo, ProtocolV2DeviceInfo } from '@onekeyfe/hd-transport';
32
+ import type {
33
+ DeviceFirmwareImageInfo,
34
+ DeviceStatus,
35
+ ProtocolV2DeviceInfo,
36
+ } from '@onekeyfe/hd-transport';
33
37
 
34
38
  type BuildProtocolV1ProfileParams = {
35
39
  protocol?: DeviceInfoProtocol;
@@ -42,6 +46,7 @@ type BuildProtocolV1ProfileParams = {
42
46
 
43
47
  type BuildProtocolV2ProfileParams = {
44
48
  deviceInfo?: ProtocolV2DeviceInfo;
49
+ deviceStatus?: DeviceStatus;
45
50
  sources?: DeviceInfoSource[];
46
51
  scope?: GetDeviceInfoParams['scope'];
47
52
  includeRaw?: boolean;
@@ -89,10 +94,13 @@ const getDeviceMode = (features?: Features): DeviceInfoStatus['mode'] => {
89
94
  return 'unknown';
90
95
  };
91
96
 
92
- const getProtocolV2Mode = (deviceInfo?: ProtocolV2DeviceInfo): DeviceInfoStatus['mode'] => {
93
- if (isProtocolV2RomloaderDeviceInfo(deviceInfo)) return 'romloader';
94
- if (isProtocolV2BootloaderDeviceInfo(deviceInfo)) return 'bootloader';
95
- const initialized = deviceInfo?.status?.init_states;
97
+ const getProtocolV2Mode = (
98
+ deviceInfo?: ProtocolV2DeviceInfo,
99
+ deviceStatus?: DeviceStatus
100
+ ): DeviceInfoStatus['mode'] => {
101
+ if (isProtocolV2RomloaderDeviceInfo(deviceInfo, deviceStatus)) return 'romloader';
102
+ if (isProtocolV2BootloaderDeviceInfo(deviceInfo, deviceStatus)) return 'bootloader';
103
+ const initialized = deviceStatus?.init_states;
96
104
  if (initialized === false) return 'notInitialized';
97
105
  if (initialized === true) return 'normal';
98
106
  return 'unknown';
@@ -186,11 +194,14 @@ const normalizeV1Status = (features?: Features): DeviceInfoStatus => ({
186
194
  bleEnabled: features?.bleEnabled ?? null,
187
195
  });
188
196
 
189
- const normalizeV2Status = (deviceInfo?: ProtocolV2DeviceInfo): DeviceInfoStatus => {
190
- const status = deviceInfo?.status;
191
- const bootloaderMode = isProtocolV2BootloaderDeviceInfo(deviceInfo);
197
+ const normalizeV2Status = (
198
+ deviceInfo?: ProtocolV2DeviceInfo,
199
+ deviceStatus?: DeviceStatus
200
+ ): DeviceInfoStatus => {
201
+ const status = deviceStatus;
202
+ const bootloaderMode = isProtocolV2BootloaderDeviceInfo(deviceInfo, deviceStatus);
192
203
  return {
193
- mode: getProtocolV2Mode(deviceInfo),
204
+ mode: getProtocolV2Mode(deviceInfo, deviceStatus),
194
205
  initialized: status?.init_states ?? null,
195
206
  bootloaderMode,
196
207
  unlocked: status?.unlocked ?? null,
@@ -274,14 +285,17 @@ const normalizeRaw = ({
274
285
  features,
275
286
  protocolV1OneKeyFeatures,
276
287
  protocolV2DeviceInfo,
288
+ protocolV2DeviceStatus,
277
289
  }: {
278
290
  features?: Features;
279
291
  protocolV1OneKeyFeatures?: OnekeyFeatures;
280
292
  protocolV2DeviceInfo?: ProtocolV2DeviceInfo;
293
+ protocolV2DeviceStatus?: DeviceStatus;
281
294
  }): DeviceProfileRaw => ({
282
295
  ...(features ? { features } : {}),
283
296
  ...(protocolV1OneKeyFeatures ? { protocolV1OneKeyFeatures } : {}),
284
297
  ...(protocolV2DeviceInfo ? { protocolV2DeviceInfo } : {}),
298
+ ...(protocolV2DeviceStatus ? { protocolV2DeviceStatus } : {}),
285
299
  });
286
300
 
287
301
  export function buildProfileFromProtocolV1({
@@ -320,12 +334,13 @@ export function buildProfileFromProtocolV1({
320
334
 
321
335
  export function buildProfileFromProtocolV2({
322
336
  deviceInfo,
337
+ deviceStatus,
323
338
  sources = ['deviceInfo'],
324
339
  scope = 'basic',
325
340
  includeRaw = false,
326
341
  }: BuildProtocolV2ProfileParams): DeviceProfile {
327
342
  const info = deviceInfo;
328
- const deviceId = info?.status?.device_id || '';
343
+ const deviceId = deviceStatus?.device_id || '';
329
344
  const serialNo = deviceInfo?.hw?.serial_no || '';
330
345
  const label = null;
331
346
  const bleName = info?.coprocessor?.bt_adv_name ?? null;
@@ -340,13 +355,14 @@ export function buildProfileFromProtocolV2({
340
355
  serialNo,
341
356
  label,
342
357
  bleName,
343
- status: normalizeV2Status(deviceInfo),
358
+ status: normalizeV2Status(deviceInfo, deviceStatus),
344
359
  versions: normalizeV2Versions(deviceInfo),
345
360
  ...(shouldIncludeVerify(scope) ? { verify } : {}),
346
361
  ...(includeRaw
347
362
  ? {
348
363
  raw: normalizeRaw({
349
364
  protocolV2DeviceInfo: deviceInfo,
365
+ protocolV2DeviceStatus: deviceStatus,
350
366
  }),
351
367
  }
352
368
  : {}),
@@ -23,6 +23,7 @@ export const DEVICE = {
23
23
  PIN: 'pin',
24
24
  PASSPHRASE: 'passphrase',
25
25
  PASSPHRASE_ON_DEVICE: 'passphrase_on_device',
26
+ ATTACH_PIN_ON_DEVICE: 'attach_pin_on_device',
26
27
  WORD: 'word',
27
28
  SUPPORT_FEATURES: 'support_features',
28
29
  SELECT_DEVICE_IN_BOOTLOADER_FOR_WEB_DEVICE: 'select_device_in_bootloader_for_web_device',
@@ -47,6 +48,9 @@ export interface DeviceButtonRequestPayload extends Omit<PROTO.ButtonRequest, 'c
47
48
 
48
49
  export type PassphraseRequestPayload = {
49
50
  existsAttachPinUser?: boolean;
51
+ source?: 'wallet-session-coordinator';
52
+ reason?: 'open-wallet' | 'session-recovery';
53
+ expectedPassphraseState?: string;
50
54
  };
51
55
 
52
56
  export interface DeviceButtonRequest {
@@ -49,6 +49,23 @@ export const UI_REQUEST = {
49
49
  NOT_USE_ONEKEY_DEVICE: 'ui-device_please_use_onekey_device',
50
50
  } as const;
51
51
 
52
+ export type ProtocolV2UiEventSource =
53
+ | 'unlock-coordinator'
54
+ | 'wallet-session-coordinator'
55
+ | 'method-lifecycle';
56
+
57
+ export type ProtocolV2UiCompletion = 'page-accepted' | 'operation-completed';
58
+
59
+ export type ProtocolV2UiEventMetadata = {
60
+ source?: ProtocolV2UiEventSource;
61
+ reason?: string;
62
+ deviceOnly?: boolean;
63
+ completion?: ProtocolV2UiCompletion;
64
+ method?: string;
65
+ page?: string | number;
66
+ operation?: string;
67
+ };
68
+
52
69
  export interface UiRequestWithoutPayload {
53
70
  type:
54
71
  | typeof UI_REQUEST.CLOSE_UI_WINDOW
@@ -73,7 +90,7 @@ export interface UiRequestFirmwareProgressing {
73
90
 
74
91
  export type UiRequestDeviceAction = {
75
92
  type: typeof UI_REQUEST.REQUEST_PIN;
76
- payload: {
93
+ payload: ProtocolV2UiEventMetadata & {
77
94
  device: Device;
78
95
  type?: PROTO.PinMatrixRequestType | 'ButtonRequest_PinEntry' | 'ButtonRequest_AttachPin';
79
96
  };
@@ -81,7 +98,7 @@ export type UiRequestDeviceAction = {
81
98
 
82
99
  export interface UiRequestButton {
83
100
  type: typeof UI_REQUEST.REQUEST_BUTTON;
84
- payload: DeviceButtonRequest['payload'];
101
+ payload: DeviceButtonRequest['payload'] & ProtocolV2UiEventMetadata;
85
102
  }
86
103
 
87
104
  export interface UiRequestPassphrase {
@@ -90,6 +107,9 @@ export interface UiRequestPassphrase {
90
107
  device: Device;
91
108
  passphraseState?: string;
92
109
  existsAttachPinUser?: boolean;
110
+ source?: 'wallet-session-coordinator';
111
+ reason?: 'open-wallet' | 'session-recovery';
112
+ expectedPassphraseState?: string;
93
113
  };
94
114
  }
95
115
 
@@ -98,6 +118,8 @@ export interface UiRequestPassphraseOnDevice {
98
118
  payload: {
99
119
  device: Device;
100
120
  passphraseState?: string;
121
+ source?: 'wallet-session-coordinator';
122
+ reason?: 'open-wallet' | 'session-recovery';
101
123
  };
102
124
  }
103
125
 
package/src/inject.ts CHANGED
@@ -164,8 +164,8 @@ export const createCoreApi = (
164
164
  deviceStatusGet: (connectId, params) => call({ ...params, connectId, method: 'deviceStatusGet' }),
165
165
  deviceGetOnboardingStatus: (connectId, params) =>
166
166
  call({ ...params, connectId, method: 'deviceGetOnboardingStatus' }),
167
- deviceSessionGet: (connectId, params) =>
168
- call({ ...params, connectId, method: 'deviceSessionGet' }),
167
+ deviceSessionOpen: (connectId, params) =>
168
+ call({ ...params, connectId, method: 'deviceSessionOpen' }),
169
169
  deviceFirmwareUpdate: (connectId, params) =>
170
170
  call({ ...params, connectId, method: 'deviceFirmwareUpdate' }),
171
171
  deviceGetFirmwareUpdateStatus: (connectId, params) =>
@@ -1,6 +1,11 @@
1
1
  import { DeviceSEState, DeviceSeType } from '@onekeyfe/hd-transport';
2
2
 
3
- import type { DeviceInfoGet, DeviceSEInfo, ProtocolV2DeviceInfo } from '@onekeyfe/hd-transport';
3
+ import type {
4
+ DeviceInfoGet,
5
+ DeviceSEInfo,
6
+ DeviceStatus,
7
+ ProtocolV2DeviceInfo,
8
+ } from '@onekeyfe/hd-transport';
4
9
  import type { DeviceCommands } from '../../device/DeviceCommands';
5
10
 
6
11
  // 单源类型:直接使用 hd-transport 生成的 ProtocolV2DeviceInfo / DeviceSEInfo /
@@ -56,9 +61,12 @@ export const getProtocolV2SeType = (se?: DeviceSEInfo): string | null =>
56
61
  * 当前 romloader 只上报 hw、fw.romloader 和 fw.bootloader;bootloader
57
62
  * 还会上报 application/application_data、coprocessor 或 SE 信息。
58
63
  */
59
- export const isProtocolV2RomloaderDeviceInfo = (deviceInfo?: ProtocolV2DeviceInfo | null) =>
64
+ export const isProtocolV2RomloaderDeviceInfo = (
65
+ deviceInfo?: ProtocolV2DeviceInfo | null,
66
+ deviceStatus?: DeviceStatus | null
67
+ ) =>
60
68
  !!deviceInfo &&
61
- deviceInfo.status == null &&
69
+ deviceStatus == null &&
62
70
  deviceInfo.fw?.romloader != null &&
63
71
  deviceInfo.fw?.application == null &&
64
72
  deviceInfo.fw?.application_data == null &&
@@ -68,15 +76,19 @@ export const isProtocolV2RomloaderDeviceInfo = (deviceInfo?: ProtocolV2DeviceInf
68
76
  deviceInfo.se3 == null &&
69
77
  deviceInfo.se4 == null;
70
78
 
71
- export const isProtocolV2BootloaderDeviceInfo = (deviceInfo?: ProtocolV2DeviceInfo | null) =>
72
- !!deviceInfo && deviceInfo.status == null && !isProtocolV2RomloaderDeviceInfo(deviceInfo);
79
+ export const isProtocolV2BootloaderDeviceInfo = (
80
+ deviceInfo?: ProtocolV2DeviceInfo | null,
81
+ deviceStatus?: DeviceStatus | null
82
+ ) =>
83
+ !!deviceInfo &&
84
+ deviceStatus == null &&
85
+ !isProtocolV2RomloaderDeviceInfo(deviceInfo, deviceStatus);
73
86
 
74
87
  export const PROTOCOL_V2_FEATURES_DEVICE_INFO_REQUEST = {
75
88
  targets: {
76
89
  hw: true,
77
90
  fw: true,
78
91
  coprocessor: true,
79
- status: true,
80
92
  },
81
93
  types: {
82
94
  version: true,
@@ -90,18 +102,6 @@ export const PROTOCOL_V2_FEATURES_DEVICE_INFO_REQUEST = {
90
102
  * status 提供 init_states / passphrase_enabled 等会在设备端变化的字段;
91
103
  * hw / coprocessor 提供 serialNo / bleName 等身份字段;不含 fw/SE targets,单帧请求开销很小。
92
104
  */
93
- export const PROTOCOL_V2_STATUS_DEVICE_INFO_REQUEST = {
94
- targets: {
95
- hw: true,
96
- coprocessor: true,
97
- status: true,
98
- },
99
- types: {
100
- version: true,
101
- specific: true,
102
- },
103
- };
104
-
105
105
  export const PROTOCOL_V2_VERSIONS_DEVICE_INFO_REQUEST = {
106
106
  targets: {
107
107
  hw: true,
@@ -111,7 +111,6 @@ export const PROTOCOL_V2_VERSIONS_DEVICE_INFO_REQUEST = {
111
111
  se2: true,
112
112
  se3: true,
113
113
  se4: true,
114
- status: true,
115
114
  },
116
115
  types: {
117
116
  version: true,
@@ -128,7 +127,6 @@ export const PROTOCOL_V2_FULL_DEVICE_INFO_REQUEST = {
128
127
  se2: true,
129
128
  se3: true,
130
129
  se4: true,
131
- status: true,
132
130
  },
133
131
  types: {
134
132
  version: true,
@@ -157,3 +155,12 @@ export async function requestProtocolV2DeviceInfo({
157
155
  // DeviceInfoGet 是 V2-only 消息,这里收窄到 V2 形态。
158
156
  return message as ProtocolV2DeviceInfo;
159
157
  }
158
+
159
+ export async function requestProtocolV2DeviceStatus({
160
+ commands,
161
+ }: {
162
+ commands: DeviceCommands;
163
+ }): Promise<DeviceStatus> {
164
+ const { message } = await commands.typedCall('DeviceStatusGet', 'DeviceStatus', {});
165
+ return message;
166
+ }
@@ -2,7 +2,6 @@ export {
2
2
  PROTOCOL_V2_DEVICE_INFO_REQUEST,
3
3
  PROTOCOL_V2_DEVICE_INFO_TIMEOUT_MS,
4
4
  PROTOCOL_V2_FEATURES_DEVICE_INFO_REQUEST,
5
- PROTOCOL_V2_STATUS_DEVICE_INFO_REQUEST,
6
5
  PROTOCOL_V2_VERSIONS_DEVICE_INFO_REQUEST,
7
6
  isProtocolV2BootloaderDeviceInfo,
8
7
  isProtocolV2RomloaderDeviceInfo,
@@ -0,0 +1,209 @@
1
+ import { UI_REQUEST, createUiMessage } from '../../events';
2
+
3
+ import type { CoreMessage, ProtocolV2UiCompletion } from '../../events';
4
+ import type { Device } from '../../device/Device';
5
+ import type { KnownDevice } from '../../types';
6
+
7
+ export type ProtocolV2InteractionDescriptor = {
8
+ request: 'button' | 'pin';
9
+ source: 'method-lifecycle';
10
+ reason:
11
+ | 'change-pin'
12
+ | 'device-unlock'
13
+ | 'settings-page'
14
+ | 'address-confirmation'
15
+ | 'public-key-confirmation'
16
+ | 'signing-confirmation'
17
+ | 'device-management';
18
+ completion: ProtocolV2UiCompletion;
19
+ deviceOnly: true;
20
+ page?: string | number;
21
+ operation?: string;
22
+ };
23
+
24
+ type ProtocolV2InteractionMethod = {
25
+ name?: string;
26
+ params?: unknown;
27
+ payload?: unknown;
28
+ protocolV2UiInteraction?: ProtocolV2InteractionDescriptor;
29
+ };
30
+
31
+ type InteractionDevice = Pick<Device, 'isProtocolV2' | 'toMessageObject'>;
32
+ type PostMessage = (message: CoreMessage) => void;
33
+
34
+ export const isProtocolV2UiEnabled = (method: { protocolV2UiMode?: 'auto' | 'none' }) =>
35
+ method.protocolV2UiMode !== 'none';
36
+
37
+ const getDisplayState = (value: unknown) => {
38
+ const visited = new Set<object>();
39
+ let seen = false;
40
+ let enabled = false;
41
+
42
+ const visit = (current: unknown) => {
43
+ if (current == null || typeof current !== 'object') return;
44
+ if (visited.has(current)) return;
45
+ visited.add(current);
46
+
47
+ if (Array.isArray(current)) {
48
+ current.forEach(visit);
49
+ return;
50
+ }
51
+
52
+ Object.entries(current).forEach(([key, item]) => {
53
+ if ((key === 'show_display' || key === 'showOnOneKey') && typeof item === 'boolean') {
54
+ seen = true;
55
+ enabled ||= item;
56
+ return;
57
+ }
58
+ visit(item);
59
+ });
60
+ };
61
+
62
+ visit(value);
63
+ return { seen, enabled };
64
+ };
65
+
66
+ const createMethodInteraction = (
67
+ reason: 'address-confirmation' | 'public-key-confirmation' | 'signing-confirmation',
68
+ operation: string
69
+ ): ProtocolV2InteractionDescriptor => ({
70
+ request: 'button',
71
+ source: 'method-lifecycle',
72
+ reason,
73
+ completion: 'operation-completed',
74
+ deviceOnly: true,
75
+ operation,
76
+ });
77
+
78
+ const hasCipherConfirmation = (value: unknown): boolean => {
79
+ if (Array.isArray(value)) return value.some(hasCipherConfirmation);
80
+ if (value == null || typeof value !== 'object') return false;
81
+
82
+ const params = value as {
83
+ encrypt?: boolean;
84
+ ask_on_encrypt?: boolean;
85
+ ask_on_decrypt?: boolean;
86
+ };
87
+ return params.encrypt === true ? params.ask_on_encrypt === true : params.ask_on_decrypt === true;
88
+ };
89
+
90
+ /**
91
+ * Protocol V2 不再依赖固件 ButtonRequest,因此在统一层根据业务方法生成兼容 UI Event。
92
+ * 显式声明始终优先;地址和公钥只在设备实际展示时提示,签名统一提示一次。
93
+ */
94
+ export const resolveProtocolV2UiInteraction = (
95
+ method: ProtocolV2InteractionMethod
96
+ ): ProtocolV2InteractionDescriptor | undefined => {
97
+ if (method.protocolV2UiInteraction) return method.protocolV2UiInteraction;
98
+
99
+ const operation = method.name;
100
+ if (!operation) return undefined;
101
+
102
+ const isAddress = /getAddress(?:ByLoop)?$/i.test(operation);
103
+ const isPublicKey = /getPublicKey$/i.test(operation);
104
+ if (isAddress || isPublicKey) {
105
+ const paramsDisplay = getDisplayState(method.params);
106
+ const payloadDisplay = getDisplayState(method.payload);
107
+ const display = paramsDisplay.seen ? paramsDisplay : payloadDisplay;
108
+
109
+ // 地址接口通常默认在设备展示;公钥接口存在默认静默读取,优先依赖归一化参数。
110
+ const shouldDisplay = display.seen ? display.enabled : isAddress;
111
+ if (!shouldDisplay) return undefined;
112
+
113
+ return createMethodInteraction(
114
+ isAddress ? 'address-confirmation' : 'public-key-confirmation',
115
+ operation
116
+ );
117
+ }
118
+
119
+ if (/sign/i.test(operation) || /verifyMessage$/i.test(operation) || operation === 'lnurlAuth') {
120
+ return createMethodInteraction('signing-confirmation', operation);
121
+ }
122
+
123
+ if (operation === 'nostrEncryptMessage' || operation === 'nostrDecryptMessage') {
124
+ const display = getDisplayState(method.params);
125
+ if (!display.enabled) return undefined;
126
+ return createMethodInteraction('signing-confirmation', operation);
127
+ }
128
+
129
+ if (operation === 'cipherKeyValue' && hasCipherConfirmation(method.params)) {
130
+ return createMethodInteraction('signing-confirmation', operation);
131
+ }
132
+
133
+ return undefined;
134
+ };
135
+
136
+ export class ProtocolV2UiInteractionCoordinator {
137
+ private readonly device: InteractionDevice;
138
+
139
+ private readonly postMessage: PostMessage;
140
+
141
+ private methodInteraction?: ProtocolV2InteractionDescriptor;
142
+
143
+ private currentPhase?: string;
144
+
145
+ private opened = false;
146
+
147
+ private closed = false;
148
+
149
+ constructor(device: InteractionDevice, postMessage: PostMessage) {
150
+ this.device = device;
151
+ this.postMessage = postMessage;
152
+ }
153
+
154
+ enterMethodInteraction(interaction?: ProtocolV2InteractionDescriptor) {
155
+ this.methodInteraction = interaction;
156
+ if (!interaction) return;
157
+ const { request, ...metadata } = interaction;
158
+
159
+ this.emit(
160
+ request === 'pin' ? UI_REQUEST.REQUEST_PIN : UI_REQUEST.REQUEST_BUTTON,
161
+ {
162
+ device: this.device.toMessageObject() as KnownDevice,
163
+ ...metadata,
164
+ },
165
+ `method:${request}:${interaction.reason}:${interaction.page ?? ''}:${
166
+ interaction.operation ?? ''
167
+ }`
168
+ );
169
+ }
170
+
171
+ enterUnlockInteraction(method?: string) {
172
+ this.emit(
173
+ UI_REQUEST.REQUEST_PIN,
174
+ {
175
+ device: this.device.toMessageObject() as KnownDevice,
176
+ source: 'unlock-coordinator',
177
+ reason: 'device-locked',
178
+ deviceOnly: true,
179
+ method,
180
+ },
181
+ `unlock:${method ?? ''}`
182
+ );
183
+ }
184
+
185
+ resumeMethodInteraction() {
186
+ this.enterMethodInteraction(this.methodInteraction);
187
+ }
188
+
189
+ close() {
190
+ if (!this.device.isProtocolV2() || !this.opened || this.closed) return;
191
+ this.closed = true;
192
+ this.postMessage(createUiMessage(UI_REQUEST.CLOSE_UI_WINDOW));
193
+ }
194
+
195
+ private emit(
196
+ type: typeof UI_REQUEST.REQUEST_BUTTON | typeof UI_REQUEST.REQUEST_PIN,
197
+ payload: any,
198
+ phase: string
199
+ ) {
200
+ if (!this.device.isProtocolV2() || this.closed || this.currentPhase === phase) return;
201
+ this.currentPhase = phase;
202
+ this.opened = true;
203
+ const message =
204
+ type === UI_REQUEST.REQUEST_BUTTON
205
+ ? createUiMessage(UI_REQUEST.REQUEST_BUTTON, payload)
206
+ : createUiMessage(UI_REQUEST.REQUEST_PIN, payload);
207
+ this.postMessage(message);
208
+ }
209
+ }
@@ -1,15 +1,49 @@
1
1
  import { LoggerNames, getLogger } from '../../utils';
2
2
  import { isDeviceLockedError } from './lockedError';
3
+ import { isProtocolV2UiEnabled, resolveProtocolV2UiInteraction } from './uiInteraction';
3
4
 
4
5
  import type { BaseMethod } from '../../api/BaseMethod';
5
6
  import type { Device } from '../../device/Device';
7
+ import type { ProtocolV2UiInteractionCoordinator } from './uiInteraction';
6
8
 
7
9
  const Log = getLogger(LoggerNames.Core);
8
10
 
9
- type RunnableMethod = Pick<BaseMethod, 'run' | 'unlockPolicy'> & { name?: string };
10
- type UnlockableDevice = Pick<Device, 'isProtocolV2' | 'unlockDevice'>;
11
+ type RunnableMethod = Pick<
12
+ BaseMethod,
13
+ 'run' | 'unlockPolicy' | 'protocolV2UiInteraction' | 'protocolV2UiMode' | 'params' | 'payload'
14
+ > & { name?: string };
15
+ type UnlockableDevice = Pick<Device, 'isProtocolV2' | 'unlockDevice' | 'features'>;
16
+ type UiInteractionCoordinator = Pick<
17
+ ProtocolV2UiInteractionCoordinator,
18
+ 'enterMethodInteraction' | 'enterUnlockInteraction' | 'resumeMethodInteraction'
19
+ >;
11
20
 
12
- export async function runMethodWithUnlockRetry(method: RunnableMethod, device: UnlockableDevice) {
21
+ export async function runMethodWithUnlockRetry(
22
+ method: RunnableMethod,
23
+ device: UnlockableDevice,
24
+ uiCoordinator?: UiInteractionCoordinator
25
+ ) {
26
+ const shouldEmitUi = isProtocolV2UiEnabled(method);
27
+ const shouldUnlockBeforeRun =
28
+ device.isProtocolV2() &&
29
+ method.unlockPolicy === 'retry-on-locked' &&
30
+ device.features?.unlocked === false;
31
+
32
+ if (shouldUnlockBeforeRun) {
33
+ if (shouldEmitUi) {
34
+ uiCoordinator?.enterUnlockInteraction(method.name);
35
+ }
36
+ await device.unlockDevice();
37
+ Log.debug('Protocol V2 pre-unlock completed', { method: method.name });
38
+ if (shouldEmitUi) {
39
+ uiCoordinator?.enterMethodInteraction(resolveProtocolV2UiInteraction(method));
40
+ }
41
+ return method.run();
42
+ }
43
+
44
+ if (shouldEmitUi) {
45
+ uiCoordinator?.enterMethodInteraction(resolveProtocolV2UiInteraction(method));
46
+ }
13
47
  try {
14
48
  return await method.run();
15
49
  } catch (error) {
@@ -22,8 +56,14 @@ export async function runMethodWithUnlockRetry(method: RunnableMethod, device: U
22
56
  }
23
57
 
24
58
  Log.debug('Protocol V2 unlock retry triggered', { method: method.name });
59
+ if (shouldEmitUi) {
60
+ uiCoordinator?.enterUnlockInteraction(method.name);
61
+ }
25
62
  await device.unlockDevice();
26
63
  Log.debug('Protocol V2 unlock completed', { method: method.name });
64
+ if (shouldEmitUi) {
65
+ uiCoordinator?.resumeMethodInteraction();
66
+ }
27
67
  try {
28
68
  const response = await method.run();
29
69
  Log.debug('Protocol V2 method retry completed', { method: method.name, success: true });