@onekeyfe/hd-core 1.2.0-alpha.15 → 1.2.0-alpha.17

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 (118) hide show
  1. package/__tests__/DeviceCommands.test.ts +77 -0
  2. package/__tests__/DeviceEventRegistration.test.ts +8 -3
  3. package/__tests__/deviceFeaturesUtils.test.ts +27 -0
  4. package/__tests__/evmLedgerLegacySafety.test.ts +3 -0
  5. package/__tests__/homescreen.test.ts +24 -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/allnetwork/AllNetworkGetAddressBase.d.ts.map +1 -1
  17. package/dist/api/device/DeviceCancel.d.ts.map +1 -1
  18. package/dist/api/device/DeviceChangePin.d.ts.map +1 -1
  19. package/dist/api/device/DeviceLock.d.ts.map +1 -1
  20. package/dist/api/device/DeviceUnlock.d.ts.map +1 -1
  21. package/dist/api/device/DeviceWipe.d.ts.map +1 -1
  22. package/dist/api/helpers/protocolV2FileWrite.d.ts +1 -0
  23. package/dist/api/helpers/protocolV2FileWrite.d.ts.map +1 -1
  24. package/dist/api/index.d.ts +1 -1
  25. package/dist/api/index.d.ts.map +1 -1
  26. package/dist/api/protocol-v2/DeviceInfoGet.d.ts.map +1 -1
  27. package/dist/api/protocol-v2/DeviceSessionOpen.d.ts +28 -0
  28. package/dist/api/protocol-v2/DeviceSessionOpen.d.ts.map +1 -0
  29. package/dist/api/protocol-v2/DeviceSettingsPageShow.d.ts.map +1 -1
  30. package/dist/api/protocol-v2/DeviceSettingsSet.d.ts.map +1 -1
  31. package/dist/api/protocol-v2/DeviceStatusGet.d.ts.map +1 -1
  32. package/dist/api/protocol-v2/DeviceUploadWallpaper.d.ts.map +1 -1
  33. package/dist/core/deviceEventRegistration.d.ts +2 -2
  34. package/dist/core/deviceEventRegistration.d.ts.map +1 -1
  35. package/dist/core/index.d.ts.map +1 -1
  36. package/dist/device/Device.d.ts +3 -3
  37. package/dist/device/Device.d.ts.map +1 -1
  38. package/dist/device/DeviceCommands.d.ts +3 -1
  39. package/dist/device/DeviceCommands.d.ts.map +1 -1
  40. package/dist/device/DevicePool.d.ts +2 -2
  41. package/dist/device/DevicePool.d.ts.map +1 -1
  42. package/dist/deviceProfile/buildDeviceFeatures.d.ts +6 -2
  43. package/dist/deviceProfile/buildDeviceFeatures.d.ts.map +1 -1
  44. package/dist/deviceProfile/buildDeviceProfile.d.ts +3 -2
  45. package/dist/deviceProfile/buildDeviceProfile.d.ts.map +1 -1
  46. package/dist/events/device.d.ts +4 -0
  47. package/dist/events/device.d.ts.map +1 -1
  48. package/dist/events/ui-request.d.ts +18 -2
  49. package/dist/events/ui-request.d.ts.map +1 -1
  50. package/dist/index.d.ts +56 -11
  51. package/dist/index.js +1014 -559
  52. package/dist/protocols/protocol-v2/features.d.ts +6 -18
  53. package/dist/protocols/protocol-v2/features.d.ts.map +1 -1
  54. package/dist/protocols/protocol-v2/index.d.ts +1 -1
  55. package/dist/protocols/protocol-v2/index.d.ts.map +1 -1
  56. package/dist/protocols/protocol-v2/uiInteraction.d.ts +39 -0
  57. package/dist/protocols/protocol-v2/uiInteraction.d.ts.map +1 -0
  58. package/dist/protocols/protocol-v2/unlockRetry.d.ts +5 -3
  59. package/dist/protocols/protocol-v2/unlockRetry.d.ts.map +1 -1
  60. package/dist/protocols/protocol-v2/walletSession.d.ts +2 -1
  61. package/dist/protocols/protocol-v2/walletSession.d.ts.map +1 -1
  62. package/dist/types/api/getDeviceInfo.d.ts +2 -1
  63. package/dist/types/api/getDeviceInfo.d.ts.map +1 -1
  64. package/dist/types/api/index.d.ts +2 -2
  65. package/dist/types/api/index.d.ts.map +1 -1
  66. package/dist/types/api/protocolV2.d.ts +4 -2
  67. package/dist/types/api/protocolV2.d.ts.map +1 -1
  68. package/dist/types/device.d.ts +2 -1
  69. package/dist/types/device.d.ts.map +1 -1
  70. package/dist/utils/deviceFeaturesUtils.d.ts.map +1 -1
  71. package/dist/utils/homescreen.d.ts.map +1 -1
  72. package/dist/utils/patch.d.ts +1 -1
  73. package/dist/utils/patch.d.ts.map +1 -1
  74. package/package.json +4 -4
  75. package/src/api/BaseMethod.ts +10 -2
  76. package/src/api/FirmwareUpdateV4.ts +27 -73
  77. package/src/api/GetDeviceInfo.ts +9 -2
  78. package/src/api/GetPassphraseState.ts +5 -2
  79. package/src/api/UploadPortfolio.ts +2 -0
  80. package/src/api/allnetwork/AllNetworkGetAddressBase.ts +8 -13
  81. package/src/api/device/DeviceCancel.ts +1 -0
  82. package/src/api/device/DeviceChangePin.ts +23 -0
  83. package/src/api/device/DeviceLock.ts +1 -0
  84. package/src/api/device/DeviceUnlock.ts +9 -0
  85. package/src/api/device/DeviceWipe.ts +18 -0
  86. package/src/api/helpers/protocolV2FileWrite.ts +35 -11
  87. package/src/api/index.ts +1 -1
  88. package/src/api/protocol-v2/DeviceInfoGet.ts +0 -1
  89. package/src/api/protocol-v2/DeviceSessionOpen.ts +100 -0
  90. package/src/api/protocol-v2/DeviceSettingsPageShow.ts +9 -1
  91. package/src/api/protocol-v2/DeviceSettingsSet.ts +11 -1
  92. package/src/api/protocol-v2/DeviceStatusGet.ts +1 -0
  93. package/src/api/protocol-v2/DeviceUploadWallpaper.ts +2 -1
  94. package/src/core/deviceEventRegistration.ts +3 -8
  95. package/src/core/index.ts +36 -3
  96. package/src/data/messages/messages-protocol-v2.json +122 -23
  97. package/src/device/Device.ts +33 -41
  98. package/src/device/DeviceCommands.ts +22 -4
  99. package/src/device/DevicePool.ts +14 -6
  100. package/src/deviceProfile/buildDeviceFeatures.ts +21 -9
  101. package/src/deviceProfile/buildDeviceProfile.ts +27 -11
  102. package/src/events/device.ts +4 -0
  103. package/src/events/ui-request.ts +24 -2
  104. package/src/inject.ts +2 -2
  105. package/src/protocols/protocol-v2/features.ts +27 -20
  106. package/src/protocols/protocol-v2/index.ts +0 -1
  107. package/src/protocols/protocol-v2/uiInteraction.ts +209 -0
  108. package/src/protocols/protocol-v2/unlockRetry.ts +43 -3
  109. package/src/protocols/protocol-v2/walletSession.ts +122 -31
  110. package/src/types/api/getDeviceInfo.ts +6 -1
  111. package/src/types/api/index.ts +2 -2
  112. package/src/types/api/protocolV2.ts +5 -3
  113. package/src/types/device.ts +6 -1
  114. package/src/utils/deviceFeaturesUtils.ts +13 -0
  115. package/src/utils/homescreen.ts +10 -0
  116. package/dist/api/protocol-v2/DeviceSessionGet.d.ts +0 -6
  117. package/dist/api/protocol-v2/DeviceSessionGet.d.ts.map +0 -1
  118. package/src/api/protocol-v2/DeviceSessionGet.ts +0 -15
package/dist/index.js CHANGED
@@ -146,7 +146,7 @@ const createCoreApi = (call) => ({
146
146
  deviceInfoGet: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'deviceInfoGet' })),
147
147
  deviceStatusGet: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'deviceStatusGet' })),
148
148
  deviceGetOnboardingStatus: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'deviceGetOnboardingStatus' })),
149
- deviceSessionGet: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'deviceSessionGet' })),
149
+ deviceSessionOpen: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'deviceSessionOpen' })),
150
150
  deviceFirmwareUpdate: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'deviceFirmwareUpdate' })),
151
151
  deviceGetFirmwareUpdateStatus: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'deviceGetFirmwareUpdateStatus' })),
152
152
  deviceFactoryInfoSet: (connectId, params) => call(Object.assign(Object.assign({}, params), { connectId, method: 'deviceFactoryInfoSet' })),
@@ -25779,7 +25779,7 @@ var nested = {
25779
25779
  MessageType_DeviceStatus: 60603,
25780
25780
  MessageType_DevGetOnboardingStatus: 60604,
25781
25781
  MessageType_DevOnboardingStatus: 60605,
25782
- MessageType_DeviceSessionGet: 60606,
25782
+ MessageType_DeviceSessionOpen: 60606,
25783
25783
  MessageType_DeviceSession: 60607,
25784
25784
  MessageType_DeviceSessionAskPin: 60608,
25785
25785
  MessageType_FilesystemPermissionFix: 60800,
@@ -37765,14 +37765,77 @@ var nested = {
37765
37765
  }
37766
37766
  }
37767
37767
  },
37768
- DeviceSessionGet: {
37768
+ DeviceSessionResume: {
37769
37769
  fields: {
37770
37770
  session_id: {
37771
+ rule: "required",
37771
37772
  type: "bytes",
37772
37773
  id: 1
37773
37774
  }
37774
37775
  }
37775
37776
  },
37777
+ DeviceHostPassphrase: {
37778
+ fields: {
37779
+ passphrase: {
37780
+ rule: "required",
37781
+ type: "string",
37782
+ id: 1
37783
+ }
37784
+ }
37785
+ },
37786
+ DevicePassphraseOnDevice: {
37787
+ fields: {
37788
+ }
37789
+ },
37790
+ DeviceAttachPinOnDevice: {
37791
+ fields: {
37792
+ }
37793
+ },
37794
+ DeviceWalletSelect: {
37795
+ oneofs: {
37796
+ access: {
37797
+ oneof: [
37798
+ "host_passphrase",
37799
+ "passphrase_on_device",
37800
+ "attach_pin_on_device"
37801
+ ]
37802
+ }
37803
+ },
37804
+ fields: {
37805
+ host_passphrase: {
37806
+ type: "DeviceHostPassphrase",
37807
+ id: 1
37808
+ },
37809
+ passphrase_on_device: {
37810
+ type: "DevicePassphraseOnDevice",
37811
+ id: 2
37812
+ },
37813
+ attach_pin_on_device: {
37814
+ type: "DeviceAttachPinOnDevice",
37815
+ id: 3
37816
+ }
37817
+ }
37818
+ },
37819
+ DeviceSessionOpen: {
37820
+ oneofs: {
37821
+ mode: {
37822
+ oneof: [
37823
+ "resume",
37824
+ "select"
37825
+ ]
37826
+ }
37827
+ },
37828
+ fields: {
37829
+ resume: {
37830
+ type: "DeviceSessionResume",
37831
+ id: 1
37832
+ },
37833
+ select: {
37834
+ type: "DeviceWalletSelect",
37835
+ id: 2
37836
+ }
37837
+ }
37838
+ },
37776
37839
  DeviceSession: {
37777
37840
  fields: {
37778
37841
  session_id: {
@@ -37830,21 +37893,59 @@ var nested = {
37830
37893
  fields: {
37831
37894
  }
37832
37895
  },
37833
- DevOnboardingStage: {
37896
+ DevOnboardingStep: {
37897
+ values: {
37898
+ DEV_ONBOARDING_STEP_UNKNOWN: 0,
37899
+ DEV_ONBOARDING_STEP_CHECKING: 1,
37900
+ DEV_ONBOARDING_STEP_PERSONALIZATION: 2,
37901
+ DEV_ONBOARDING_STEP_PIN: 3,
37902
+ DEV_ONBOARDING_STEP_SETUP: 4,
37903
+ DEV_ONBOARDING_STEP_DONE: 5
37904
+ }
37905
+ },
37906
+ DevOnboardingPhase: {
37907
+ values: {
37908
+ DEV_ONBOARDING_PHASE_UNKNOWN: 0,
37909
+ DEV_ONBOARDING_PHASE_SAFETY_CHECK: 1,
37910
+ DEV_ONBOARDING_PHASE_PIN_SETUP: 2,
37911
+ DEV_ONBOARDING_PHASE_FINGERPRINT_SETUP: 3,
37912
+ DEV_ONBOARDING_PHASE_SETUP_CHOICE: 4,
37913
+ DEV_ONBOARDING_PHASE_WALLET_CREATE_START: 5,
37914
+ DEV_ONBOARDING_PHASE_RECOVERY_PHRASE_VIEW: 6,
37915
+ DEV_ONBOARDING_PHASE_RECOVERY_PHRASE_CONFIRM: 7,
37916
+ DEV_ONBOARDING_PHASE_RESTORE_METHOD_CHOICE: 8,
37917
+ DEV_ONBOARDING_PHASE_RECOVERY_PHRASE_RESTORE: 9,
37918
+ DEV_ONBOARDING_PHASE_SEEDCARD_RESTORE: 10,
37919
+ DEV_ONBOARDING_PHASE_WALLET_READY: 11,
37920
+ DEV_ONBOARDING_PHASE_SEEDCARD_BACKUP_PROMPT: 12,
37921
+ DEV_ONBOARDING_PHASE_SEEDCARD_BACKUP: 13
37922
+ }
37923
+ },
37924
+ DevOnboardingSetupKind: {
37925
+ values: {
37926
+ DEV_ONBOARDING_SETUP_KIND_UNKNOWN: 0,
37927
+ DEV_ONBOARDING_SETUP_KIND_CHOICE: 1,
37928
+ DEV_ONBOARDING_SETUP_KIND_CREATE: 2,
37929
+ DEV_ONBOARDING_SETUP_KIND_RESTORE: 3
37930
+ }
37931
+ },
37932
+ DevOnboardingSetupMethod: {
37834
37933
  values: {
37835
- DEV_ONBOARDING_STAGE_UNKNOWN: 0,
37836
- DEV_ONBOARDING_STAGE_SAFETY_CHECK: 1,
37837
- DEV_ONBOARDING_STAGE_PERSONALIZATION: 2,
37838
- DEV_ONBOARDING_STAGE_SELECT_SETUP_METHOD: 3,
37839
- DEV_ONBOARDING_STAGE_NEW_DEVICE: 4,
37840
- DEV_ONBOARDING_STAGE_SELECT_RESTORE_METHOD: 5,
37841
- DEV_ONBOARDING_STAGE_RESTORE_MNEMONIC: 6,
37842
- DEV_ONBOARDING_STAGE_RESTORE_SEEDCARD: 7,
37843
- DEV_ONBOARDING_STAGE_WALLET_READY: 8,
37844
- DEV_ONBOARDING_STAGE_SEEDCARD_BACKUP_PROMPT: 9,
37845
- DEV_ONBOARDING_STAGE_SELECT_SEEDCARD_BACKUP_METHOD: 10,
37846
- DEV_ONBOARDING_STAGE_SEEDCARD_BACKUP: 11,
37847
- DEV_ONBOARDING_STAGE_DONE: 12
37934
+ DEV_ONBOARDING_SETUP_METHOD_UNKNOWN: 0,
37935
+ DEV_ONBOARDING_SETUP_METHOD_RECOVERY_PHRASE: 1,
37936
+ DEV_ONBOARDING_SETUP_METHOD_SEEDCARD: 2
37937
+ }
37938
+ },
37939
+ DevOnboardingSetupStatus: {
37940
+ fields: {
37941
+ kind: {
37942
+ type: "DevOnboardingSetupKind",
37943
+ id: 1
37944
+ },
37945
+ method: {
37946
+ type: "DevOnboardingSetupMethod",
37947
+ id: 2
37948
+ }
37848
37949
  }
37849
37950
  },
37850
37951
  DevGetOnboardingStatus: {
@@ -37853,18 +37954,25 @@ var nested = {
37853
37954
  },
37854
37955
  DevOnboardingStatus: {
37855
37956
  fields: {
37856
- stage: {
37857
- rule: "required",
37858
- type: "DevOnboardingStage",
37957
+ step: {
37958
+ type: "DevOnboardingStep",
37859
37959
  id: 1
37860
37960
  },
37861
- status_code: {
37862
- type: "uint32",
37961
+ phase: {
37962
+ type: "DevOnboardingPhase",
37863
37963
  id: 2
37864
37964
  },
37865
- detail_code: {
37866
- type: "uint32",
37965
+ setup: {
37966
+ type: "DevOnboardingSetupStatus",
37867
37967
  id: 3
37968
+ },
37969
+ pin_set: {
37970
+ type: "bool",
37971
+ id: 4
37972
+ },
37973
+ wallet_initialized: {
37974
+ type: "bool",
37975
+ id: 5
37868
37976
  }
37869
37977
  }
37870
37978
  },
@@ -39250,6 +39358,197 @@ const PROTOBUF_MESSAGE_CONFIG = {
39250
39358
  ],
39251
39359
  };
39252
39360
 
39361
+ const CORE_EVENT = 'CORE_EVENT';
39362
+ const parseMessage = (messageData) => {
39363
+ const { data } = messageData;
39364
+ const message = {
39365
+ event: data.event,
39366
+ type: data.type,
39367
+ payload: data.payload,
39368
+ };
39369
+ if (typeof messageData.id === 'number') {
39370
+ message.id = messageData.id;
39371
+ }
39372
+ if (typeof message.success === 'boolean') {
39373
+ message.success = data.success;
39374
+ }
39375
+ return message;
39376
+ };
39377
+ const createErrorMessage = (error) => {
39378
+ let payload = { error: error.message, code: error.code };
39379
+ if (error instanceof hdShared.HardwareError) {
39380
+ payload = { error: error.message, code: error.errorCode };
39381
+ }
39382
+ return {
39383
+ success: false,
39384
+ payload,
39385
+ };
39386
+ };
39387
+
39388
+ const UI_EVENT = 'UI_EVENT';
39389
+ const UI_REQUEST = {
39390
+ REQUEST_PIN: 'ui-request_pin',
39391
+ INVALID_PIN: 'ui-invalid_pin',
39392
+ REQUEST_BUTTON: 'ui-button',
39393
+ REQUEST_PASSPHRASE: 'ui-request_passphrase',
39394
+ REQUEST_PASSPHRASE_ON_DEVICE: 'ui-request_passphrase_on_device',
39395
+ REQUEST_DEVICE_IN_BOOTLOADER_FOR_WEB_DEVICE: 'ui-request_select_device_in_bootloader_for_web_device',
39396
+ REQUEST_DEVICE_FOR_SWITCH_FIRMWARE_WEB_DEVICE: 'ui-request_select_device_for_switch_firmware_web_device',
39397
+ CLOSE_UI_WINDOW: 'ui-close_window',
39398
+ CLOSE_UI_PIN_WINDOW: 'ui-close_pin_window',
39399
+ DEVICE_PROGRESS: 'ui-device_progress',
39400
+ BLUETOOTH_PERMISSION: 'ui-bluetooth_permission',
39401
+ BLUETOOTH_UNSUPPORTED: 'ui-bluetooth_unsupported',
39402
+ BLUETOOTH_POWERED_OFF: 'ui-bluetooth_powered_off',
39403
+ BLUETOOTH_CHARACTERISTIC_NOTIFY_CHANGE_FAILURE: 'ui-bluetooth_characteristic_notify_change_failure',
39404
+ LOCATION_PERMISSION: 'ui-location_permission',
39405
+ LOCATION_SERVICE_PERMISSION: 'ui-location_service_permission',
39406
+ FIRMWARE_PROCESSING: 'ui-firmware-processing',
39407
+ FIRMWARE_PROGRESS: 'ui-firmware-progress',
39408
+ FIRMWARE_TIP: 'ui-firmware-tip',
39409
+ PREVIOUS_ADDRESS_RESULT: 'ui-previous_address_result',
39410
+ WEB_DEVICE_PROMPT_ACCESS_PERMISSION: 'ui-web_device_prompt_access_permission',
39411
+ BOOTLOADER: 'ui-device_bootloader_mode',
39412
+ NOT_IN_BOOTLOADER: 'ui-device_not_in_bootloader_mode',
39413
+ REQUIRE_MODE: 'ui-device_require_mode',
39414
+ NOT_INITIALIZE: 'ui-device_not_initialized',
39415
+ SEEDLESS: 'ui-device_seedless',
39416
+ FIRMWARE_OLD: 'ui-device_firmware_old',
39417
+ FIRMWARE_NOT_SUPPORTED: 'ui-device_firmware_unsupported',
39418
+ FIRMWARE_NOT_COMPATIBLE: 'ui-device_firmware_not_compatible',
39419
+ FIRMWARE_NOT_INSTALLED: 'ui-device_firmware_not_installed',
39420
+ NOT_USE_ONEKEY_DEVICE: 'ui-device_please_use_onekey_device',
39421
+ };
39422
+ exports.FirmwareUpdateTipMessage = void 0;
39423
+ (function (FirmwareUpdateTipMessage) {
39424
+ FirmwareUpdateTipMessage["CheckLatestUiResource"] = "CheckLatestUiResource";
39425
+ FirmwareUpdateTipMessage["StartDownloadFirmware"] = "StartDownloadFirmware";
39426
+ FirmwareUpdateTipMessage["FinishDownloadFirmware"] = "FinishDownloadFirmware";
39427
+ FirmwareUpdateTipMessage["DownloadLatestUiResource"] = "DownloadLatestUiResource";
39428
+ FirmwareUpdateTipMessage["DownloadFirmware"] = "DownloadFirmware";
39429
+ FirmwareUpdateTipMessage["DownloadBleFirmware"] = "DownloadBleFirmware";
39430
+ FirmwareUpdateTipMessage["DownloadLatestBootloaderResource"] = "DownloadLatestBootloaderResource";
39431
+ FirmwareUpdateTipMessage["DownloadLatestUiResourceSuccess"] = "DownloadLatestUiResourceSuccess";
39432
+ FirmwareUpdateTipMessage["DownloadFirmwareSuccess"] = "DownloadFirmwareSuccess";
39433
+ FirmwareUpdateTipMessage["DownloadBleFirmwareSuccess"] = "DownloadBleFirmwareSuccess";
39434
+ FirmwareUpdateTipMessage["DownloadLatestBootloaderResourceSuccess"] = "DownloadLatestBootloaderResourceSuccess";
39435
+ FirmwareUpdateTipMessage["AutoRebootToBootloader"] = "AutoRebootToBootloader";
39436
+ FirmwareUpdateTipMessage["GoToBootloaderSuccess"] = "GoToBootloaderSuccess";
39437
+ FirmwareUpdateTipMessage["SelectDeviceInBootloaderForWebDevice"] = "SelectDeviceInBootloaderForWebDevice";
39438
+ FirmwareUpdateTipMessage["SwitchFirmwareReconnectDevice"] = "SwitchFirmwareReconnectDevice";
39439
+ FirmwareUpdateTipMessage["ConfirmOnDevice"] = "ConfirmOnDevice";
39440
+ FirmwareUpdateTipMessage["FirmwareEraseSuccess"] = "FirmwareEraseSuccess";
39441
+ FirmwareUpdateTipMessage["StartTransferData"] = "StartTransferData";
39442
+ FirmwareUpdateTipMessage["InstallingFirmware"] = "InstallingFirmware";
39443
+ FirmwareUpdateTipMessage["UpdateBootloader"] = "UpdateBootloader";
39444
+ FirmwareUpdateTipMessage["UpdateBootloaderSuccess"] = "UpdateBootloaderSuccess";
39445
+ FirmwareUpdateTipMessage["UpdateSysResource"] = "UpdateSysResource";
39446
+ FirmwareUpdateTipMessage["UpdateSysResourceSuccess"] = "UpdateSysResourceSuccess";
39447
+ FirmwareUpdateTipMessage["FirmwareUpdating"] = "FirmwareUpdating";
39448
+ FirmwareUpdateTipMessage["FirmwareUpdateCompleted"] = "FirmwareUpdateCompleted";
39449
+ })(exports.FirmwareUpdateTipMessage || (exports.FirmwareUpdateTipMessage = {}));
39450
+ const createUiMessage = (type, payload) => ({
39451
+ event: UI_EVENT,
39452
+ type,
39453
+ payload,
39454
+ });
39455
+
39456
+ const IFRAME = {
39457
+ INIT: 'iframe-init',
39458
+ INIT_BRIDGE: 'iframe-init-bridge',
39459
+ CALL: 'iframe-call',
39460
+ CANCEL: 'iframe-cancel',
39461
+ CANCEL_OPERATION: 'iframe-cancel-operation',
39462
+ SWITCH_TRANSPORT: 'iframe-switch-transport',
39463
+ CALLBACK: 'iframe-callback',
39464
+ };
39465
+ const createIFrameMessage = (type, payload) => ({
39466
+ event: UI_EVENT,
39467
+ type,
39468
+ payload,
39469
+ });
39470
+
39471
+ const RESPONSE_EVENT = 'RESPONSE_EVENT';
39472
+ const createResponseMessage = (id, success, payload) => ({
39473
+ event: RESPONSE_EVENT,
39474
+ type: RESPONSE_EVENT,
39475
+ id,
39476
+ success,
39477
+ payload: success ? payload : hdShared.serializeError(payload),
39478
+ });
39479
+
39480
+ const UI_RESPONSE = {
39481
+ RECEIVE_PIN: 'ui-receive_pin',
39482
+ RECEIVE_PASSPHRASE: 'ui-receive_passphrase',
39483
+ SELECT_DEVICE_IN_BOOTLOADER_FOR_WEB_DEVICE: 'ui-receive_select-device-in-bootloader-for-web-device',
39484
+ SELECT_DEVICE_FOR_SWITCH_FIRMWARE_WEB_DEVICE: 'ui-receive_select-device-for-switch-firmware-web-device',
39485
+ };
39486
+ const createUiResponse = (type, payload) => ({
39487
+ event: UI_EVENT,
39488
+ type,
39489
+ payload,
39490
+ });
39491
+
39492
+ const DEVICE_EVENT = 'DEVICE_EVENT';
39493
+ const DEVICE = {
39494
+ CONNECT: 'device-connect',
39495
+ CONNECT_UNACQUIRED: 'device-connect_unacquired',
39496
+ DISCONNECT: 'device-disconnect',
39497
+ CHANGED: 'device-changed',
39498
+ ACQUIRE: 'device-acquire',
39499
+ RELEASE: 'device-release',
39500
+ ACQUIRED: 'device-acquired',
39501
+ RELEASED: 'device-released',
39502
+ USED_ELSEWHERE: 'device-used_elsewhere',
39503
+ UNREADABLE: 'unreadable-device',
39504
+ LOADING: 'device-loading',
39505
+ BUTTON: 'button',
39506
+ PIN: 'pin',
39507
+ PASSPHRASE: 'passphrase',
39508
+ PASSPHRASE_ON_DEVICE: 'passphrase_on_device',
39509
+ ATTACH_PIN_ON_DEVICE: 'attach_pin_on_device',
39510
+ WORD: 'word',
39511
+ SUPPORT_FEATURES: 'support_features',
39512
+ SELECT_DEVICE_IN_BOOTLOADER_FOR_WEB_DEVICE: 'select_device_in_bootloader_for_web_device',
39513
+ SELECT_DEVICE_FOR_SWITCH_FIRMWARE_WEB_DEVICE: 'select_device_for_switch_firmware_web_device',
39514
+ FEATURES: 'features',
39515
+ };
39516
+ const createDeviceMessage = (type, payload) => ({
39517
+ event: DEVICE_EVENT,
39518
+ type,
39519
+ payload,
39520
+ });
39521
+
39522
+ const FIRMWARE_EVENT = 'FIRMWARE_EVENT';
39523
+ const FIRMWARE = {
39524
+ RELEASE_INFO: 'firmware-release-info',
39525
+ BLE_RELEASE_INFO: 'ble-firmware-release-info',
39526
+ };
39527
+ const createFirmwareMessage = (type, payload) => ({
39528
+ event: FIRMWARE_EVENT,
39529
+ type,
39530
+ payload,
39531
+ });
39532
+
39533
+ const LogBlockEvent = new Set([
39534
+ UI_RESPONSE.RECEIVE_PIN,
39535
+ UI_RESPONSE.RECEIVE_PASSPHRASE,
39536
+ ]);
39537
+ const LogBlockMethod = new Set(['evmSignTypedData']);
39538
+ function getLogBlockLabel(message) {
39539
+ if (!message || typeof message !== 'object')
39540
+ return undefined;
39541
+ const { type, payload, method } = message;
39542
+ if (type && LogBlockEvent.has(type)) {
39543
+ return type;
39544
+ }
39545
+ const methodName = method !== null && method !== void 0 ? method : payload === null || payload === void 0 ? void 0 : payload.method;
39546
+ if (methodName && LogBlockMethod.has(methodName)) {
39547
+ return methodName;
39548
+ }
39549
+ return undefined;
39550
+ }
39551
+
39253
39552
  function isDeviceLockedError(error) {
39254
39553
  return (typeof error === 'object' &&
39255
39554
  error !== null &&
@@ -39271,7 +39570,14 @@ const getErrorText = (error) => {
39271
39570
  return String(error !== null && error !== void 0 ? error : '');
39272
39571
  };
39273
39572
  const isProtocolV2InvalidSessionError = (error) => getErrorText(error).toLowerCase().includes('failure_invalidsession');
39274
- function requestProtocolV2DeviceStatus(device) {
39573
+ const normalizeHostPassphrase = (passphrase) => {
39574
+ const normalized = (passphrase !== null && passphrase !== void 0 ? passphrase : '').normalize('NFKD');
39575
+ if (!normalized || normalized.includes('\0') || normalized.length > 50) {
39576
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.CallMethodInvalidParameter, 'Invalid hidden wallet passphrase.');
39577
+ }
39578
+ return normalized;
39579
+ };
39580
+ function requestProtocolV2DeviceStatus$1(device) {
39275
39581
  return __awaiter(this, void 0, void 0, function* () {
39276
39582
  const { message } = yield device.commands.typedCall('DeviceStatusGet', 'DeviceStatus', {});
39277
39583
  return message;
@@ -39279,57 +39585,118 @@ function requestProtocolV2DeviceStatus(device) {
39279
39585
  }
39280
39586
  function refreshProtocolV2DeviceStatus(device) {
39281
39587
  return __awaiter(this, void 0, void 0, function* () {
39282
- const status = yield requestProtocolV2DeviceStatus(device);
39588
+ const status = yield requestProtocolV2DeviceStatus$1(device);
39283
39589
  return device.updateProtocolV2Status(status);
39284
39590
  });
39285
39591
  }
39592
+ const openDeviceSession = (device, request) => __awaiter(void 0, void 0, void 0, function* () {
39593
+ try {
39594
+ return yield device.commands.typedCall('DeviceSessionOpen', 'DeviceSession', request);
39595
+ }
39596
+ catch (error) {
39597
+ if (!isDeviceLockedError(error)) {
39598
+ throw error;
39599
+ }
39600
+ yield device.unlockDevice();
39601
+ return device.commands.typedCall('DeviceSessionOpen', 'DeviceSession', request);
39602
+ }
39603
+ });
39604
+ const createHiddenWalletRequest = (response) => {
39605
+ if (response.attachPinOnDevice) {
39606
+ return {
39607
+ request: {
39608
+ select: {
39609
+ attach_pin_on_device: {},
39610
+ },
39611
+ },
39612
+ deviceEvent: DEVICE.ATTACH_PIN_ON_DEVICE,
39613
+ };
39614
+ }
39615
+ if (response.passphraseOnDevice) {
39616
+ return {
39617
+ request: {
39618
+ select: {
39619
+ passphrase_on_device: {},
39620
+ },
39621
+ },
39622
+ deviceEvent: DEVICE.PASSPHRASE_ON_DEVICE,
39623
+ };
39624
+ }
39625
+ return {
39626
+ request: {
39627
+ select: {
39628
+ host_passphrase: { passphrase: normalizeHostPassphrase(response.passphrase) },
39629
+ },
39630
+ },
39631
+ };
39632
+ };
39633
+ const openSelectedHiddenWallet = (device, promptPayload) => __awaiter(void 0, void 0, void 0, function* () {
39634
+ const response = yield device.commands.promptPassphrase(promptPayload, {
39635
+ cancelDeviceOnReject: false,
39636
+ });
39637
+ const { request, deviceEvent } = createHiddenWalletRequest(response);
39638
+ if (deviceEvent) {
39639
+ device.emit(deviceEvent, device, promptPayload);
39640
+ }
39641
+ return openDeviceSession(device, request);
39642
+ });
39286
39643
  function getProtocolV2WalletSession(device, options) {
39287
- var _a, _b, _c, _d;
39644
+ var _a, _b, _c, _d, _e, _f;
39288
39645
  return __awaiter(this, void 0, void 0, function* () {
39289
39646
  if (options === null || options === void 0 ? void 0 : options.initSession) {
39290
39647
  device.clearInternalState();
39291
39648
  }
39292
- let sessionId = typeof device.getInternalState === 'function' ? device.getInternalState() : undefined;
39649
+ const expectedPassphraseState = (_a = options === null || options === void 0 ? void 0 : options.expectedPassphraseState) !== null && _a !== void 0 ? _a : device.passphraseState;
39293
39650
  try {
39294
- const requestDeviceSession = (sessionId) => device.commands.typedCall('DeviceSessionGet', 'DeviceSession', sessionId ? { session_id: sessionId } : {});
39295
- const requestWalletSession = () => __awaiter(this, void 0, void 0, function* () {
39651
+ if (((_b = device.features) === null || _b === void 0 ? void 0 : _b.unlocked) === false) {
39652
+ yield device.unlockDevice();
39653
+ }
39654
+ if ((options === null || options === void 0 ? void 0 : options.onlyMainPin) || device.getCurrentPassphraseProtection() === false) {
39655
+ return {
39656
+ passphraseState: undefined,
39657
+ newSession: undefined,
39658
+ unlockedAttachPin: false,
39659
+ };
39660
+ }
39661
+ const cachedSessionId = typeof device.getInternalState === 'function' ? device.getInternalState() : undefined;
39662
+ let response;
39663
+ let recoveryFailed = false;
39664
+ if (cachedSessionId && expectedPassphraseState) {
39296
39665
  try {
39297
- return yield requestDeviceSession(sessionId);
39666
+ response = yield openDeviceSession(device, {
39667
+ resume: { session_id: cachedSessionId },
39668
+ });
39298
39669
  }
39299
39670
  catch (error) {
39300
- if (!sessionId || !isProtocolV2InvalidSessionError(error)) {
39671
+ if (!isProtocolV2InvalidSessionError(error)) {
39301
39672
  throw error;
39302
39673
  }
39303
39674
  device.clearInternalState();
39304
- sessionId = undefined;
39305
- return requestDeviceSession();
39675
+ recoveryFailed = true;
39306
39676
  }
39307
- });
39308
- let response;
39309
- try {
39310
- response = yield requestWalletSession();
39311
39677
  }
39312
- catch (error) {
39313
- if (!isDeviceLockedError(error)) {
39314
- throw error;
39315
- }
39316
- yield device.unlockDevice();
39317
- response = yield requestWalletSession();
39678
+ if (!response) {
39679
+ const promptPayload = {
39680
+ source: 'wallet-session-coordinator',
39681
+ reason: recoveryFailed ? 'session-recovery' : 'open-wallet',
39682
+ expectedPassphraseState,
39683
+ existsAttachPinUser: ((_c = device.features) === null || _c === void 0 ? void 0 : _c.attachToPinEnabled) === true,
39684
+ };
39685
+ response = yield openSelectedHiddenWallet(device, promptPayload);
39318
39686
  }
39319
39687
  const { message } = response;
39320
- if ((options === null || options === void 0 ? void 0 : options.expectedPassphraseState) &&
39321
- options.expectedPassphraseState !== message.btc_test_address) {
39688
+ if (expectedPassphraseState && expectedPassphraseState !== message.btc_test_address) {
39322
39689
  device.clearInternalState();
39323
39690
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceCheckPassphraseStateError);
39324
39691
  }
39325
39692
  if (message.btc_test_address && device.getCurrentPassphraseProtection() !== true) {
39326
39693
  yield refreshProtocolV2DeviceStatus(device);
39327
39694
  }
39328
- device.updateInternalState(((_a = device.getCurrentPassphraseProtection()) !== null && _a !== void 0 ? _a : false) || Boolean(message.btc_test_address), message.btc_test_address, device.getCurrentDeviceId(), message.session_id, (options === null || options === void 0 ? void 0 : options.initSession) ? null : (_b = device.features) === null || _b === void 0 ? void 0 : _b.sessionId);
39695
+ device.updateInternalState(true, message.btc_test_address, device.getCurrentDeviceId(), message.session_id, (options === null || options === void 0 ? void 0 : options.initSession) ? null : (_d = device.features) === null || _d === void 0 ? void 0 : _d.sessionId);
39329
39696
  return {
39330
39697
  passphraseState: message.btc_test_address,
39331
39698
  newSession: message.session_id,
39332
- unlockedAttachPin: (_d = (_c = device.features) === null || _c === void 0 ? void 0 : _c.unlockedAttachPin) !== null && _d !== void 0 ? _d : undefined,
39699
+ unlockedAttachPin: (_f = (_e = device.features) === null || _e === void 0 ? void 0 : _e.unlockedAttachPin) !== null && _f !== void 0 ? _f : undefined,
39333
39700
  };
39334
39701
  }
39335
39702
  catch (error) {
@@ -39350,6 +39717,14 @@ const getSupportProtocolV1MessageSchema = (features) => {
39350
39717
  };
39351
39718
  const currentDeviceVersion = getDeviceFirmwareVersion(features).join('.');
39352
39719
  const deviceType = getDeviceType(features);
39720
+ if (features.bootloaderMode === true &&
39721
+ features.firmwarePresent === false &&
39722
+ DeviceModelToTypes.model_mini.includes(deviceType)) {
39723
+ return {
39724
+ messages: DataManager.messages.v1CurrentSchema,
39725
+ protocolV1MessageSchema: 'v1CurrentSchema',
39726
+ };
39727
+ }
39353
39728
  const deviceVersionConfigs = PROTOBUF_MESSAGE_CONFIG[deviceType] ||
39354
39729
  (DeviceTypeToModels[deviceType] &&
39355
39730
  DeviceTypeToModels[deviceType]
@@ -39392,6 +39767,7 @@ const getPassphraseStateWithRefreshDeviceInfo = (device, options) => __awaiter(v
39392
39767
  return getProtocolV2WalletSession(device, {
39393
39768
  initSession: options === null || options === void 0 ? void 0 : options.initSession,
39394
39769
  expectedPassphraseState: options === null || options === void 0 ? void 0 : options.expectPassphraseState,
39770
+ onlyMainPin: options === null || options === void 0 ? void 0 : options.onlyMainPin,
39395
39771
  });
39396
39772
  }
39397
39773
  const { features } = device;
@@ -39429,6 +39805,7 @@ const getPassphraseState = (device, options) => __awaiter(void 0, void 0, void 0
39429
39805
  return getProtocolV2WalletSession(device, {
39430
39806
  initSession: options === null || options === void 0 ? void 0 : options.initSession,
39431
39807
  expectedPassphraseState: options === null || options === void 0 ? void 0 : options.expectPassphraseState,
39808
+ onlyMainPin: options === null || options === void 0 ? void 0 : options.onlyMainPin,
39432
39809
  });
39433
39810
  }
39434
39811
  const supportAttachPinCapability = existCapability(features, hdTransport.Enum_Capability.Capability_AttachToPin);
@@ -39831,6 +40208,93 @@ const getAutoShutDownOptions = (_deviceType) => {
39831
40208
  }
39832
40209
  };
39833
40210
 
40211
+ const PRO2_WALLPAPER_WIDTH = 604;
40212
+ const PRO2_WALLPAPER_HEIGHT = 1024;
40213
+ const COLOR_FORMAT_RGB565 = 0x12;
40214
+ const COLOR_FORMAT_RGB565A8 = 0x14;
40215
+ const RED_THRESHOLD = [
40216
+ 1, 7, 3, 5, 0, 8, 2, 6, 7, 1, 5, 3, 8, 0, 6, 2, 3, 5, 0, 8, 2, 6, 1, 7, 5, 3, 8,
40217
+ 0, 6, 2, 7, 1, 0, 8, 2, 6, 1, 7, 3, 5, 8, 0, 6, 2, 7, 1, 5, 3, 2, 6, 1, 7, 3, 5, 0,
40218
+ 8, 6, 2, 7, 1, 5, 3, 8, 0,
40219
+ ];
40220
+ const GREEN_THRESHOLD = [
40221
+ 1, 3, 2, 2, 3, 1, 2, 2, 2, 2, 0, 4, 2, 2, 4, 0, 3, 1, 2, 2, 1, 3, 2, 2, 2, 2, 4,
40222
+ 0, 2, 2, 0, 4, 1, 3, 2, 2, 3, 1, 2, 2, 2, 2, 0, 4, 2, 2, 4, 0, 3, 1, 2, 2, 1, 3, 2,
40223
+ 2, 2, 2, 4, 0, 2, 2, 0, 4,
40224
+ ];
40225
+ const BLUE_THRESHOLD = [
40226
+ 5, 3, 8, 0, 6, 2, 7, 1, 3, 5, 0, 8, 2, 6, 1, 7, 8, 0, 6, 2, 7, 1, 5, 3, 0, 8, 2,
40227
+ 6, 1, 7, 3, 5, 6, 2, 7, 1, 5, 3, 8, 0, 2, 6, 1, 7, 3, 5, 0, 8, 7, 1, 5, 3, 8, 0, 6,
40228
+ 2, 1, 7, 3, 5, 0, 8, 2, 6,
40229
+ ];
40230
+ function invalidParameter$2(message) {
40231
+ return hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.CallMethodInvalidParameter, message);
40232
+ }
40233
+ function asBytes(rgba) {
40234
+ return rgba instanceof Uint8Array ? rgba : new Uint8Array(rgba);
40235
+ }
40236
+ function align(value, boundary) {
40237
+ return Math.ceil(value / boundary) * boundary;
40238
+ }
40239
+ function encodePro2Wallpaper(options) {
40240
+ const { width, height } = options;
40241
+ if (!Number.isInteger(width) || width <= 0 || width > 0xffff) {
40242
+ throw invalidParameter$2('Wallpaper width must be an integer between 1 and 65535.');
40243
+ }
40244
+ if (!Number.isInteger(height) || height <= 0 || height > 0xffff) {
40245
+ throw invalidParameter$2('Wallpaper height must be an integer between 1 and 65535.');
40246
+ }
40247
+ const rgba = asBytes(options.rgba);
40248
+ const expectedLength = width * height * 4;
40249
+ if (rgba.byteLength !== expectedLength) {
40250
+ throw invalidParameter$2(`Wallpaper RGBA data length must be ${expectedLength} bytes, received ${rgba.byteLength}.`);
40251
+ }
40252
+ let hasTransparency = false;
40253
+ for (let index = 3; index < rgba.length; index += 4) {
40254
+ if (rgba[index] !== 0xff) {
40255
+ hasTransparency = true;
40256
+ break;
40257
+ }
40258
+ }
40259
+ const colorFormat = hasTransparency ? 'RGB565A8' : 'RGB565';
40260
+ const stride = align(width * 2, 4);
40261
+ const alphaStride = stride / 2;
40262
+ const rgbSize = stride * height;
40263
+ const alphaSize = hasTransparency ? alphaStride * height : 0;
40264
+ const data = new Uint8Array(12 + rgbSize + alphaSize);
40265
+ const view = new DataView(data.buffer);
40266
+ data[0] = 0x19;
40267
+ data[1] = hasTransparency ? COLOR_FORMAT_RGB565A8 : COLOR_FORMAT_RGB565;
40268
+ view.setUint16(2, 0, true);
40269
+ view.setUint16(4, width, true);
40270
+ view.setUint16(6, height, true);
40271
+ view.setUint16(8, stride, true);
40272
+ view.setUint16(10, 0, true);
40273
+ for (let y = 0; y < height; y += 1) {
40274
+ for (let x = 0; x < width; x += 1) {
40275
+ const sourceOffset = (y * width + x) * 4;
40276
+ const thresholdIndex = ((y & 7) << 3) + (x & 7);
40277
+ let red = Math.min(rgba[sourceOffset] + RED_THRESHOLD[thresholdIndex], 0xff) & 0xf8;
40278
+ let green = Math.min(rgba[sourceOffset + 1] + GREEN_THRESHOLD[thresholdIndex], 0xff) & 0xfc;
40279
+ let blue = Math.min(rgba[sourceOffset + 2] + BLUE_THRESHOLD[thresholdIndex], 0xff) & 0xf8;
40280
+ if (!hasTransparency) {
40281
+ const alpha = rgba[sourceOffset + 3];
40282
+ red = (red * alpha) >> 8;
40283
+ green = (green * alpha) >> 8;
40284
+ blue = (blue * alpha) >> 8;
40285
+ }
40286
+ const rgb565 = ((red >> 3) << 11) | ((green >> 2) << 5) | (blue >> 3);
40287
+ const rgbOffset = 12 + y * stride + x * 2;
40288
+ data[rgbOffset] = rgb565 & 0xff;
40289
+ data[rgbOffset + 1] = rgb565 >> 8;
40290
+ if (hasTransparency) {
40291
+ data[12 + rgbSize + y * alphaStride + x] = rgba[sourceOffset + 3];
40292
+ }
40293
+ }
40294
+ }
40295
+ return { data, colorFormat };
40296
+ }
40297
+
39834
40298
  const getT1Data = () => ({
39835
40299
  default: {
39836
40300
  name: 'default',
@@ -40114,6 +40578,14 @@ const getHomeScreenDefaultList = (features) => {
40114
40578
  return Object.keys(data);
40115
40579
  };
40116
40580
  const getHomeScreenSize = ({ deviceType, homeScreenType, thumbnail, }) => {
40581
+ if (deviceType === hdShared.EDeviceType.Pro2) {
40582
+ return thumbnail
40583
+ ? undefined
40584
+ : {
40585
+ width: PRO2_WALLPAPER_WIDTH,
40586
+ height: PRO2_WALLPAPER_HEIGHT,
40587
+ };
40588
+ }
40117
40589
  const sizes = {
40118
40590
  touch: {
40119
40591
  thumbnail: {
@@ -40136,93 +40608,6 @@ const getHomeScreenSize = ({ deviceType, homeScreenType, thumbnail, }) => {
40136
40608
  return thumbnail ? deviceConfig.thumbnail[homeScreenType] : deviceConfig.full;
40137
40609
  };
40138
40610
 
40139
- const PRO2_WALLPAPER_WIDTH = 604;
40140
- const PRO2_WALLPAPER_HEIGHT = 1024;
40141
- const COLOR_FORMAT_RGB565 = 0x12;
40142
- const COLOR_FORMAT_RGB565A8 = 0x14;
40143
- const RED_THRESHOLD = [
40144
- 1, 7, 3, 5, 0, 8, 2, 6, 7, 1, 5, 3, 8, 0, 6, 2, 3, 5, 0, 8, 2, 6, 1, 7, 5, 3, 8,
40145
- 0, 6, 2, 7, 1, 0, 8, 2, 6, 1, 7, 3, 5, 8, 0, 6, 2, 7, 1, 5, 3, 2, 6, 1, 7, 3, 5, 0,
40146
- 8, 6, 2, 7, 1, 5, 3, 8, 0,
40147
- ];
40148
- const GREEN_THRESHOLD = [
40149
- 1, 3, 2, 2, 3, 1, 2, 2, 2, 2, 0, 4, 2, 2, 4, 0, 3, 1, 2, 2, 1, 3, 2, 2, 2, 2, 4,
40150
- 0, 2, 2, 0, 4, 1, 3, 2, 2, 3, 1, 2, 2, 2, 2, 0, 4, 2, 2, 4, 0, 3, 1, 2, 2, 1, 3, 2,
40151
- 2, 2, 2, 4, 0, 2, 2, 0, 4,
40152
- ];
40153
- const BLUE_THRESHOLD = [
40154
- 5, 3, 8, 0, 6, 2, 7, 1, 3, 5, 0, 8, 2, 6, 1, 7, 8, 0, 6, 2, 7, 1, 5, 3, 0, 8, 2,
40155
- 6, 1, 7, 3, 5, 6, 2, 7, 1, 5, 3, 8, 0, 2, 6, 1, 7, 3, 5, 0, 8, 7, 1, 5, 3, 8, 0, 6,
40156
- 2, 1, 7, 3, 5, 0, 8, 2, 6,
40157
- ];
40158
- function invalidParameter$2(message) {
40159
- return hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.CallMethodInvalidParameter, message);
40160
- }
40161
- function asBytes(rgba) {
40162
- return rgba instanceof Uint8Array ? rgba : new Uint8Array(rgba);
40163
- }
40164
- function align(value, boundary) {
40165
- return Math.ceil(value / boundary) * boundary;
40166
- }
40167
- function encodePro2Wallpaper(options) {
40168
- const { width, height } = options;
40169
- if (!Number.isInteger(width) || width <= 0 || width > 0xffff) {
40170
- throw invalidParameter$2('Wallpaper width must be an integer between 1 and 65535.');
40171
- }
40172
- if (!Number.isInteger(height) || height <= 0 || height > 0xffff) {
40173
- throw invalidParameter$2('Wallpaper height must be an integer between 1 and 65535.');
40174
- }
40175
- const rgba = asBytes(options.rgba);
40176
- const expectedLength = width * height * 4;
40177
- if (rgba.byteLength !== expectedLength) {
40178
- throw invalidParameter$2(`Wallpaper RGBA data length must be ${expectedLength} bytes, received ${rgba.byteLength}.`);
40179
- }
40180
- let hasTransparency = false;
40181
- for (let index = 3; index < rgba.length; index += 4) {
40182
- if (rgba[index] !== 0xff) {
40183
- hasTransparency = true;
40184
- break;
40185
- }
40186
- }
40187
- const colorFormat = hasTransparency ? 'RGB565A8' : 'RGB565';
40188
- const stride = align(width * 2, 4);
40189
- const alphaStride = stride / 2;
40190
- const rgbSize = stride * height;
40191
- const alphaSize = hasTransparency ? alphaStride * height : 0;
40192
- const data = new Uint8Array(12 + rgbSize + alphaSize);
40193
- const view = new DataView(data.buffer);
40194
- data[0] = 0x19;
40195
- data[1] = hasTransparency ? COLOR_FORMAT_RGB565A8 : COLOR_FORMAT_RGB565;
40196
- view.setUint16(2, 0, true);
40197
- view.setUint16(4, width, true);
40198
- view.setUint16(6, height, true);
40199
- view.setUint16(8, stride, true);
40200
- view.setUint16(10, 0, true);
40201
- for (let y = 0; y < height; y += 1) {
40202
- for (let x = 0; x < width; x += 1) {
40203
- const sourceOffset = (y * width + x) * 4;
40204
- const thresholdIndex = ((y & 7) << 3) + (x & 7);
40205
- let red = Math.min(rgba[sourceOffset] + RED_THRESHOLD[thresholdIndex], 0xff) & 0xf8;
40206
- let green = Math.min(rgba[sourceOffset + 1] + GREEN_THRESHOLD[thresholdIndex], 0xff) & 0xfc;
40207
- let blue = Math.min(rgba[sourceOffset + 2] + BLUE_THRESHOLD[thresholdIndex], 0xff) & 0xf8;
40208
- if (!hasTransparency) {
40209
- const alpha = rgba[sourceOffset + 3];
40210
- red = (red * alpha) >> 8;
40211
- green = (green * alpha) >> 8;
40212
- blue = (blue * alpha) >> 8;
40213
- }
40214
- const rgb565 = ((red >> 3) << 11) | ((green >> 2) << 5) | (blue >> 3);
40215
- const rgbOffset = 12 + y * stride + x * 2;
40216
- data[rgbOffset] = rgb565 & 0xff;
40217
- data[rgbOffset + 1] = rgb565 >> 8;
40218
- if (hasTransparency) {
40219
- data[12 + rgbSize + y * alphaStride + x] = rgba[sourceOffset + 3];
40220
- }
40221
- }
40222
- }
40223
- return { data, colorFormat };
40224
- }
40225
-
40226
40611
  const isBleConnect = (env) => env === 'react-native' || env === 'lowlevel';
40227
40612
  const wait = (ms) => new Promise(resolve => {
40228
40613
  setTimeout(resolve, ms);
@@ -40252,196 +40637,6 @@ const getDefectiveDeviceInfo = (features) => {
40252
40637
  };
40253
40638
  };
40254
40639
 
40255
- const CORE_EVENT = 'CORE_EVENT';
40256
- const parseMessage = (messageData) => {
40257
- const { data } = messageData;
40258
- const message = {
40259
- event: data.event,
40260
- type: data.type,
40261
- payload: data.payload,
40262
- };
40263
- if (typeof messageData.id === 'number') {
40264
- message.id = messageData.id;
40265
- }
40266
- if (typeof message.success === 'boolean') {
40267
- message.success = data.success;
40268
- }
40269
- return message;
40270
- };
40271
- const createErrorMessage = (error) => {
40272
- let payload = { error: error.message, code: error.code };
40273
- if (error instanceof hdShared.HardwareError) {
40274
- payload = { error: error.message, code: error.errorCode };
40275
- }
40276
- return {
40277
- success: false,
40278
- payload,
40279
- };
40280
- };
40281
-
40282
- const UI_EVENT = 'UI_EVENT';
40283
- const UI_REQUEST = {
40284
- REQUEST_PIN: 'ui-request_pin',
40285
- INVALID_PIN: 'ui-invalid_pin',
40286
- REQUEST_BUTTON: 'ui-button',
40287
- REQUEST_PASSPHRASE: 'ui-request_passphrase',
40288
- REQUEST_PASSPHRASE_ON_DEVICE: 'ui-request_passphrase_on_device',
40289
- REQUEST_DEVICE_IN_BOOTLOADER_FOR_WEB_DEVICE: 'ui-request_select_device_in_bootloader_for_web_device',
40290
- REQUEST_DEVICE_FOR_SWITCH_FIRMWARE_WEB_DEVICE: 'ui-request_select_device_for_switch_firmware_web_device',
40291
- CLOSE_UI_WINDOW: 'ui-close_window',
40292
- CLOSE_UI_PIN_WINDOW: 'ui-close_pin_window',
40293
- DEVICE_PROGRESS: 'ui-device_progress',
40294
- BLUETOOTH_PERMISSION: 'ui-bluetooth_permission',
40295
- BLUETOOTH_UNSUPPORTED: 'ui-bluetooth_unsupported',
40296
- BLUETOOTH_POWERED_OFF: 'ui-bluetooth_powered_off',
40297
- BLUETOOTH_CHARACTERISTIC_NOTIFY_CHANGE_FAILURE: 'ui-bluetooth_characteristic_notify_change_failure',
40298
- LOCATION_PERMISSION: 'ui-location_permission',
40299
- LOCATION_SERVICE_PERMISSION: 'ui-location_service_permission',
40300
- FIRMWARE_PROCESSING: 'ui-firmware-processing',
40301
- FIRMWARE_PROGRESS: 'ui-firmware-progress',
40302
- FIRMWARE_TIP: 'ui-firmware-tip',
40303
- PREVIOUS_ADDRESS_RESULT: 'ui-previous_address_result',
40304
- WEB_DEVICE_PROMPT_ACCESS_PERMISSION: 'ui-web_device_prompt_access_permission',
40305
- BOOTLOADER: 'ui-device_bootloader_mode',
40306
- NOT_IN_BOOTLOADER: 'ui-device_not_in_bootloader_mode',
40307
- REQUIRE_MODE: 'ui-device_require_mode',
40308
- NOT_INITIALIZE: 'ui-device_not_initialized',
40309
- SEEDLESS: 'ui-device_seedless',
40310
- FIRMWARE_OLD: 'ui-device_firmware_old',
40311
- FIRMWARE_NOT_SUPPORTED: 'ui-device_firmware_unsupported',
40312
- FIRMWARE_NOT_COMPATIBLE: 'ui-device_firmware_not_compatible',
40313
- FIRMWARE_NOT_INSTALLED: 'ui-device_firmware_not_installed',
40314
- NOT_USE_ONEKEY_DEVICE: 'ui-device_please_use_onekey_device',
40315
- };
40316
- exports.FirmwareUpdateTipMessage = void 0;
40317
- (function (FirmwareUpdateTipMessage) {
40318
- FirmwareUpdateTipMessage["CheckLatestUiResource"] = "CheckLatestUiResource";
40319
- FirmwareUpdateTipMessage["StartDownloadFirmware"] = "StartDownloadFirmware";
40320
- FirmwareUpdateTipMessage["FinishDownloadFirmware"] = "FinishDownloadFirmware";
40321
- FirmwareUpdateTipMessage["DownloadLatestUiResource"] = "DownloadLatestUiResource";
40322
- FirmwareUpdateTipMessage["DownloadFirmware"] = "DownloadFirmware";
40323
- FirmwareUpdateTipMessage["DownloadBleFirmware"] = "DownloadBleFirmware";
40324
- FirmwareUpdateTipMessage["DownloadLatestBootloaderResource"] = "DownloadLatestBootloaderResource";
40325
- FirmwareUpdateTipMessage["DownloadLatestUiResourceSuccess"] = "DownloadLatestUiResourceSuccess";
40326
- FirmwareUpdateTipMessage["DownloadFirmwareSuccess"] = "DownloadFirmwareSuccess";
40327
- FirmwareUpdateTipMessage["DownloadBleFirmwareSuccess"] = "DownloadBleFirmwareSuccess";
40328
- FirmwareUpdateTipMessage["DownloadLatestBootloaderResourceSuccess"] = "DownloadLatestBootloaderResourceSuccess";
40329
- FirmwareUpdateTipMessage["AutoRebootToBootloader"] = "AutoRebootToBootloader";
40330
- FirmwareUpdateTipMessage["GoToBootloaderSuccess"] = "GoToBootloaderSuccess";
40331
- FirmwareUpdateTipMessage["SelectDeviceInBootloaderForWebDevice"] = "SelectDeviceInBootloaderForWebDevice";
40332
- FirmwareUpdateTipMessage["SwitchFirmwareReconnectDevice"] = "SwitchFirmwareReconnectDevice";
40333
- FirmwareUpdateTipMessage["ConfirmOnDevice"] = "ConfirmOnDevice";
40334
- FirmwareUpdateTipMessage["FirmwareEraseSuccess"] = "FirmwareEraseSuccess";
40335
- FirmwareUpdateTipMessage["StartTransferData"] = "StartTransferData";
40336
- FirmwareUpdateTipMessage["InstallingFirmware"] = "InstallingFirmware";
40337
- FirmwareUpdateTipMessage["UpdateBootloader"] = "UpdateBootloader";
40338
- FirmwareUpdateTipMessage["UpdateBootloaderSuccess"] = "UpdateBootloaderSuccess";
40339
- FirmwareUpdateTipMessage["UpdateSysResource"] = "UpdateSysResource";
40340
- FirmwareUpdateTipMessage["UpdateSysResourceSuccess"] = "UpdateSysResourceSuccess";
40341
- FirmwareUpdateTipMessage["FirmwareUpdating"] = "FirmwareUpdating";
40342
- FirmwareUpdateTipMessage["FirmwareUpdateCompleted"] = "FirmwareUpdateCompleted";
40343
- })(exports.FirmwareUpdateTipMessage || (exports.FirmwareUpdateTipMessage = {}));
40344
- const createUiMessage = (type, payload) => ({
40345
- event: UI_EVENT,
40346
- type,
40347
- payload,
40348
- });
40349
-
40350
- const IFRAME = {
40351
- INIT: 'iframe-init',
40352
- INIT_BRIDGE: 'iframe-init-bridge',
40353
- CALL: 'iframe-call',
40354
- CANCEL: 'iframe-cancel',
40355
- CANCEL_OPERATION: 'iframe-cancel-operation',
40356
- SWITCH_TRANSPORT: 'iframe-switch-transport',
40357
- CALLBACK: 'iframe-callback',
40358
- };
40359
- const createIFrameMessage = (type, payload) => ({
40360
- event: UI_EVENT,
40361
- type,
40362
- payload,
40363
- });
40364
-
40365
- const RESPONSE_EVENT = 'RESPONSE_EVENT';
40366
- const createResponseMessage = (id, success, payload) => ({
40367
- event: RESPONSE_EVENT,
40368
- type: RESPONSE_EVENT,
40369
- id,
40370
- success,
40371
- payload: success ? payload : hdShared.serializeError(payload),
40372
- });
40373
-
40374
- const UI_RESPONSE = {
40375
- RECEIVE_PIN: 'ui-receive_pin',
40376
- RECEIVE_PASSPHRASE: 'ui-receive_passphrase',
40377
- SELECT_DEVICE_IN_BOOTLOADER_FOR_WEB_DEVICE: 'ui-receive_select-device-in-bootloader-for-web-device',
40378
- SELECT_DEVICE_FOR_SWITCH_FIRMWARE_WEB_DEVICE: 'ui-receive_select-device-for-switch-firmware-web-device',
40379
- };
40380
- const createUiResponse = (type, payload) => ({
40381
- event: UI_EVENT,
40382
- type,
40383
- payload,
40384
- });
40385
-
40386
- const DEVICE_EVENT = 'DEVICE_EVENT';
40387
- const DEVICE = {
40388
- CONNECT: 'device-connect',
40389
- CONNECT_UNACQUIRED: 'device-connect_unacquired',
40390
- DISCONNECT: 'device-disconnect',
40391
- CHANGED: 'device-changed',
40392
- ACQUIRE: 'device-acquire',
40393
- RELEASE: 'device-release',
40394
- ACQUIRED: 'device-acquired',
40395
- RELEASED: 'device-released',
40396
- USED_ELSEWHERE: 'device-used_elsewhere',
40397
- UNREADABLE: 'unreadable-device',
40398
- LOADING: 'device-loading',
40399
- BUTTON: 'button',
40400
- PIN: 'pin',
40401
- PASSPHRASE: 'passphrase',
40402
- PASSPHRASE_ON_DEVICE: 'passphrase_on_device',
40403
- WORD: 'word',
40404
- SUPPORT_FEATURES: 'support_features',
40405
- SELECT_DEVICE_IN_BOOTLOADER_FOR_WEB_DEVICE: 'select_device_in_bootloader_for_web_device',
40406
- SELECT_DEVICE_FOR_SWITCH_FIRMWARE_WEB_DEVICE: 'select_device_for_switch_firmware_web_device',
40407
- FEATURES: 'features',
40408
- };
40409
- const createDeviceMessage = (type, payload) => ({
40410
- event: DEVICE_EVENT,
40411
- type,
40412
- payload,
40413
- });
40414
-
40415
- const FIRMWARE_EVENT = 'FIRMWARE_EVENT';
40416
- const FIRMWARE = {
40417
- RELEASE_INFO: 'firmware-release-info',
40418
- BLE_RELEASE_INFO: 'ble-firmware-release-info',
40419
- };
40420
- const createFirmwareMessage = (type, payload) => ({
40421
- event: FIRMWARE_EVENT,
40422
- type,
40423
- payload,
40424
- });
40425
-
40426
- const LogBlockEvent = new Set([
40427
- UI_RESPONSE.RECEIVE_PIN,
40428
- UI_RESPONSE.RECEIVE_PASSPHRASE,
40429
- ]);
40430
- const LogBlockMethod = new Set(['evmSignTypedData']);
40431
- function getLogBlockLabel(message) {
40432
- if (!message || typeof message !== 'object')
40433
- return undefined;
40434
- const { type, payload, method } = message;
40435
- if (type && LogBlockEvent.has(type)) {
40436
- return type;
40437
- }
40438
- const methodName = method !== null && method !== void 0 ? method : payload === null || payload === void 0 ? void 0 : payload.method;
40439
- if (methodName && LogBlockMethod.has(methodName)) {
40440
- return methodName;
40441
- }
40442
- return undefined;
40443
- }
40444
-
40445
40640
  const Log$g = getLogger(exports.LoggerNames.DevicePool);
40446
40641
  const getDiff = (current, descriptors) => {
40447
40642
  const connected = descriptors.filter(d => current.find(x => x.path === d.path) === undefined);
@@ -40484,8 +40679,7 @@ class DevicePool extends events.exports {
40484
40679
  this.connector = connector;
40485
40680
  }
40486
40681
  static getDevices(descriptorList, connectId, initOptions) {
40487
- var _a, descriptorList_1, descriptorList_1_1;
40488
- var _b, e_1, _c, _d;
40682
+ var _a, e_1, _b, _c;
40489
40683
  return __awaiter(this, void 0, void 0, function* () {
40490
40684
  const devices = {};
40491
40685
  const deviceList = [];
@@ -40497,17 +40691,21 @@ class DevicePool extends events.exports {
40497
40691
  device.updateDescriptor(exist, true);
40498
40692
  devices[connectId] = device;
40499
40693
  deviceList.push(device);
40500
- yield this._checkDevicePool(initOptions);
40694
+ yield this._checkDevicePool(initOptions, connectId);
40501
40695
  return { devices, deviceList };
40502
40696
  }
40503
40697
  Log$g.debug('found device in cache, but path is different: ', connectId);
40504
40698
  }
40505
40699
  }
40700
+ const matchedDescriptor = connectId
40701
+ ? descriptorList.find(descriptor => descriptor.path === connectId)
40702
+ : undefined;
40703
+ const descriptorsToInitialize = matchedDescriptor ? [matchedDescriptor] : descriptorList;
40506
40704
  try {
40507
- for (_a = true, descriptorList_1 = __asyncValues(descriptorList); descriptorList_1_1 = yield descriptorList_1.next(), _b = descriptorList_1_1.done, !_b; _a = true) {
40508
- _d = descriptorList_1_1.value;
40509
- _a = false;
40510
- const descriptor = _d;
40705
+ for (var _d = true, descriptorsToInitialize_1 = __asyncValues(descriptorsToInitialize), descriptorsToInitialize_1_1; descriptorsToInitialize_1_1 = yield descriptorsToInitialize_1.next(), _a = descriptorsToInitialize_1_1.done, !_a; _d = true) {
40706
+ _c = descriptorsToInitialize_1_1.value;
40707
+ _d = false;
40708
+ const descriptor = _c;
40511
40709
  const device = yield this._createDevice(descriptor, initOptions);
40512
40710
  const connectId = device.getConnectId();
40513
40711
  if (connectId) {
@@ -40524,11 +40722,11 @@ class DevicePool extends events.exports {
40524
40722
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
40525
40723
  finally {
40526
40724
  try {
40527
- if (!_a && !_b && (_c = descriptorList_1.return)) yield _c.call(descriptorList_1);
40725
+ if (!_d && !_a && (_b = descriptorsToInitialize_1.return)) yield _b.call(descriptorsToInitialize_1);
40528
40726
  }
40529
40727
  finally { if (e_1) throw e_1.error; }
40530
40728
  }
40531
- yield this._checkDevicePool(initOptions);
40729
+ yield this._checkDevicePool(initOptions, matchedDescriptor ? connectId : undefined);
40532
40730
  return { devices, deviceList };
40533
40731
  });
40534
40732
  }
@@ -40550,16 +40748,19 @@ class DevicePool extends events.exports {
40550
40748
  return device;
40551
40749
  });
40552
40750
  }
40553
- static _checkDevicePool(initOptions) {
40751
+ static _checkDevicePool(initOptions, connectId) {
40554
40752
  return __awaiter(this, void 0, void 0, function* () {
40555
- yield this._sendConnectMessage(initOptions);
40753
+ yield this._sendConnectMessage(initOptions, connectId);
40556
40754
  this._sendDisconnectMessage();
40557
40755
  });
40558
40756
  }
40559
- static _sendConnectMessage(initOptions) {
40757
+ static _sendConnectMessage(initOptions, connectId) {
40560
40758
  return __awaiter(this, void 0, void 0, function* () {
40561
40759
  for (let i = this.connectedPool.length - 1; i >= 0; i--) {
40562
40760
  const descriptor = this.connectedPool[i];
40761
+ if (connectId && descriptor.path !== connectId) {
40762
+ continue;
40763
+ }
40563
40764
  const device = yield this._createDevice(descriptor, initOptions);
40564
40765
  Log$g.debug('emit DEVICE.CONNECT: ', device === null || device === void 0 ? void 0 : device.features);
40565
40766
  this.emitter.emit(DEVICE.CONNECT, device);
@@ -41246,7 +41447,7 @@ class DeviceCommands {
41246
41447
  }
41247
41448
  if (res.type === 'PassphraseRequest') {
41248
41449
  const existsAttachPinUser = res.message.exists_attach_pin_user;
41249
- return this._promptPassphrase({
41450
+ return this.promptPassphrase({
41250
41451
  existsAttachPinUser,
41251
41452
  }).then(response => {
41252
41453
  const { passphrase, passphraseOnDevice, attachPinOnDevice } = response;
@@ -41310,22 +41511,31 @@ class DeviceCommands {
41310
41511
  }
41311
41512
  });
41312
41513
  }
41313
- _promptPassphrase(options) {
41514
+ promptPassphrase(options, promptOptions = {}) {
41314
41515
  return new Promise((resolve, reject) => {
41315
- const cancelAndReject = (_error) => cancelDeviceInPrompt(this.device, false)
41316
- .then(onCancel => {
41317
- const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.CallQueueActionCancelled, `${DEVICE.PASSPHRASE} canceled`);
41318
- if (onCancel) {
41319
- const { payload } = onCancel || {};
41320
- reject(error || new Error(payload === null || payload === void 0 ? void 0 : payload.message));
41321
- }
41322
- else {
41516
+ const cancelAndReject = (_error) => {
41517
+ const rejectWithCancelledError = () => {
41518
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.CallQueueActionCancelled, `${DEVICE.PASSPHRASE} canceled`));
41519
+ };
41520
+ if (promptOptions.cancelDeviceOnReject === false) {
41521
+ rejectWithCancelledError();
41522
+ return Promise.resolve();
41523
+ }
41524
+ return cancelDeviceInPrompt(this.device, false)
41525
+ .then(onCancel => {
41526
+ const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.CallQueueActionCancelled, `${DEVICE.PASSPHRASE} canceled`);
41527
+ if (onCancel) {
41528
+ const { payload } = onCancel || {};
41529
+ reject(error || new Error(payload === null || payload === void 0 ? void 0 : payload.message));
41530
+ }
41531
+ else {
41532
+ reject(error);
41533
+ }
41534
+ })
41535
+ .catch(error => {
41323
41536
  reject(error);
41324
- }
41325
- })
41326
- .catch(error => {
41327
- reject(error);
41328
- });
41537
+ });
41538
+ };
41329
41539
  if (this.device.listenerCount(DEVICE.PASSPHRASE) > 0) {
41330
41540
  this.device.setCancelableAction(cancelAndReject);
41331
41541
  this.device.emit(DEVICE.PASSPHRASE, this.device, options, (response, error) => {
@@ -41425,10 +41635,10 @@ class DeviceWalletSessionStore {
41425
41635
  }
41426
41636
  const deviceWalletSessionStore = new DeviceWalletSessionStore();
41427
41637
 
41428
- const isProtocolV2RomloaderDeviceInfo = (deviceInfo) => {
41638
+ const isProtocolV2RomloaderDeviceInfo = (deviceInfo, deviceStatus) => {
41429
41639
  var _a, _b, _c;
41430
41640
  return !!deviceInfo &&
41431
- deviceInfo.status == null &&
41641
+ deviceStatus == null &&
41432
41642
  ((_a = deviceInfo.fw) === null || _a === void 0 ? void 0 : _a.romloader) != null &&
41433
41643
  ((_b = deviceInfo.fw) === null || _b === void 0 ? void 0 : _b.application) == null &&
41434
41644
  ((_c = deviceInfo.fw) === null || _c === void 0 ? void 0 : _c.application_data) == null &&
@@ -41438,24 +41648,14 @@ const isProtocolV2RomloaderDeviceInfo = (deviceInfo) => {
41438
41648
  deviceInfo.se3 == null &&
41439
41649
  deviceInfo.se4 == null;
41440
41650
  };
41441
- const isProtocolV2BootloaderDeviceInfo = (deviceInfo) => !!deviceInfo && deviceInfo.status == null && !isProtocolV2RomloaderDeviceInfo(deviceInfo);
41651
+ const isProtocolV2BootloaderDeviceInfo = (deviceInfo, deviceStatus) => !!deviceInfo &&
41652
+ deviceStatus == null &&
41653
+ !isProtocolV2RomloaderDeviceInfo(deviceInfo, deviceStatus);
41442
41654
  const PROTOCOL_V2_FEATURES_DEVICE_INFO_REQUEST = {
41443
41655
  targets: {
41444
41656
  hw: true,
41445
41657
  fw: true,
41446
41658
  coprocessor: true,
41447
- status: true,
41448
- },
41449
- types: {
41450
- version: true,
41451
- specific: true,
41452
- },
41453
- };
41454
- const PROTOCOL_V2_STATUS_DEVICE_INFO_REQUEST = {
41455
- targets: {
41456
- hw: true,
41457
- coprocessor: true,
41458
- status: true,
41459
41659
  },
41460
41660
  types: {
41461
41661
  version: true,
@@ -41471,7 +41671,6 @@ const PROTOCOL_V2_VERSIONS_DEVICE_INFO_REQUEST = {
41471
41671
  se2: true,
41472
41672
  se3: true,
41473
41673
  se4: true,
41474
- status: true,
41475
41674
  },
41476
41675
  types: {
41477
41676
  version: true,
@@ -41487,7 +41686,6 @@ const PROTOCOL_V2_FULL_DEVICE_INFO_REQUEST = {
41487
41686
  se2: true,
41488
41687
  se3: true,
41489
41688
  se4: true,
41490
- status: true,
41491
41689
  },
41492
41690
  types: {
41493
41691
  version: true,
@@ -41506,6 +41704,12 @@ function requestProtocolV2DeviceInfo({ commands, timeoutMs = PROTOCOL_V2_DEVICE_
41506
41704
  return message;
41507
41705
  });
41508
41706
  }
41707
+ function requestProtocolV2DeviceStatus({ commands, }) {
41708
+ return __awaiter(this, void 0, void 0, function* () {
41709
+ const { message } = yield commands.typedCall('DeviceStatusGet', 'DeviceStatus', {});
41710
+ return message;
41711
+ });
41712
+ }
41509
41713
 
41510
41714
  const isMeaningfulVersion = (version) => Boolean(version && version !== '0.0.0');
41511
41715
  const firstMeaningfulVersion$1 = (...versions) => { var _a; return (_a = versions.find(isMeaningfulVersion)) !== null && _a !== void 0 ? _a : null; };
@@ -41545,13 +41749,12 @@ const getDeviceMode = (features) => {
41545
41749
  return 'normal';
41546
41750
  return 'unknown';
41547
41751
  };
41548
- const getProtocolV2Mode = (deviceInfo) => {
41549
- var _a;
41550
- if (isProtocolV2RomloaderDeviceInfo(deviceInfo))
41752
+ const getProtocolV2Mode = (deviceInfo, deviceStatus) => {
41753
+ if (isProtocolV2RomloaderDeviceInfo(deviceInfo, deviceStatus))
41551
41754
  return 'romloader';
41552
- if (isProtocolV2BootloaderDeviceInfo(deviceInfo))
41755
+ if (isProtocolV2BootloaderDeviceInfo(deviceInfo, deviceStatus))
41553
41756
  return 'bootloader';
41554
- const initialized = (_a = deviceInfo === null || deviceInfo === void 0 ? void 0 : deviceInfo.status) === null || _a === void 0 ? void 0 : _a.init_states;
41757
+ const initialized = deviceStatus === null || deviceStatus === void 0 ? void 0 : deviceStatus.init_states;
41555
41758
  if (initialized === false)
41556
41759
  return 'notInitialized';
41557
41760
  if (initialized === true)
@@ -41606,12 +41809,12 @@ const normalizeV1Status = (features) => {
41606
41809
  bleEnabled: (_k = features === null || features === void 0 ? void 0 : features.bleEnabled) !== null && _k !== void 0 ? _k : null,
41607
41810
  });
41608
41811
  };
41609
- const normalizeV2Status = (deviceInfo) => {
41812
+ const normalizeV2Status = (deviceInfo, deviceStatus) => {
41610
41813
  var _a, _b, _c, _d, _e, _f;
41611
- const status = deviceInfo === null || deviceInfo === void 0 ? void 0 : deviceInfo.status;
41612
- const bootloaderMode = isProtocolV2BootloaderDeviceInfo(deviceInfo);
41814
+ const status = deviceStatus;
41815
+ const bootloaderMode = isProtocolV2BootloaderDeviceInfo(deviceInfo, deviceStatus);
41613
41816
  return {
41614
- mode: getProtocolV2Mode(deviceInfo),
41817
+ mode: getProtocolV2Mode(deviceInfo, deviceStatus),
41615
41818
  initialized: (_a = status === null || status === void 0 ? void 0 : status.init_states) !== null && _a !== void 0 ? _a : null,
41616
41819
  bootloaderMode,
41617
41820
  unlocked: (_b = status === null || status === void 0 ? void 0 : status.unlocked) !== null && _b !== void 0 ? _b : null,
@@ -41683,7 +41886,7 @@ const normalizeV2Verify = (deviceInfo) => {
41683
41886
  se04BootHash: getImageHash$1((_z = info === null || info === void 0 ? void 0 : info.se4) === null || _z === void 0 ? void 0 : _z.bootloader),
41684
41887
  };
41685
41888
  };
41686
- const normalizeRaw = ({ features, protocolV1OneKeyFeatures, protocolV2DeviceInfo, }) => (Object.assign(Object.assign(Object.assign({}, (features ? { features } : {})), (protocolV1OneKeyFeatures ? { protocolV1OneKeyFeatures } : {})), (protocolV2DeviceInfo ? { protocolV2DeviceInfo } : {})));
41889
+ const normalizeRaw = ({ features, protocolV1OneKeyFeatures, protocolV2DeviceInfo, protocolV2DeviceStatus, }) => (Object.assign(Object.assign(Object.assign(Object.assign({}, (features ? { features } : {})), (protocolV1OneKeyFeatures ? { protocolV1OneKeyFeatures } : {})), (protocolV2DeviceInfo ? { protocolV2DeviceInfo } : {})), (protocolV2DeviceStatus ? { protocolV2DeviceStatus } : {})));
41687
41890
  function buildProfileFromProtocolV1({ protocol = 'V1', features, protocolV1OneKeyFeatures, sources = ['features'], scope = 'basic', includeRaw = false, }) {
41688
41891
  const sourceFeatures = features;
41689
41892
  const verify = normalizeV1Verify(sourceFeatures, protocolV1OneKeyFeatures);
@@ -41697,21 +41900,22 @@ function buildProfileFromProtocolV1({ protocol = 'V1', features, protocolV1OneKe
41697
41900
  }
41698
41901
  : {}));
41699
41902
  }
41700
- function buildProfileFromProtocolV2({ deviceInfo, sources = ['deviceInfo'], scope = 'basic', includeRaw = false, }) {
41701
- var _a, _b, _c, _d;
41903
+ function buildProfileFromProtocolV2({ deviceInfo, deviceStatus, sources = ['deviceInfo'], scope = 'basic', includeRaw = false, }) {
41904
+ var _a, _b, _c;
41702
41905
  const info = deviceInfo;
41703
- const deviceId = ((_a = info === null || info === void 0 ? void 0 : info.status) === null || _a === void 0 ? void 0 : _a.device_id) || '';
41704
- const serialNo = ((_b = deviceInfo === null || deviceInfo === void 0 ? void 0 : deviceInfo.hw) === null || _b === void 0 ? void 0 : _b.serial_no) || '';
41906
+ const deviceId = (deviceStatus === null || deviceStatus === void 0 ? void 0 : deviceStatus.device_id) || '';
41907
+ const serialNo = ((_a = deviceInfo === null || deviceInfo === void 0 ? void 0 : deviceInfo.hw) === null || _a === void 0 ? void 0 : _a.serial_no) || '';
41705
41908
  const label = null;
41706
- const bleName = (_d = (_c = info === null || info === void 0 ? void 0 : info.coprocessor) === null || _c === void 0 ? void 0 : _c.bt_adv_name) !== null && _d !== void 0 ? _d : null;
41909
+ const bleName = (_c = (_b = info === null || info === void 0 ? void 0 : info.coprocessor) === null || _b === void 0 ? void 0 : _b.bt_adv_name) !== null && _c !== void 0 ? _c : null;
41707
41910
  const verify = normalizeV2Verify(deviceInfo);
41708
41911
  return Object.assign(Object.assign({ protocol: 'V2', sources, deviceType: hdShared.EDeviceType.Pro2, firmwareType: hdShared.EFirmwareType.Universal, deviceId,
41709
41912
  serialNo,
41710
41913
  label,
41711
- bleName, status: normalizeV2Status(deviceInfo), versions: normalizeV2Versions(deviceInfo) }, (shouldIncludeVerify(scope) ? { verify } : {})), (includeRaw
41914
+ bleName, status: normalizeV2Status(deviceInfo, deviceStatus), versions: normalizeV2Versions(deviceInfo) }, (shouldIncludeVerify(scope) ? { verify } : {})), (includeRaw
41712
41915
  ? {
41713
41916
  raw: normalizeRaw({
41714
41917
  protocolV2DeviceInfo: deviceInfo,
41918
+ protocolV2DeviceStatus: deviceStatus,
41715
41919
  }),
41716
41920
  }
41717
41921
  : {}));
@@ -41846,14 +42050,14 @@ const buildProtocolV1FeaturesPayload = (protocolV1Features, previous) => {
41846
42050
  protocolV1Features,
41847
42051
  } });
41848
42052
  };
41849
- const buildProtocolV2FeaturesPayload = (deviceInfo, previous) => {
42053
+ const buildProtocolV2FeaturesPayload = ({ deviceInfo, deviceStatus, previous, }) => {
41850
42054
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, _65, _66, _67, _68, _69, _70;
41851
42055
  const info = deviceInfo;
41852
42056
  const fwApplication = (_a = info === null || info === void 0 ? void 0 : info.fw) === null || _a === void 0 ? void 0 : _a.application;
41853
42057
  const fwBootloader = (_b = info === null || info === void 0 ? void 0 : info.fw) === null || _b === void 0 ? void 0 : _b.bootloader;
41854
42058
  const fwBoard = (_c = info === null || info === void 0 ? void 0 : info.fw) === null || _c === void 0 ? void 0 : _c.romloader;
41855
42059
  const bleApplication = (_d = info === null || info === void 0 ? void 0 : info.coprocessor) === null || _d === void 0 ? void 0 : _d.application;
41856
- const status = info === null || info === void 0 ? void 0 : info.status;
42060
+ const status = deviceStatus;
41857
42061
  const firmwareVersion = firstMeaningfulVersion(getImageVersion(fwApplication), previous === null || previous === void 0 ? void 0 : previous.firmwareVersion);
41858
42062
  const bootloaderVersion = firstMeaningfulVersion(getImageVersion(fwBootloader), previous === null || previous === void 0 ? void 0 : previous.bootloaderVersion);
41859
42063
  const boardVersion = firstMeaningfulVersion(getImageVersion(fwBoard), previous === null || previous === void 0 ? void 0 : previous.boardVersion);
@@ -41863,15 +42067,15 @@ const buildProtocolV2FeaturesPayload = (deviceInfo, previous) => {
41863
42067
  const label = (_h = previous === null || previous === void 0 ? void 0 : previous.label) !== null && _h !== void 0 ? _h : null;
41864
42068
  const bleName = firstValue((_j = info === null || info === void 0 ? void 0 : info.coprocessor) === null || _j === void 0 ? void 0 : _j.bt_adv_name, previous === null || previous === void 0 ? void 0 : previous.bleName);
41865
42069
  const initialized = (_k = firstValue(status === null || status === void 0 ? void 0 : status.init_states, previous === null || previous === void 0 ? void 0 : previous.initialized)) !== null && _k !== void 0 ? _k : null;
41866
- const passphraseProtection = (_l = status === null || status === void 0 ? void 0 : status.passphrase_enabled) !== null && _l !== void 0 ? _l : null;
42070
+ const passphraseProtection = (status === null || status === void 0 ? void 0 : status.unlocked) === true ? (_l = status.passphrase_enabled) !== null && _l !== void 0 ? _l : null : null;
41867
42071
  const language = (_m = previous === null || previous === void 0 ? void 0 : previous.language) !== null && _m !== void 0 ? _m : null;
41868
42072
  const backupRequired = (_o = firstValue(status === null || status === void 0 ? void 0 : status.backup_required, previous === null || previous === void 0 ? void 0 : previous.backupRequired)) !== null && _o !== void 0 ? _o : null;
41869
42073
  const bleEnabled = previous === null || previous === void 0 ? void 0 : previous.bleEnabled;
41870
42074
  const unlocked = (_p = firstValue(status === null || status === void 0 ? void 0 : status.unlocked, previous === null || previous === void 0 ? void 0 : previous.unlocked)) !== null && _p !== void 0 ? _p : null;
41871
42075
  const attachToPinEnabled = (_q = status === null || status === void 0 ? void 0 : status.attach_to_pin_enabled) !== null && _q !== void 0 ? _q : null;
41872
42076
  const unlockedAttachPin = (_r = status === null || status === void 0 ? void 0 : status.unlocked_by_attach_to_pin) !== null && _r !== void 0 ? _r : undefined;
41873
- const romloaderMode = isProtocolV2RomloaderDeviceInfo(info);
41874
- const bootloaderMode = isProtocolV2BootloaderDeviceInfo(info);
42077
+ const romloaderMode = isProtocolV2RomloaderDeviceInfo(info, status);
42078
+ const bootloaderMode = isProtocolV2BootloaderDeviceInfo(info, status);
41875
42079
  let mode = 'unknown';
41876
42080
  if (romloaderMode) {
41877
42081
  mode = 'romloader';
@@ -41969,6 +42173,7 @@ const buildProtocolV2FeaturesPayload = (deviceInfo, previous) => {
41969
42173
  unlockedAttachPin,
41970
42174
  raw: {
41971
42175
  protocolV2DeviceInfo: deviceInfo,
42176
+ protocolV2DeviceStatus: deviceStatus,
41972
42177
  },
41973
42178
  };
41974
42179
  };
@@ -42370,7 +42575,6 @@ class Device extends events.exports {
42370
42575
  if (this.features.bootloaderMode) {
42371
42576
  return;
42372
42577
  }
42373
- yield this._refreshProtocolV2Status(options);
42374
42578
  return;
42375
42579
  }
42376
42580
  yield this._initializeProtocolV2(options);
@@ -42419,7 +42623,13 @@ class Device extends events.exports {
42419
42623
  commands: this.commands,
42420
42624
  timeoutMs: options === null || options === void 0 ? void 0 : options.protocolV2DeviceInfoTimeoutMs,
42421
42625
  });
42422
- const features = this.updateProtocolV2Features(deviceInfo);
42626
+ const deviceStatus = yield requestProtocolV2DeviceStatus({
42627
+ commands: this.commands,
42628
+ }).catch(error => {
42629
+ Log$d.debug('Protocol V2 status unavailable during initialization:', error);
42630
+ return undefined;
42631
+ });
42632
+ const features = this.updateProtocolV2Features(deviceInfo, deviceStatus);
42423
42633
  Log$d.debug('Protocol V2 features:', features);
42424
42634
  this.featuresNeedsReload = false;
42425
42635
  }
@@ -42429,30 +42639,16 @@ class Device extends events.exports {
42429
42639
  }
42430
42640
  });
42431
42641
  }
42432
- _refreshProtocolV2Status(options) {
42433
- return __awaiter(this, void 0, void 0, function* () {
42434
- try {
42435
- const deviceInfo = yield requestProtocolV2DeviceInfo({
42436
- commands: this.commands,
42437
- request: PROTOCOL_V2_STATUS_DEVICE_INFO_REQUEST,
42438
- timeoutMs: options === null || options === void 0 ? void 0 : options.protocolV2DeviceInfoTimeoutMs,
42439
- });
42440
- const features = this.updateProtocolV2Features(deviceInfo);
42441
- Log$d.debug('Protocol V2 features (status refresh):', features);
42442
- }
42443
- catch (error) {
42444
- Log$d.error('Protocol V2 status refresh failed:', error);
42445
- throw error;
42446
- }
42447
- });
42448
- }
42449
42642
  getFeatures() {
42450
42643
  return __awaiter(this, void 0, void 0, function* () {
42451
42644
  if (this.isProtocolV2()) {
42452
42645
  const deviceInfo = yield requestProtocolV2DeviceInfo({
42453
42646
  commands: this.commands,
42454
42647
  });
42455
- return this.updateProtocolV2Features(deviceInfo);
42648
+ const deviceStatus = yield requestProtocolV2DeviceStatus({
42649
+ commands: this.commands,
42650
+ }).catch(() => undefined);
42651
+ return this.updateProtocolV2Features(deviceInfo, deviceStatus);
42456
42652
  }
42457
42653
  const { message } = yield this.commands.typedCall('GetFeatures', 'Features', {});
42458
42654
  this._updateFeatures(message);
@@ -42481,9 +42677,17 @@ class Device extends events.exports {
42481
42677
  this.featuresNeedsReload = false;
42482
42678
  this.emit(DEVICE.FEATURES, this, feat);
42483
42679
  }
42484
- updateProtocolV2Features(deviceInfo) {
42680
+ updateProtocolV2Features(deviceInfo, deviceStatus) {
42681
+ var _a, _b;
42485
42682
  const previousCacheDeviceKey = this.getSessionCacheDeviceKey();
42486
- const features = fixFeaturesFirmwareVersion(buildProtocolV2FeaturesPayload(deviceInfo, this.features));
42683
+ const resolvedDeviceStatus = deviceStatus === undefined
42684
+ ? (_b = (_a = this.features) === null || _a === void 0 ? void 0 : _a.raw) === null || _b === void 0 ? void 0 : _b.protocolV2DeviceStatus
42685
+ : deviceStatus !== null && deviceStatus !== void 0 ? deviceStatus : undefined;
42686
+ const features = fixFeaturesFirmwareVersion(buildProtocolV2FeaturesPayload({
42687
+ deviceInfo,
42688
+ deviceStatus: resolvedDeviceStatus,
42689
+ previous: this.features,
42690
+ }));
42487
42691
  this.features = features;
42488
42692
  const nextCacheDeviceKey = this.getSessionCacheDeviceKey();
42489
42693
  if (previousCacheDeviceKey && nextCacheDeviceKey) {
@@ -42494,10 +42698,10 @@ class Device extends events.exports {
42494
42698
  return features;
42495
42699
  }
42496
42700
  updateProtocolV2Status(status) {
42497
- var _a, _b, _c, _d, _e;
42701
+ var _a, _b, _c, _d;
42498
42702
  const previousDeviceInfo = (_b = (_a = this.features) === null || _a === void 0 ? void 0 : _a.raw) === null || _b === void 0 ? void 0 : _b.protocolV2DeviceInfo;
42499
- const previousStatus = previousDeviceInfo === null || previousDeviceInfo === void 0 ? void 0 : previousDeviceInfo.status;
42500
- return this.updateProtocolV2Features(Object.assign(Object.assign({}, (previousDeviceInfo !== null && previousDeviceInfo !== void 0 ? previousDeviceInfo : {})), { protocol_version: (_e = (_c = previousDeviceInfo === null || previousDeviceInfo === void 0 ? void 0 : previousDeviceInfo.protocol_version) !== null && _c !== void 0 ? _c : (_d = this.features) === null || _d === void 0 ? void 0 : _d.protocolVersion) !== null && _e !== void 0 ? _e : 2, status: Object.assign(Object.assign({}, previousStatus), status) }));
42703
+ const previousStatus = (_d = (_c = this.features) === null || _c === void 0 ? void 0 : _c.raw) === null || _d === void 0 ? void 0 : _d.protocolV2DeviceStatus;
42704
+ return this.updateProtocolV2Features(previousDeviceInfo, Object.assign(Object.assign({}, previousStatus), status));
42501
42705
  }
42502
42706
  updateDescriptor(descriptor, forceUpdate = false) {
42503
42707
  var _a;
@@ -42740,7 +42944,9 @@ class Device extends events.exports {
42740
42944
  return __awaiter(this, void 0, void 0, function* () {
42741
42945
  if (this.isProtocolV2()) {
42742
42946
  try {
42743
- yield this.commands.typedCall('DeviceSessionAskPin', 'Success');
42947
+ yield this.commands.typedCall('DeviceSessionAskPin', 'Success', undefined, {
42948
+ timeoutMs: 120000,
42949
+ });
42744
42950
  }
42745
42951
  catch (error) {
42746
42952
  const errorText = error instanceof Error
@@ -42975,7 +43181,8 @@ class BaseMethod {
42975
43181
  this.preWarmTtl = 60 * 1000;
42976
43182
  this.strictCheckDeviceSupport = false;
42977
43183
  this.requireProtocolV2 = false;
42978
- this.unlockPolicy = 'none';
43184
+ this.unlockPolicy = 'retry-on-locked';
43185
+ this.protocolV2UiMode = 'auto';
42979
43186
  this.temporarySafetyCheckPrompted = false;
42980
43187
  this.postPreviousAddressMessage = (data) => {
42981
43188
  this.postMessage(createUiMessage(UI_REQUEST.PREVIOUS_ADDRESS_RESULT, {
@@ -43307,13 +43514,17 @@ class GetDeviceInfo extends BaseMethod {
43307
43514
  commands: this.device.commands,
43308
43515
  request: resolveProtocolV2DeviceInfoRequest(this.params),
43309
43516
  });
43517
+ const protocolV2DeviceStatus = yield requestProtocolV2DeviceStatus({
43518
+ commands: this.device.commands,
43519
+ }).catch(() => undefined);
43310
43520
  const profile = buildProfileFromProtocolV2({
43311
43521
  deviceInfo: protocolV2DeviceInfo,
43522
+ deviceStatus: protocolV2DeviceStatus,
43312
43523
  sources,
43313
43524
  scope: this.params.scope,
43314
43525
  includeRaw: this.params.includeRaw,
43315
43526
  });
43316
- this.device.updateProtocolV2Features(protocolV2DeviceInfo);
43527
+ this.device.updateProtocolV2Features(protocolV2DeviceInfo, protocolV2DeviceStatus);
43317
43528
  return profile;
43318
43529
  });
43319
43530
  }
@@ -43448,8 +43659,10 @@ class GetPassphraseState extends BaseMethod {
43448
43659
  });
43449
43660
  const passphraseProtection = this.device.getCurrentPassphraseProtection();
43450
43661
  const deviceType = this.device.getCurrentDeviceType();
43451
- const isProSeries = deviceType === hdShared.EDeviceType.Pro || deviceType === hdShared.EDeviceType.Pro2;
43452
- return Promise.resolve(isProSeries || passphraseProtection === true ? passphraseState : undefined);
43662
+ if (deviceType === hdShared.EDeviceType.Pro2) {
43663
+ return Promise.resolve(passphraseProtection === true ? passphraseState : undefined);
43664
+ }
43665
+ return Promise.resolve(deviceType === hdShared.EDeviceType.Pro || passphraseProtection === true ? passphraseState : undefined);
43453
43666
  });
43454
43667
  }
43455
43668
  }
@@ -43951,6 +44164,45 @@ function validateResult(result, nonNullableFields, options) {
43951
44164
  }
43952
44165
  }
43953
44166
 
44167
+ const invalidParameter = (message) => hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.CallMethodInvalidParameter, message);
44168
+ function validateNonEmptyString(value, name) {
44169
+ if (typeof value !== 'string' || value.trim().length === 0) {
44170
+ throw invalidParameter(`Parameter [${name}] is required and must be a non-empty string.`);
44171
+ }
44172
+ return value;
44173
+ }
44174
+ function validateNonNegativeInteger(value, name, defaultValue) {
44175
+ if (value === undefined || value === null) {
44176
+ if (defaultValue !== undefined)
44177
+ return defaultValue;
44178
+ throw invalidParameter(`Missing required parameter: ${name}`);
44179
+ }
44180
+ const numeric = typeof value === 'string' && value.trim() !== '' ? Number(value) : value;
44181
+ if (typeof numeric !== 'number' || !Number.isSafeInteger(numeric) || numeric < 0) {
44182
+ throw invalidParameter(`Parameter [${name}] must be a non-negative integer.`);
44183
+ }
44184
+ return numeric;
44185
+ }
44186
+ function validateOptionalNonNegativeInteger(value, name) {
44187
+ if (value === undefined || value === null)
44188
+ return undefined;
44189
+ return validateNonNegativeInteger(value, name);
44190
+ }
44191
+ function validateOptionalPercentage(value, name) {
44192
+ const numeric = validateOptionalNonNegativeInteger(value, name);
44193
+ if (numeric === undefined)
44194
+ return undefined;
44195
+ if (numeric > 100) {
44196
+ throw invalidParameter(`Parameter [${name}] must be between 0 and 100.`);
44197
+ }
44198
+ return numeric;
44199
+ }
44200
+ function validateRequiredData(value, name) {
44201
+ if (value === undefined || value === null) {
44202
+ throw invalidParameter(`Missing required parameter: ${name}`);
44203
+ }
44204
+ }
44205
+
43954
44206
  class DeviceChangePin extends BaseMethod {
43955
44207
  init() {
43956
44208
  this.useDevicePassphraseState = false;
@@ -43958,9 +44210,26 @@ class DeviceChangePin extends BaseMethod {
43958
44210
  this.params = {
43959
44211
  remove: this.payload.remove,
43960
44212
  };
44213
+ this.protocolV2UiInteraction = {
44214
+ request: 'button',
44215
+ source: 'method-lifecycle',
44216
+ reason: 'change-pin',
44217
+ completion: 'operation-completed',
44218
+ deviceOnly: true,
44219
+ page: hdTransport.DeviceSettingsPage.DevicePinChange,
44220
+ };
43961
44221
  }
43962
44222
  run() {
43963
44223
  return __awaiter(this, void 0, void 0, function* () {
44224
+ if (this.device.isProtocolV2()) {
44225
+ if (this.params.remove) {
44226
+ throw invalidParameter('Parameter [remove=true] is not supported by the Pro2 device PIN page.');
44227
+ }
44228
+ const res = yield this.device.commands.typedCall('DeviceSettingsPageShow', 'Success', {
44229
+ page: hdTransport.DeviceSettingsPage.DevicePinChange,
44230
+ });
44231
+ return Promise.resolve(res.message);
44232
+ }
43964
44233
  const res = yield this.device.commands.typedCall('ChangePin', 'Success', Object.assign({}, this.params));
43965
44234
  return Promise.resolve(res.message);
43966
44235
  });
@@ -44404,9 +44673,24 @@ class DeviceVerify extends BaseMethod {
44404
44673
  class DeviceWipe extends BaseMethod {
44405
44674
  init() {
44406
44675
  this.useDevicePassphraseState = false;
44676
+ this.protocolV2UiInteraction = {
44677
+ request: 'button',
44678
+ source: 'method-lifecycle',
44679
+ reason: 'device-management',
44680
+ completion: 'operation-completed',
44681
+ deviceOnly: true,
44682
+ page: hdTransport.DeviceSettingsPage.DeviceReset,
44683
+ operation: 'wipe-device',
44684
+ };
44407
44685
  }
44408
44686
  run() {
44409
44687
  return __awaiter(this, void 0, void 0, function* () {
44688
+ if (this.device.isProtocolV2()) {
44689
+ const res = yield this.device.commands.typedCall('DeviceSettingsPageShow', 'Success', {
44690
+ page: hdTransport.DeviceSettingsPage.DeviceReset,
44691
+ });
44692
+ return Promise.resolve(res.message);
44693
+ }
44410
44694
  const res = yield this.device.commands.typedCall('WipeDevice', 'Success');
44411
44695
  return Promise.resolve(res.message);
44412
44696
  });
@@ -45347,6 +45631,7 @@ class DeviceUpdateBootloader extends FirmwareUpdateBaseMethod {
45347
45631
  class DeviceLock extends BaseMethod {
45348
45632
  init() {
45349
45633
  this.useDevicePassphraseState = false;
45634
+ this.unlockPolicy = 'none';
45350
45635
  }
45351
45636
  run() {
45352
45637
  return __awaiter(this, void 0, void 0, function* () {
@@ -45358,6 +45643,15 @@ class DeviceLock extends BaseMethod {
45358
45643
  class DeviceUnlock extends BaseMethod {
45359
45644
  init() {
45360
45645
  this.useDevicePassphraseState = false;
45646
+ this.unlockPolicy = 'none';
45647
+ this.protocolV2UiInteraction = {
45648
+ request: 'pin',
45649
+ source: 'method-lifecycle',
45650
+ reason: 'device-unlock',
45651
+ completion: 'operation-completed',
45652
+ deviceOnly: true,
45653
+ operation: 'unlock-device',
45654
+ };
45361
45655
  }
45362
45656
  run() {
45363
45657
  return __awaiter(this, void 0, void 0, function* () {
@@ -45369,6 +45663,7 @@ class DeviceUnlock extends BaseMethod {
45369
45663
  class DeviceCancel extends BaseMethod {
45370
45664
  init() {
45371
45665
  this.useDevicePassphraseState = false;
45666
+ this.unlockPolicy = 'none';
45372
45667
  }
45373
45668
  run() {
45374
45669
  return __awaiter(this, void 0, void 0, function* () {
@@ -46267,45 +46562,6 @@ class FirmwareUpdateV3 extends FirmwareUpdateBaseMethod {
46267
46562
  }
46268
46563
  }
46269
46564
 
46270
- const invalidParameter = (message) => hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.CallMethodInvalidParameter, message);
46271
- function validateNonEmptyString(value, name) {
46272
- if (typeof value !== 'string' || value.trim().length === 0) {
46273
- throw invalidParameter(`Parameter [${name}] is required and must be a non-empty string.`);
46274
- }
46275
- return value;
46276
- }
46277
- function validateNonNegativeInteger(value, name, defaultValue) {
46278
- if (value === undefined || value === null) {
46279
- if (defaultValue !== undefined)
46280
- return defaultValue;
46281
- throw invalidParameter(`Missing required parameter: ${name}`);
46282
- }
46283
- const numeric = typeof value === 'string' && value.trim() !== '' ? Number(value) : value;
46284
- if (typeof numeric !== 'number' || !Number.isSafeInteger(numeric) || numeric < 0) {
46285
- throw invalidParameter(`Parameter [${name}] must be a non-negative integer.`);
46286
- }
46287
- return numeric;
46288
- }
46289
- function validateOptionalNonNegativeInteger(value, name) {
46290
- if (value === undefined || value === null)
46291
- return undefined;
46292
- return validateNonNegativeInteger(value, name);
46293
- }
46294
- function validateOptionalPercentage(value, name) {
46295
- const numeric = validateOptionalNonNegativeInteger(value, name);
46296
- if (numeric === undefined)
46297
- return undefined;
46298
- if (numeric > 100) {
46299
- throw invalidParameter(`Parameter [${name}] must be between 0 and 100.`);
46300
- }
46301
- return numeric;
46302
- }
46303
- function validateRequiredData(value, name) {
46304
- if (value === undefined || value === null) {
46305
- throw invalidParameter(`Missing required parameter: ${name}`);
46306
- }
46307
- }
46308
-
46309
46565
  const DEVICE_REBOOT_TYPES = {
46310
46566
  Normal: hdTransport.DeviceRebootType.Normal,
46311
46567
  normal: hdTransport.DeviceRebootType.Normal,
@@ -46539,15 +46795,6 @@ const isProtocolV2ReconnectProbeError = (error) => {
46539
46795
  return ((message.includes('device protocol mismatch') && message.includes('expected v2')) ||
46540
46796
  message.includes('did not respond to expected protocol'));
46541
46797
  };
46542
- const isProtocolV2PollingTransientError = (error) => {
46543
- const message = getProtocolV2UnknownErrorText(error).toLowerCase();
46544
- return (isProtocolV2DeviceDisconnectedError(error) ||
46545
- isProtocolV2ReconnectProbeError(error) ||
46546
- message.includes('libusb_transfer_timed_out') ||
46547
- (message.includes('response timeout') && message.includes('devicefirmwareupdatestatusget')) ||
46548
- message.includes('device not found') ||
46549
- message.includes('transportnotfound'));
46550
- };
46551
46798
  const isProtocolV2StartUpdateTransientError = (error) => {
46552
46799
  const message = getProtocolV2UnknownErrorText(error).toLowerCase();
46553
46800
  return (isProtocolV2DeviceDisconnectedError(error) ||
@@ -46656,10 +46903,12 @@ const parseProtocolV2OkppHeader = (bytes) => {
46656
46903
  headerHash: bytesToHex(bytes.slice(PROTOCOL_V2_OKPP_HEADER_HASH_OFFSET, PROTOCOL_V2_OKPP_HEADER_HASH_OFFSET + PROTOCOL_V2_OKPP_HASH_SIZE)),
46657
46904
  };
46658
46905
  };
46659
- const assertProtocolV2ReconnectIdentity = (expectedDeviceId, actualDeviceId) => {
46906
+ const assertProtocolV2ReconnectIdentity = (expectedDeviceId, actualDeviceId, options = {}) => {
46660
46907
  if (!expectedDeviceId)
46661
46908
  return;
46662
46909
  if (!actualDeviceId) {
46910
+ if (options.allowMissingActual)
46911
+ return;
46663
46912
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceNotFound, 'Protocol V2 reconnect identity unavailable');
46664
46913
  }
46665
46914
  if (actualDeviceId !== expectedDeviceId) {
@@ -47104,8 +47353,8 @@ class FirmwareUpdateV4 extends FirmwareUpdateBaseMethod {
47104
47353
  commands: this.device.getCommands(),
47105
47354
  timeoutMs: PROTOCOL_V2_SHORT_RESPONSE_TIMEOUT,
47106
47355
  });
47107
- const features = this.device.updateProtocolV2Features(deviceInfo);
47108
- assertProtocolV2ReconnectIdentity(this.protocolV2ExpectedDeviceId, (_a = features.deviceId) !== null && _a !== void 0 ? _a : undefined);
47356
+ const features = this.device.updateProtocolV2Features(deviceInfo, null);
47357
+ assertProtocolV2ReconnectIdentity(this.protocolV2ExpectedDeviceId, (_a = features.deviceId) !== null && _a !== void 0 ? _a : undefined, { allowMissingActual: !!features.bootloaderMode });
47109
47358
  if (features === null || features === void 0 ? void 0 : features.bootloaderMode) {
47110
47359
  return features;
47111
47360
  }
@@ -47221,34 +47470,20 @@ class FirmwareUpdateV4 extends FirmwareUpdateBaseMethod {
47221
47470
  }
47222
47471
  });
47223
47472
  }
47224
- queryProtocolV2FirmwareUpdateStatus() {
47225
- return __awaiter(this, void 0, void 0, function* () {
47226
- const typedCall = this.device.getCommands().typedCall.bind(this.device.getCommands());
47227
- return typedCall('DeviceFirmwareUpdateStatusGet', 'DeviceFirmwareUpdateStatus', {}, {
47228
- timeoutMs: PROTOCOL_V2_SHORT_RESPONSE_TIMEOUT,
47229
- });
47230
- });
47231
- }
47232
- pingProtocolV2Device() {
47233
- return __awaiter(this, void 0, void 0, function* () {
47234
- const typedCall = this.device.getCommands().typedCall.bind(this.device.getCommands());
47235
- yield typedCall('Ping', 'Success', { message: 'firmware-update' }, {
47236
- timeoutMs: PROTOCOL_V2_SHORT_RESPONSE_TIMEOUT,
47237
- });
47238
- });
47239
- }
47240
47473
  isProtocolV2NormalModeFeatures(features) {
47241
47474
  return !!features && !features.bootloaderMode && features.mode !== 'bootloader';
47242
47475
  }
47243
47476
  probeProtocolV2NormalMode() {
47244
47477
  var _a;
47245
47478
  return __awaiter(this, void 0, void 0, function* () {
47479
+ const typedCall = this.device.getCommands().typedCall.bind(this.device.getCommands());
47480
+ const { message: deviceStatus } = yield typedCall('DeviceStatusGet', 'DeviceStatus', {}, { timeoutMs: PROTOCOL_V2_SHORT_RESPONSE_TIMEOUT });
47246
47481
  const deviceInfo = yield requestProtocolV2DeviceInfo({
47247
47482
  commands: this.device.getCommands(),
47248
47483
  timeoutMs: PROTOCOL_V2_SHORT_RESPONSE_TIMEOUT,
47249
47484
  request: PROTOCOL_V2_VERSIONS_DEVICE_INFO_REQUEST,
47250
47485
  });
47251
- const features = this.device.updateProtocolV2Features(deviceInfo);
47486
+ const features = this.device.updateProtocolV2Features(deviceInfo, deviceStatus);
47252
47487
  assertProtocolV2ReconnectIdentity(this.protocolV2ExpectedDeviceId, (_a = features.deviceId) !== null && _a !== void 0 ? _a : undefined);
47253
47488
  if (this.isProtocolV2NormalModeFeatures(features)) {
47254
47489
  Log$5.log('Protocol V2 firmware install finished; device is back in normal mode');
@@ -47285,51 +47520,29 @@ class FirmwareUpdateV4 extends FirmwareUpdateBaseMethod {
47285
47520
  return false;
47286
47521
  }
47287
47522
  waitForProtocolV2FirmwareUpdateComplete(targets, startResponse) {
47288
- var _a, _b;
47523
+ var _a;
47289
47524
  return __awaiter(this, void 0, void 0, function* () {
47290
47525
  const expectedTargetIds = new Set(targets.map(target => target.target_id));
47291
47526
  if ((startResponse === null || startResponse === void 0 ? void 0 : startResponse.type) === 'DeviceFirmwareUpdateStatus') {
47292
47527
  const statusTargets = ((_a = startResponse.message.records) !== null && _a !== void 0 ? _a : []);
47293
- if (this.assertProtocolV2TargetStatus(statusTargets, expectedTargetIds)) {
47294
- return;
47295
- }
47528
+ this.assertProtocolV2TargetStatus(statusTargets, expectedTargetIds);
47296
47529
  }
47297
47530
  const startTime = Date.now();
47298
47531
  let lastError;
47299
47532
  while (Date.now() - startTime < PROTOCOL_V2_INSTALL_TIMEOUT) {
47300
47533
  try {
47301
- const statusRes = yield this.queryProtocolV2FirmwareUpdateStatus();
47302
- const statusTargets = ((_b = statusRes.message.records) !== null && _b !== void 0 ? _b : []);
47303
- if (this.assertProtocolV2TargetStatus(statusTargets, expectedTargetIds)) {
47534
+ yield this.reconnectProtocolV2Device();
47535
+ if (yield this.probeProtocolV2NormalMode()) {
47304
47536
  return;
47305
47537
  }
47538
+ lastError = new Error('Protocol V2 device is reachable but is not in normal mode');
47306
47539
  }
47307
47540
  catch (error) {
47308
47541
  lastError = error;
47309
47542
  if (error instanceof hdShared.HardwareError && error.errorCode === hdShared.HardwareErrorCode.FirmwareError) {
47310
47543
  throw error;
47311
47544
  }
47312
- Log$5.log('Protocol V2 firmware install status polling failed: ', error);
47313
- if (isProtocolV2PollingTransientError(error)) {
47314
- try {
47315
- yield this.reconnectProtocolV2Device();
47316
- if (yield this.probeProtocolV2NormalMode()) {
47317
- return;
47318
- }
47319
- }
47320
- catch (reconnectError) {
47321
- lastError = reconnectError;
47322
- Log$5.log('Protocol V2 firmware install reconnect/normal-mode probe failed: ', reconnectError);
47323
- }
47324
- try {
47325
- yield this.pingProtocolV2Device();
47326
- Log$5.log('Protocol V2 firmware status unavailable, Ping is ready');
47327
- }
47328
- catch (pingError) {
47329
- lastError = pingError;
47330
- Log$5.log('Protocol V2 firmware install Ping polling failed: ', pingError);
47331
- }
47332
- }
47545
+ Log$5.log('Protocol V2 firmware install device readiness probe failed: ', error);
47333
47546
  }
47334
47547
  yield hdShared.wait(1000);
47335
47548
  }
@@ -47412,8 +47625,7 @@ class FirmwareUpdateV4 extends FirmwareUpdateBaseMethod {
47412
47625
  yield this.device.acquire(PROTOCOL_V2_CONNECT_PROTOCOL, { throwOnRunPromiseError: true });
47413
47626
  this.device.commands.disposed = false;
47414
47627
  this.device.getCommands().mainId = (_c = this.device.mainId) !== null && _c !== void 0 ? _c : '';
47415
- yield this.device.initialize();
47416
- assertProtocolV2ReconnectIdentity(this.protocolV2ExpectedDeviceId, this.device.getCurrentDeviceId());
47628
+ assertProtocolV2ReconnectIdentity(this.protocolV2ExpectedDeviceId, this.device.getCurrentDeviceId(), { allowMissingActual: this.isProtocolV2BootloaderMode() });
47417
47629
  return;
47418
47630
  }
47419
47631
  const { deviceList } = yield DevicePool.getDevices(devicesDescriptor, undefined, {
@@ -47427,8 +47639,7 @@ class FirmwareUpdateV4 extends FirmwareUpdateBaseMethod {
47427
47639
  yield this.device.acquire(PROTOCOL_V2_CONNECT_PROTOCOL, { throwOnRunPromiseError: true });
47428
47640
  this.device.commands.disposed = false;
47429
47641
  this.device.getCommands().mainId = (_d = this.device.mainId) !== null && _d !== void 0 ? _d : '';
47430
- yield this.device.initialize();
47431
- assertProtocolV2ReconnectIdentity(this.protocolV2ExpectedDeviceId, this.device.getCurrentDeviceId());
47642
+ assertProtocolV2ReconnectIdentity(this.protocolV2ExpectedDeviceId, this.device.getCurrentDeviceId(), { allowMissingActual: this.isProtocolV2BootloaderMode() });
47432
47643
  });
47433
47644
  }
47434
47645
  protocolV2CommonUpdateProcess(params) {
@@ -47721,7 +47932,6 @@ const DEFAULT_TARGETS = {
47721
47932
  hw: true,
47722
47933
  fw: true,
47723
47934
  coprocessor: true,
47724
- status: true,
47725
47935
  };
47726
47936
  const DEFAULT_TYPES = {
47727
47937
  version: true,
@@ -47800,6 +48010,7 @@ class DeviceStatusGet extends BaseMethod {
47800
48010
  run() {
47801
48011
  return __awaiter(this, void 0, void 0, function* () {
47802
48012
  const { message } = yield this.device.commands.typedCall('DeviceStatusGet', 'DeviceStatus', {});
48013
+ this.device.updateProtocolV2Status(message);
47803
48014
  return message;
47804
48015
  });
47805
48016
  }
@@ -47819,16 +48030,59 @@ class DeviceGetOnboardingStatus extends BaseMethod {
47819
48030
  }
47820
48031
  }
47821
48032
 
47822
- class DeviceSessionGet extends BaseMethod {
48033
+ const isRecord = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
48034
+ const normalizeParams = (payload) => {
48035
+ const hasResume = payload.resume !== undefined;
48036
+ const hasSelect = payload.select !== undefined;
48037
+ if (hasResume === hasSelect) {
48038
+ throw invalidParameter('DeviceSessionOpen requires exactly one of [resume] or [select].');
48039
+ }
48040
+ if (hasResume) {
48041
+ if (!isRecord(payload.resume) || typeof payload.resume.session_id !== 'string') {
48042
+ throw invalidParameter('Parameter [resume.session_id] must be a non-empty string.');
48043
+ }
48044
+ const sessionId = payload.resume.session_id.trim();
48045
+ if (!sessionId) {
48046
+ throw invalidParameter('Parameter [resume.session_id] must be a non-empty string.');
48047
+ }
48048
+ return { resume: { session_id: sessionId } };
48049
+ }
48050
+ if (!isRecord(payload.select)) {
48051
+ throw invalidParameter('Parameter [select] must be a hidden-wallet selection object.');
48052
+ }
48053
+ const { select } = payload;
48054
+ const accessKeys = ['host_passphrase', 'passphrase_on_device', 'attach_pin_on_device'];
48055
+ const selected = accessKeys.filter(key => select[key] !== undefined);
48056
+ const unknown = Object.keys(select).filter(key => !accessKeys.includes(key));
48057
+ if (unknown.length > 0 || selected.length !== 1) {
48058
+ throw invalidParameter('Parameter [select] requires exactly one hidden-wallet access mode.');
48059
+ }
48060
+ if (selected[0] === 'host_passphrase') {
48061
+ const host = select.host_passphrase;
48062
+ if (!isRecord(host) || typeof host.passphrase !== 'string') {
48063
+ throw invalidParameter('Parameter [select.host_passphrase.passphrase] is required.');
48064
+ }
48065
+ const passphrase = host.passphrase.normalize('NFKD');
48066
+ if (!passphrase || passphrase.includes('\0') || passphrase.length > 50) {
48067
+ throw invalidParameter('Parameter [select.host_passphrase.passphrase] is invalid.');
48068
+ }
48069
+ return { select: { host_passphrase: { passphrase } } };
48070
+ }
48071
+ if (selected[0] === 'passphrase_on_device') {
48072
+ return { select: { passphrase_on_device: {} } };
48073
+ }
48074
+ return { select: { attach_pin_on_device: {} } };
48075
+ };
48076
+ class DeviceSessionOpen extends BaseMethod {
47823
48077
  init() {
47824
48078
  this.requireProtocolV2 = true;
47825
48079
  this.useDevicePassphraseState = false;
47826
48080
  this.skipForceUpdateCheck = true;
47827
- this.params = undefined;
48081
+ this.params = normalizeParams(this.payload);
47828
48082
  }
47829
48083
  run() {
47830
48084
  return __awaiter(this, void 0, void 0, function* () {
47831
- const { message } = yield this.device.commands.typedCall('DeviceSessionGet', 'DeviceSession', {});
48085
+ const { message } = yield this.device.commands.typedCall('DeviceSessionOpen', 'DeviceSession', this.params);
47832
48086
  return message;
47833
48087
  });
47834
48088
  }
@@ -47976,7 +48230,7 @@ class DeviceSettingsGet extends BaseMethod {
47976
48230
 
47977
48231
  class DeviceSettingsSet extends BaseMethod {
47978
48232
  init() {
47979
- const settings = this.payload.settings;
48233
+ const { settings } = this.payload;
47980
48234
  if (!settings || typeof settings !== 'object' || Array.isArray(settings)) {
47981
48235
  throw invalidParameter('Parameter [settings] must be an object.');
47982
48236
  }
@@ -47989,6 +48243,16 @@ class DeviceSettingsSet extends BaseMethod {
47989
48243
  this.skipForceUpdateCheck = true;
47990
48244
  this.useDevicePassphraseState = false;
47991
48245
  this.params = { settings: supported };
48246
+ if (typeof supported.label === 'string') {
48247
+ this.protocolV2UiInteraction = {
48248
+ request: 'button',
48249
+ source: 'method-lifecycle',
48250
+ reason: 'device-management',
48251
+ completion: 'operation-completed',
48252
+ deviceOnly: true,
48253
+ operation: 'change-label',
48254
+ };
48255
+ }
47992
48256
  }
47993
48257
  run() {
47994
48258
  return __awaiter(this, void 0, void 0, function* () {
@@ -48022,6 +48286,14 @@ class DeviceSettingsPageShow extends BaseMethod {
48022
48286
  page: normalizePage(this.payload.page),
48023
48287
  field_name: (_a = this.payload.field_name) !== null && _a !== void 0 ? _a : this.payload.fieldName,
48024
48288
  };
48289
+ this.protocolV2UiInteraction = {
48290
+ request: 'button',
48291
+ source: 'method-lifecycle',
48292
+ reason: 'settings-page',
48293
+ completion: 'operation-completed',
48294
+ deviceOnly: true,
48295
+ page: this.params.page,
48296
+ };
48025
48297
  }
48026
48298
  run() {
48027
48299
  return __awaiter(this, void 0, void 0, function* () {
@@ -48032,6 +48304,15 @@ class DeviceSettingsPageShow extends BaseMethod {
48032
48304
  }
48033
48305
 
48034
48306
  const MIN_FILE_CHUNK_SIZE = 64;
48307
+ function isRetryableFileWriteTimeout(error) {
48308
+ var _a, _b;
48309
+ if (!error || typeof error !== 'object')
48310
+ return false;
48311
+ const candidate = error;
48312
+ const code = (_a = candidate.errorCode) !== null && _a !== void 0 ? _a : candidate.code;
48313
+ return (code === hdShared.HardwareErrorCode.BleTimeoutError ||
48314
+ /Lowlevel response timeout/i.test((_b = candidate.message) !== null && _b !== void 0 ? _b : ''));
48315
+ }
48035
48316
  function getProtocolV2FileChunkLimit() {
48036
48317
  const env = DataManager.getSettings('env');
48037
48318
  return env && DataManager.isBleConnect(env)
@@ -48079,7 +48360,7 @@ function getConfirmedProgress(processed, total, written, length) {
48079
48360
  return 100;
48080
48361
  }
48081
48362
  function writeProtocolV2File(options) {
48082
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
48363
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
48083
48364
  return __awaiter(this, void 0, void 0, function* () {
48084
48365
  (_a = options.throwIfAborted) === null || _a === void 0 ? void 0 : _a.call(options);
48085
48366
  const data = yield dataToUint8Array(options.data);
@@ -48101,15 +48382,30 @@ function writeProtocolV2File(options) {
48101
48382
  const chunk = data.slice(written, Math.min(written + chunkSize, dataLength));
48102
48383
  const offset = startOffset + written;
48103
48384
  const progress = (_d = options.uiPercentage) !== null && _d !== void 0 ? _d : getDeviceTransferProgress$1(offset, offset + chunk.byteLength, totalSize);
48104
- const response = yield options.commands.typedCall('FilesystemFileWrite', 'FilesystemFile', {
48385
+ const request = {
48105
48386
  file: { path: options.path, offset, total_size: totalSize, data: chunk },
48106
48387
  overwrite: chunks === 0 ? (_e = options.overwrite) !== null && _e !== void 0 ? _e : false : false,
48107
48388
  append: (_f = options.append) !== null && _f !== void 0 ? _f : false,
48108
48389
  ui_percentage: progress,
48109
- }, { timeoutMs: options.timeoutMs });
48110
- (_g = options.throwIfAborted) === null || _g === void 0 ? void 0 : _g.call(options);
48390
+ };
48391
+ const maxChunkRetries = Math.max(Math.floor((_g = options.maxChunkRetries) !== null && _g !== void 0 ? _g : 0), 0);
48392
+ let retryCount = 0;
48393
+ let response;
48394
+ while (true) {
48395
+ try {
48396
+ response = yield options.commands.typedCall('FilesystemFileWrite', 'FilesystemFile', request, { timeoutMs: options.timeoutMs });
48397
+ break;
48398
+ }
48399
+ catch (error) {
48400
+ if (retryCount >= maxChunkRetries || !isRetryableFileWriteTimeout(error))
48401
+ throw error;
48402
+ retryCount += 1;
48403
+ (_h = options.throwIfAborted) === null || _h === void 0 ? void 0 : _h.call(options);
48404
+ }
48405
+ }
48406
+ (_j = options.throwIfAborted) === null || _j === void 0 ? void 0 : _j.call(options);
48111
48407
  lastMessage = response.message;
48112
- const rawProcessedByte = (_h = response.message) === null || _h === void 0 ? void 0 : _h.processed_byte;
48408
+ const rawProcessedByte = (_k = response.message) === null || _k === void 0 ? void 0 : _k.processed_byte;
48113
48409
  const processedByte = Number(rawProcessedByte);
48114
48410
  if (rawProcessedByte !== undefined &&
48115
48411
  (!Number.isFinite(processedByte) ||
@@ -48122,7 +48418,7 @@ function writeProtocolV2File(options) {
48122
48418
  chunks += 1;
48123
48419
  const elapsedMs = Date.now() - startTime;
48124
48420
  const transferredBytes = Math.min(written, dataLength);
48125
- (_j = options.onProgress) === null || _j === void 0 ? void 0 : _j.call(options, {
48421
+ (_l = options.onProgress) === null || _l === void 0 ? void 0 : _l.call(options, {
48126
48422
  progress: getConfirmedProgress(startOffset + written, totalSize, written, dataLength),
48127
48423
  transferredBytes,
48128
48424
  totalBytes: dataLength,
@@ -48134,7 +48430,7 @@ function writeProtocolV2File(options) {
48134
48430
  });
48135
48431
  }
48136
48432
 
48137
- const WALLPAPER_DIRECTORY = 'vol0:/wallpapers/user';
48433
+ const WALLPAPER_DIRECTORY = 'vol1:/wallpapers';
48138
48434
  const SAFE_FILE_NAME = /^[A-Za-z0-9_-]+(?:\.bin)?$/;
48139
48435
  function normalizeFileName(fileName, data) {
48140
48436
  if (fileName !== undefined && (!fileName || !SAFE_FILE_NAME.test(fileName))) {
@@ -48202,6 +48498,7 @@ class DeviceUploadWallpaper extends BaseMethod {
48202
48498
  data: encoded.data,
48203
48499
  totalSize: encoded.data.byteLength,
48204
48500
  chunkSize: this.params.chunkSize,
48501
+ maxChunkRetries: 3,
48205
48502
  overwrite: true,
48206
48503
  append: false,
48207
48504
  throwIfAborted: () => this.throwIfAborted(),
@@ -48548,6 +48845,7 @@ class UploadPortfolio extends FileWrite {
48548
48845
  this.payload = Object.assign(Object.assign({}, this.payload), { path: PORTFOLIO_PENDING_PATH, offset: 0, data: packageBytes, chunkSize: PORTFOLIO_CHUNK_SIZE, overwrite: true, append: false, emitProgress: false, timeoutMs });
48549
48846
  super.init();
48550
48847
  this.unlockPolicy = 'retry-on-locked';
48848
+ this.protocolV2UiMode = 'none';
48551
48849
  }
48552
48850
  run() {
48553
48851
  const _super = Object.create(null, {
@@ -48610,18 +48908,6 @@ class CipherKeyValue extends BaseMethod {
48610
48908
  }
48611
48909
  }
48612
48910
 
48613
- const shouldRegisterHardwareUiEvents = (device) => !device.isProtocolV2();
48614
- function registerHardwareUiEventListeners(device, handlers) {
48615
- if (!shouldRegisterHardwareUiEvents(device)) {
48616
- return false;
48617
- }
48618
- device.on(DEVICE.PIN, handlers.pin);
48619
- device.on(DEVICE.BUTTON, handlers.button);
48620
- device.on(DEVICE.PASSPHRASE, handlers.passphrase);
48621
- device.on(DEVICE.PASSPHRASE_ON_DEVICE, handlers.passphraseOnDevice);
48622
- return true;
48623
- }
48624
-
48625
48911
  const Mainnet = 'mainnet';
48626
48912
  const networkAliases = {
48627
48913
  tbtc: { name: 'btc', coin: 'Testnet' },
@@ -48889,11 +49175,9 @@ class AllNetworkGetAddressBase extends BaseMethod {
48889
49175
  commandsInstanceId: (_c = this.device.commands) === null || _c === void 0 ? void 0 : _c.instanceId,
48890
49176
  });
48891
49177
  }
48892
- if (shouldRegisterHardwareUiEvents(this.device)) {
48893
- this.device.on(DEVICE.BUTTON, buttonListener);
48894
- this.device.on(DEVICE.PIN, onSignalAbort);
48895
- this.device.on(DEVICE.PASSPHRASE, onSignalAbort);
48896
- }
49178
+ this.device.on(DEVICE.BUTTON, buttonListener);
49179
+ this.device.on(DEVICE.PIN, onSignalAbort);
49180
+ this.device.on(DEVICE.PASSPHRASE, onSignalAbort);
48897
49181
  preCheckDeviceSupport(this.device, method);
48898
49182
  if (this.temporarySafetyCheckPrompted) {
48899
49183
  method.temporarySafetyCheckPrompted = true;
@@ -48932,11 +49216,9 @@ class AllNetworkGetAddressBase extends BaseMethod {
48932
49216
  }
48933
49217
  }
48934
49218
  finally {
48935
- if (shouldRegisterHardwareUiEvents(this.device)) {
48936
- this.device.off(DEVICE.BUTTON, buttonListener);
48937
- this.device.off(DEVICE.PIN, onSignalAbort);
48938
- this.device.off(DEVICE.PASSPHRASE, onSignalAbort);
48939
- }
49219
+ this.device.off(DEVICE.BUTTON, buttonListener);
49220
+ this.device.off(DEVICE.PIN, onSignalAbort);
49221
+ this.device.off(DEVICE.PASSPHRASE, onSignalAbort);
48940
49222
  }
48941
49223
  return result;
48942
49224
  });
@@ -57796,7 +58078,7 @@ var ApiMethods = /*#__PURE__*/Object.freeze({
57796
58078
  deviceInfoGet: DeviceInfoGet,
57797
58079
  deviceStatusGet: DeviceStatusGet,
57798
58080
  deviceGetOnboardingStatus: DeviceGetOnboardingStatus,
57799
- deviceSessionGet: DeviceSessionGet,
58081
+ deviceSessionOpen: DeviceSessionOpen,
57800
58082
  deviceFirmwareUpdate: DeviceFirmwareUpdate,
57801
58083
  deviceGetFirmwareUpdateStatus: DeviceGetFirmwareUpdateStatus,
57802
58084
  deviceFactoryInfoSet: DeviceFactoryInfoSet,
@@ -58185,6 +58467,15 @@ class RequestQueue {
58185
58467
  }
58186
58468
  }
58187
58469
 
58470
+ function registerHardwareUiEventListeners(device, handlers) {
58471
+ device.on(DEVICE.PIN, handlers.pin);
58472
+ device.on(DEVICE.BUTTON, handlers.button);
58473
+ device.on(DEVICE.PASSPHRASE, handlers.passphrase);
58474
+ device.on(DEVICE.PASSPHRASE_ON_DEVICE, handlers.passphraseOnDevice);
58475
+ device.on(DEVICE.ATTACH_PIN_ON_DEVICE, handlers.attachPinOnDevice);
58476
+ return true;
58477
+ }
58478
+
58188
58479
  const getMutex = () => {
58189
58480
  const DEFAULT_ID = Symbol();
58190
58481
  const locks = {};
@@ -58207,9 +58498,147 @@ const getSynchronize = (mutex) => {
58207
58498
  return (action, lockId) => lock(lockId).then(unlock => Promise.resolve().then(action).finally(unlock));
58208
58499
  };
58209
58500
 
58501
+ const isProtocolV2UiEnabled = (method) => method.protocolV2UiMode !== 'none';
58502
+ const getDisplayState = (value) => {
58503
+ const visited = new Set();
58504
+ let seen = false;
58505
+ let enabled = false;
58506
+ const visit = (current) => {
58507
+ if (current == null || typeof current !== 'object')
58508
+ return;
58509
+ if (visited.has(current))
58510
+ return;
58511
+ visited.add(current);
58512
+ if (Array.isArray(current)) {
58513
+ current.forEach(visit);
58514
+ return;
58515
+ }
58516
+ Object.entries(current).forEach(([key, item]) => {
58517
+ if ((key === 'show_display' || key === 'showOnOneKey') && typeof item === 'boolean') {
58518
+ seen = true;
58519
+ enabled || (enabled = item);
58520
+ return;
58521
+ }
58522
+ visit(item);
58523
+ });
58524
+ };
58525
+ visit(value);
58526
+ return { seen, enabled };
58527
+ };
58528
+ const createMethodInteraction = (reason, operation) => ({
58529
+ request: 'button',
58530
+ source: 'method-lifecycle',
58531
+ reason,
58532
+ completion: 'operation-completed',
58533
+ deviceOnly: true,
58534
+ operation,
58535
+ });
58536
+ const hasCipherConfirmation = (value) => {
58537
+ if (Array.isArray(value))
58538
+ return value.some(hasCipherConfirmation);
58539
+ if (value == null || typeof value !== 'object')
58540
+ return false;
58541
+ const params = value;
58542
+ return params.encrypt === true ? params.ask_on_encrypt === true : params.ask_on_decrypt === true;
58543
+ };
58544
+ const resolveProtocolV2UiInteraction = (method) => {
58545
+ if (method.protocolV2UiInteraction)
58546
+ return method.protocolV2UiInteraction;
58547
+ const operation = method.name;
58548
+ if (!operation)
58549
+ return undefined;
58550
+ const isAddress = /getAddress(?:ByLoop)?$/i.test(operation);
58551
+ const isPublicKey = /getPublicKey$/i.test(operation);
58552
+ if (isAddress || isPublicKey) {
58553
+ const paramsDisplay = getDisplayState(method.params);
58554
+ const payloadDisplay = getDisplayState(method.payload);
58555
+ const display = paramsDisplay.seen ? paramsDisplay : payloadDisplay;
58556
+ const shouldDisplay = display.seen ? display.enabled : isAddress;
58557
+ if (!shouldDisplay)
58558
+ return undefined;
58559
+ return createMethodInteraction(isAddress ? 'address-confirmation' : 'public-key-confirmation', operation);
58560
+ }
58561
+ if (/sign/i.test(operation) || /verifyMessage$/i.test(operation) || operation === 'lnurlAuth') {
58562
+ return createMethodInteraction('signing-confirmation', operation);
58563
+ }
58564
+ if (operation === 'nostrEncryptMessage' || operation === 'nostrDecryptMessage') {
58565
+ const display = getDisplayState(method.params);
58566
+ if (!display.enabled)
58567
+ return undefined;
58568
+ return createMethodInteraction('signing-confirmation', operation);
58569
+ }
58570
+ if (operation === 'cipherKeyValue' && hasCipherConfirmation(method.params)) {
58571
+ return createMethodInteraction('signing-confirmation', operation);
58572
+ }
58573
+ return undefined;
58574
+ };
58575
+ class ProtocolV2UiInteractionCoordinator {
58576
+ constructor(device, postMessage) {
58577
+ this.opened = false;
58578
+ this.closed = false;
58579
+ this.device = device;
58580
+ this.postMessage = postMessage;
58581
+ }
58582
+ enterMethodInteraction(interaction) {
58583
+ var _a, _b;
58584
+ this.methodInteraction = interaction;
58585
+ if (!interaction)
58586
+ return;
58587
+ const { request } = interaction, metadata = __rest(interaction, ["request"]);
58588
+ this.emit(request === 'pin' ? UI_REQUEST.REQUEST_PIN : UI_REQUEST.REQUEST_BUTTON, Object.assign({ device: this.device.toMessageObject() }, metadata), `method:${request}:${interaction.reason}:${(_a = interaction.page) !== null && _a !== void 0 ? _a : ''}:${(_b = interaction.operation) !== null && _b !== void 0 ? _b : ''}`);
58589
+ }
58590
+ enterUnlockInteraction(method) {
58591
+ this.emit(UI_REQUEST.REQUEST_PIN, {
58592
+ device: this.device.toMessageObject(),
58593
+ source: 'unlock-coordinator',
58594
+ reason: 'device-locked',
58595
+ deviceOnly: true,
58596
+ method,
58597
+ }, `unlock:${method !== null && method !== void 0 ? method : ''}`);
58598
+ }
58599
+ resumeMethodInteraction() {
58600
+ this.enterMethodInteraction(this.methodInteraction);
58601
+ }
58602
+ close() {
58603
+ if (!this.device.isProtocolV2() || !this.opened || this.closed)
58604
+ return;
58605
+ this.closed = true;
58606
+ this.postMessage(createUiMessage(UI_REQUEST.CLOSE_UI_WINDOW));
58607
+ }
58608
+ emit(type, payload, phase) {
58609
+ if (!this.device.isProtocolV2() || this.closed || this.currentPhase === phase)
58610
+ return;
58611
+ this.currentPhase = phase;
58612
+ this.opened = true;
58613
+ const message = type === UI_REQUEST.REQUEST_BUTTON
58614
+ ? createUiMessage(UI_REQUEST.REQUEST_BUTTON, payload)
58615
+ : createUiMessage(UI_REQUEST.REQUEST_PIN, payload);
58616
+ this.postMessage(message);
58617
+ }
58618
+ }
58619
+
58210
58620
  const Log$1 = getLogger(exports.LoggerNames.Core);
58211
- function runMethodWithUnlockRetry(method, device) {
58621
+ function runMethodWithUnlockRetry(method, device, uiCoordinator) {
58622
+ var _a;
58212
58623
  return __awaiter(this, void 0, void 0, function* () {
58624
+ const shouldEmitUi = isProtocolV2UiEnabled(method);
58625
+ const shouldUnlockBeforeRun = device.isProtocolV2() &&
58626
+ method.unlockPolicy === 'retry-on-locked' &&
58627
+ ((_a = device.features) === null || _a === void 0 ? void 0 : _a.unlocked) === false;
58628
+ if (shouldUnlockBeforeRun) {
58629
+ if (shouldEmitUi) {
58630
+ uiCoordinator === null || uiCoordinator === void 0 ? void 0 : uiCoordinator.enterUnlockInteraction(method.name);
58631
+ }
58632
+ yield device.unlockDevice();
58633
+ Log$1.debug('Protocol V2 pre-unlock completed', { method: method.name });
58634
+ if (shouldEmitUi) {
58635
+ uiCoordinator === null || uiCoordinator === void 0 ? void 0 : uiCoordinator.enterMethodInteraction(resolveProtocolV2UiInteraction(method));
58636
+ }
58637
+ return method.run();
58638
+ }
58639
+ if (shouldEmitUi) {
58640
+ uiCoordinator === null || uiCoordinator === void 0 ? void 0 : uiCoordinator.enterMethodInteraction(resolveProtocolV2UiInteraction(method));
58641
+ }
58213
58642
  try {
58214
58643
  return yield method.run();
58215
58644
  }
@@ -58220,8 +58649,14 @@ function runMethodWithUnlockRetry(method, device) {
58220
58649
  throw error;
58221
58650
  }
58222
58651
  Log$1.debug('Protocol V2 unlock retry triggered', { method: method.name });
58652
+ if (shouldEmitUi) {
58653
+ uiCoordinator === null || uiCoordinator === void 0 ? void 0 : uiCoordinator.enterUnlockInteraction(method.name);
58654
+ }
58223
58655
  yield device.unlockDevice();
58224
58656
  Log$1.debug('Protocol V2 unlock completed', { method: method.name });
58657
+ if (shouldEmitUi) {
58658
+ uiCoordinator === null || uiCoordinator === void 0 ? void 0 : uiCoordinator.resumeMethodInteraction();
58659
+ }
58225
58660
  try {
58226
58661
  const response = yield method.run();
58227
58662
  Log$1.debug('Protocol V2 method retry completed', { method: method.name, success: true });
@@ -58468,9 +58903,11 @@ const onCallDevice = (context, message, method) => __awaiter(void 0, void 0, voi
58468
58903
  ? onEmptyPassphraseHandler
58469
58904
  : onDevicePassphraseHandler,
58470
58905
  passphraseOnDevice: onEnterPassphraseOnDeviceHandler,
58906
+ attachPinOnDevice: onEnterAttachPinOnDeviceHandler,
58471
58907
  });
58472
58908
  device.on(DEVICE.FEATURES, onDeviceFeaturesHandler);
58473
58909
  device.on(DEVICE.SELECT_DEVICE_IN_BOOTLOADER_FOR_WEB_DEVICE, onSelectDeviceInBootloaderForWebDeviceHandler);
58910
+ const protocolV2UiCoordinator = new ProtocolV2UiInteractionCoordinator(device, postMessage);
58474
58911
  device.on(DEVICE.SELECT_DEVICE_FOR_SWITCH_FIRMWARE_WEB_DEVICE, onSelectDeviceForSwitchFirmwareWebDeviceHandler);
58475
58912
  try {
58476
58913
  if (method.connectId) {
@@ -58590,7 +59027,7 @@ const onCallDevice = (context, message, method) => __awaiter(void 0, void 0, voi
58590
59027
  }
58591
59028
  (_p = (_o = method.device) === null || _o === void 0 ? void 0 : _o.commands) === null || _p === void 0 ? void 0 : _p.checkDisposed();
58592
59029
  try {
58593
- const response = yield runMethodWithUnlockRetry(method, device);
59030
+ const response = yield runMethodWithUnlockRetry(method, device, protocolV2UiCoordinator);
58594
59031
  messageResponse = createResponseMessage(method.responseID, true, response);
58595
59032
  requestQueue.resolveRequest(method.responseID, messageResponse);
58596
59033
  completeMethodRequestContext(method);
@@ -58605,6 +59042,9 @@ const onCallDevice = (context, message, method) => __awaiter(void 0, void 0, voi
58605
59042
  throw error;
58606
59043
  }
58607
59044
  }
59045
+ finally {
59046
+ protocolV2UiCoordinator.close();
59047
+ }
58608
59048
  });
58609
59049
  Log.debug('Call API - Device Run: ', device.mainId);
58610
59050
  const runOptions = Object.assign({ keepSession: method.payload.keepSession, skipInitialize: canSkipInitialize(method, device) }, parseInitOptions(method));
@@ -58634,7 +59074,9 @@ const onCallDevice = (context, message, method) => __awaiter(void 0, void 0, voi
58634
59074
  }
58635
59075
  }
58636
59076
  requestQueue.releaseTask(method.responseID);
58637
- closePopup();
59077
+ if (isProtocolV2UiEnabled(method)) {
59078
+ closePopup();
59079
+ }
58638
59080
  cleanup();
58639
59081
  if (device) {
58640
59082
  const stillActive = getActiveRequestsByDeviceInstance(device.instanceId);
@@ -59062,6 +59504,9 @@ const onDevicePassphraseHandler = (...[device, requestPayload, callback]) => __a
59062
59504
  device: device.toMessageObject(),
59063
59505
  passphraseState: device.passphraseState,
59064
59506
  existsAttachPinUser: requestPayload.existsAttachPinUser,
59507
+ source: requestPayload.source,
59508
+ reason: requestPayload.reason,
59509
+ expectedPassphraseState: requestPayload.expectedPassphraseState,
59065
59510
  }));
59066
59511
  const uiResp = yield uiPromise.promise;
59067
59512
  const { value, passphraseOnDevice, save, attachPinOnDevice } = uiResp.payload;
@@ -59076,10 +59521,20 @@ const onEmptyPassphraseHandler = (...[_, , callback]) => {
59076
59521
  Log.debug('onEmptyPassphraseHandler');
59077
59522
  callback({ passphrase: '' });
59078
59523
  };
59079
- const onEnterPassphraseOnDeviceHandler = (...[device]) => {
59524
+ const onEnterPassphraseOnDeviceHandler = (...[device, requestPayload]) => {
59080
59525
  postMessage(createUiMessage(UI_REQUEST.REQUEST_PASSPHRASE_ON_DEVICE, {
59081
59526
  device: device.toMessageObject(),
59082
59527
  passphraseState: device.passphraseState,
59528
+ source: requestPayload === null || requestPayload === void 0 ? void 0 : requestPayload.source,
59529
+ reason: requestPayload === null || requestPayload === void 0 ? void 0 : requestPayload.reason,
59530
+ }));
59531
+ };
59532
+ const onEnterAttachPinOnDeviceHandler = (...[device, requestPayload]) => {
59533
+ postMessage(createUiMessage(UI_REQUEST.REQUEST_PIN, {
59534
+ device: device.toMessageObject(),
59535
+ type: 'ButtonRequest_AttachPin',
59536
+ source: requestPayload === null || requestPayload === void 0 ? void 0 : requestPayload.source,
59537
+ reason: requestPayload === null || requestPayload === void 0 ? void 0 : requestPayload.reason,
59083
59538
  }));
59084
59539
  };
59085
59540
  const onSelectDeviceInBootloaderForWebDeviceHandler = (...[device, callback]) => __awaiter(void 0, void 0, void 0, function* () {