@trezor/connect 9.7.0-beta.1 → 9.7.0

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 (408) hide show
  1. package/CHANGELOG.md +49 -16
  2. package/README.md +1 -1
  3. package/lib/api/applyFlags.js +31 -26
  4. package/lib/api/applySettings.js +43 -40
  5. package/lib/api/authenticateDevice.js +82 -54
  6. package/lib/api/authorizeCoinjoin.js +35 -28
  7. package/lib/api/backupDevice.js +32 -27
  8. package/lib/api/bitcoin/TransactionComposer.js +131 -123
  9. package/lib/api/bitcoin/createPendingTx.js +55 -52
  10. package/lib/api/bitcoin/enhanceSignTx.js +57 -55
  11. package/lib/api/bitcoin/index.js +4 -1
  12. package/lib/api/bitcoin/inputs.js +71 -46
  13. package/lib/api/bitcoin/outputs.js +108 -85
  14. package/lib/api/bitcoin/refTx.d.ts +1 -1
  15. package/lib/api/bitcoin/refTx.js +233 -201
  16. package/lib/api/bitcoin/signtx.js +208 -152
  17. package/lib/api/bitcoin/signtxLegacy.js +169 -119
  18. package/lib/api/bitcoin/signtxVerify.js +80 -67
  19. package/lib/api/bitcoin/transactionBytes.js +61 -59
  20. package/lib/api/bleUnpair.js +28 -25
  21. package/lib/api/blockchainDisconnect.js +31 -24
  22. package/lib/api/blockchainEstimateFee.js +94 -61
  23. package/lib/api/blockchainEvmRpcCall.js +51 -34
  24. package/lib/api/blockchainGetAccountBalanceHistory.d.ts +1 -1
  25. package/lib/api/blockchainGetAccountBalanceHistory.js +50 -32
  26. package/lib/api/blockchainGetCurrentFiatRates.d.ts +1 -1
  27. package/lib/api/blockchainGetCurrentFiatRates.js +43 -29
  28. package/lib/api/blockchainGetFiatRatesForTimestamps.d.ts +1 -1
  29. package/lib/api/blockchainGetFiatRatesForTimestamps.js +49 -32
  30. package/lib/api/blockchainGetInfo.js +31 -22
  31. package/lib/api/blockchainGetTransactions.d.ts +1 -1
  32. package/lib/api/blockchainGetTransactions.js +36 -24
  33. package/lib/api/blockchainSetCustomBackend.js +34 -25
  34. package/lib/api/blockchainSubscribe.js +57 -36
  35. package/lib/api/blockchainSubscribeFiatRates.js +36 -24
  36. package/lib/api/blockchainUnsubscribe.js +57 -37
  37. package/lib/api/blockchainUnsubscribeFiatRates.js +31 -22
  38. package/lib/api/cancelCoinjoinAuthorization.js +26 -20
  39. package/lib/api/cardano/api/cardanoComposeTransaction.js +75 -50
  40. package/lib/api/cardano/api/cardanoGetAddress.js +105 -102
  41. package/lib/api/cardano/api/cardanoGetNativeScriptHash.js +59 -56
  42. package/lib/api/cardano/api/cardanoGetPublicKey.js +58 -58
  43. package/lib/api/cardano/api/cardanoSignMessage.js +81 -78
  44. package/lib/api/cardano/api/cardanoSignTransaction.js +269 -240
  45. package/lib/api/cardano/api/index.js +40 -7
  46. package/lib/api/cardano/cardanoAddressParameters.js +71 -65
  47. package/lib/api/cardano/cardanoAuxiliaryData.js +68 -63
  48. package/lib/api/cardano/cardanoCertificate.js +124 -119
  49. package/lib/api/cardano/cardanoInputs.js +33 -33
  50. package/lib/api/cardano/cardanoOutputs.d.ts +1 -1
  51. package/lib/api/cardano/cardanoOutputs.js +63 -61
  52. package/lib/api/cardano/cardanoTokenBundle.d.ts +2 -2
  53. package/lib/api/cardano/cardanoTokenBundle.js +18 -13
  54. package/lib/api/cardano/cardanoUtils.js +94 -89
  55. package/lib/api/cardano/cardanoWitnesses.js +46 -42
  56. package/lib/api/changeLanguage.js +40 -29
  57. package/lib/api/changePin.js +21 -16
  58. package/lib/api/changeWipeCode.js +24 -16
  59. package/lib/api/cipherKeyValue.js +42 -41
  60. package/lib/api/common/Discovery.js +114 -112
  61. package/lib/api/common/paramsValidator.js +110 -116
  62. package/lib/api/composeTransaction.d.ts +1 -1
  63. package/lib/api/composeTransaction.js +307 -256
  64. package/lib/api/discoverAccounts.js +291 -191
  65. package/lib/api/eos/api/eosGetPublicKey.js +56 -52
  66. package/lib/api/eos/api/eosSignTransaction.js +35 -26
  67. package/lib/api/eos/api/index.js +16 -3
  68. package/lib/api/eos/eosSignTx.js +308 -312
  69. package/lib/api/ethereum/api/ethereumGetAddress.js +106 -107
  70. package/lib/api/ethereum/api/ethereumGetPublicKey.js +72 -62
  71. package/lib/api/ethereum/api/ethereumSignMessage.js +55 -48
  72. package/lib/api/ethereum/api/ethereumSignTransaction.d.ts +33 -0
  73. package/lib/api/ethereum/api/ethereumSignTransaction.js +137 -132
  74. package/lib/api/ethereum/api/ethereumSignTypedData.d.ts +4 -4
  75. package/lib/api/ethereum/api/ethereumSignTypedData.js +183 -181
  76. package/lib/api/ethereum/api/ethereumVerifyMessage.js +27 -24
  77. package/lib/api/ethereum/api/index.js +40 -7
  78. package/lib/api/ethereum/ethereumDefinitions.js +94 -87
  79. package/lib/api/ethereum/ethereumSignTx.js +116 -111
  80. package/lib/api/ethereum/ethereumSignTypedData.js +98 -95
  81. package/lib/api/evoluGetDelegatedIdentityKey.js +30 -26
  82. package/lib/api/evoluGetNode.js +24 -19
  83. package/lib/api/evoluSignRegistrationRequest.js +26 -21
  84. package/lib/api/firmware/calculateFirmwareHash.js +44 -32
  85. package/lib/api/firmware/getBinary.js +30 -22
  86. package/lib/api/firmware/index.js +46 -8
  87. package/lib/api/firmware/modifyFirmware.js +13 -12
  88. package/lib/api/firmware/parseFirmwareHeaders.js +29 -30
  89. package/lib/api/firmware/uploadFirmware.js +84 -67
  90. package/lib/api/firmware/verifyEntropy.js +88 -83
  91. package/lib/api/getAccountDescriptor.js +118 -120
  92. package/lib/api/getAccountInfo.d.ts +14 -14
  93. package/lib/api/getAccountInfo.js +316 -287
  94. package/lib/api/getAddress.js +128 -118
  95. package/lib/api/getCoinInfo.js +22 -17
  96. package/lib/api/getDeviceState.js +16 -10
  97. package/lib/api/getFeatures.d.ts +1 -1
  98. package/lib/api/getFeatures.js +15 -12
  99. package/lib/api/getFirmwareHash.js +23 -18
  100. package/lib/api/getNonce.js +12 -9
  101. package/lib/api/getOwnershipId.js +57 -51
  102. package/lib/api/getOwnershipProof.js +66 -60
  103. package/lib/api/getPublicKey.js +72 -66
  104. package/lib/api/getSettings.js +12 -9
  105. package/lib/api/index.js +346 -58
  106. package/lib/api/loadDevice.js +40 -35
  107. package/lib/api/monero/api/index.js +28 -5
  108. package/lib/api/monero/api/moneroGetAddress.js +108 -97
  109. package/lib/api/monero/api/moneroGetWatchKey.js +37 -32
  110. package/lib/api/monero/api/moneroKeyImageSync.js +111 -107
  111. package/lib/api/monero/api/moneroSignTransaction.js +173 -185
  112. package/lib/api/nem/api/index.js +16 -3
  113. package/lib/api/nem/api/nemGetAddress.js +107 -102
  114. package/lib/api/nem/api/nemSignTransaction.js +25 -20
  115. package/lib/api/nem/nemSignTx.js +128 -125
  116. package/lib/api/pushTransaction.js +31 -27
  117. package/lib/api/recoveryDevice.js +44 -39
  118. package/lib/api/requestLogin.d.ts +0 -1
  119. package/lib/api/requestLogin.js +47 -52
  120. package/lib/api/resetDevice.js +100 -90
  121. package/lib/api/ripple/api/index.js +16 -3
  122. package/lib/api/ripple/api/rippleGetAddress.js +92 -88
  123. package/lib/api/ripple/api/rippleSignTransaction.js +44 -34
  124. package/lib/api/setBrightness.js +21 -16
  125. package/lib/api/setBusy.js +27 -20
  126. package/lib/api/setProxy.js +22 -15
  127. package/lib/api/showDeviceTutorial.js +18 -15
  128. package/lib/api/signMessage.js +50 -46
  129. package/lib/api/signTransaction.js +325 -238
  130. package/lib/api/solana/additionalInfo.js +17 -14
  131. package/lib/api/solana/api/index.js +28 -5
  132. package/lib/api/solana/api/solanaComposeTransaction.js +46 -50
  133. package/lib/api/solana/api/solanaGetAddress.js +92 -90
  134. package/lib/api/solana/api/solanaGetPublicKey.js +56 -52
  135. package/lib/api/solana/api/solanaSignTransaction.js +175 -168
  136. package/lib/api/solana/solanaDefinitions.js +32 -25
  137. package/lib/api/solana/solanaUtils.d.ts +2 -2
  138. package/lib/api/solana/solanaUtils.js +231 -177
  139. package/lib/api/stellar/api/index.js +16 -3
  140. package/lib/api/stellar/api/stellarGetAddress.js +92 -88
  141. package/lib/api/stellar/api/stellarSignTransaction.js +51 -44
  142. package/lib/api/stellar/stellarSignTx.js +184 -179
  143. package/lib/api/tezos/api/index.js +22 -4
  144. package/lib/api/tezos/api/tezosGetAddress.js +92 -88
  145. package/lib/api/tezos/api/tezosGetPublicKey.js +55 -51
  146. package/lib/api/tezos/api/tezosSignTransaction.js +23 -18
  147. package/lib/api/tezos/tezosSignTx.js +183 -169
  148. package/lib/api/thpGetCredentials.js +23 -20
  149. package/lib/api/thpRemoveCredentials.js +28 -21
  150. package/lib/api/unlockPath.js +28 -21
  151. package/lib/api/verifyMessage.js +35 -33
  152. package/lib/api/wipeDevice.js +39 -34
  153. package/lib/backend/BackendManager.js +127 -107
  154. package/lib/backend/Blockchain.d.ts +1 -1
  155. package/lib/backend/Blockchain.js +220 -205
  156. package/lib/backend/BlockchainLink.js +17 -5
  157. package/lib/backend/fees/BitcoinFeeLevels.js +41 -34
  158. package/lib/backend/fees/EthereumFeeLevels.js +51 -51
  159. package/lib/backend/fees/MiscFeeLevels.js +25 -24
  160. package/lib/backend/fees/index.js +28 -21
  161. package/lib/constants/cardano.js +11 -8
  162. package/lib/constants/errors.js +72 -65
  163. package/lib/constants/firmware.js +5 -5
  164. package/lib/constants/index.js +16 -3
  165. package/lib/constants/nem.js +19 -16
  166. package/lib/constants/network.js +15 -22
  167. package/lib/constants/utxo.js +4 -1
  168. package/lib/core/AbstractMethod.d.ts +1 -1
  169. package/lib/core/AbstractMethod.js +248 -224
  170. package/lib/core/index.js +936 -775
  171. package/lib/core/method.js +19 -16
  172. package/lib/core/method.native.js +28 -23
  173. package/lib/core/onCallFirmwareUpdate.js +368 -299
  174. package/lib/data/DataManager.js +85 -77
  175. package/lib/data/analyticsInfo.js +35 -29
  176. package/lib/data/coinInfo.js +154 -156
  177. package/lib/data/config.d.ts +1 -1
  178. package/lib/data/config.js +362 -330
  179. package/lib/data/connectSettings.js +131 -144
  180. package/lib/data/defaultFeeLevels.js +154 -108
  181. package/lib/data/firmwareInfo.d.ts +1 -0
  182. package/lib/data/firmwareInfo.js +407 -377
  183. package/lib/data/thpSettings.js +36 -35
  184. package/lib/data/udevInfo.js +24 -24
  185. package/lib/data/version.d.ts +1 -1
  186. package/lib/data/version.js +6 -5
  187. package/lib/device/Device.d.ts +6 -7
  188. package/lib/device/Device.js +731 -749
  189. package/lib/device/DeviceCommands.js +226 -194
  190. package/lib/device/DeviceCurrentSession.d.ts +333 -333
  191. package/lib/device/DeviceCurrentSession.js +235 -236
  192. package/lib/device/DeviceList.d.ts +2 -0
  193. package/lib/device/DeviceList.js +219 -181
  194. package/lib/device/StateStorage.js +32 -29
  195. package/lib/device/TransportList.d.ts +1 -1
  196. package/lib/device/TransportList.js +37 -36
  197. package/lib/device/TransportManager.js +136 -140
  198. package/lib/device/calculateRevisionForDevice.js +20 -14
  199. package/lib/device/checkFirmwareRevision.js +66 -54
  200. package/lib/device/resolveDescriptorForTaproot.js +26 -16
  201. package/lib/device/thp/handshake.js +95 -82
  202. package/lib/device/thp/index.js +53 -38
  203. package/lib/device/thp/pairing.js +209 -199
  204. package/lib/device/thp/session.js +27 -19
  205. package/lib/device/thp/thpCall.js +53 -43
  206. package/lib/device/workflow/checkFirmwareHash.js +77 -67
  207. package/lib/device/workflow/checkFirmwareHashWithRetries.js +32 -29
  208. package/lib/device/workflow/handshake.js +50 -41
  209. package/lib/device/workflow/index.js +10 -2
  210. package/lib/device/workflow/trezorPushNotification.js +68 -64
  211. package/lib/device/workflow/validateState.js +155 -129
  212. package/lib/events/blockchain.js +13 -10
  213. package/lib/events/call.d.ts +6 -4
  214. package/lib/events/call.js +14 -13
  215. package/lib/events/core.js +24 -21
  216. package/lib/events/device.d.ts +2 -2
  217. package/lib/events/device.js +32 -19
  218. package/lib/events/iframe.js +13 -10
  219. package/lib/events/index.d.ts +0 -1
  220. package/lib/events/index.js +6 -3
  221. package/lib/events/popup.js +20 -17
  222. package/lib/events/transport.d.ts +2 -2
  223. package/lib/events/transport.js +16 -11
  224. package/lib/events/ui-promise.js +4 -1
  225. package/lib/events/ui-request.d.ts +0 -4
  226. package/lib/events/ui-request.js +48 -46
  227. package/lib/events/ui-response.d.ts +2 -2
  228. package/lib/events/ui-response.js +20 -17
  229. package/lib/events/webextension.js +9 -6
  230. package/lib/exports.js +10 -2
  231. package/lib/factory.d.ts +3 -2
  232. package/lib/factory.js +34 -143
  233. package/lib/impl/core-in-module.d.ts +1 -6
  234. package/lib/impl/core-in-module.js +187 -191
  235. package/lib/impl/dynamic.d.ts +0 -1
  236. package/lib/impl/dynamic.js +108 -97
  237. package/lib/index-browser.d.ts +1 -0
  238. package/lib/index-browser.js +18 -16
  239. package/lib/index.d.ts +2 -0
  240. package/lib/index.js +144 -148
  241. package/lib/types/account.js +4 -1
  242. package/lib/types/api/applyFlags.js +4 -1
  243. package/lib/types/api/applySettings.d.ts +2 -2
  244. package/lib/types/api/applySettings.js +7 -7
  245. package/lib/types/api/authenticateDevice.js +7 -4
  246. package/lib/types/api/authorizeCoinjoin.js +13 -10
  247. package/lib/types/api/backupDevice.js +4 -1
  248. package/lib/types/api/bitcoin/index.d.ts +5 -2
  249. package/lib/types/api/bitcoin/index.js +14 -11
  250. package/lib/types/api/bleUnpair.js +4 -1
  251. package/lib/types/api/blockchainDisconnect.js +4 -1
  252. package/lib/types/api/blockchainEstimateFee.js +4 -1
  253. package/lib/types/api/blockchainEvmRpcCall.js +4 -1
  254. package/lib/types/api/blockchainGetAccountBalanceHistory.js +4 -1
  255. package/lib/types/api/blockchainGetCurrentFiatRates.js +4 -1
  256. package/lib/types/api/blockchainGetFiatRatesForTimestamps.js +4 -1
  257. package/lib/types/api/blockchainGetInfo.js +4 -1
  258. package/lib/types/api/blockchainGetTransactions.js +4 -1
  259. package/lib/types/api/blockchainSetCustomBackend.js +4 -1
  260. package/lib/types/api/blockchainSubscribe.js +4 -1
  261. package/lib/types/api/blockchainSubscribeFiatRates.js +4 -1
  262. package/lib/types/api/blockchainUnsubscribe.js +4 -1
  263. package/lib/types/api/blockchainUnsubscribeFiatRates.js +4 -1
  264. package/lib/types/api/cancel.js +4 -1
  265. package/lib/types/api/cancelCoinjoinAuthorization.js +5 -2
  266. package/lib/types/api/cardano/index.d.ts +4 -4
  267. package/lib/types/api/cardano/index.js +173 -180
  268. package/lib/types/api/cardanoComposeTransaction.js +76 -65
  269. package/lib/types/api/cardanoGetAddress.js +4 -1
  270. package/lib/types/api/cardanoGetNativeScriptHash.js +4 -1
  271. package/lib/types/api/cardanoGetPublicKey.js +4 -1
  272. package/lib/types/api/cardanoSignMessage.js +4 -1
  273. package/lib/types/api/cardanoSignTransaction.js +4 -1
  274. package/lib/types/api/changeLanguage.d.ts +1 -1
  275. package/lib/types/api/changeLanguage.js +13 -13
  276. package/lib/types/api/changePin.js +4 -1
  277. package/lib/types/api/changeWipeCode.js +4 -1
  278. package/lib/types/api/cipherKeyValue.d.ts +2 -2
  279. package/lib/types/api/cipherKeyValue.js +11 -8
  280. package/lib/types/api/composeTransaction.js +4 -1
  281. package/lib/types/api/device.js +1 -2
  282. package/lib/types/api/disableWebUSB.js +4 -1
  283. package/lib/types/api/discoverAccounts.js +204 -55
  284. package/lib/types/api/dispose.js +4 -1
  285. package/lib/types/api/eos/index.d.ts +3 -3
  286. package/lib/types/api/eos/index.js +106 -162
  287. package/lib/types/api/eosGetPublicKey.js +4 -1
  288. package/lib/types/api/eosSignTransaction.js +4 -1
  289. package/lib/types/api/ethereum/index.d.ts +7 -7
  290. package/lib/types/api/ethereum/index.js +70 -67
  291. package/lib/types/api/ethereumGetAddress.js +4 -1
  292. package/lib/types/api/ethereumGetPublicKey.js +4 -1
  293. package/lib/types/api/ethereumSignMessage.js +4 -1
  294. package/lib/types/api/ethereumSignTransaction.js +4 -1
  295. package/lib/types/api/ethereumSignTypedData.js +4 -1
  296. package/lib/types/api/ethereumVerifyMessage.js +4 -1
  297. package/lib/types/api/evoluGetDelegatedIdentityKey.js +4 -1
  298. package/lib/types/api/evoluGetNode.js +4 -1
  299. package/lib/types/api/evoluSignRegistrationRequest.js +4 -1
  300. package/lib/types/api/firmwareUpdate.d.ts +1 -1
  301. package/lib/types/api/firmwareUpdate.js +12 -12
  302. package/lib/types/api/getAccountDescriptor.js +8 -5
  303. package/lib/types/api/getAccountInfo.js +4 -1
  304. package/lib/types/api/getAddress.js +11 -11
  305. package/lib/types/api/getCoinInfo.js +4 -1
  306. package/lib/types/api/getDeviceState.js +4 -1
  307. package/lib/types/api/getFeatures.js +4 -1
  308. package/lib/types/api/getFirmwareHash.js +4 -1
  309. package/lib/types/api/getNonce.d.ts +1 -1
  310. package/lib/types/api/getNonce.js +4 -1
  311. package/lib/types/api/getOwnershipId.js +8 -5
  312. package/lib/types/api/getOwnershipProof.js +14 -9
  313. package/lib/types/api/getPublicKey.js +25 -28
  314. package/lib/types/api/getSettings.js +4 -1
  315. package/lib/types/api/index.js +4 -1
  316. package/lib/types/api/init.js +4 -1
  317. package/lib/types/api/loadDevice.js +4 -1
  318. package/lib/types/api/manifest.js +4 -1
  319. package/lib/types/api/monero/index.js +117 -114
  320. package/lib/types/api/moneroGetAddress.js +4 -1
  321. package/lib/types/api/moneroGetWatchKey.js +4 -1
  322. package/lib/types/api/moneroKeyImageSync.js +4 -1
  323. package/lib/types/api/moneroSignTransaction.js +4 -1
  324. package/lib/types/api/nem/index.d.ts +7 -7
  325. package/lib/types/api/nem/index.js +78 -112
  326. package/lib/types/api/nemGetAddress.js +7 -7
  327. package/lib/types/api/nemSignTransaction.js +4 -1
  328. package/lib/types/api/off.js +4 -1
  329. package/lib/types/api/on.js +4 -1
  330. package/lib/types/api/pushTransaction.js +10 -10
  331. package/lib/types/api/recoveryDevice.d.ts +1 -1
  332. package/lib/types/api/recoveryDevice.js +7 -7
  333. package/lib/types/api/removeAllListeners.js +4 -1
  334. package/lib/types/api/renderWebUSBButton.js +4 -1
  335. package/lib/types/api/requestLogin.d.ts +4 -24
  336. package/lib/types/api/requestLogin.js +11 -13
  337. package/lib/types/api/requestWebUSBDevice.js +4 -1
  338. package/lib/types/api/resetDevice.js +4 -1
  339. package/lib/types/api/ripple/index.js +17 -14
  340. package/lib/types/api/rippleGetAddress.js +4 -1
  341. package/lib/types/api/rippleSignTransaction.js +4 -1
  342. package/lib/types/api/setBrightness.js +4 -1
  343. package/lib/types/api/setBusy.js +4 -1
  344. package/lib/types/api/setProxy.js +4 -1
  345. package/lib/types/api/setTransports.js +4 -1
  346. package/lib/types/api/showDeviceTutorial.js +4 -1
  347. package/lib/types/api/signMessage.js +4 -1
  348. package/lib/types/api/signTransaction.js +4 -1
  349. package/lib/types/api/solana/index.js +55 -56
  350. package/lib/types/api/solanaComposeTransaction.js +4 -1
  351. package/lib/types/api/solanaGetAddress.js +4 -1
  352. package/lib/types/api/solanaGetPublicKey.js +4 -1
  353. package/lib/types/api/solanaSignTransaction.js +4 -1
  354. package/lib/types/api/stellar/index.d.ts +146 -146
  355. package/lib/types/api/stellar/index.js +151 -221
  356. package/lib/types/api/stellarGetAddress.js +4 -1
  357. package/lib/types/api/stellarSignTransaction.js +4 -1
  358. package/lib/types/api/tezos/index.js +46 -43
  359. package/lib/types/api/tezosGetAddress.js +4 -1
  360. package/lib/types/api/tezosGetPublicKey.js +4 -1
  361. package/lib/types/api/tezosSignTransaction.js +4 -1
  362. package/lib/types/api/thpGetCredentials.js +4 -1
  363. package/lib/types/api/thpRemoveCredentials.js +4 -1
  364. package/lib/types/api/uiResponse.js +4 -1
  365. package/lib/types/api/unlockPath.js +6 -3
  366. package/lib/types/api/verifyMessage.js +4 -1
  367. package/lib/types/api/wipeDevice.js +4 -1
  368. package/lib/types/coinInfo.js +62 -77
  369. package/lib/types/device.d.ts +7 -2
  370. package/lib/types/device.js +7 -4
  371. package/lib/types/fees.js +31 -37
  372. package/lib/types/firmware.js +4 -1
  373. package/lib/types/index.d.ts +1 -0
  374. package/lib/types/index.js +18 -3
  375. package/lib/types/params.js +25 -16
  376. package/lib/types/settings.js +4 -1
  377. package/lib/types/utils.js +4 -1
  378. package/lib/types/workflow.js +4 -1
  379. package/lib/utils/accountUtils.js +76 -81
  380. package/lib/utils/addressUtils.js +21 -21
  381. package/lib/utils/assetUtils.js +29 -26
  382. package/lib/utils/assets-browser.js +19 -13
  383. package/lib/utils/assets.js +10 -9
  384. package/lib/utils/assets.native.js +24 -23
  385. package/lib/utils/assetsTypes.js +4 -1
  386. package/lib/utils/debug.js +18 -13
  387. package/lib/utils/deviceFeaturesUtils.js +105 -127
  388. package/lib/utils/ethereumUtils.js +9 -6
  389. package/lib/utils/firmwareReleaseConfigUtils.js +69 -57
  390. package/lib/utils/firmwareUtils.js +45 -57
  391. package/lib/utils/formatUtils.d.ts +0 -1
  392. package/lib/utils/formatUtils.js +63 -62
  393. package/lib/utils/hdnodeUtils.d.ts +0 -1
  394. package/lib/utils/hdnodeUtils.js +51 -57
  395. package/lib/utils/interactionTimeout.js +26 -23
  396. package/lib/utils/pathUtils.js +132 -148
  397. package/lib/utils/popupPromiseManager.js +23 -14
  398. package/lib/utils/proxy-event-emitter.js +63 -60
  399. package/lib/utils/uiPromiseManager.js +55 -43
  400. package/lib/utils/urlUtils.js +20 -26
  401. package/lib/utils/versionCheck.js +10 -10
  402. package/lib/workers/workers-browser.d.ts +5 -5
  403. package/lib/workers/workers-browser.js +5 -2
  404. package/lib/workers/workers.d.ts +1 -1
  405. package/lib/workers/workers.js +49 -38
  406. package/lib/workers/workers.native.d.ts +5 -5
  407. package/lib/workers/workers.native.js +4 -1
  408. package/package.json +23 -20
@@ -1,5 +1,8 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
3
6
  exports.Device = void 0;
4
7
  const device_utils_1 = require("@trezor/device-utils");
5
8
  const protocol_1 = require("@trezor/protocol");
@@ -20,765 +23,744 @@ const assetUtils_1 = require("../utils/assetUtils");
20
23
  const debug_1 = require("../utils/debug");
21
24
  const deviceFeaturesUtils_1 = require("../utils/deviceFeaturesUtils");
22
25
  const firmwareUtils_1 = require("../utils/firmwareUtils");
23
- const trezorPushNotification_1 = require("./workflow/trezorPushNotification");
24
26
  const _log = (0, debug_1.initLog)('Device');
25
27
  class Device extends utils_1.TypedEmitter {
26
- transport;
27
- thp;
28
- descriptor;
29
- sessionAcquired;
30
- _protocol;
31
- get protocol() {
32
- return this._protocol;
33
- }
34
- getThpState() {
35
- return this.thp;
36
- }
37
- unreadableError;
38
- channels = {
39
- 'battery-level': false,
40
- 'trezor-push-notification': false,
28
+ transport;
29
+ thp;
30
+ descriptor;
31
+ sessionAcquired;
32
+ _protocol;
33
+ get protocol() {
34
+ return this._protocol;
35
+ }
36
+ getThpState() {
37
+ return this.thp;
38
+ }
39
+ unreadableError;
40
+ _firmwareStatus;
41
+ get firmwareStatus() {
42
+ return this._firmwareStatus;
43
+ }
44
+ _currentRelease;
45
+ get currentRelease() {
46
+ return this._currentRelease;
47
+ }
48
+ _firmwareReleaseConfigInfo;
49
+ get firmwareReleaseConfigInfo() {
50
+ return this._firmwareReleaseConfigInfo;
51
+ }
52
+ _features;
53
+ get features() {
54
+ return this._features;
55
+ }
56
+ wasUsedElsewhere = false;
57
+ acquirePromise;
58
+ releasePromise;
59
+ runAbort;
60
+ runPromise;
61
+ keepTransportSession = false;
62
+ currentSession;
63
+ instance = 0;
64
+ state = [];
65
+ stateStorage = undefined;
66
+ busy;
67
+ _unavailableCapabilities = {};
68
+ get unavailableCapabilities() {
69
+ return this._unavailableCapabilities;
70
+ }
71
+ _firmwareType;
72
+ get firmwareType() {
73
+ return this._firmwareType;
74
+ }
75
+ get possibleHIDdevice() {
76
+ return this.descriptor.type === 0 || this.descriptor.type === 2;
77
+ }
78
+ get possibleT1() {
79
+ return (this.descriptor.type ?? 0) <= 2;
80
+ }
81
+ name = 'Trezor';
82
+ color;
83
+ availableTranslations = {};
84
+ authenticityChecks = {
85
+ firmwareRevision: null,
86
+ firmwareHash: null
87
+ };
88
+ uniquePath;
89
+ lifecycle = new utils_1.TypedEmitter();
90
+ sessionDfd;
91
+ constructor({
92
+ id,
93
+ transport,
94
+ descriptor
95
+ }) {
96
+ super();
97
+ this._protocol = protocol_1.v1;
98
+ this.uniquePath = id;
99
+ this.transport = transport;
100
+ this.descriptor = {
101
+ id: descriptor.id,
102
+ apiType: descriptor.apiType,
103
+ type: descriptor.type,
104
+ path: descriptor.path
41
105
  };
42
- _firmwareStatus;
43
- get firmwareStatus() {
44
- return this._firmwareStatus;
45
- }
46
- _currentRelease;
47
- get currentRelease() {
48
- return this._currentRelease;
49
- }
50
- _firmwareReleaseConfigInfo;
51
- get firmwareReleaseConfigInfo() {
52
- return this._firmwareReleaseConfigInfo;
53
- }
54
- _features;
55
- get features() {
56
- return this._features;
57
- }
58
- wasUsedElsewhere = false;
59
- acquirePromise;
60
- releasePromise;
61
- runAbort;
62
- runPromise;
63
- keepTransportSession = false;
64
- currentSession;
65
- instance = 0;
66
- state = [];
67
- stateStorage = undefined;
68
- busy;
69
- _unavailableCapabilities = {};
70
- get unavailableCapabilities() {
71
- return this._unavailableCapabilities;
72
- }
73
- _firmwareType;
74
- get firmwareType() {
75
- return this._firmwareType;
76
- }
77
- get possibleHIDdevice() {
78
- return this.descriptor.type === 0 || this.descriptor.type === 2;
79
- }
80
- get possibleT1() {
81
- return (this.descriptor.type ?? 0) <= 2;
82
- }
83
- name = 'Trezor';
84
- color;
85
- availableTranslations = {};
86
- authenticityChecks = {
87
- firmwareRevision: null,
88
- firmwareHash: null,
89
- };
90
- uniquePath;
91
- lifecycle = new utils_1.TypedEmitter();
92
- sessionDfd;
93
- constructor({ id, transport, descriptor }) {
94
- super();
95
- this._protocol = protocol_1.v1;
96
- this.uniquePath = id;
97
- this.transport = transport;
98
- this.descriptor = {
99
- id: descriptor.id,
100
- apiType: descriptor.apiType,
101
- type: descriptor.type,
102
- path: descriptor.path,
106
+ this.sessionAcquired = null;
107
+ transport.on(transport_1.TRANSPORT.STOPPED, this.onTransportStopped);
108
+ transport.deviceEvents.on(this.descriptor.path, this.onTransportDeviceEvent);
109
+ }
110
+ get transportPath() {
111
+ return this.descriptor.path;
112
+ }
113
+ onTransportStopped = () => this.disconnect();
114
+ onTransportDeviceEvent = event => {
115
+ switch (event.type) {
116
+ case transport_1.TRANSPORT.DEVICE_SESSION_CHANGED:
117
+ return this.updateDescriptor(event.descriptor);
118
+ case transport_1.TRANSPORT.DEVICE_REQUEST_RELEASE:
119
+ return this.usedElsewhere();
120
+ case transport_1.TRANSPORT.DEVICE_DISCONNECTED:
121
+ {
122
+ return this.disconnect();
123
+ }
124
+ }
125
+ };
126
+ getSessionChangePromise() {
127
+ if (!this.sessionDfd) {
128
+ this.sessionDfd = (0, utils_1.createDeferred)();
129
+ this.sessionDfd.promise.catch(() => {}).finally(() => {
130
+ this.sessionDfd = undefined;
131
+ });
132
+ }
133
+ return this.sessionDfd.promise;
134
+ }
135
+ async waitAndCompareSession(response, sessionPromise) {
136
+ if (response.success) {
137
+ try {
138
+ if ((await sessionPromise) !== response.payload) {
139
+ return {
140
+ success: false,
141
+ error: transport_1.TRANSPORT_ERROR.SESSION_WRONG_PREVIOUS
142
+ };
143
+ }
144
+ } catch {
145
+ return {
146
+ success: false,
147
+ error: transport_1.TRANSPORT_ERROR.DEVICE_DISCONNECTED_DURING_ACTION
103
148
  };
149
+ }
150
+ }
151
+ return response;
152
+ }
153
+ acquire() {
154
+ const sessionPromise = this.getSessionChangePromise();
155
+ const previous = this.transport.getDescriptor(this.descriptor.path)?.session ?? null;
156
+ this.acquirePromise = this.transport.acquire({
157
+ input: {
158
+ path: this.descriptor.path,
159
+ previous
160
+ }
161
+ }).then(result => this.waitAndCompareSession(result, sessionPromise)).then(result => {
162
+ if (result.success) {
163
+ this.wasUsedElsewhere = false;
164
+ this.sessionAcquired = result.payload;
165
+ this.currentSession = new DeviceCurrentSession_1.DeviceCurrentSession(this, this.transport, this.sessionAcquired);
166
+ return result;
167
+ } else {
168
+ throw new Error(result.error);
169
+ }
170
+ }).finally(() => {
171
+ this.acquirePromise = undefined;
172
+ });
173
+ return this.acquirePromise;
174
+ }
175
+ reset() {
176
+ _log.info(`Resetting Features and ThpState`);
177
+ this._features = undefined;
178
+ this._protocol = protocol_1.v1;
179
+ this.thp?.resetState();
180
+ this.thp = undefined;
181
+ }
182
+ setBusy(value) {
183
+ this.busy = value;
184
+ }
185
+ release() {
186
+ if (!this.sessionAcquired || this.keepTransportSession || this.releasePromise) {
187
+ return;
188
+ }
189
+ const sessionPromise = this.getSessionChangePromise();
190
+ this.releasePromise = this.transport.release({
191
+ session: this.sessionAcquired,
192
+ path: this.descriptor.path
193
+ }).then(result => this.waitAndCompareSession(result, sessionPromise)).then(result => {
194
+ if (result.success) {
104
195
  this.sessionAcquired = null;
105
- transport.on(transport_1.TRANSPORT.STOPPED, this.onTransportStopped);
106
- transport.deviceEvents.on(this.descriptor.path, this.onTransportDeviceEvent);
107
- }
108
- get transportPath() {
109
- return this.descriptor.path;
110
- }
111
- onTransportStopped = () => this.disconnect();
112
- onTransportDeviceEvent = (event) => {
113
- switch (event.type) {
114
- case transport_1.TRANSPORT.DEVICE_SESSION_CHANGED:
115
- return this.updateDescriptor(event.descriptor);
116
- case transport_1.TRANSPORT.DEVICE_REQUEST_RELEASE:
117
- return this.usedElsewhere();
118
- case transport_1.TRANSPORT.DEVICE_DISCONNECTED: {
119
- return this.disconnect();
120
- }
121
- }
122
- };
123
- getSessionChangePromise() {
124
- if (!this.sessionDfd) {
125
- this.sessionDfd = (0, utils_1.createDeferred)();
126
- this.sessionDfd.promise
127
- .catch(() => { })
128
- .finally(() => {
129
- this.sessionDfd = undefined;
130
- });
131
- }
132
- return this.sessionDfd.promise;
133
- }
134
- async waitAndCompareSession(response, sessionPromise) {
135
- if (response.success) {
136
- try {
137
- if ((await sessionPromise) !== response.payload) {
138
- return {
139
- success: false,
140
- error: transport_1.TRANSPORT_ERROR.SESSION_WRONG_PREVIOUS,
141
- };
142
- }
143
- }
144
- catch {
145
- return {
146
- success: false,
147
- error: transport_1.TRANSPORT_ERROR.DEVICE_DISCONNECTED_DURING_ACTION,
148
- };
149
- }
150
- }
151
- return response;
152
- }
153
- acquire() {
154
- const sessionPromise = this.getSessionChangePromise();
155
- const previous = this.transport.getDescriptor(this.descriptor.path)?.session ?? null;
156
- this.acquirePromise = this.transport
157
- .acquire({ input: { path: this.descriptor.path, previous } })
158
- .then(result => this.waitAndCompareSession(result, sessionPromise))
159
- .then(result => {
160
- if (result.success) {
161
- this.wasUsedElsewhere = false;
162
- this.sessionAcquired = result.payload;
163
- this.currentSession = new DeviceCurrentSession_1.DeviceCurrentSession(this, this.transport, this.sessionAcquired);
164
- return result;
165
- }
166
- else {
167
- throw new Error(result.error);
168
- }
169
- })
170
- .finally(() => {
171
- this.acquirePromise = undefined;
196
+ }
197
+ return result;
198
+ }).finally(() => {
199
+ this.releasePromise = undefined;
200
+ });
201
+ return this.releasePromise;
202
+ }
203
+ async setupThp() {
204
+ _log.info('Setup THP device');
205
+ this._protocol = protocol_1.v2;
206
+ if (this.transport.name === 'BridgeTransport' && !utils_1.versionUtils.isNewerOrEqual(this.transport.version, '3.0.0')) {
207
+ this.unreadableError = 'THP incompatible with bridge ' + this.transport.version;
208
+ } else {
209
+ try {
210
+ await this.transport.loadMessages('thp', protocol_1.thp.getProtobufDefinitions);
211
+ this.thp = new protocol_1.thp.ThpState();
212
+ } catch (error) {
213
+ this.unreadableError = error.message;
214
+ }
215
+ }
216
+ }
217
+ async handshake() {
218
+ if (this.isUsedElsewhere()) {
219
+ return true;
220
+ }
221
+ try {
222
+ await this.run();
223
+ } catch (error) {
224
+ _log.warn(`device.run error.message: ${error.message}, code: ${error.code}`);
225
+ if (error.code === 'Device_NotFound' || error.code === 'Device_Disconnected' || error.message === transport_1.TRANSPORT_ERROR.DEVICE_NOT_FOUND || error.message === transport_1.TRANSPORT_ERROR.DEVICE_DISCONNECTED_DURING_ACTION || error.message === transport_1.TRANSPORT_ERROR.HTTP_ERROR) {
226
+ return false;
227
+ }
228
+ if (this.possibleHIDdevice && error.message === transport_1.TRANSPORT_ERROR.INTERFACE_UNABLE_TO_OPEN_DEVICE || error.message === transport_1.TRANSPORT_ERROR.LIBUSB_ERROR_ACCESS) {
229
+ this.unreadableError = error.message;
230
+ }
231
+ }
232
+ return true;
233
+ }
234
+ async updateDescriptor(descriptor) {
235
+ this.sessionDfd?.resolve(descriptor.session);
236
+ await Promise.all([this.acquirePromise, this.releasePromise]);
237
+ if (descriptor.session && descriptor.session !== this.sessionAcquired) {
238
+ this.usedElsewhere();
239
+ }
240
+ if (!descriptor.session) {
241
+ this.keepTransportSession = false;
242
+ }
243
+ this.lifecycle.emit(events_1.DEVICE.CHANGED);
244
+ }
245
+ run(fn, options = {}) {
246
+ if (this.runPromise) {
247
+ _log.warn('Previous call is still running');
248
+ throw constants_1.ERRORS.TypedError('Device_CallInProgress');
249
+ }
250
+ const wasUnacquired = this.isUnacquired();
251
+ this.runAbort = new AbortController();
252
+ const {
253
+ signal
254
+ } = this.runAbort;
255
+ this.runPromise = Promise.race([this._runInner(fn, options, signal), new Promise((_, reject) => {
256
+ signal.addEventListener('abort', () => reject(signal.reason));
257
+ })]).catch(async err => {
258
+ this.keepTransportSession = false;
259
+ await this.acquirePromise;
260
+ await this.release();
261
+ throw err;
262
+ }).finally(() => {
263
+ this.runAbort = undefined;
264
+ this.runPromise = undefined;
265
+ }).then(() => {
266
+ if (wasUnacquired && !this.isUnacquired()) {
267
+ this.lifecycle.emit(events_1.DEVICE.CONNECT);
268
+ }
269
+ });
270
+ return this.runPromise;
271
+ }
272
+ async interrupt(reason) {
273
+ await (0, thp_1.abortThpWorkflow)(this);
274
+ await this.currentSession?.abort(reason);
275
+ this.runAbort?.abort(reason);
276
+ await this.currentRun;
277
+ }
278
+ get currentRun() {
279
+ return this.runPromise?.catch(() => {});
280
+ }
281
+ usedElsewhere() {
282
+ this.wasUsedElsewhere = true;
283
+ if (!this.sessionAcquired) {
284
+ return;
285
+ }
286
+ this.transport.releaseDevice(this.sessionAcquired);
287
+ this.sessionAcquired = null;
288
+ _log.debug('interruptionFromOutside');
289
+ this.runAbort?.abort(constants_1.ERRORS.TypedError('Device_UsedElsewhere'));
290
+ }
291
+ async _runInner(fn, options, abortSignal) {
292
+ if (this.releasePromise) {
293
+ await this.releasePromise;
294
+ }
295
+ const acquireNeeded = !this.isUsedHere() || this.currentSession?.isDisposed();
296
+ if (acquireNeeded) {
297
+ await this.acquire();
298
+ }
299
+ if (abortSignal.aborted) throw abortSignal.reason;
300
+ const {
301
+ staticSessionId,
302
+ deriveCardano
303
+ } = this.getState() || {};
304
+ if (acquireNeeded || !staticSessionId || !deriveCardano && options.useCardanoDerivation) {
305
+ try {
306
+ await (0, handshake_1.handshakeCancel)({
307
+ device: this,
308
+ logger: _log,
309
+ signal: abortSignal
172
310
  });
173
- return this.acquirePromise;
174
- }
175
- reset() {
176
- _log.info(`Resetting Features and ThpState`);
177
- this._features = undefined;
178
- this._protocol = protocol_1.v1;
179
- this.thp?.resetState();
180
- this.thp = undefined;
181
- }
182
- setBusy(value) {
183
- this.busy = value;
184
- }
185
- subscribe() {
186
- if (this.descriptor.id && this.descriptor.apiType === 'bluetooth') {
187
- this.transport
188
- .subscribe({
189
- path: this.descriptor.id,
190
- channels: ['battery-level', 'trezor-push-notification'],
191
- })
192
- .then(result => {
193
- if (result.success) {
194
- this.channels = result.payload;
195
- this.lifecycle.emit(events_1.DEVICE.CHANGED);
196
- }
197
- if (this.channels['battery-level']) {
198
- this.transport.on('battery-level', event => {
199
- this._updateFeature('soc', event.data[0]);
200
- this.lifecycle.emit(events_1.DEVICE.CHANGED);
201
- });
202
- }
203
- if (this.channels['trezor-push-notification']) {
204
- this.transport.on('trezor-push-notification', ({ id, data }) => {
205
- if (id === this.descriptor.id) {
206
- (0, trezorPushNotification_1.trezorPushNotificationHandler)({ device: this, message: data });
207
- }
208
- });
209
- }
210
- });
211
- }
212
- }
213
- release() {
214
- if (!this.sessionAcquired || this.keepTransportSession || this.releasePromise) {
215
- return;
216
- }
217
- const sessionPromise = this.getSessionChangePromise();
218
- this.releasePromise = this.transport
219
- .release({ session: this.sessionAcquired, path: this.descriptor.path })
220
- .then(result => this.waitAndCompareSession(result, sessionPromise))
221
- .then(result => {
222
- if (result.success) {
223
- this.sessionAcquired = null;
224
- }
225
- return result;
226
- })
227
- .finally(() => {
228
- this.releasePromise = undefined;
311
+ if (this.protocol.name === 'v2') {
312
+ const withInteraction = !!fn;
313
+ this.busy = await (0, thp_1.getThpChannel)(this, withInteraction);
314
+ if (!this.busy) {
315
+ await this.getFeatures();
316
+ }
317
+ } else if (fn) {
318
+ await this.initialize(!!options.useCardanoDerivation);
319
+ } else {
320
+ await this.getFeatures();
321
+ }
322
+ } catch (error) {
323
+ _log.warn('Device._runInner error: ', error.message);
324
+ if (error.code === 'Failure_Busy') {
325
+ this.busy = 'busy';
326
+ }
327
+ if (error.code === 'ThpDeviceLocked') {
328
+ this.busy = 'pin-locked';
329
+ }
330
+ if (error.code === 'Device_ThpPairingTagInvalid') {
331
+ return Promise.reject(error);
332
+ }
333
+ return Promise.reject(constants_1.ERRORS.TypedError('Device_InitializeFailed', `Initialize failed: ${error.message}${error.code ? `, code: ${error.code}` : ''}`));
334
+ }
335
+ }
336
+ if (!options.skipFirmwareChecks) {
337
+ await (0, checkFirmwareHashWithRetries_1.checkFirmwareHashWithRetries)({
338
+ device: this,
339
+ logger: _log
340
+ });
341
+ await this.checkFirmwareRevisionWithRetries();
342
+ }
343
+ if (!options.skipLanguageChecks && this.features?.language && !this.features.language_version_matches && this.atLeast('2.7.0')) {
344
+ _log.info('language version mismatch. silently updating...');
345
+ try {
346
+ await this.changeLanguage({
347
+ language: this.features.language
229
348
  });
230
- return this.releasePromise;
231
- }
232
- async setupThp() {
233
- _log.info('Setup THP device');
234
- this._protocol = protocol_1.v2;
235
- if (this.transport.name === 'BridgeTransport' &&
236
- !utils_1.versionUtils.isNewerOrEqual(this.transport.version, '3.0.0')) {
237
- this.unreadableError = 'THP incompatible with bridge ' + this.transport.version;
238
- }
239
- else {
240
- try {
241
- await this.transport.loadMessages('thp', protocol_1.thp.getProtobufDefinitions);
242
- this.thp = new protocol_1.thp.ThpState();
243
- }
244
- catch (error) {
245
- this.unreadableError = error.message;
246
- }
247
- }
248
- }
249
- async handshake() {
250
- if (this.isUsedElsewhere()) {
251
- return true;
252
- }
253
- try {
254
- await this.run();
255
- }
256
- catch (error) {
257
- _log.warn(`device.run error.message: ${error.message}, code: ${error.code}`);
258
- if (error.code === 'Device_NotFound' ||
259
- error.code === 'Device_Disconnected' ||
260
- error.message === transport_1.TRANSPORT_ERROR.DEVICE_NOT_FOUND ||
261
- error.message === transport_1.TRANSPORT_ERROR.DEVICE_DISCONNECTED_DURING_ACTION ||
262
- error.message === transport_1.TRANSPORT_ERROR.HTTP_ERROR) {
263
- return false;
264
- }
265
- if ((this.possibleHIDdevice &&
266
- error.message === transport_1.TRANSPORT_ERROR.INTERFACE_UNABLE_TO_OPEN_DEVICE) ||
267
- error.message === transport_1.TRANSPORT_ERROR.LIBUSB_ERROR_ACCESS) {
268
- this.unreadableError = error.message;
269
- }
270
- }
271
- this.subscribe();
272
- return true;
273
- }
274
- async updateDescriptor(descriptor) {
275
- this.sessionDfd?.resolve(descriptor.session);
276
- await Promise.all([this.acquirePromise, this.releasePromise]);
277
- if (descriptor.session && descriptor.session !== this.sessionAcquired) {
278
- this.usedElsewhere();
279
- }
280
- if (!descriptor.session) {
281
- this.keepTransportSession = false;
282
- }
283
- this.lifecycle.emit(events_1.DEVICE.CHANGED);
284
- }
285
- run(fn, options = {}) {
286
- if (this.runPromise) {
287
- _log.warn('Previous call is still running');
288
- throw constants_1.ERRORS.TypedError('Device_CallInProgress');
289
- }
290
- const wasUnacquired = this.isUnacquired();
291
- this.runAbort = new AbortController();
292
- const { signal } = this.runAbort;
293
- this.runPromise = Promise.race([
294
- this._runInner(fn, options, signal),
295
- new Promise((_, reject) => {
296
- signal.addEventListener('abort', () => reject(signal.reason));
297
- }),
298
- ])
299
- .catch(async (err) => {
300
- this.keepTransportSession = false;
301
- await this.acquirePromise;
302
- await this.release();
303
- throw err;
304
- })
305
- .finally(() => {
306
- this.runAbort = undefined;
307
- this.runPromise = undefined;
308
- })
309
- .then(() => {
310
- if (wasUnacquired && !this.isUnacquired()) {
311
- this.lifecycle.emit(events_1.DEVICE.CONNECT);
312
- }
313
- });
314
- return this.runPromise;
315
- }
316
- async interrupt(reason) {
317
- await (0, thp_1.abortThpWorkflow)(this);
318
- await this.currentSession?.abort(reason);
319
- this.runAbort?.abort(reason);
320
- await this.currentRun;
321
- }
322
- get currentRun() {
323
- return this.runPromise?.catch(() => { });
324
- }
325
- usedElsewhere() {
326
- this.wasUsedElsewhere = true;
327
- if (!this.sessionAcquired) {
328
- return;
329
- }
330
- this.transport.releaseDevice(this.sessionAcquired);
349
+ } catch (err) {
350
+ _log.error('change language failed silently', err);
351
+ }
352
+ }
353
+ if (options.keepSession) {
354
+ this.keepTransportSession = true;
355
+ }
356
+ if (fn) {
357
+ await fn();
358
+ if (!options.skipFinalReload) {
359
+ await this.getFeatures();
360
+ }
361
+ }
362
+ if (!this.keepTransportSession && typeof options.keepSession !== 'boolean' || options.keepSession === false) {
363
+ this.keepTransportSession = false;
364
+ await this.release();
365
+ }
366
+ }
367
+ getCurrentSession() {
368
+ if (!this.currentSession) {
369
+ throw constants_1.ERRORS.TypedError('Runtime', `Device: commands not defined`);
370
+ }
371
+ return this.currentSession;
372
+ }
373
+ getCommands() {
374
+ return (0, DeviceCommands_1.DeviceCommands)(this.getCurrentSession());
375
+ }
376
+ setInstance(instance = 0) {
377
+ if (this.instance !== instance) {
378
+ if (this.keepTransportSession) {
331
379
  this.sessionAcquired = null;
332
- _log.debug('interruptionFromOutside');
333
- this.runAbort?.abort(constants_1.ERRORS.TypedError('Device_UsedElsewhere'));
334
- }
335
- async _runInner(fn, options, abortSignal) {
336
- if (this.releasePromise) {
337
- await this.releasePromise;
338
- }
339
- const acquireNeeded = !this.isUsedHere() || this.currentSession?.isDisposed();
340
- if (acquireNeeded) {
341
- await this.acquire();
342
- }
343
- if (abortSignal.aborted)
344
- throw abortSignal.reason;
345
- const { staticSessionId, deriveCardano } = this.getState() || {};
346
- if (acquireNeeded || !staticSessionId || (!deriveCardano && options.useCardanoDerivation)) {
347
- try {
348
- await (0, handshake_1.handshakeCancel)({ device: this, logger: _log, signal: abortSignal });
349
- if (this.protocol.name === 'v2') {
350
- const withInteraction = !!fn;
351
- this.busy = await (0, thp_1.getThpChannel)(this, withInteraction);
352
- if (!this.busy) {
353
- await this.getFeatures();
354
- }
355
- }
356
- else if (fn) {
357
- await this.initialize(!!options.useCardanoDerivation);
358
- }
359
- else {
360
- await this.getFeatures();
361
- }
362
- }
363
- catch (error) {
364
- _log.warn('Device._runInner error: ', error.message);
365
- if (error.code === 'Failure_Busy') {
366
- this.busy = 'busy';
367
- }
368
- if (error.code === 'ThpDeviceLocked') {
369
- this.busy = 'pin-locked';
370
- }
371
- if (error.code === 'Device_ThpPairingTagInvalid') {
372
- return Promise.reject(error);
373
- }
374
- return Promise.reject(constants_1.ERRORS.TypedError('Device_InitializeFailed', `Initialize failed: ${error.message}${error.code ? `, code: ${error.code}` : ''}`));
375
- }
376
- }
377
- if (!options.skipFirmwareChecks) {
378
- await (0, checkFirmwareHashWithRetries_1.checkFirmwareHashWithRetries)({ device: this, logger: _log });
379
- await this.checkFirmwareRevisionWithRetries();
380
- }
381
- if (!options.skipLanguageChecks &&
382
- this.features?.language &&
383
- !this.features.language_version_matches &&
384
- this.atLeast('2.7.0')) {
385
- _log.info('language version mismatch. silently updating...');
386
- try {
387
- await this.changeLanguage({ language: this.features.language });
388
- }
389
- catch (err) {
390
- _log.error('change language failed silently', err);
391
- }
392
- }
393
- if (options.keepSession) {
394
- this.keepTransportSession = true;
395
- }
396
- if (fn) {
397
- await fn();
398
- if (!options.skipFinalReload) {
399
- await this.getFeatures();
400
- }
401
- }
402
- if ((!this.keepTransportSession && typeof options.keepSession !== 'boolean') ||
403
- options.keepSession === false) {
404
- this.keepTransportSession = false;
405
- await this.release();
406
- }
407
- }
408
- getCurrentSession() {
409
- if (!this.currentSession) {
410
- throw constants_1.ERRORS.TypedError('Runtime', `Device: commands not defined`);
411
- }
412
- return this.currentSession;
413
- }
414
- getCommands() {
415
- return (0, DeviceCommands_1.DeviceCommands)(this.getCurrentSession());
416
- }
417
- setInstance(instance = 0) {
418
- if (this.instance !== instance) {
419
- if (this.keepTransportSession) {
420
- this.sessionAcquired = null;
421
- this.keepTransportSession = false;
422
- }
423
- }
424
- this.instance = instance;
425
- }
426
- getInstance() {
427
- return this.instance;
428
- }
429
- getState() {
430
- return this.state[this.instance];
431
- }
432
- setState(state) {
433
- if (!state) {
434
- delete this.state[this.instance];
435
- }
436
- else {
437
- const prevState = this.state[this.instance];
438
- const newState = {
439
- ...prevState,
440
- ...state,
441
- };
442
- this.state[this.instance] = newState;
443
- this.stateStorage?.saveState(this, newState);
444
- }
445
- }
446
- async initialize(useCardanoDerivation) {
447
- let payload;
448
- if (this.features) {
449
- const { sessionId, deriveCardano } = this.getState() || {};
450
- payload = {
451
- derive_cardano: deriveCardano || useCardanoDerivation,
452
- };
453
- if (sessionId) {
454
- payload.session_id = sessionId;
455
- }
456
- }
457
- const { message } = await this.getCurrentSession().typedCall('Initialize', 'Features', payload);
458
- this._updateFeatures(message);
459
- this._updateCurrentRelease(message);
460
- this.setState({ deriveCardano: payload?.derive_cardano });
461
- }
462
- initStorage(storage) {
463
- this.stateStorage = storage;
464
- this.setState(storage.loadState(this));
465
- }
466
- async getFeatures() {
467
- const { message } = await this.getCurrentSession().typedCall('GetFeatures', 'Features', {});
468
- this._updateFeatures(message);
469
- this._updateCurrentRelease(message);
470
- }
471
- getAuthenticityChecks() {
472
- return this.authenticityChecks;
473
- }
474
- setAuthenticityChecks(firmwareHash) {
475
- this.authenticityChecks.firmwareHash = firmwareHash;
476
- }
477
- async checkFirmwareRevisionWithRetries() {
478
- const lastResult = this.authenticityChecks.firmwareRevision;
479
- const notDoneYet = lastResult === null;
480
- const wasError = lastResult !== null && !lastResult.success;
481
- const wasErrorRetriable = wasError && (0, utils_1.isArrayMember)(lastResult.error, constants_1.FIRMWARE.REVISION_CHECK_RETRIABLE_ERRORS);
482
- if (notDoneYet || wasErrorRetriable) {
483
- await this.checkFirmwareRevision();
484
- }
485
- }
486
- async checkFirmwareRevision() {
487
- const firmwareVersion = this.getVersion();
488
- if (!firmwareVersion || !this.features || !this.firmwareType) {
489
- return;
490
- }
491
- if (this.features && this.features.bootloader_mode === true) {
492
- return;
493
- }
494
- const release = (0, assetUtils_1.getReleaseAsset)(this.features.internal_model, firmwareVersion, this.firmwareType);
495
- const result = await (0, checkFirmwareRevision_1.checkFirmwareRevision)({
496
- internalModel: this.features.internal_model,
497
- deviceRevision: this.features.revision,
498
- firmwareVersion,
499
- expectedRevision: release?.firmware_revision,
500
- firmwareType: this.firmwareType,
380
+ this.keepTransportSession = false;
381
+ }
382
+ }
383
+ this.instance = instance;
384
+ }
385
+ getInstance() {
386
+ return this.instance;
387
+ }
388
+ getState() {
389
+ return this.state[this.instance];
390
+ }
391
+ setState(state) {
392
+ if (!state) {
393
+ delete this.state[this.instance];
394
+ } else {
395
+ const prevState = this.state[this.instance];
396
+ const newState = {
397
+ ...prevState,
398
+ ...state
399
+ };
400
+ this.state[this.instance] = newState;
401
+ this.stateStorage?.saveState(this, newState);
402
+ }
403
+ }
404
+ async initialize(useCardanoDerivation) {
405
+ let payload;
406
+ if (this.features) {
407
+ const {
408
+ sessionId,
409
+ deriveCardano
410
+ } = this.getState() || {};
411
+ payload = {
412
+ derive_cardano: deriveCardano || useCardanoDerivation
413
+ };
414
+ if (sessionId) {
415
+ payload.session_id = sessionId;
416
+ }
417
+ }
418
+ const {
419
+ message
420
+ } = await this.getCurrentSession().typedCall('Initialize', 'Features', payload);
421
+ this._updateFeatures(message);
422
+ this._updateCurrentRelease(message);
423
+ this.setState({
424
+ deriveCardano: payload?.derive_cardano
425
+ });
426
+ }
427
+ initStorage(storage) {
428
+ this.stateStorage = storage;
429
+ this.setState(storage.loadState(this));
430
+ }
431
+ async getFeatures() {
432
+ const {
433
+ message
434
+ } = await this.getCurrentSession().typedCall('GetFeatures', 'Features', {});
435
+ this._updateFeatures(message);
436
+ this._updateCurrentRelease(message);
437
+ }
438
+ getAuthenticityChecks() {
439
+ return this.authenticityChecks;
440
+ }
441
+ setAuthenticityChecks(firmwareHash) {
442
+ this.authenticityChecks.firmwareHash = firmwareHash;
443
+ }
444
+ async checkFirmwareRevisionWithRetries() {
445
+ const lastResult = this.authenticityChecks.firmwareRevision;
446
+ const notDoneYet = lastResult === null;
447
+ const wasError = lastResult !== null && !lastResult.success;
448
+ const wasErrorRetriable = wasError && (0, utils_1.isArrayMember)(lastResult.error, constants_1.FIRMWARE.REVISION_CHECK_RETRIABLE_ERRORS);
449
+ if (notDoneYet || wasErrorRetriable) {
450
+ await this.checkFirmwareRevision();
451
+ }
452
+ }
453
+ async checkFirmwareRevision() {
454
+ const firmwareVersion = this.getVersion();
455
+ if (!firmwareVersion || !this.features || !this.firmwareType) {
456
+ return;
457
+ }
458
+ if (this.features && this.features.bootloader_mode === true) {
459
+ return;
460
+ }
461
+ const release = (0, assetUtils_1.getReleaseAsset)(this.features.internal_model, firmwareVersion, this.firmwareType);
462
+ const result = await (0, checkFirmwareRevision_1.checkFirmwareRevision)({
463
+ internalModel: this.features.internal_model,
464
+ deviceRevision: this.features.revision,
465
+ firmwareVersion,
466
+ expectedRevision: release?.firmware_revision,
467
+ firmwareType: this.firmwareType
468
+ });
469
+ this.authenticityChecks = {
470
+ ...this.authenticityChecks,
471
+ firmwareRevision: result
472
+ };
473
+ }
474
+ async changeLanguage({
475
+ language,
476
+ binary
477
+ }) {
478
+ if (language === 'en-US') {
479
+ return this._uploadTranslationData(null);
480
+ }
481
+ if (binary) {
482
+ return this._uploadTranslationData(binary);
483
+ }
484
+ const version = this.getVersion();
485
+ if (!version) {
486
+ throw constants_1.ERRORS.TypedError('Runtime', 'changeLanguage: device version unknown');
487
+ }
488
+ if (!this.firmwareType) {
489
+ throw constants_1.ERRORS.TypedError('Runtime', 'changeLanguage: firmware type unknown');
490
+ }
491
+ if (!this._currentRelease) {
492
+ throw constants_1.ERRORS.TypedError('Runtime', 'changeLanguage: release not found');
493
+ }
494
+ const languageBinPath = this._currentRelease.translations[language];
495
+ const downloadedBinary = await (0, firmwareInfo_1.getLanguage)(languageBinPath);
496
+ if (!downloadedBinary) {
497
+ throw constants_1.ERRORS.TypedError('Runtime', 'changeLanguage: translation not found');
498
+ }
499
+ let dataToSend;
500
+ if (Buffer.isBuffer(downloadedBinary)) {
501
+ dataToSend = new Uint8Array(downloadedBinary).buffer;
502
+ } else {
503
+ dataToSend = downloadedBinary;
504
+ }
505
+ return this._uploadTranslationData(dataToSend);
506
+ }
507
+ async _uploadTranslationData(payload) {
508
+ if (payload === null) {
509
+ const response = await this.getCurrentSession().typedCall('ChangeLanguage', ['Success'], {
510
+ data_length: 0
511
+ });
512
+ return response.message;
513
+ }
514
+ const length = payload.byteLength;
515
+ let response = await this.getCurrentSession().typedCall('ChangeLanguage', ['DataChunkRequest', 'Success'], {
516
+ data_length: length
517
+ });
518
+ while (response.type !== 'Success') {
519
+ const start = response.message.data_offset;
520
+ const end = response.message.data_offset + response.message.data_length;
521
+ const chunk = payload.slice(start, end);
522
+ response = await this.getCurrentSession().typedCall('DataChunkAck', ['DataChunkRequest', 'Success'], {
523
+ data_chunk: Buffer.from(chunk).toString('hex')
524
+ });
525
+ }
526
+ return response.message;
527
+ }
528
+ async _updateCurrentRelease(feat) {
529
+ const {
530
+ firmwareVersion
531
+ } = (0, firmwareInfo_1.getCurrentVersion)(feat);
532
+ const newFirmwareType = (0, firmwareUtils_1.getFirmwareType)(feat);
533
+ if (!firmwareVersion) {
534
+ return;
535
+ }
536
+ if (this._currentRelease && newFirmwareType === this.firmwareType && utils_1.versionUtils.isEqual(this._currentRelease.version, firmwareVersion)) {
537
+ return;
538
+ }
539
+ const release = await (0, firmwareInfo_1.getReleaseByVersion)(feat, firmwareVersion, newFirmwareType);
540
+ this._currentRelease = release;
541
+ this.availableTranslations = this._currentRelease?.translations ?? {};
542
+ }
543
+ _updateFeatures(feat) {
544
+ const capabilities = (0, deviceFeaturesUtils_1.parseCapabilities)(feat);
545
+ feat.capabilities = capabilities;
546
+ if (this.features && this.features.session_id && !feat.session_id) {
547
+ feat.session_id = this.features.session_id;
548
+ }
549
+ feat.unlocked = feat.unlocked ?? true;
550
+ const revision = (0, deviceFeaturesUtils_1.parseRevision)(feat);
551
+ feat.revision = revision;
552
+ if (!feat.model && feat.major_version === 1) {
553
+ feat.model = '1';
554
+ }
555
+ if (!feat.internal_model || !device_utils_1.DeviceModelInternal[feat.internal_model]) {
556
+ feat.internal_model = (0, deviceFeaturesUtils_1.ensureInternalModelFeature)(feat.model);
557
+ }
558
+ const version = this.getVersion();
559
+ const newVersion = [feat.major_version, feat.minor_version, feat.patch_version];
560
+ if (!version || !utils_1.versionUtils.isEqual(version, newVersion)) {
561
+ if (version) {
562
+ this.emit(events_1.DEVICE.FIRMWARE_VERSION_CHANGED, {
563
+ oldVersion: version,
564
+ newVersion,
565
+ device: this.toMessageObject()
501
566
  });
502
- this.authenticityChecks = {
503
- ...this.authenticityChecks,
504
- firmwareRevision: result,
505
- };
506
- }
507
- async changeLanguage({ language, binary, }) {
508
- if (language === 'en-US') {
509
- return this._uploadTranslationData(null);
510
- }
511
- if (binary) {
512
- return this._uploadTranslationData(binary);
513
- }
514
- const version = this.getVersion();
515
- if (!version) {
516
- throw constants_1.ERRORS.TypedError('Runtime', 'changeLanguage: device version unknown');
517
- }
518
- if (!this.firmwareType) {
519
- throw constants_1.ERRORS.TypedError('Runtime', 'changeLanguage: firmware type unknown');
520
- }
521
- if (!this._currentRelease) {
522
- throw constants_1.ERRORS.TypedError('Runtime', 'changeLanguage: release not found');
523
- }
524
- const languageBinPath = this._currentRelease.translations[language];
525
- const downloadedBinary = await (0, firmwareInfo_1.getLanguage)(languageBinPath);
526
- if (!downloadedBinary) {
527
- throw constants_1.ERRORS.TypedError('Runtime', 'changeLanguage: translation not found');
528
- }
529
- let dataToSend;
530
- if (Buffer.isBuffer(downloadedBinary)) {
531
- dataToSend = new Uint8Array(downloadedBinary).buffer;
532
- }
533
- else {
534
- dataToSend = downloadedBinary;
535
- }
536
- return this._uploadTranslationData(dataToSend);
537
- }
538
- async _uploadTranslationData(payload) {
539
- if (payload === null) {
540
- const response = await this.getCurrentSession().typedCall('ChangeLanguage', ['Success'], { data_length: 0 });
541
- return response.message;
542
- }
543
- const length = payload.byteLength;
544
- let response = await this.getCurrentSession().typedCall('ChangeLanguage', ['DataChunkRequest', 'Success'], { data_length: length });
545
- while (response.type !== 'Success') {
546
- const start = response.message.data_offset;
547
- const end = response.message.data_offset + response.message.data_length;
548
- const chunk = payload.slice(start, end);
549
- response = await this.getCurrentSession().typedCall('DataChunkAck', ['DataChunkRequest', 'Success'], {
550
- data_chunk: Buffer.from(chunk).toString('hex'),
551
- });
552
- }
553
- return response.message;
554
- }
555
- async _updateCurrentRelease(feat) {
556
- const newVersion = [
557
- feat.major_version,
558
- feat.minor_version,
559
- feat.patch_version,
560
- ];
561
- const newFirmwareType = (0, firmwareUtils_1.getFirmwareType)(feat);
562
- if (this._currentRelease &&
563
- newFirmwareType === this.firmwareType &&
564
- utils_1.versionUtils.isEqual(this._currentRelease.version, newVersion)) {
565
- return;
566
- }
567
- const release = await (0, firmwareInfo_1.getReleaseByVersion)(feat, newVersion, newFirmwareType);
568
- this._currentRelease = release;
569
- this.availableTranslations = this._currentRelease?.translations ?? {};
570
- }
571
- _updateFeatures(feat) {
572
- const capabilities = (0, deviceFeaturesUtils_1.parseCapabilities)(feat);
573
- feat.capabilities = capabilities;
574
- if (this.features && this.features.session_id && !feat.session_id) {
575
- feat.session_id = this.features.session_id;
576
- }
577
- feat.unlocked = feat.unlocked ?? true;
578
- const revision = (0, deviceFeaturesUtils_1.parseRevision)(feat);
579
- feat.revision = revision;
580
- if (!feat.model && feat.major_version === 1) {
581
- feat.model = '1';
582
- }
583
- if (!feat.internal_model || !device_utils_1.DeviceModelInternal[feat.internal_model]) {
584
- feat.internal_model = (0, deviceFeaturesUtils_1.ensureInternalModelFeature)(feat.model);
585
- }
586
- const version = this.getVersion();
587
- const newVersion = [
588
- feat.major_version,
589
- feat.minor_version,
590
- feat.patch_version,
591
- ];
592
- if (!version || !utils_1.versionUtils.isEqual(version, newVersion)) {
593
- if (version) {
594
- this.emit(events_1.DEVICE.FIRMWARE_VERSION_CHANGED, {
595
- oldVersion: version,
596
- newVersion,
597
- device: this.toMessageObject(),
598
- });
599
- }
600
- this._unavailableCapabilities = (0, deviceFeaturesUtils_1.getUnavailableCapabilities)(feat, (0, coinInfo_1.getAllNetworks)());
601
- this._firmwareStatus = (0, firmwareInfo_1.getFirmwareStatus)(feat, (0, firmwareUtils_1.getFirmwareType)(feat));
602
- this._firmwareReleaseConfigInfo = (0, firmwareInfo_1.getFirmwareReleaseConfigInfo)(feat, (0, firmwareUtils_1.getFirmwareType)(feat));
603
- this._currentRelease = (0, assetUtils_1.getReleaseAsset)(feat.internal_model, newVersion, (0, firmwareUtils_1.getFirmwareType)(feat));
604
- this.availableTranslations = this._currentRelease?.translations ?? {};
605
- }
606
- this._features = feat;
607
- this._firmwareType = (0, firmwareUtils_1.getFirmwareType)(feat);
608
- const deviceInfo = device_utils_1.models[feat.internal_model] ?? {
609
- name: `Unknown ${feat.internal_model}`,
610
- colors: {},
567
+ }
568
+ this._unavailableCapabilities = (0, deviceFeaturesUtils_1.getUnavailableCapabilities)(feat, (0, coinInfo_1.getAllNetworks)());
569
+ this._firmwareStatus = (0, firmwareInfo_1.getFirmwareStatus)(feat, (0, firmwareUtils_1.getFirmwareType)(feat));
570
+ this._firmwareReleaseConfigInfo = (0, firmwareInfo_1.getFirmwareReleaseConfigInfo)(feat, (0, firmwareUtils_1.getFirmwareType)(feat));
571
+ this._currentRelease = (0, assetUtils_1.getReleaseAsset)(feat.internal_model, newVersion, (0, firmwareUtils_1.getFirmwareType)(feat));
572
+ this.availableTranslations = this._currentRelease?.translations ?? {};
573
+ }
574
+ this._features = feat;
575
+ this._firmwareType = (0, firmwareUtils_1.getFirmwareType)(feat);
576
+ const deviceInfo = device_utils_1.models[feat.internal_model] ?? {
577
+ name: `Unknown ${feat.internal_model}`,
578
+ colors: {}
579
+ };
580
+ this.name = deviceInfo.name;
581
+ this.busy = undefined;
582
+ if (feat?.unit_color) {
583
+ const deviceUnitColor = feat.unit_color.toString();
584
+ if (deviceUnitColor in deviceInfo.colors) {
585
+ this.color = deviceInfo.colors[deviceUnitColor];
586
+ }
587
+ }
588
+ }
589
+ updateFeature(key, value) {
590
+ if (this._features) {
591
+ this._features = {
592
+ ...this._features,
593
+ [key]: value
594
+ };
595
+ this.lifecycle.emit(events_1.DEVICE.CHANGED);
596
+ }
597
+ }
598
+ prompt(type, args) {
599
+ return new Promise(callback => {
600
+ if (!this.listenerCount(type)) {
601
+ const payload = {
602
+ success: false,
603
+ error: new Error(`${type} callback not configured`)
611
604
  };
612
- this.name = deviceInfo.name;
613
- this.busy = undefined;
614
- if (feat?.unit_color) {
615
- const deviceUnitColor = feat.unit_color.toString();
616
- if (deviceUnitColor in deviceInfo.colors) {
617
- this.color = deviceInfo.colors[deviceUnitColor];
618
- }
619
- }
620
- }
621
- _updateFeature(key, value) {
622
- if (this._features) {
623
- this._features = {
624
- ...this._features,
625
- [key]: value,
626
- };
627
- }
628
- }
629
- prompt(type, args) {
630
- return new Promise(callback => {
631
- if (!this.listenerCount(type)) {
632
- const payload = {
633
- success: false,
634
- error: new Error(`${type} callback not configured`),
635
- };
636
- callback(payload);
637
- }
638
- else {
639
- this.emit(type, { callback, ...args });
640
- }
605
+ callback(payload);
606
+ } else {
607
+ this.emit(type, {
608
+ callback,
609
+ ...args
641
610
  });
642
- }
643
- isUnacquired() {
644
- return this.features === undefined;
645
- }
646
- isUnreadable() {
647
- return !!this.unreadableError;
648
- }
649
- disconnect() {
650
- _log.debug('Disconnect cleanup');
651
- this.transport.off(transport_1.TRANSPORT.STOPPED, this.onTransportStopped);
652
- this.transport.deviceEvents.off(this.descriptor.path, this.onTransportDeviceEvent);
653
- this.removeAllListeners();
654
- this.sessionDfd?.reject(new Error());
655
- if (this.sessionAcquired) {
656
- this.transport.releaseSync(this.sessionAcquired);
657
- this.sessionAcquired = null;
658
- }
659
- this.lifecycle.emit(events_1.DEVICE.DISCONNECT);
660
- return this.interrupt(constants_1.ERRORS.TypedError('Device_Disconnected'));
661
- }
662
- isBootloader() {
663
- return this.features && !!this.features.bootloader_mode;
664
- }
665
- isInitialized() {
666
- return this.features && !!this.features.initialized;
667
- }
668
- isSeedless() {
669
- return this.features && !!this.features.no_backup;
670
- }
671
- getVersion() {
672
- if (!this.features)
673
- return;
674
- return [
675
- this.features.major_version,
676
- this.features.minor_version,
677
- this.features.patch_version,
678
- ];
679
- }
680
- atLeast(versions) {
681
- const version = this.getVersion();
682
- if (!this.features || !version)
683
- return false;
684
- const modelVersion = typeof versions === 'string' ? versions : versions[this.features.major_version - 1];
685
- return utils_1.versionUtils.isNewerOrEqual(version, modelVersion);
686
- }
687
- isUsed() {
688
- return !!this.transport.getDescriptor(this.descriptor.path)?.session;
689
- }
690
- isUsedHere() {
691
- return !!this.sessionAcquired;
692
- }
693
- isUsedElsewhere() {
694
- return this.isUsed() && !this.isUsedHere();
695
- }
696
- getUniquePath() {
697
- return this.uniquePath;
698
- }
699
- isT1() {
700
- return this.features ? this.features.major_version === 1 : false;
701
- }
702
- hasUnexpectedMode(allow, require) {
703
- if (this.features) {
704
- if (this.isBootloader() && !allow.includes(events_1.UI.BOOTLOADER)) {
705
- return events_1.UI.BOOTLOADER;
706
- }
707
- if (!this.isInitialized() && !allow.includes(events_1.UI.INITIALIZE)) {
708
- return events_1.UI.INITIALIZE;
709
- }
710
- if (this.isSeedless() && !allow.includes(events_1.UI.SEEDLESS)) {
711
- return events_1.UI.SEEDLESS;
712
- }
713
- if (!this.isBootloader() && require.includes(events_1.UI.BOOTLOADER)) {
714
- return events_1.UI.NOT_IN_BOOTLOADER;
715
- }
716
- }
717
- return null;
718
- }
719
- getStatus() {
720
- if (this.isUsedElsewhere())
721
- return 'occupied';
722
- if (this.wasUsedElsewhere)
723
- return 'used';
724
- if (this.busy)
725
- return this.busy;
726
- return 'available';
727
- }
728
- toMessageObject() {
729
- const { name, uniquePath: path, descriptor } = this;
730
- const { apiType, id } = descriptor;
731
- const base = { path, name, descriptor: { apiType, id } };
732
- const bluetoothProps = this.descriptor.id && this.descriptor.apiType === 'bluetooth'
733
- ? {
734
- id: (0, types_1.asBluetoothDeviceId)(this.descriptor.id),
735
- }
736
- : undefined;
737
- if (this.unreadableError) {
738
- return {
739
- ...base,
740
- type: 'unreadable',
741
- error: this.unreadableError,
742
- label: 'Unreadable device',
743
- hid: this.possibleHIDdevice,
744
- };
745
- }
746
- if (this.isUnacquired()) {
747
- const sessionOwner = this.transport.getDescriptor(this.descriptor.path)?.sessionOwner;
748
- return {
749
- ...base,
750
- type: 'unacquired',
751
- label: 'Unacquired device',
752
- name: this.name,
753
- transportSessionOwner: this.sessionAcquired ? undefined : sessionOwner,
754
- bluetoothProps,
755
- thp: this.thp?.serialize(),
756
- status: this.busy ? this.busy : undefined,
757
- };
758
- }
759
- const defaultLabel = 'My Trezor';
760
- const label = this.features.label === '' || !this.features.label ? defaultLabel : this.features.label;
761
- return {
762
- ...base,
763
- type: 'acquired',
764
- id: this.features.device_id,
765
- label,
766
- _state: this.getState(),
767
- state: this.getState()?.staticSessionId,
768
- status: this.getStatus(),
769
- mode: (0, firmwareUtils_1.getFirmwareMode)(this.features),
770
- color: this.color,
771
- firmware: this.firmwareStatus,
772
- firmwareReleaseConfigInfo: this.firmwareReleaseConfigInfo,
773
- firmwareType: this.firmwareType,
774
- features: this.features,
775
- unavailableCapabilities: this.unavailableCapabilities,
776
- availableTranslations: this.availableTranslations,
777
- authenticityChecks: this.authenticityChecks,
778
- bluetoothProps,
779
- thp: this.thp?.serialize(),
780
- };
781
- }
611
+ }
612
+ });
613
+ }
614
+ isUnacquired() {
615
+ return this.features === undefined;
616
+ }
617
+ isUnreadable() {
618
+ return !!this.unreadableError;
619
+ }
620
+ disconnect() {
621
+ _log.debug('Disconnect cleanup');
622
+ this.transport.off(transport_1.TRANSPORT.STOPPED, this.onTransportStopped);
623
+ this.transport.deviceEvents.off(this.descriptor.path, this.onTransportDeviceEvent);
624
+ this.removeAllListeners();
625
+ this.sessionDfd?.reject(new Error());
626
+ if (this.sessionAcquired) {
627
+ this.transport.releaseSync(this.sessionAcquired);
628
+ this.sessionAcquired = null;
629
+ }
630
+ this.lifecycle.emit(events_1.DEVICE.DISCONNECT);
631
+ return this.interrupt(constants_1.ERRORS.TypedError('Device_Disconnected'));
632
+ }
633
+ isBootloader() {
634
+ return this.features && !!this.features.bootloader_mode;
635
+ }
636
+ isInitialized() {
637
+ return this.features && !!this.features.initialized;
638
+ }
639
+ isSeedless() {
640
+ return this.features && !!this.features.no_backup;
641
+ }
642
+ getVersion() {
643
+ if (!this.features) return;
644
+ return [this.features.major_version, this.features.minor_version, this.features.patch_version];
645
+ }
646
+ atLeast(versions) {
647
+ const version = this.getVersion();
648
+ if (!this.features || !version) return false;
649
+ const modelVersion = typeof versions === 'string' ? versions : versions[this.features.major_version - 1];
650
+ return utils_1.versionUtils.isNewerOrEqual(version, modelVersion);
651
+ }
652
+ isUsed() {
653
+ return !!this.transport.getDescriptor(this.descriptor.path)?.session;
654
+ }
655
+ isUsedHere() {
656
+ return !!this.sessionAcquired;
657
+ }
658
+ isUsedElsewhere() {
659
+ return this.isUsed() && !this.isUsedHere();
660
+ }
661
+ getUniquePath() {
662
+ return this.uniquePath;
663
+ }
664
+ isT1() {
665
+ return this.features ? this.features.major_version === 1 : false;
666
+ }
667
+ hasUnexpectedMode(allow, require) {
668
+ if (this.features) {
669
+ if (this.isBootloader() && !allow.includes(events_1.UI.BOOTLOADER)) {
670
+ return events_1.UI.BOOTLOADER;
671
+ }
672
+ if (!this.isInitialized() && !allow.includes(events_1.UI.INITIALIZE)) {
673
+ return events_1.UI.INITIALIZE;
674
+ }
675
+ if (this.isSeedless() && !allow.includes(events_1.UI.SEEDLESS)) {
676
+ return events_1.UI.SEEDLESS;
677
+ }
678
+ if (!this.isBootloader() && require.includes(events_1.UI.BOOTLOADER)) {
679
+ return events_1.UI.NOT_IN_BOOTLOADER;
680
+ }
681
+ }
682
+ return null;
683
+ }
684
+ getStatus() {
685
+ if (this.isUsedElsewhere()) return 'occupied';
686
+ if (this.wasUsedElsewhere) return 'used';
687
+ if (this.busy) return this.busy;
688
+ return 'available';
689
+ }
690
+ getDeviceThp() {
691
+ const state = this.thp?.serialize();
692
+ return state ? {
693
+ properties: state.properties,
694
+ credentials: state.credentials,
695
+ channel: state.channel
696
+ } : undefined;
697
+ }
698
+ toMessageObject() {
699
+ const {
700
+ name,
701
+ uniquePath: path,
702
+ descriptor
703
+ } = this;
704
+ const {
705
+ apiType,
706
+ id
707
+ } = descriptor;
708
+ const base = {
709
+ path,
710
+ name,
711
+ descriptor: {
712
+ apiType,
713
+ id
714
+ }
715
+ };
716
+ const bluetoothProps = this.descriptor.id && this.descriptor.apiType === 'bluetooth' ? {
717
+ id: (0, types_1.asBluetoothDeviceId)(this.descriptor.id)
718
+ } : undefined;
719
+ if (this.unreadableError) {
720
+ return {
721
+ ...base,
722
+ type: 'unreadable',
723
+ error: this.unreadableError,
724
+ label: 'Unreadable device',
725
+ hid: this.possibleHIDdevice
726
+ };
727
+ }
728
+ if (this.isUnacquired()) {
729
+ const sessionOwner = this.transport.getDescriptor(this.descriptor.path)?.sessionOwner;
730
+ return {
731
+ ...base,
732
+ type: 'unacquired',
733
+ label: 'Unacquired device',
734
+ name: this.name,
735
+ transportSessionOwner: this.sessionAcquired ? undefined : sessionOwner,
736
+ bluetoothProps,
737
+ thp: this.getDeviceThp(),
738
+ status: this.busy ? this.busy : undefined
739
+ };
740
+ }
741
+ const defaultLabel = 'My Trezor';
742
+ const label = this.features.label === '' || !this.features.label ? defaultLabel : this.features.label;
743
+ return {
744
+ ...base,
745
+ type: 'acquired',
746
+ id: this.features.device_id,
747
+ label,
748
+ _state: this.getState(),
749
+ state: this.getState()?.staticSessionId,
750
+ status: this.getStatus(),
751
+ mode: (0, firmwareUtils_1.getFirmwareMode)(this.features),
752
+ color: this.color,
753
+ firmware: this.firmwareStatus,
754
+ firmwareReleaseConfigInfo: this.firmwareReleaseConfigInfo,
755
+ firmwareType: this.firmwareType,
756
+ features: this.features,
757
+ unavailableCapabilities: this.unavailableCapabilities,
758
+ availableTranslations: this.availableTranslations,
759
+ authenticityChecks: this.authenticityChecks,
760
+ bluetoothProps,
761
+ thp: this.getDeviceThp()
762
+ };
763
+ }
782
764
  }
783
765
  exports.Device = Device;
784
766
  //# sourceMappingURL=Device.js.map