@onekeyfe/hd-transport 1.2.0-alpha.4 → 1.2.0-alpha.41

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 (68) hide show
  1. package/__tests__/messages.test.js +176 -0
  2. package/__tests__/protocol-v2-ble-frame-writer.test.js +119 -0
  3. package/__tests__/protocol-v2-link-manager.test.js +437 -0
  4. package/__tests__/protocol-v2-usb-transport-base.test.js +330 -0
  5. package/__tests__/protocol-v2.test.js +465 -56
  6. package/__tests__/transport-log.test.js +79 -0
  7. package/dist/constants.d.ts +4 -1
  8. package/dist/constants.d.ts.map +1 -1
  9. package/dist/index.d.ts +784 -198
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +820 -227
  12. package/dist/protocols/index.d.ts +14 -5
  13. package/dist/protocols/index.d.ts.map +1 -1
  14. package/dist/protocols/v2/ble-frame-writer.d.ts +15 -0
  15. package/dist/protocols/v2/ble-frame-writer.d.ts.map +1 -0
  16. package/dist/protocols/v2/constants.d.ts +1 -0
  17. package/dist/protocols/v2/constants.d.ts.map +1 -1
  18. package/dist/protocols/v2/decode.d.ts +13 -2
  19. package/dist/protocols/v2/decode.d.ts.map +1 -1
  20. package/dist/protocols/v2/encode.d.ts +2 -3
  21. package/dist/protocols/v2/encode.d.ts.map +1 -1
  22. package/dist/protocols/v2/errors.d.ts +8 -0
  23. package/dist/protocols/v2/errors.d.ts.map +1 -0
  24. package/dist/protocols/v2/frame-assembler.d.ts.map +1 -1
  25. package/dist/protocols/v2/index.d.ts +2 -1
  26. package/dist/protocols/v2/index.d.ts.map +1 -1
  27. package/dist/protocols/v2/link-manager.d.ts +39 -0
  28. package/dist/protocols/v2/link-manager.d.ts.map +1 -0
  29. package/dist/protocols/v2/sequence-cursor.d.ts +5 -0
  30. package/dist/protocols/v2/sequence-cursor.d.ts.map +1 -0
  31. package/dist/protocols/v2/session.d.ts +19 -5
  32. package/dist/protocols/v2/session.d.ts.map +1 -1
  33. package/dist/protocols/v2/usb-transport-base.d.ts +32 -0
  34. package/dist/protocols/v2/usb-transport-base.d.ts.map +1 -0
  35. package/dist/serialization/protobuf/decode.d.ts.map +1 -1
  36. package/dist/types/messages.d.ts +376 -110
  37. package/dist/types/messages.d.ts.map +1 -1
  38. package/dist/types/transport.d.ts +14 -3
  39. package/dist/types/transport.d.ts.map +1 -1
  40. package/dist/utils/transportLog.d.ts +9 -0
  41. package/dist/utils/transportLog.d.ts.map +1 -0
  42. package/messages-protocol-v2.json +1155 -481
  43. package/package.json +3 -3
  44. package/scripts/protobuf-build.sh +86 -208
  45. package/scripts/protobuf-patches/index.js +1 -0
  46. package/scripts/protobuf-types.js +19 -1
  47. package/src/constants.ts +28 -14
  48. package/src/index.ts +12 -1
  49. package/src/protocols/index.ts +39 -40
  50. package/src/protocols/v2/ble-frame-writer.ts +77 -0
  51. package/src/protocols/v2/constants.ts +1 -0
  52. package/src/protocols/v2/crc8.ts +1 -1
  53. package/src/protocols/v2/decode.ts +71 -37
  54. package/src/protocols/v2/encode.ts +2 -28
  55. package/src/protocols/v2/errors.ts +25 -0
  56. package/src/protocols/v2/frame-assembler.ts +6 -4
  57. package/src/protocols/v2/index.ts +2 -1
  58. package/src/protocols/v2/link-manager.ts +209 -0
  59. package/src/protocols/v2/sequence-cursor.ts +10 -0
  60. package/src/protocols/v2/session.ts +157 -200
  61. package/src/protocols/v2/usb-transport-base.ts +213 -0
  62. package/src/serialization/protobuf/decode.ts +4 -1
  63. package/src/types/messages.ts +458 -142
  64. package/src/types/transport.ts +14 -3
  65. package/src/utils/transportLog.ts +102 -0
  66. package/dist/protocols/v2/debug.d.ts +0 -13
  67. package/dist/protocols/v2/debug.d.ts.map +0 -1
  68. package/src/protocols/v2/debug.ts +0 -26
package/dist/index.js CHANGED
@@ -140,7 +140,7 @@ function messageToJSON(Message, fields) {
140
140
  res[key] = field.resolvedType.valuesById[value];
141
141
  }
142
142
  else if (field.resolvedType.fields) {
143
- res[key] = messageToJSON(value, field.resolvedType.fields);
143
+ res[key] = value == null ? null : messageToJSON(value, field.resolvedType.fields);
144
144
  }
145
145
  else {
146
146
  throw new Error(`case not handled: ${key}`);
@@ -267,14 +267,17 @@ const PROTOCOL_V1_CHUNK_PAYLOAD_SIZE = 63;
267
267
  const PROTOCOL_V1_USB_PACKET_SIZE = PROTOCOL_V1_CHUNK_PAYLOAD_SIZE + 1;
268
268
  const PROTOCOL_V1_MESSAGE_HEADER_SIZE = 2 + 4;
269
269
  const PROTOCOL_V1_ENVELOPE_HEADER_SIZE = 1 + 1 + PROTOCOL_V1_MESSAGE_HEADER_SIZE;
270
- const PROTOCOL_V2_FRAME_MAX_BYTES = 4608;
270
+ const PROTOCOL_V2_FRAME_MAX_BYTES = 4200;
271
271
  const PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE = 4000;
272
272
  const PROTOCOL_V2_BLE_FILE_CHUNK_SIZE = 1800;
273
+ const PROTOCOL_V2_BLE_FILE_READ_CHUNK_SIZE = 900;
274
+ const PROTOCOL_V2_BLE_FRAME_MAX_BYTES = 2048;
273
275
  const PROTOCOL_V2_FILE_CHUNK_SIZE = PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE;
274
276
  const PROTOCOL_V2_CHANNEL_USB = 0;
275
277
  const PROTOCOL_V2_CHANNEL_BLE_UART = 1;
276
278
  const PROTOCOL_V2_CHANNEL_SOCKET = 2;
277
279
  const PROTOCOL_V2_PACKET_SRC_COMMAND = 0;
280
+ const PROTOCOL_V2_DEFAULT_RESPONSE_TIMEOUT_MS = 5 * 60 * 1000;
278
281
 
279
282
  function encodeEnvelope(data, options) {
280
283
  const { addTrezorHeaders, chunked, messageTypeId } = options;
@@ -381,6 +384,7 @@ const PROTO_HEAD_CRC_SIZE = 8;
381
384
  const CRC8_INIT = 0x30;
382
385
  const PACKET_SIZE = 4096;
383
386
  const PROTO_DATA_TYPE_PACKET = 0;
387
+ const PROTO_DATA_TYPE_ACK = 1;
384
388
 
385
389
  const CRC8_TABLE = new Uint8Array([
386
390
  0x00, 0x5e, 0xbc, 0xe2, 0x61, 0x3f, 0xdd, 0x83, 0xc2, 0x9c, 0x7e, 0x20, 0xa3, 0xfd, 0x1f, 0x41,
@@ -408,16 +412,11 @@ function crc8(data, len) {
408
412
  return crc;
409
413
  }
410
414
 
411
- function logProtocolV2Debug(options, stage, details) {
412
- var _a, _b, _c;
413
- (_b = (_a = options === null || options === void 0 ? void 0 : options.logger) === null || _a === void 0 ? void 0 : _a.debug) === null || _b === void 0 ? void 0 : _b.call(_a, `[${(_c = options.logPrefix) !== null && _c !== void 0 ? _c : 'ProtocolV2'}] ${stage}`, Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (options.context ? { context: options.context } : {})), (options.messageName ? { messageName: options.messageName } : {})), (options.messageTypeId !== undefined ? { messageTypeId: options.messageTypeId } : {})), (options.pbPayloadLength !== undefined ? { pbPayloadLength: options.pbPayloadLength } : {})), details));
414
- }
415
-
416
415
  const PROTO_SEQ_DEFAULT = 1;
417
416
  function nextProtoSeq(current) {
418
417
  return current >= 255 ? 1 : current + 1;
419
418
  }
420
- function encodeFrame(payload, packetSrc, router, debugOptions, seq) {
419
+ function encodeFrame(payload, packetSrc, router, seq) {
421
420
  const resolvedPacketSrc = packetSrc !== null && packetSrc !== void 0 ? packetSrc : 0;
422
421
  const resolvedRouter = router !== null && router !== void 0 ? router : 0;
423
422
  const resolvedSeq = seq !== null && seq !== void 0 ? seq : PROTO_SEQ_DEFAULT;
@@ -427,7 +426,7 @@ function encodeFrame(payload, packetSrc, router, debugOptions, seq) {
427
426
  const payloadLen = payload ? payload.length : 0;
428
427
  const frameLen = payloadLen + PROTO_HEAD_CRC_SIZE;
429
428
  if (frameLen > PROTOCOL_V2_FRAME_MAX_BYTES) {
430
- throw new Error(`Protocol V2 frame too large: ${frameLen}`);
429
+ throw new Error(`Protocol V2 frame too large: ${frameLen} > ${PROTOCOL_V2_FRAME_MAX_BYTES}`);
431
430
  }
432
431
  const frame = new Uint8Array(frameLen);
433
432
  frame[0] = PROTO_HEAD_SOF;
@@ -442,27 +441,17 @@ function encodeFrame(payload, packetSrc, router, debugOptions, seq) {
442
441
  frame.set(payload, 7);
443
442
  }
444
443
  frame[frameLen - 1] = crc8(frame, frameLen - 1);
445
- logProtocolV2Debug(debugOptions, 'encode raw frame', {
446
- frameLen,
447
- payloadLen,
448
- packetSrc: resolvedPacketSrc,
449
- router: frame[4],
450
- attr: frame[5],
451
- seq: frame[6],
452
- headerCrc: frame[3],
453
- frameCrc: frame[frameLen - 1],
454
- });
455
444
  return frame;
456
445
  }
457
- function encodeProtobufFrame(messageTypeId, pbPayload, packetSrc, router, debugOptions, seq) {
446
+ function encodeProtobufFrame(messageTypeId, pbPayload, packetSrc, router, seq) {
458
447
  const payload = new Uint8Array(2 + pbPayload.length);
459
448
  payload[0] = messageTypeId % 256;
460
449
  payload[1] = Math.floor(messageTypeId / 256) % 256;
461
450
  payload.set(pbPayload, 2);
462
- return encodeFrame(payload, packetSrc, router, Object.assign(Object.assign({}, debugOptions), { messageTypeId, pbPayloadLength: pbPayload.length }), seq);
451
+ return encodeFrame(payload, packetSrc, router, seq);
463
452
  }
464
453
 
465
- function decodeFrame(data, debugOptions) {
454
+ function inspectFrameHeader(data) {
466
455
  if (data.length < PROTO_HEAD_CRC_SIZE) {
467
456
  throw new Error(`Protocol V2 frame too short: ${data.length} bytes`);
468
457
  }
@@ -470,8 +459,8 @@ function decodeFrame(data, debugOptions) {
470
459
  throw new Error(`Invalid SOF byte: expected 0x5A, got 0x${data[0].toString(16).padStart(2, '0')}`);
471
460
  }
472
461
  const frameLen = data[1] + data[2] * 256;
473
- if (data.length < frameLen) {
474
- throw new Error(`Frame truncated: expected ${frameLen} bytes, got ${data.length}`);
462
+ if (data.length !== frameLen) {
463
+ throw new Error(`Protocol V2 frame length mismatch: expected ${frameLen} bytes, got ${data.length}`);
475
464
  }
476
465
  const expectedHeaderCrc = crc8(data, 3);
477
466
  if (data[3] !== expectedHeaderCrc) {
@@ -485,28 +474,53 @@ function decodeFrame(data, debugOptions) {
485
474
  .toString(16)
486
475
  .padStart(2, '0')}, got 0x${data[frameLen - 1].toString(16).padStart(2, '0')}`);
487
476
  }
477
+ const dataType = data[5] & 0x03;
478
+ const packetSrc = (data[5] >> 2) & 0x0f;
488
479
  const seq = data[6];
480
+ if (seq === 0) {
481
+ throw new Error('Invalid Protocol V2 sequence: 0 is reserved');
482
+ }
483
+ return {
484
+ frameLen,
485
+ router: data[4],
486
+ packetSrc,
487
+ dataType,
488
+ seq,
489
+ };
490
+ }
491
+ function isAckFrame(data) {
492
+ if (data.length < 6 || (data[5] & 0x03) !== PROTO_DATA_TYPE_ACK) {
493
+ return false;
494
+ }
495
+ const header = inspectFrameHeader(data);
496
+ if (header.frameLen !== PROTO_HEAD_CRC_SIZE) {
497
+ throw new Error(`Invalid Protocol V2 ACK frame length: ${header.frameLen}`);
498
+ }
499
+ return true;
500
+ }
501
+ function decodeFrame(data) {
502
+ const { frameLen, router, packetSrc, dataType, seq } = inspectFrameHeader(data);
503
+ if (dataType !== PROTO_DATA_TYPE_PACKET) {
504
+ throw new Error(`Invalid Protocol V2 data type: expected packet, got ${dataType}`);
505
+ }
489
506
  const payloadData = data.slice(7, frameLen - 1);
490
507
  if (payloadData.length < 2) {
491
508
  throw new Error(`Protocol V2 payload too short (need >=2 bytes for messageTypeId)`);
492
509
  }
493
510
  const messageTypeId = payloadData[0] + payloadData[1] * 256;
494
511
  const pbPayload = payloadData.slice(2);
495
- logProtocolV2Debug(debugOptions, 'decode raw frame', {
496
- frameLen,
497
- dataLength: data.length,
498
- router: data[4],
499
- attr: data[5],
500
- seq,
501
- headerCrc: data[3],
502
- expectedHeaderCrc,
503
- frameCrc: data[frameLen - 1],
504
- expectedFrameCrc,
505
- messageTypeId,
506
- pbPayloadLength: pbPayload.length,
507
- });
508
- return { messageTypeId, pbPayload, seq };
512
+ return { messageTypeId, pbPayload, seq, router, packetSrc, dataType };
513
+ }
514
+
515
+ class ProtocolV2LinkError extends Error {
516
+ constructor(code, message, cause) {
517
+ super(message);
518
+ this.name = 'ProtocolV2LinkError';
519
+ this.code = code;
520
+ this.cause = cause;
521
+ }
509
522
  }
523
+ const isProtocolV2LinkError = (error) => error instanceof ProtocolV2LinkError;
510
524
 
511
525
  function concatUint8Arrays(arrays) {
512
526
  const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
@@ -551,23 +565,23 @@ class ProtocolV2FrameAssembler {
551
565
  return undefined;
552
566
  if (this.buffer[0] !== PROTO_HEAD_SOF) {
553
567
  this.reset();
554
- throw new Error('Invalid Protocol V2 SOF');
568
+ throw new ProtocolV2LinkError('frame', 'Invalid Protocol V2 SOF');
555
569
  }
556
570
  const expectedLen = this.buffer[1] + this.buffer[2] * 256;
557
571
  if (expectedLen < PROTO_HEAD_CRC_SIZE) {
558
572
  this.reset();
559
- throw new Error(`Protocol V2 frame length too small: ${expectedLen}`);
573
+ throw new ProtocolV2LinkError('frame', `Protocol V2 frame length too small: ${expectedLen}`);
560
574
  }
561
575
  if (expectedLen > this.maxFrameBytes) {
562
576
  this.reset();
563
- throw new Error(`Protocol V2 frame too large: ${expectedLen}`);
577
+ throw new ProtocolV2LinkError('frame', `Protocol V2 frame too large: ${expectedLen}`);
564
578
  }
565
579
  if (this.buffer.length < PROTO_PRE_HEAD_SIZE)
566
580
  return undefined;
567
581
  const expectedHeaderCrc = crc8(this.buffer, 3);
568
582
  if (this.buffer[3] !== expectedHeaderCrc) {
569
583
  this.reset();
570
- throw new Error(`Protocol V2 header CRC mismatch: expected 0x${expectedHeaderCrc
584
+ throw new ProtocolV2LinkError('frame', `Protocol V2 header CRC mismatch: expected 0x${expectedHeaderCrc
571
585
  .toString(16)
572
586
  .padStart(2, '0')}`);
573
587
  }
@@ -579,6 +593,51 @@ class ProtocolV2FrameAssembler {
579
593
  }
580
594
  }
581
595
 
596
+ const defaultWait = (timeoutMs) => new Promise(resolve => {
597
+ setTimeout(resolve, timeoutMs);
598
+ });
599
+ function writeProtocolV2BleFrame({ frame, packetCapacity, writePacket, assertActive, signal, abortMessage = 'Protocol V2 BLE write aborted', initialDelayMs = 0, burstSize, burstPauseMs = 0, flushDelayMs = 0, wait = defaultWait, }) {
600
+ return __awaiter(this, void 0, void 0, function* () {
601
+ if (!Number.isInteger(packetCapacity) || packetCapacity <= 0) {
602
+ throw new Error('Protocol V2 BLE packet capacity must be a positive integer');
603
+ }
604
+ if (burstSize !== undefined && (!Number.isInteger(burstSize) || burstSize <= 0)) {
605
+ throw new Error('Protocol V2 BLE burst size must be a positive integer');
606
+ }
607
+ const assertWritable = () => {
608
+ assertActive === null || assertActive === void 0 ? void 0 : assertActive();
609
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
610
+ throw new Error(abortMessage);
611
+ }
612
+ };
613
+ if (frame.length > 0 && initialDelayMs > 0) {
614
+ assertWritable();
615
+ yield wait(initialDelayMs);
616
+ assertWritable();
617
+ }
618
+ let packetsWritten = 0;
619
+ for (let offset = 0; offset < frame.length; offset += packetCapacity) {
620
+ assertWritable();
621
+ const packet = frame.slice(offset, offset + packetCapacity);
622
+ yield writePacket(packet, packetsWritten);
623
+ packetsWritten += 1;
624
+ assertWritable();
625
+ const hasMorePackets = offset + packetCapacity < frame.length;
626
+ if (hasMorePackets &&
627
+ burstSize !== undefined &&
628
+ packetsWritten % burstSize === 0 &&
629
+ burstPauseMs > 0) {
630
+ yield wait(burstPauseMs);
631
+ assertWritable();
632
+ }
633
+ }
634
+ if (burstSize !== undefined && packetsWritten > burstSize && flushDelayMs > 0) {
635
+ yield wait(flushDelayMs);
636
+ assertWritable();
637
+ }
638
+ });
639
+ }
640
+
582
641
  var protocolV2Codec = /*#__PURE__*/Object.freeze({
583
642
  __proto__: null,
584
643
  PROTO_HEAD_SOF: PROTO_HEAD_SOF,
@@ -587,15 +646,20 @@ var protocolV2Codec = /*#__PURE__*/Object.freeze({
587
646
  CRC8_INIT: CRC8_INIT,
588
647
  PACKET_SIZE: PACKET_SIZE,
589
648
  PROTO_DATA_TYPE_PACKET: PROTO_DATA_TYPE_PACKET,
649
+ PROTO_DATA_TYPE_ACK: PROTO_DATA_TYPE_ACK,
590
650
  CRC8_TABLE: CRC8_TABLE,
591
651
  crc8: crc8,
592
- logProtocolV2Debug: logProtocolV2Debug,
593
652
  nextProtoSeq: nextProtoSeq,
594
653
  encodeFrame: encodeFrame,
595
654
  encodeProtobufFrame: encodeProtobufFrame,
655
+ inspectFrameHeader: inspectFrameHeader,
656
+ isAckFrame: isAckFrame,
596
657
  decodeFrame: decodeFrame,
658
+ ProtocolV2LinkError: ProtocolV2LinkError,
659
+ isProtocolV2LinkError: isProtocolV2LinkError,
597
660
  concatUint8Arrays: concatUint8Arrays,
598
- ProtocolV2FrameAssembler: ProtocolV2FrameAssembler
661
+ ProtocolV2FrameAssembler: ProtocolV2FrameAssembler,
662
+ writeProtocolV2BleFrame: writeProtocolV2BleFrame
599
663
  });
600
664
 
601
665
  const PROTOCOL_V2_SYS_MESSAGE_THRESHOLD = 60000;
@@ -643,46 +707,46 @@ const ProtocolV1 = {
643
707
  decodeMessage: decodeMessage,
644
708
  };
645
709
  const ProtocolV2 = {
710
+ isAckFrame,
711
+ inspectFrameHeader,
712
+ inspectFrame(schemas, frame) {
713
+ const { messageTypeId, pbPayload, seq, router, packetSrc, dataType } = decodeFrame(frame);
714
+ const { messageName } = createProtocolV2MessageFromType(messageTypeId, schemas);
715
+ return {
716
+ messageName,
717
+ messageTypeId,
718
+ pbPayload,
719
+ seq,
720
+ router,
721
+ packetSrc,
722
+ dataType,
723
+ type: messageName,
724
+ };
725
+ },
646
726
  encodeFrame(schemas, name, data, options = {}) {
647
- var _a, _b, _c, _d, _e, _f, _g;
648
727
  const encodeMessages = resolveProtocolV2EncodeSchema(name, schemas);
649
728
  const { Message, messageTypeId } = createMessageFromName(encodeMessages, name);
650
729
  const pbBuffer = encode(Message, data);
651
730
  pbBuffer.reset();
652
731
  const rawPbBuffer = pbBuffer.toBuffer();
653
732
  const pbBytes = new Uint8Array(rawPbBuffer);
654
- (_b = (_a = options.logger) === null || _a === void 0 ? void 0 : _a.debug) === null || _b === void 0 ? void 0 : _b.call(_a, `[${(_c = options.logPrefix) !== null && _c !== void 0 ? _c : 'ProtocolV2'}] encode protobuf`, {
655
- context: (_d = options.context) !== null && _d !== void 0 ? _d : `encode:${name}`,
656
- messageName: name,
657
- messageTypeId,
658
- pbPayloadLength: pbBytes.length,
659
- packetSrc: (_e = options.packetSrc) !== null && _e !== void 0 ? _e : 0,
660
- router: (_f = options.router) !== null && _f !== void 0 ? _f : 0,
661
- });
662
- return encodeProtobufFrame(messageTypeId, pbBytes, options.packetSrc, options.router, {
663
- logger: options.logger,
664
- logPrefix: options.logPrefix,
665
- context: (_g = options.context) !== null && _g !== void 0 ? _g : `encode:${name}`,
666
- messageName: name,
667
- }, options.seq);
733
+ return encodeProtobufFrame(messageTypeId, pbBytes, options.packetSrc, options.router, options.seq);
668
734
  },
669
- decodeFrame(schemas, frame, options = {}) {
670
- var _a, _b, _c, _d, _e;
671
- const { messageTypeId, pbPayload, seq } = decodeFrame(frame, {
672
- logger: options.logger,
673
- logPrefix: options.logPrefix,
674
- context: (_a = options.context) !== null && _a !== void 0 ? _a : 'decode',
675
- });
676
- const { Message, messageName } = createProtocolV2MessageFromType(messageTypeId, schemas);
735
+ decodeFrame(schemas, frame) {
736
+ const { messageTypeId, pbPayload, seq, messageName } = this.inspectFrame(schemas, frame);
737
+ const { Message } = createProtocolV2MessageFromType(messageTypeId, schemas);
677
738
  const rxByteBuffer = ByteBuffer__default["default"].wrap(Buffer.from(pbPayload));
678
- const message = decode(Message, rxByteBuffer);
679
- (_c = (_b = options.logger) === null || _b === void 0 ? void 0 : _b.debug) === null || _c === void 0 ? void 0 : _c.call(_b, `[${(_d = options.logPrefix) !== null && _d !== void 0 ? _d : 'ProtocolV2'}] decode protobuf`, {
680
- context: (_e = options.context) !== null && _e !== void 0 ? _e : `decode:${messageName}`,
681
- messageName,
682
- messageTypeId,
683
- pbPayloadLength: pbPayload.length,
684
- seq,
685
- });
739
+ let message;
740
+ try {
741
+ message = decode(Message, rxByteBuffer);
742
+ }
743
+ catch (cause) {
744
+ const error = new Error(`Protocol V2 protobuf decode failed for "${messageName}" ` +
745
+ `(${messageTypeId}, ${pbPayload.length}-byte payload); ` +
746
+ 'the payload is malformed or incompatible with the active SDK schema.');
747
+ error.cause = cause;
748
+ throw error;
749
+ }
686
750
  return {
687
751
  message,
688
752
  messageName,
@@ -705,6 +769,16 @@ var index$1 = /*#__PURE__*/Object.freeze({
705
769
  decodeMessage: decodeMessage
706
770
  });
707
771
 
772
+ class ProtocolV2SequenceCursor {
773
+ constructor() {
774
+ this.current = 0;
775
+ }
776
+ next() {
777
+ this.current = nextProtoSeq(this.current);
778
+ return this.current;
779
+ }
780
+ }
781
+
708
782
  const ERROR = 'Wrong result type.';
709
783
  function info(res) {
710
784
  if (typeof res !== 'object' || res == null) {
@@ -821,11 +895,6 @@ function bytesToHex(bytes) {
821
895
  .map(b => b.toString(16).padStart(2, '0'))
822
896
  .join('');
823
897
  }
824
- const PROTOCOL_V2_DEBUG_HEADER_BYTES = 7;
825
- const PROTOCOL_V2_DEBUG_ARRAY_ITEMS_LIMIT = 20;
826
- const PROTOCOL_V2_DEBUG_OBJECT_KEYS_LIMIT = 40;
827
- const PROTOCOL_V2_DEBUG_STRING_LIMIT = 512;
828
- const PROTOCOL_V2_DEBUG_DEPTH_LIMIT = 4;
829
898
  const HIGH_VOLUME_PROTOCOL_V2_CALLS = new Set([
830
899
  ...LogBlockCommand,
831
900
  'FilesystemFileRead',
@@ -835,80 +904,6 @@ const HIGH_VOLUME_PROTOCOL_V2_CALLS = new Set([
835
904
  function shouldReduceProtocolV2Debug(name) {
836
905
  return HIGH_VOLUME_PROTOCOL_V2_CALLS.has(name);
837
906
  }
838
- function frameHeaderDebugHex(frame) {
839
- return bytesToHex(frame.slice(0, PROTOCOL_V2_DEBUG_HEADER_BYTES));
840
- }
841
- function getBinaryByteLength(value) {
842
- if (value instanceof ArrayBuffer) {
843
- return value.byteLength;
844
- }
845
- if (ArrayBuffer.isView(value)) {
846
- return value.byteLength;
847
- }
848
- if (typeof Blob !== 'undefined' && value instanceof Blob) {
849
- return value.size;
850
- }
851
- return undefined;
852
- }
853
- function summarizeRedactedData(value) {
854
- const byteLength = getBinaryByteLength(value);
855
- if (byteLength !== undefined) {
856
- return `[redacted data: ${byteLength} bytes]`;
857
- }
858
- if (typeof value === 'string') {
859
- return `[redacted data: string length=${value.length}]`;
860
- }
861
- if (Array.isArray(value)) {
862
- return `[redacted data: array length=${value.length}]`;
863
- }
864
- if (value && typeof value === 'object') {
865
- return `[redacted data: object keys=${Object.keys(value).length}]`;
866
- }
867
- return `[redacted data: ${typeof value}]`;
868
- }
869
- function sanitizeProtocolV2DebugPayload(value, key = '', depth = 0) {
870
- if (/^(data|payload)$/i.test(key) && value !== null && value !== undefined) {
871
- return summarizeRedactedData(value);
872
- }
873
- if (/(passphrase|pin|mnemonic|seed|private)/i.test(key)) {
874
- return '[redacted sensitive value]';
875
- }
876
- const byteLength = getBinaryByteLength(value);
877
- if (byteLength !== undefined) {
878
- return `[binary: ${byteLength} bytes]`;
879
- }
880
- if (typeof value === 'string') {
881
- return value.length > PROTOCOL_V2_DEBUG_STRING_LIMIT
882
- ? `${value.slice(0, PROTOCOL_V2_DEBUG_STRING_LIMIT)}... (len=${value.length})`
883
- : value;
884
- }
885
- if (!value || typeof value !== 'object') {
886
- return value;
887
- }
888
- if (depth >= PROTOCOL_V2_DEBUG_DEPTH_LIMIT) {
889
- return Array.isArray(value)
890
- ? `[array length=${value.length}]`
891
- : `[object keys=${Object.keys(value).length}]`;
892
- }
893
- if (Array.isArray(value)) {
894
- const items = value
895
- .slice(0, PROTOCOL_V2_DEBUG_ARRAY_ITEMS_LIMIT)
896
- .map(item => sanitizeProtocolV2DebugPayload(item, key, depth + 1));
897
- if (value.length > PROTOCOL_V2_DEBUG_ARRAY_ITEMS_LIMIT) {
898
- items.push(`... (${value.length - PROTOCOL_V2_DEBUG_ARRAY_ITEMS_LIMIT} more)`);
899
- }
900
- return items;
901
- }
902
- const entries = Object.entries(value).slice(0, PROTOCOL_V2_DEBUG_OBJECT_KEYS_LIMIT);
903
- const sanitized = {};
904
- entries.forEach(([entryKey, entryValue]) => {
905
- sanitized[entryKey] = sanitizeProtocolV2DebugPayload(entryValue, entryKey, depth + 1);
906
- });
907
- if (Object.keys(value).length > PROTOCOL_V2_DEBUG_OBJECT_KEYS_LIMIT) {
908
- sanitized.__truncated__ = `${Object.keys(value).length - PROTOCOL_V2_DEBUG_OBJECT_KEYS_LIMIT} more keys`;
909
- }
910
- return sanitized;
911
- }
912
907
  const COMMON_TERMINAL_RESPONSE_TYPES = new Set([
913
908
  'Failure',
914
909
  'ButtonRequest',
@@ -934,11 +929,12 @@ function getErrorMessage(error) {
934
929
  }
935
930
  return String(error);
936
931
  }
937
- function withProtocolTimeout(promise, timeoutMs, createTimeoutError, onTimeout) {
932
+ function withProtocolTimeout(promise, timeoutMs, createTimeoutError, onTimeout, abortSignal) {
938
933
  return __awaiter(this, void 0, void 0, function* () {
939
934
  if (!timeoutMs)
940
935
  return promise;
941
936
  let timer;
937
+ let abortHandler;
942
938
  try {
943
939
  return yield Promise.race([
944
940
  promise,
@@ -948,20 +944,38 @@ function withProtocolTimeout(promise, timeoutMs, createTimeoutError, onTimeout)
948
944
  reject(createTimeoutError());
949
945
  }, timeoutMs);
950
946
  }),
947
+ ...(abortSignal
948
+ ? [
949
+ new Promise((_, reject) => {
950
+ abortHandler = () => {
951
+ reject(new Error('Protocol V2 operation aborted'));
952
+ };
953
+ if (abortSignal.aborted) {
954
+ abortHandler();
955
+ }
956
+ else {
957
+ abortSignal.addEventListener('abort', abortHandler, { once: true });
958
+ }
959
+ }),
960
+ ]
961
+ : []),
951
962
  ]);
952
963
  }
953
964
  finally {
954
965
  if (timer)
955
966
  clearTimeout(timer);
967
+ if (abortHandler) {
968
+ abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener('abort', abortHandler);
969
+ }
956
970
  }
957
971
  });
958
972
  }
959
- const PROTOCOL_V2_WRITE_WATCHDOG_TIMEOUT_MS = 0;
960
973
  class ProtocolV2Session {
961
974
  constructor(options) {
975
+ var _a;
962
976
  this.pendingCall = Promise.resolve();
963
- this.protoSeq = 0;
964
977
  this.options = options;
978
+ this.sequenceCursor = (_a = options.sequenceCursor) !== null && _a !== void 0 ? _a : new ProtocolV2SequenceCursor();
965
979
  }
966
980
  call(name, data, callOptions = {}) {
967
981
  const run = () => this.executeCall(name, data, callOptions);
@@ -970,69 +984,91 @@ class ProtocolV2Session {
970
984
  return result;
971
985
  }
972
986
  executeCall(name, data, callOptions) {
973
- var _a, _b;
974
- return __awaiter(this, void 0, void 0, function* () {
975
- const { schemas, router, packetSrc = PROTOCOL_V2_PACKET_SRC_COMMAND, writeFrame, readFrame, logger, logPrefix = 'ProtocolV2', createTimeoutError, } = this.options;
976
- const shouldReduceDebug = shouldReduceProtocolV2Debug(name);
977
- this.protoSeq = nextProtoSeq(this.protoSeq);
987
+ const { schemas, router, packetSrc = PROTOCOL_V2_PACKET_SRC_COMMAND, maxFrameBytes, prepareCall, writeFrame, readFrame, logger, logPrefix = 'ProtocolV2', createTimeoutError, generation = 0, } = this.options;
988
+ const timeoutMs = callOptions.timeoutMs && callOptions.timeoutMs > 0
989
+ ? callOptions.timeoutMs
990
+ : PROTOCOL_V2_DEFAULT_RESPONSE_TIMEOUT_MS;
991
+ const abortController = new AbortController();
992
+ const shouldReduceDebug = shouldReduceProtocolV2Debug(name);
993
+ const baseCallContext = {
994
+ messageName: name,
995
+ timeoutMs,
996
+ highVolume: shouldReduceDebug,
997
+ generation,
998
+ signal: abortController.signal,
999
+ };
1000
+ const runCall = () => __awaiter(this, void 0, void 0, function* () {
1001
+ var _a, _b, _c, _d;
1002
+ yield (prepareCall === null || prepareCall === void 0 ? void 0 : prepareCall(baseCallContext));
1003
+ const protoSeq = this.sequenceCursor.next();
978
1004
  const frame = ProtocolV2.encodeFrame(schemas, name, data, {
979
1005
  packetSrc,
980
1006
  router,
981
- seq: this.protoSeq,
982
- logger: shouldReduceDebug ? undefined : logger,
983
- logPrefix,
984
- context: `tx:${name}`,
1007
+ seq: protoSeq,
985
1008
  });
986
- const expectedSeq = frame[6];
987
- if (!shouldReduceDebug) {
988
- (_a = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _a === void 0 ? void 0 : _a.call(logger, `[${logPrefix}] TX payload name=${name}`, sanitizeProtocolV2DebugPayload(data));
989
- (_b = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _b === void 0 ? void 0 : _b.call(logger, `[${logPrefix}] TX frame name=${name} len=${frame.length} router=${frame[4]} attr=${frame[5]} seq=${expectedSeq} headerHex=${frameHeaderDebugHex(frame)}`);
1009
+ if (maxFrameBytes !== undefined && frame.length > maxFrameBytes) {
1010
+ throw new Error(`Protocol V2 frame too large for transport: ${frame.length} > ${maxFrameBytes}`);
990
1011
  }
991
- yield withProtocolTimeout(writeFrame(frame), PROTOCOL_V2_WRITE_WATCHDOG_TIMEOUT_MS, () => new Error(`Protocol V2 write timeout after ${PROTOCOL_V2_WRITE_WATCHDOG_TIMEOUT_MS}ms for ${name}`));
992
- const cancellation = { cancelled: false };
993
- const readResponse = () => __awaiter(this, void 0, void 0, function* () {
994
- var _c, _d, _e, _f, _g, _h, _j, _k;
995
- while (!cancellation.cancelled) {
996
- const rxFrame = yield readFrame();
997
- if (cancellation.cancelled) {
998
- break;
1012
+ yield writeFrame(frame, baseCallContext);
1013
+ while (!abortController.signal.aborted) {
1014
+ const rxFrame = yield readFrame(baseCallContext);
1015
+ if (abortController.signal.aborted)
1016
+ break;
1017
+ let header;
1018
+ try {
1019
+ header = ProtocolV2.inspectFrameHeader(rxFrame);
1020
+ }
1021
+ catch (cause) {
1022
+ throw new ProtocolV2LinkError('frame', `Protocol V2 frame validation failed: ${getErrorMessage(cause)}`, cause);
1023
+ }
1024
+ if (header.router !== router) {
1025
+ throw new ProtocolV2LinkError('router', `Protocol V2 router mismatch: expected ${router}, got ${header.router}`);
1026
+ }
1027
+ if (header.packetSrc !== packetSrc) {
1028
+ throw new ProtocolV2LinkError('packet-source', `Protocol V2 packet source mismatch: expected ${packetSrc}, got ${header.packetSrc}`);
1029
+ }
1030
+ let isAck;
1031
+ try {
1032
+ isAck = ProtocolV2.isAckFrame(rxFrame);
1033
+ }
1034
+ catch (cause) {
1035
+ throw new ProtocolV2LinkError('frame', `Protocol V2 ACK validation failed: ${getErrorMessage(cause)}`, cause);
1036
+ }
1037
+ if (isAck) {
1038
+ if (header.seq !== protoSeq) {
1039
+ throw new ProtocolV2LinkError('ack-sequence', `Protocol V2 ACK sequence mismatch: expected ${protoSeq}, got ${header.seq}`);
999
1040
  }
1000
- if (!shouldReduceDebug) {
1001
- (_c = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _c === void 0 ? void 0 : _c.call(logger, `[${logPrefix}] RX frame len=${rxFrame.length} router=${rxFrame[4]} attr=${rxFrame[5]} seq=${rxFrame[6]} headerHex=${frameHeaderDebugHex(rxFrame)}`);
1041
+ }
1042
+ else {
1043
+ let decoded;
1044
+ try {
1045
+ decoded = ProtocolV2.decodeFrame(schemas, rxFrame);
1002
1046
  }
1003
- const decoded = ProtocolV2.decodeFrame(schemas, rxFrame, {
1004
- logger: shouldReduceDebug ? undefined : logger,
1005
- logPrefix,
1006
- context: `rx:${name}`,
1007
- });
1008
- if (!shouldReduceDebug && decoded.seq !== expectedSeq) {
1009
- (_d = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _d === void 0 ? void 0 : _d.call(logger, `[${logPrefix}] seq differs for ${name}: tx=${expectedSeq}, rx=${decoded.seq}`);
1047
+ catch (cause) {
1048
+ throw new ProtocolV2LinkError('frame', `Protocol V2 frame decode failed: ${getErrorMessage(cause)}`, cause);
1010
1049
  }
1011
- if (!shouldReduceDebug) {
1012
- (_e = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _e === void 0 ? void 0 : _e.call(logger, `[${logPrefix}] TX name=${name} seq=${expectedSeq} | RX seq=${decoded.seq} messageTypeId=${decoded.messageTypeId} pbPayload=${decoded.pbPayload.length}B`);
1013
- (_f = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _f === void 0 ? void 0 : _f.call(logger, `[${logPrefix}] RX payload type=${decoded.type} messageTypeId=${decoded.messageTypeId}`, sanitizeProtocolV2DebugPayload(decoded.message));
1050
+ if (this.lastResponseSequence === decoded.seq) {
1051
+ throw new ProtocolV2LinkError('response-sequence', `Protocol V2 duplicate response sequence: ${decoded.seq}`);
1014
1052
  }
1053
+ this.lastResponseSequence = decoded.seq;
1015
1054
  const response = call(decoded);
1016
- if ((_g = callOptions.intermediateTypes) === null || _g === void 0 ? void 0 : _g.includes(response.type)) {
1017
- (_h = callOptions.onIntermediateResponse) === null || _h === void 0 ? void 0 : _h.call(callOptions, response);
1055
+ if ((_a = callOptions.intermediateTypes) === null || _a === void 0 ? void 0 : _a.includes(response.type)) {
1056
+ (_b = callOptions.onIntermediateResponse) === null || _b === void 0 ? void 0 : _b.call(callOptions, response);
1018
1057
  }
1019
1058
  else if (isExpectedTerminalResponse(response, callOptions.expectedTypes)) {
1020
1059
  return response;
1021
1060
  }
1022
1061
  else if (!shouldReduceDebug) {
1023
- (_j = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _j === void 0 ? void 0 : _j.call(logger, `[${logPrefix}] skip unexpected response for ${name}: expected=${(_k = callOptions.expectedTypes) === null || _k === void 0 ? void 0 : _k.join('|')} got=${response.type}`);
1062
+ (_c = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _c === void 0 ? void 0 : _c.call(logger, `[${logPrefix}] skip unexpected response for ${name}: expected=${(_d = callOptions.expectedTypes) === null || _d === void 0 ? void 0 : _d.join('|')} got=${response.type}`);
1024
1063
  }
1025
1064
  }
1026
- throw new Error(`Protocol V2 read loop cancelled after timeout for ${name}`);
1027
- });
1028
- return withProtocolTimeout(readResponse(), callOptions.timeoutMs, () => {
1029
- var _a;
1030
- return createTimeoutError
1031
- ? createTimeoutError(name, (_a = callOptions.timeoutMs) !== null && _a !== void 0 ? _a : 0)
1032
- : new Error(`Protocol V2 response timeout after ${callOptions.timeoutMs}ms for ${name}`);
1033
- }, () => {
1034
- cancellation.cancelled = true;
1035
- });
1065
+ }
1066
+ throw new Error(`Protocol V2 read loop cancelled after timeout for ${name}`);
1067
+ });
1068
+ return withProtocolTimeout(runCall(), timeoutMs, () => createTimeoutError
1069
+ ? createTimeoutError(name, timeoutMs)
1070
+ : new Error(`Protocol V2 response timeout after ${timeoutMs}ms for ${name}`), () => {
1071
+ abortController.abort();
1036
1072
  });
1037
1073
  }
1038
1074
  }
@@ -1042,7 +1078,10 @@ function probeProtocolV2({ call, timeoutMs, logger, logPrefix = 'ProtocolV2', on
1042
1078
  let probeError;
1043
1079
  try {
1044
1080
  yield (onBeforeProbe === null || onBeforeProbe === void 0 ? void 0 : onBeforeProbe());
1045
- const response = yield call('Ping', { message: 'protocol-v2-probe' }, { timeoutMs, expectedTypes: ['Success'] });
1081
+ const response = yield call('Ping', { message: 'protocol-v2-probe' }, {
1082
+ timeoutMs,
1083
+ expectedTypes: ['Success'],
1084
+ });
1046
1085
  if (response.type === 'Success') {
1047
1086
  return true;
1048
1087
  }
@@ -1057,6 +1096,305 @@ function probeProtocolV2({ call, timeoutMs, logger, logPrefix = 'ProtocolV2', on
1057
1096
  });
1058
1097
  }
1059
1098
 
1099
+ class ProtocolV2LinkManager {
1100
+ constructor(options) {
1101
+ this.links = new Map();
1102
+ this.sequences = new Map();
1103
+ this.callQueues = new Map();
1104
+ this.generations = new Map();
1105
+ this.invalidationReasons = new Map();
1106
+ this.invalidations = new Map();
1107
+ this.options = options;
1108
+ }
1109
+ call(key, createAdapter, name, data, options) {
1110
+ var _a, _b;
1111
+ const generation = (_a = this.generations.get(key)) !== null && _a !== void 0 ? _a : 0;
1112
+ const run = () => {
1113
+ this.assertCallGeneration(key, generation);
1114
+ return this.executeCall(key, createAdapter, name, data, options);
1115
+ };
1116
+ const previous = (_b = this.callQueues.get(key)) !== null && _b !== void 0 ? _b : Promise.resolve();
1117
+ const result = previous.then(run, run);
1118
+ const queue = result.catch(() => undefined);
1119
+ this.callQueues.set(key, queue);
1120
+ result
1121
+ .then(() => this.clearSettledCallQueue(key, queue), () => this.clearSettledCallQueue(key, queue))
1122
+ .catch(() => undefined);
1123
+ return result;
1124
+ }
1125
+ invalidateLink(key, reason) {
1126
+ var _a;
1127
+ return __awaiter(this, void 0, void 0, function* () {
1128
+ const generation = ((_a = this.generations.get(key)) !== null && _a !== void 0 ? _a : 0) + 1;
1129
+ this.generations.set(key, generation);
1130
+ this.invalidationReasons.set(key, { generation, reason });
1131
+ const pendingInvalidation = this.invalidations.get(key);
1132
+ const link = this.links.get(key);
1133
+ if (!link) {
1134
+ yield pendingInvalidation;
1135
+ return;
1136
+ }
1137
+ this.links.delete(key);
1138
+ link.state.invalidatedReason = reason;
1139
+ const invalidation = (() => __awaiter(this, void 0, void 0, function* () {
1140
+ var _b, _c;
1141
+ yield (pendingInvalidation === null || pendingInvalidation === void 0 ? void 0 : pendingInvalidation.catch(() => undefined));
1142
+ yield link.adapter.reset(reason);
1143
+ yield ((_c = (_b = this.options).onLinkInvalidated) === null || _c === void 0 ? void 0 : _c.call(_b, key, reason));
1144
+ }))();
1145
+ this.invalidations.set(key, invalidation);
1146
+ try {
1147
+ yield invalidation;
1148
+ }
1149
+ finally {
1150
+ if (this.invalidations.get(key) === invalidation) {
1151
+ this.invalidations.delete(key);
1152
+ }
1153
+ }
1154
+ });
1155
+ }
1156
+ invalidateAllLinks(reason) {
1157
+ return __awaiter(this, void 0, void 0, function* () {
1158
+ const keys = new Set([
1159
+ ...this.links.keys(),
1160
+ ...this.callQueues.keys(),
1161
+ ...this.invalidations.keys(),
1162
+ ]);
1163
+ yield Promise.all(Array.from(keys, key => this.invalidateLink(key, reason)));
1164
+ });
1165
+ }
1166
+ dispose(reason) {
1167
+ return __awaiter(this, void 0, void 0, function* () {
1168
+ yield this.invalidateAllLinks(reason);
1169
+ this.sequences.clear();
1170
+ this.callQueues.clear();
1171
+ this.invalidations.clear();
1172
+ });
1173
+ }
1174
+ getOrCreateLink(key, createAdapter) {
1175
+ const existing = this.links.get(key);
1176
+ if (existing)
1177
+ return existing;
1178
+ const adapter = createAdapter();
1179
+ const state = {};
1180
+ const assertLinkActive = () => {
1181
+ if (state.invalidatedReason) {
1182
+ throw new Error(state.invalidatedReason);
1183
+ }
1184
+ };
1185
+ let sequenceCursor = this.sequences.get(key);
1186
+ if (!sequenceCursor) {
1187
+ sequenceCursor = new ProtocolV2SequenceCursor();
1188
+ this.sequences.set(key, sequenceCursor);
1189
+ }
1190
+ const session = new ProtocolV2Session({
1191
+ schemas: this.options.getSchemas(),
1192
+ router: adapter.router,
1193
+ maxFrameBytes: adapter.maxFrameBytes,
1194
+ generation: adapter.generation,
1195
+ sequenceCursor,
1196
+ prepareCall: (context) => __awaiter(this, void 0, void 0, function* () {
1197
+ assertLinkActive();
1198
+ yield adapter.prepareCall(context);
1199
+ assertLinkActive();
1200
+ }),
1201
+ writeFrame: (frame, context) => __awaiter(this, void 0, void 0, function* () {
1202
+ assertLinkActive();
1203
+ yield adapter.writeFrame(frame, context);
1204
+ assertLinkActive();
1205
+ }),
1206
+ readFrame: (context) => __awaiter(this, void 0, void 0, function* () {
1207
+ assertLinkActive();
1208
+ const frame = yield adapter.readFrame(context);
1209
+ assertLinkActive();
1210
+ return frame;
1211
+ }),
1212
+ logger: adapter.logger,
1213
+ logPrefix: adapter.logPrefix,
1214
+ createTimeoutError: adapter.createTimeoutError,
1215
+ });
1216
+ const link = { adapter, session, state };
1217
+ this.links.set(key, link);
1218
+ return link;
1219
+ }
1220
+ executeCall(key, createAdapter, name, data, options) {
1221
+ return __awaiter(this, void 0, void 0, function* () {
1222
+ try {
1223
+ return yield this.getOrCreateLink(key, createAdapter).session.call(name, data, options);
1224
+ }
1225
+ catch (error) {
1226
+ if (this.options.classifyError(error) === 'link-fatal') {
1227
+ const errorMessage = getErrorMessage(error) || 'unknown error';
1228
+ yield this.invalidateLink(key, `Protocol V2 link-fatal error: ${errorMessage}`);
1229
+ }
1230
+ throw error;
1231
+ }
1232
+ });
1233
+ }
1234
+ clearSettledCallQueue(key, queue) {
1235
+ if (this.callQueues.get(key) === queue) {
1236
+ this.callQueues.delete(key);
1237
+ }
1238
+ }
1239
+ assertCallGeneration(key, generation) {
1240
+ var _a;
1241
+ const currentGeneration = (_a = this.generations.get(key)) !== null && _a !== void 0 ? _a : 0;
1242
+ if (currentGeneration === generation)
1243
+ return;
1244
+ const invalidation = this.invalidationReasons.get(key);
1245
+ const reason = (invalidation === null || invalidation === void 0 ? void 0 : invalidation.generation) === currentGeneration
1246
+ ? invalidation.reason
1247
+ : 'Protocol V2 link generation changed';
1248
+ throw new ProtocolV2LinkError('generation', reason);
1249
+ }
1250
+ }
1251
+
1252
+ class ProtocolV2UsbTransportBase {
1253
+ constructor(options) {
1254
+ this.protocolV2UsbAssemblers = new Map();
1255
+ this.protocolV2UsbGenerations = new Map();
1256
+ this.protocolV2UsbCancellations = new Map();
1257
+ this.protocolV2UsbOptions = options;
1258
+ this.protocolV2UsbLinks = new ProtocolV2LinkManager({
1259
+ getSchemas: () => this.getProtocolV2UsbSchemas(),
1260
+ classifyError: error => (isProtocolV2LinkError(error) ? 'link-fatal' : 'recoverable'),
1261
+ onLinkInvalidated: (key, reason) => __awaiter(this, void 0, void 0, function* () {
1262
+ var _a;
1263
+ (_a = this.protocolV2UsbAssemblers.get(key)) === null || _a === void 0 ? void 0 : _a.reset();
1264
+ yield this.resetProtocolV2UsbNativeLink(key, reason);
1265
+ yield this.onProtocolV2UsbLinkInvalidated(key, reason);
1266
+ }),
1267
+ });
1268
+ }
1269
+ onProtocolV2UsbLinkInvalidated(_key, _reason) {
1270
+ }
1271
+ rotateProtocolV2UsbGeneration(key, reason) {
1272
+ var _a;
1273
+ return __awaiter(this, void 0, void 0, function* () {
1274
+ yield this.protocolV2UsbLinks.invalidateLink(key, reason);
1275
+ const generation = ((_a = this.protocolV2UsbGenerations.get(key)) !== null && _a !== void 0 ? _a : 0) + 1;
1276
+ this.protocolV2UsbGenerations.set(key, generation);
1277
+ this.protocolV2UsbCancellations.set(key, this.createProtocolV2UsbCancellation(generation));
1278
+ this.protocolV2UsbAssemblers.set(key, new ProtocolV2FrameAssembler(this.protocolV2UsbOptions.maxFrameBytes));
1279
+ return generation;
1280
+ });
1281
+ }
1282
+ callProtocolV2Usb(key, name, data, options) {
1283
+ return this.protocolV2UsbLinks.call(key, () => this.createProtocolV2UsbAdapter(key), name, data, options);
1284
+ }
1285
+ invalidateProtocolV2UsbLink(key, reason) {
1286
+ return this.protocolV2UsbLinks.invalidateLink(key, reason);
1287
+ }
1288
+ invalidateAllProtocolV2UsbLinks(reason) {
1289
+ return this.protocolV2UsbLinks.invalidateAllLinks(reason);
1290
+ }
1291
+ disposeProtocolV2UsbLinks(reason) {
1292
+ return __awaiter(this, void 0, void 0, function* () {
1293
+ yield this.protocolV2UsbLinks.dispose(reason);
1294
+ this.protocolV2UsbAssemblers.clear();
1295
+ this.protocolV2UsbGenerations.clear();
1296
+ this.protocolV2UsbCancellations.clear();
1297
+ });
1298
+ }
1299
+ createProtocolV2UsbAdapter(key) {
1300
+ const generation = this.protocolV2UsbGenerations.get(key);
1301
+ if (generation === undefined) {
1302
+ throw new Error('Protocol V2 USB generation has not been initialized');
1303
+ }
1304
+ const cancellation = this.protocolV2UsbCancellations.get(key);
1305
+ if (!cancellation || cancellation.generation !== generation) {
1306
+ throw new Error('Protocol V2 USB cancellation state has not been initialized');
1307
+ }
1308
+ const assertCurrentGeneration = () => {
1309
+ if (cancellation.reason) {
1310
+ throw new ProtocolV2LinkError('generation', cancellation.reason);
1311
+ }
1312
+ if (this.protocolV2UsbGenerations.get(key) !== generation) {
1313
+ throw new ProtocolV2LinkError('generation', 'Protocol V2 USB connection generation changed');
1314
+ }
1315
+ };
1316
+ return {
1317
+ router: this.protocolV2UsbOptions.router,
1318
+ maxFrameBytes: this.protocolV2UsbOptions.maxFrameBytes,
1319
+ generation,
1320
+ prepareCall: () => {
1321
+ assertCurrentGeneration();
1322
+ },
1323
+ writeFrame: (frame, context) => __awaiter(this, void 0, void 0, function* () {
1324
+ assertCurrentGeneration();
1325
+ try {
1326
+ yield this.writeProtocolV2UsbPacket(key, frame, context);
1327
+ }
1328
+ catch (error) {
1329
+ throw this.createProtocolV2UsbIoError('write', error);
1330
+ }
1331
+ assertCurrentGeneration();
1332
+ }),
1333
+ readFrame: (context) => __awaiter(this, void 0, void 0, function* () {
1334
+ assertCurrentGeneration();
1335
+ const assembler = this.getProtocolV2UsbAssembler(key);
1336
+ let frame = assembler.push(new Uint8Array(0));
1337
+ while (!frame) {
1338
+ const packetRead = this.readProtocolV2UsbPacket(key, context)
1339
+ .then(packet => ({ packet }))
1340
+ .catch(error => {
1341
+ throw this.createProtocolV2UsbIoError('read', error);
1342
+ });
1343
+ const cancelled = cancellation.promise.then(reason => ({ reason }));
1344
+ const result = yield Promise.race([packetRead, cancelled]);
1345
+ if ('reason' in result) {
1346
+ throw new ProtocolV2LinkError('generation', result.reason);
1347
+ }
1348
+ assertCurrentGeneration();
1349
+ frame = assembler.push(result.packet);
1350
+ }
1351
+ assertCurrentGeneration();
1352
+ return frame;
1353
+ }),
1354
+ reset: (reason) => {
1355
+ var _a;
1356
+ cancellation.cancel(reason);
1357
+ (_a = this.protocolV2UsbAssemblers.get(key)) === null || _a === void 0 ? void 0 : _a.reset();
1358
+ },
1359
+ logger: this.getProtocolV2UsbLogger(),
1360
+ logPrefix: this.protocolV2UsbOptions.logPrefix,
1361
+ createTimeoutError: (messageName, timeoutMs) => this.createProtocolV2UsbTimeoutError(messageName, timeoutMs),
1362
+ };
1363
+ }
1364
+ getProtocolV2UsbAssembler(key) {
1365
+ const assembler = this.protocolV2UsbAssemblers.get(key);
1366
+ if (!assembler) {
1367
+ throw new Error('Protocol V2 USB assembler has not been initialized');
1368
+ }
1369
+ return assembler;
1370
+ }
1371
+ createProtocolV2UsbCancellation(generation) {
1372
+ let resolveCancellation = () => undefined;
1373
+ const cancellation = {
1374
+ generation,
1375
+ promise: new Promise(resolve => {
1376
+ resolveCancellation = resolve;
1377
+ }),
1378
+ cancel: reason => {
1379
+ if (cancellation.reason)
1380
+ return;
1381
+ cancellation.reason = reason;
1382
+ resolveCancellation(reason);
1383
+ },
1384
+ };
1385
+ return cancellation;
1386
+ }
1387
+ createProtocolV2UsbIoError(operation, error) {
1388
+ if (isProtocolV2LinkError(error))
1389
+ return error;
1390
+ return new ProtocolV2LinkError('io', `Protocol V2 USB ${operation} failed: ${getErrorMessage(error) || 'unknown error'}`, error);
1391
+ }
1392
+ }
1393
+
1394
+ const TRANSPORT_EVENT = {
1395
+ DEVICE_DISCONNECT: 'transport-device-disconnect',
1396
+ };
1397
+
1060
1398
  exports.AptosTransactionType = void 0;
1061
1399
  (function (AptosTransactionType) {
1062
1400
  AptosTransactionType[AptosTransactionType["STANDARD"] = 0] = "STANDARD";
@@ -1303,6 +1641,24 @@ exports.EthereumDataType = void 0;
1303
1641
  EthereumDataType[EthereumDataType["ARRAY"] = 7] = "ARRAY";
1304
1642
  EthereumDataType[EthereumDataType["STRUCT"] = 8] = "STRUCT";
1305
1643
  })(exports.EthereumDataType || (exports.EthereumDataType = {}));
1644
+ exports.Enum_KaspaInputScriptType = void 0;
1645
+ (function (Enum_KaspaInputScriptType) {
1646
+ Enum_KaspaInputScriptType[Enum_KaspaInputScriptType["KASPA_SPEND_P2PK_SCHNORR"] = 0] = "KASPA_SPEND_P2PK_SCHNORR";
1647
+ Enum_KaspaInputScriptType[Enum_KaspaInputScriptType["KASPA_SPEND_P2PK_ECDSA"] = 1] = "KASPA_SPEND_P2PK_ECDSA";
1648
+ })(exports.Enum_KaspaInputScriptType || (exports.Enum_KaspaInputScriptType = {}));
1649
+ exports.Enum_KaspaOutputScriptType = void 0;
1650
+ (function (Enum_KaspaOutputScriptType) {
1651
+ Enum_KaspaOutputScriptType[Enum_KaspaOutputScriptType["KASPA_PAYTOADDRESS"] = 0] = "KASPA_PAYTOADDRESS";
1652
+ Enum_KaspaOutputScriptType[Enum_KaspaOutputScriptType["KASPA_PAYTOCHANGE"] = 1] = "KASPA_PAYTOCHANGE";
1653
+ })(exports.Enum_KaspaOutputScriptType || (exports.Enum_KaspaOutputScriptType = {}));
1654
+ exports.Enum_KaspaRequestType = void 0;
1655
+ (function (Enum_KaspaRequestType) {
1656
+ Enum_KaspaRequestType[Enum_KaspaRequestType["KASPA_TX_INPUT"] = 0] = "KASPA_TX_INPUT";
1657
+ Enum_KaspaRequestType[Enum_KaspaRequestType["KASPA_TX_OUTPUT"] = 1] = "KASPA_TX_OUTPUT";
1658
+ Enum_KaspaRequestType[Enum_KaspaRequestType["KASPA_TX_PAYLOAD"] = 2] = "KASPA_TX_PAYLOAD";
1659
+ Enum_KaspaRequestType[Enum_KaspaRequestType["KASPA_TX_FINISHED"] = 3] = "KASPA_TX_FINISHED";
1660
+ Enum_KaspaRequestType[Enum_KaspaRequestType["KASPA_TX_PREV_META"] = 4] = "KASPA_TX_PREV_META";
1661
+ })(exports.Enum_KaspaRequestType || (exports.Enum_KaspaRequestType = {}));
1306
1662
  exports.Enum_BackupType = void 0;
1307
1663
  (function (Enum_BackupType) {
1308
1664
  Enum_BackupType[Enum_BackupType["Bip39"] = 0] = "Bip39";
@@ -1496,11 +1852,6 @@ exports.CommandFlags = void 0;
1496
1852
  CommandFlags[CommandFlags["Default"] = 0] = "Default";
1497
1853
  CommandFlags[CommandFlags["Factory_Only"] = 1] = "Factory_Only";
1498
1854
  })(exports.CommandFlags || (exports.CommandFlags = {}));
1499
- exports.WallpaperTarget = void 0;
1500
- (function (WallpaperTarget) {
1501
- WallpaperTarget[WallpaperTarget["Home"] = 0] = "Home";
1502
- WallpaperTarget[WallpaperTarget["Lock"] = 1] = "Lock";
1503
- })(exports.WallpaperTarget || (exports.WallpaperTarget = {}));
1504
1855
  exports.MoneroNetworkType = void 0;
1505
1856
  (function (MoneroNetworkType) {
1506
1857
  MoneroNetworkType[MoneroNetworkType["MAINNET"] = 0] = "MAINNET";
@@ -1508,20 +1859,49 @@ exports.MoneroNetworkType = void 0;
1508
1859
  MoneroNetworkType[MoneroNetworkType["STAGENET"] = 2] = "STAGENET";
1509
1860
  MoneroNetworkType[MoneroNetworkType["FAKECHAIN"] = 3] = "FAKECHAIN";
1510
1861
  })(exports.MoneroNetworkType || (exports.MoneroNetworkType = {}));
1511
- exports.ViewTipType = void 0;
1512
- (function (ViewTipType) {
1513
- ViewTipType[ViewTipType["Default"] = 0] = "Default";
1514
- ViewTipType[ViewTipType["Highlight"] = 1] = "Highlight";
1515
- ViewTipType[ViewTipType["Recommend"] = 2] = "Recommend";
1516
- ViewTipType[ViewTipType["Warning"] = 3] = "Warning";
1517
- ViewTipType[ViewTipType["Danger"] = 4] = "Danger";
1518
- })(exports.ViewTipType || (exports.ViewTipType = {}));
1862
+ exports.UiAnimationType = void 0;
1863
+ (function (UiAnimationType) {
1864
+ UiAnimationType[UiAnimationType["Unknown"] = 0] = "Unknown";
1865
+ UiAnimationType[UiAnimationType["Signing"] = 1] = "Signing";
1866
+ })(exports.UiAnimationType || (exports.UiAnimationType = {}));
1867
+ exports.UiAnimationCommand = void 0;
1868
+ (function (UiAnimationCommand) {
1869
+ UiAnimationCommand[UiAnimationCommand["CommandUnknown"] = 0] = "CommandUnknown";
1870
+ UiAnimationCommand[UiAnimationCommand["Start"] = 1] = "Start";
1871
+ UiAnimationCommand[UiAnimationCommand["Stop"] = 2] = "Stop";
1872
+ UiAnimationCommand[UiAnimationCommand["Refresh"] = 3] = "Refresh";
1873
+ })(exports.UiAnimationCommand || (exports.UiAnimationCommand = {}));
1874
+ exports.DeviceErrorCode = void 0;
1875
+ (function (DeviceErrorCode) {
1876
+ DeviceErrorCode[DeviceErrorCode["DeviceError_None"] = 0] = "DeviceError_None";
1877
+ DeviceErrorCode[DeviceErrorCode["DeviceError_Busy"] = 1] = "DeviceError_Busy";
1878
+ DeviceErrorCode[DeviceErrorCode["DeviceError_NotInitialized"] = 2] = "DeviceError_NotInitialized";
1879
+ DeviceErrorCode[DeviceErrorCode["DeviceError_ActionCancelled"] = 3] = "DeviceError_ActionCancelled";
1880
+ DeviceErrorCode[DeviceErrorCode["DeviceError_PinAlreadyUsed"] = 4] = "DeviceError_PinAlreadyUsed";
1881
+ DeviceErrorCode[DeviceErrorCode["DeviceError_PersistFailed"] = 5] = "DeviceError_PersistFailed";
1882
+ DeviceErrorCode[DeviceErrorCode["DeviceError_SeError"] = 6] = "DeviceError_SeError";
1883
+ DeviceErrorCode[DeviceErrorCode["DeviceError_InvalidLanguage"] = 7] = "DeviceError_InvalidLanguage";
1884
+ DeviceErrorCode[DeviceErrorCode["DeviceError_WallpaperNotUsable"] = 8] = "DeviceError_WallpaperNotUsable";
1885
+ DeviceErrorCode[DeviceErrorCode["DeviceError_DeviceLocked"] = 9] = "DeviceError_DeviceLocked";
1886
+ })(exports.DeviceErrorCode || (exports.DeviceErrorCode = {}));
1519
1887
  exports.DeviceRebootType = void 0;
1520
1888
  (function (DeviceRebootType) {
1521
1889
  DeviceRebootType[DeviceRebootType["Normal"] = 0] = "Normal";
1522
1890
  DeviceRebootType[DeviceRebootType["Romloader"] = 1] = "Romloader";
1523
1891
  DeviceRebootType[DeviceRebootType["Bootloader"] = 2] = "Bootloader";
1524
1892
  })(exports.DeviceRebootType || (exports.DeviceRebootType = {}));
1893
+ exports.DeviceSettingsPage = void 0;
1894
+ (function (DeviceSettingsPage) {
1895
+ DeviceSettingsPage[DeviceSettingsPage["DeviceReset"] = 0] = "DeviceReset";
1896
+ DeviceSettingsPage[DeviceSettingsPage["DevicePinChange"] = 1] = "DevicePinChange";
1897
+ DeviceSettingsPage[DeviceSettingsPage["DevicePassphrase"] = 2] = "DevicePassphrase";
1898
+ DeviceSettingsPage[DeviceSettingsPage["DeviceAirgap"] = 3] = "DeviceAirgap";
1899
+ })(exports.DeviceSettingsPage || (exports.DeviceSettingsPage = {}));
1900
+ exports.DeviceFactoryAck = void 0;
1901
+ (function (DeviceFactoryAck) {
1902
+ DeviceFactoryAck[DeviceFactoryAck["FACTORY_ACK_SUCCESS"] = 0] = "FACTORY_ACK_SUCCESS";
1903
+ DeviceFactoryAck[DeviceFactoryAck["FACTORY_ACK_FAIL"] = 1] = "FACTORY_ACK_FAIL";
1904
+ })(exports.DeviceFactoryAck || (exports.DeviceFactoryAck = {}));
1525
1905
  exports.DeviceFirmwareTargetType = void 0;
1526
1906
  (function (DeviceFirmwareTargetType) {
1527
1907
  DeviceFirmwareTargetType[DeviceFirmwareTargetType["FW_MGMT_TARGET_INVALID"] = 0] = "FW_MGMT_TARGET_INVALID";
@@ -1550,11 +1930,6 @@ exports.DeviceFirmwareUpdateTaskStatus = void 0;
1550
1930
  DeviceFirmwareUpdateTaskStatus[DeviceFirmwareUpdateTaskStatus["FW_MGMT_UPDATER_TASK_STATUS_FAILED_BUSY"] = 9] = "FW_MGMT_UPDATER_TASK_STATUS_FAILED_BUSY";
1551
1931
  DeviceFirmwareUpdateTaskStatus[DeviceFirmwareUpdateTaskStatus["FW_MGMT_UPDATER_TASK_STATUS_FAILED_ENTRY_OUT_OF_BOUNDS"] = 10] = "FW_MGMT_UPDATER_TASK_STATUS_FAILED_ENTRY_OUT_OF_BOUNDS";
1552
1932
  })(exports.DeviceFirmwareUpdateTaskStatus || (exports.DeviceFirmwareUpdateTaskStatus = {}));
1553
- exports.DeviceFactoryAck = void 0;
1554
- (function (DeviceFactoryAck) {
1555
- DeviceFactoryAck[DeviceFactoryAck["FACTORY_ACK_SUCCESS"] = 0] = "FACTORY_ACK_SUCCESS";
1556
- DeviceFactoryAck[DeviceFactoryAck["FACTORY_ACK_FAIL"] = 1] = "FACTORY_ACK_FAIL";
1557
- })(exports.DeviceFactoryAck || (exports.DeviceFactoryAck = {}));
1558
1933
  exports.DeviceType = void 0;
1559
1934
  (function (DeviceType) {
1560
1935
  DeviceType[DeviceType["CLASSIC1"] = 0] = "CLASSIC1";
@@ -1577,6 +1952,111 @@ exports.DeviceSEState = void 0;
1577
1952
  DeviceSEState[DeviceSEState["APP_FACTORY"] = 51] = "APP_FACTORY";
1578
1953
  DeviceSEState[DeviceSEState["APP"] = 85] = "APP";
1579
1954
  })(exports.DeviceSEState || (exports.DeviceSEState = {}));
1955
+ exports.DeviceSessionErrorCode = void 0;
1956
+ (function (DeviceSessionErrorCode) {
1957
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_None"] = 0] = "DeviceSessionError_None";
1958
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_UserCancelled"] = 1] = "DeviceSessionError_UserCancelled";
1959
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_InvalidSession"] = 2] = "DeviceSessionError_InvalidSession";
1960
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_AttachPinUnavailable"] = 3] = "DeviceSessionError_AttachPinUnavailable";
1961
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_PassphraseDisabled"] = 4] = "DeviceSessionError_PassphraseDisabled";
1962
+ DeviceSessionErrorCode[DeviceSessionErrorCode["DeviceSessionError_Busy"] = 5] = "DeviceSessionError_Busy";
1963
+ })(exports.DeviceSessionErrorCode || (exports.DeviceSessionErrorCode = {}));
1964
+ exports.DeviceSessionPinType = void 0;
1965
+ (function (DeviceSessionPinType) {
1966
+ DeviceSessionPinType[DeviceSessionPinType["Any"] = 1] = "Any";
1967
+ DeviceSessionPinType[DeviceSessionPinType["Main"] = 2] = "Main";
1968
+ DeviceSessionPinType[DeviceSessionPinType["AttachToPin"] = 3] = "AttachToPin";
1969
+ })(exports.DeviceSessionPinType || (exports.DeviceSessionPinType = {}));
1970
+ exports.DeviceSessionAskPin_FailureSubCodes = void 0;
1971
+ (function (DeviceSessionAskPin_FailureSubCodes) {
1972
+ DeviceSessionAskPin_FailureSubCodes[DeviceSessionAskPin_FailureSubCodes["UserCancel"] = 1] = "UserCancel";
1973
+ })(exports.DeviceSessionAskPin_FailureSubCodes || (exports.DeviceSessionAskPin_FailureSubCodes = {}));
1974
+ exports.OnboardingStep = void 0;
1975
+ (function (OnboardingStep) {
1976
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_UNKNOWN"] = 0] = "ONBOARDING_STEP_UNKNOWN";
1977
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_CHECKING"] = 1] = "ONBOARDING_STEP_CHECKING";
1978
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_PERSONALIZATION"] = 2] = "ONBOARDING_STEP_PERSONALIZATION";
1979
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_PIN"] = 3] = "ONBOARDING_STEP_PIN";
1980
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_SETUP"] = 4] = "ONBOARDING_STEP_SETUP";
1981
+ OnboardingStep[OnboardingStep["ONBOARDING_STEP_DONE"] = 5] = "ONBOARDING_STEP_DONE";
1982
+ })(exports.OnboardingStep || (exports.OnboardingStep = {}));
1983
+ exports.OnboardingPhase = void 0;
1984
+ (function (OnboardingPhase) {
1985
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_UNKNOWN"] = 0] = "ONBOARDING_PHASE_UNKNOWN";
1986
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_SAFETY_CHECK"] = 1] = "ONBOARDING_PHASE_SAFETY_CHECK";
1987
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_PIN_SETUP"] = 2] = "ONBOARDING_PHASE_PIN_SETUP";
1988
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_FINGERPRINT_SETUP"] = 3] = "ONBOARDING_PHASE_FINGERPRINT_SETUP";
1989
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_SETUP_CHOICE"] = 4] = "ONBOARDING_PHASE_SETUP_CHOICE";
1990
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_WALLET_CREATE_START"] = 5] = "ONBOARDING_PHASE_WALLET_CREATE_START";
1991
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_RECOVERY_PHRASE_VIEW"] = 6] = "ONBOARDING_PHASE_RECOVERY_PHRASE_VIEW";
1992
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_RECOVERY_PHRASE_CONFIRM"] = 7] = "ONBOARDING_PHASE_RECOVERY_PHRASE_CONFIRM";
1993
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_RESTORE_METHOD_CHOICE"] = 8] = "ONBOARDING_PHASE_RESTORE_METHOD_CHOICE";
1994
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_RECOVERY_PHRASE_RESTORE"] = 9] = "ONBOARDING_PHASE_RECOVERY_PHRASE_RESTORE";
1995
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_SEEDCARD_RESTORE"] = 10] = "ONBOARDING_PHASE_SEEDCARD_RESTORE";
1996
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_WALLET_READY"] = 11] = "ONBOARDING_PHASE_WALLET_READY";
1997
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_SEEDCARD_BACKUP_PROMPT"] = 12] = "ONBOARDING_PHASE_SEEDCARD_BACKUP_PROMPT";
1998
+ OnboardingPhase[OnboardingPhase["ONBOARDING_PHASE_SEEDCARD_BACKUP"] = 13] = "ONBOARDING_PHASE_SEEDCARD_BACKUP";
1999
+ })(exports.OnboardingPhase || (exports.OnboardingPhase = {}));
2000
+ exports.OnboardingSetupKind = void 0;
2001
+ (function (OnboardingSetupKind) {
2002
+ OnboardingSetupKind[OnboardingSetupKind["ONBOARDING_SETUP_KIND_UNKNOWN"] = 0] = "ONBOARDING_SETUP_KIND_UNKNOWN";
2003
+ OnboardingSetupKind[OnboardingSetupKind["ONBOARDING_SETUP_KIND_CHOICE"] = 1] = "ONBOARDING_SETUP_KIND_CHOICE";
2004
+ OnboardingSetupKind[OnboardingSetupKind["ONBOARDING_SETUP_KIND_CREATE"] = 2] = "ONBOARDING_SETUP_KIND_CREATE";
2005
+ OnboardingSetupKind[OnboardingSetupKind["ONBOARDING_SETUP_KIND_RESTORE"] = 3] = "ONBOARDING_SETUP_KIND_RESTORE";
2006
+ })(exports.OnboardingSetupKind || (exports.OnboardingSetupKind = {}));
2007
+ exports.OnboardingSetupMethod = void 0;
2008
+ (function (OnboardingSetupMethod) {
2009
+ OnboardingSetupMethod[OnboardingSetupMethod["ONBOARDING_SETUP_METHOD_UNKNOWN"] = 0] = "ONBOARDING_SETUP_METHOD_UNKNOWN";
2010
+ OnboardingSetupMethod[OnboardingSetupMethod["ONBOARDING_SETUP_METHOD_RECOVERY_PHRASE"] = 1] = "ONBOARDING_SETUP_METHOD_RECOVERY_PHRASE";
2011
+ OnboardingSetupMethod[OnboardingSetupMethod["ONBOARDING_SETUP_METHOD_SEEDCARD"] = 2] = "ONBOARDING_SETUP_METHOD_SEEDCARD";
2012
+ })(exports.OnboardingSetupMethod || (exports.OnboardingSetupMethod = {}));
2013
+ exports.ViewTipType = void 0;
2014
+ (function (ViewTipType) {
2015
+ ViewTipType[ViewTipType["Default"] = 0] = "Default";
2016
+ ViewTipType[ViewTipType["Highlight"] = 1] = "Highlight";
2017
+ ViewTipType[ViewTipType["Recommend"] = 2] = "Recommend";
2018
+ ViewTipType[ViewTipType["Warning"] = 3] = "Warning";
2019
+ ViewTipType[ViewTipType["Danger"] = 4] = "Danger";
2020
+ })(exports.ViewTipType || (exports.ViewTipType = {}));
2021
+ exports.ViewSignLayout = void 0;
2022
+ (function (ViewSignLayout) {
2023
+ ViewSignLayout[ViewSignLayout["LayoutDefault"] = 0] = "LayoutDefault";
2024
+ ViewSignLayout[ViewSignLayout["LayoutSafeTxCreate"] = 1] = "LayoutSafeTxCreate";
2025
+ ViewSignLayout[ViewSignLayout["LayoutFinalConfirm"] = 2] = "LayoutFinalConfirm";
2026
+ ViewSignLayout[ViewSignLayout["Layout7702"] = 3] = "Layout7702";
2027
+ ViewSignLayout[ViewSignLayout["LayoutFlat"] = 4] = "LayoutFlat";
2028
+ ViewSignLayout[ViewSignLayout["LayoutEthApprove"] = 5] = "LayoutEthApprove";
2029
+ })(exports.ViewSignLayout || (exports.ViewSignLayout = {}));
2030
+ exports.ProtocolV2FailureType = void 0;
2031
+ (function (ProtocolV2FailureType) {
2032
+ ProtocolV2FailureType[ProtocolV2FailureType["Failure_InvalidMessage"] = 1] = "Failure_InvalidMessage";
2033
+ ProtocolV2FailureType[ProtocolV2FailureType["Failure_UndefinedError"] = 2] = "Failure_UndefinedError";
2034
+ ProtocolV2FailureType[ProtocolV2FailureType["Failure_UsageError"] = 3] = "Failure_UsageError";
2035
+ ProtocolV2FailureType[ProtocolV2FailureType["Failure_DataError"] = 4] = "Failure_DataError";
2036
+ ProtocolV2FailureType[ProtocolV2FailureType["Failure_ProcessError"] = 5] = "Failure_ProcessError";
2037
+ })(exports.ProtocolV2FailureType || (exports.ProtocolV2FailureType = {}));
2038
+ exports.Enum_ProtocolV2Capability = void 0;
2039
+ (function (Enum_ProtocolV2Capability) {
2040
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Bitcoin"] = 1] = "Capability_Bitcoin";
2041
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Bitcoin_like"] = 2] = "Capability_Bitcoin_like";
2042
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Binance"] = 3] = "Capability_Binance";
2043
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Cardano"] = 4] = "Capability_Cardano";
2044
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Crypto"] = 5] = "Capability_Crypto";
2045
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_EOS"] = 6] = "Capability_EOS";
2046
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Ethereum"] = 7] = "Capability_Ethereum";
2047
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Lisk"] = 8] = "Capability_Lisk";
2048
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Monero"] = 9] = "Capability_Monero";
2049
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_NEM"] = 10] = "Capability_NEM";
2050
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Ripple"] = 11] = "Capability_Ripple";
2051
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Stellar"] = 12] = "Capability_Stellar";
2052
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Tezos"] = 13] = "Capability_Tezos";
2053
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_U2F"] = 14] = "Capability_U2F";
2054
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_Shamir"] = 15] = "Capability_Shamir";
2055
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_ShamirGroups"] = 16] = "Capability_ShamirGroups";
2056
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_PassphraseEntry"] = 17] = "Capability_PassphraseEntry";
2057
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_AttachToPin"] = 18] = "Capability_AttachToPin";
2058
+ Enum_ProtocolV2Capability[Enum_ProtocolV2Capability["Capability_EthereumTypedData"] = 1000] = "Capability_EthereumTypedData";
2059
+ })(exports.Enum_ProtocolV2Capability || (exports.Enum_ProtocolV2Capability = {}));
1580
2060
 
1581
2061
  var messages = /*#__PURE__*/Object.freeze({
1582
2062
  __proto__: null,
@@ -1609,6 +2089,9 @@ var messages = /*#__PURE__*/Object.freeze({
1609
2089
  get EthereumGnosisSafeTxOperation () { return exports.EthereumGnosisSafeTxOperation; },
1610
2090
  get EthereumDataTypeOneKey () { return exports.EthereumDataTypeOneKey; },
1611
2091
  get EthereumDataType () { return exports.EthereumDataType; },
2092
+ get Enum_KaspaInputScriptType () { return exports.Enum_KaspaInputScriptType; },
2093
+ get Enum_KaspaOutputScriptType () { return exports.Enum_KaspaOutputScriptType; },
2094
+ get Enum_KaspaRequestType () { return exports.Enum_KaspaRequestType; },
1612
2095
  get Enum_BackupType () { return exports.Enum_BackupType; },
1613
2096
  get Enum_SafetyCheckLevel () { return exports.Enum_SafetyCheckLevel; },
1614
2097
  get OneKeyDeviceType () { return exports.OneKeyDeviceType; },
@@ -1640,18 +2123,113 @@ var messages = /*#__PURE__*/Object.freeze({
1640
2123
  get TronResourceCode () { return exports.TronResourceCode; },
1641
2124
  get TronMessageType () { return exports.TronMessageType; },
1642
2125
  get CommandFlags () { return exports.CommandFlags; },
1643
- get WallpaperTarget () { return exports.WallpaperTarget; },
1644
2126
  get MoneroNetworkType () { return exports.MoneroNetworkType; },
1645
- get ViewTipType () { return exports.ViewTipType; },
2127
+ get UiAnimationType () { return exports.UiAnimationType; },
2128
+ get UiAnimationCommand () { return exports.UiAnimationCommand; },
2129
+ get DeviceErrorCode () { return exports.DeviceErrorCode; },
1646
2130
  get DeviceRebootType () { return exports.DeviceRebootType; },
2131
+ get DeviceSettingsPage () { return exports.DeviceSettingsPage; },
2132
+ get DeviceFactoryAck () { return exports.DeviceFactoryAck; },
1647
2133
  get DeviceFirmwareTargetType () { return exports.DeviceFirmwareTargetType; },
1648
2134
  get DeviceFirmwareUpdateTaskStatus () { return exports.DeviceFirmwareUpdateTaskStatus; },
1649
- get DeviceFactoryAck () { return exports.DeviceFactoryAck; },
1650
2135
  get DeviceType () { return exports.DeviceType; },
1651
2136
  get DeviceSeType () { return exports.DeviceSeType; },
1652
- get DeviceSEState () { return exports.DeviceSEState; }
2137
+ get DeviceSEState () { return exports.DeviceSEState; },
2138
+ get DeviceSessionErrorCode () { return exports.DeviceSessionErrorCode; },
2139
+ get DeviceSessionPinType () { return exports.DeviceSessionPinType; },
2140
+ get DeviceSessionAskPin_FailureSubCodes () { return exports.DeviceSessionAskPin_FailureSubCodes; },
2141
+ get OnboardingStep () { return exports.OnboardingStep; },
2142
+ get OnboardingPhase () { return exports.OnboardingPhase; },
2143
+ get OnboardingSetupKind () { return exports.OnboardingSetupKind; },
2144
+ get OnboardingSetupMethod () { return exports.OnboardingSetupMethod; },
2145
+ get ViewTipType () { return exports.ViewTipType; },
2146
+ get ViewSignLayout () { return exports.ViewSignLayout; },
2147
+ get ProtocolV2FailureType () { return exports.ProtocolV2FailureType; },
2148
+ get Enum_ProtocolV2Capability () { return exports.Enum_ProtocolV2Capability; }
1653
2149
  });
1654
2150
 
2151
+ const REDACTED = '[REDACTED]';
2152
+ const SENSITIVE_LOG_KEYS = new Set([
2153
+ 'accesstoken',
2154
+ 'address',
2155
+ 'apikey',
2156
+ 'connectid',
2157
+ 'devicestate',
2158
+ 'deviceid',
2159
+ 'entropy',
2160
+ 'expectedpassphrasestate',
2161
+ 'mnemonic',
2162
+ 'passphrase',
2163
+ 'passphrasestate',
2164
+ 'password',
2165
+ 'pin',
2166
+ 'privatekey',
2167
+ 'publickey',
2168
+ 'seed',
2169
+ 'serialnumber',
2170
+ 'session',
2171
+ 'sessionid',
2172
+ 'signature',
2173
+ 'token',
2174
+ 'uuid',
2175
+ 'walletsessionid',
2176
+ 'xprv',
2177
+ 'xpub',
2178
+ ]);
2179
+ const normalizeLogKey = (key) => key.replace(/[_-]/g, '').toLowerCase();
2180
+ const isSensitiveLogKey = (key) => {
2181
+ const normalizedKey = normalizeLogKey(key);
2182
+ return (SENSITIVE_LOG_KEYS.has(normalizedKey) ||
2183
+ normalizedKey.endsWith('address') ||
2184
+ normalizedKey.endsWith('privatekey') ||
2185
+ normalizedKey.endsWith('publickey') ||
2186
+ normalizedKey.endsWith('signature'));
2187
+ };
2188
+ const isSigningMessage = (messageName) => Boolean(messageName && /(?:sign|txack|transaction)/i.test(messageName));
2189
+ const redactLogValue = (value, seen) => {
2190
+ if (ArrayBuffer.isView(value)) {
2191
+ return `[BINARY:${value.byteLength}]`;
2192
+ }
2193
+ if (value instanceof ArrayBuffer) {
2194
+ return `[BINARY:${value.byteLength}]`;
2195
+ }
2196
+ if (Array.isArray(value)) {
2197
+ return value.map(item => redactLogValue(item, seen));
2198
+ }
2199
+ if (!value || typeof value !== 'object') {
2200
+ return value;
2201
+ }
2202
+ if (seen.has(value)) {
2203
+ return '[CIRCULAR]';
2204
+ }
2205
+ seen.add(value);
2206
+ const redacted = Object.fromEntries(Object.entries(value).map(([key, item]) => [
2207
+ key,
2208
+ isSensitiveLogKey(key) && item !== null && item !== undefined
2209
+ ? REDACTED
2210
+ : redactLogValue(item, seen),
2211
+ ]));
2212
+ seen.delete(value);
2213
+ return redacted;
2214
+ };
2215
+ function getSafeTransportLogPayload(value, messageName) {
2216
+ if (isSigningMessage(messageName)) {
2217
+ return REDACTED;
2218
+ }
2219
+ return redactLogValue(value, new WeakSet());
2220
+ }
2221
+ function createTransportCallLog(name, protocol, data) {
2222
+ return {
2223
+ name,
2224
+ protocol,
2225
+ request: getSafeTransportLogPayload(data, name),
2226
+ };
2227
+ }
2228
+ const HIGH_VOLUME_CALLS = new Set(['FileWrite', 'FilesystemFileWrite', 'EmmcFileWrite']);
2229
+ function shouldSuppressHighVolumeCallLog(name) {
2230
+ return HIGH_VOLUME_CALLS.has(name);
2231
+ }
2232
+
1655
2233
  protobuf__namespace.util.Long = Long__default["default"];
1656
2234
  protobuf__namespace.configure();
1657
2235
  var index = {
@@ -1662,7 +2240,10 @@ var index = {
1662
2240
  ProtocolV2,
1663
2241
  PROTOCOL_V2_SYS_MESSAGE_THRESHOLD,
1664
2242
  ProtocolV2FrameAssembler,
2243
+ ProtocolV2LinkManager,
2244
+ ProtocolV2SequenceCursor,
1665
2245
  ProtocolV2Session,
2246
+ ProtocolV2UsbTransportBase,
1666
2247
  bytesToHex,
1667
2248
  concatUint8Arrays,
1668
2249
  createMessageFromName,
@@ -1684,25 +2265,37 @@ exports.PROTOCOL_V1_MESSAGE_HEADER_SIZE = PROTOCOL_V1_MESSAGE_HEADER_SIZE;
1684
2265
  exports.PROTOCOL_V1_REPORT_ID = PROTOCOL_V1_REPORT_ID;
1685
2266
  exports.PROTOCOL_V1_USB_PACKET_SIZE = PROTOCOL_V1_USB_PACKET_SIZE;
1686
2267
  exports.PROTOCOL_V2_BLE_FILE_CHUNK_SIZE = PROTOCOL_V2_BLE_FILE_CHUNK_SIZE;
2268
+ exports.PROTOCOL_V2_BLE_FILE_READ_CHUNK_SIZE = PROTOCOL_V2_BLE_FILE_READ_CHUNK_SIZE;
2269
+ exports.PROTOCOL_V2_BLE_FRAME_MAX_BYTES = PROTOCOL_V2_BLE_FRAME_MAX_BYTES;
1687
2270
  exports.PROTOCOL_V2_CHANNEL_BLE_UART = PROTOCOL_V2_CHANNEL_BLE_UART;
1688
2271
  exports.PROTOCOL_V2_CHANNEL_SOCKET = PROTOCOL_V2_CHANNEL_SOCKET;
1689
2272
  exports.PROTOCOL_V2_CHANNEL_USB = PROTOCOL_V2_CHANNEL_USB;
2273
+ exports.PROTOCOL_V2_DEFAULT_RESPONSE_TIMEOUT_MS = PROTOCOL_V2_DEFAULT_RESPONSE_TIMEOUT_MS;
1690
2274
  exports.PROTOCOL_V2_FILE_CHUNK_SIZE = PROTOCOL_V2_FILE_CHUNK_SIZE;
1691
2275
  exports.PROTOCOL_V2_FRAME_MAX_BYTES = PROTOCOL_V2_FRAME_MAX_BYTES;
1692
2276
  exports.PROTOCOL_V2_PACKET_SRC_COMMAND = PROTOCOL_V2_PACKET_SRC_COMMAND;
1693
2277
  exports.PROTOCOL_V2_SYS_MESSAGE_THRESHOLD = PROTOCOL_V2_SYS_MESSAGE_THRESHOLD;
1694
2278
  exports.PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE = PROTOCOL_V2_WEBUSB_FILE_CHUNK_SIZE;
1695
- exports.PROTOCOL_V2_WRITE_WATCHDOG_TIMEOUT_MS = PROTOCOL_V2_WRITE_WATCHDOG_TIMEOUT_MS;
1696
2279
  exports.ProtocolV1 = ProtocolV1;
1697
2280
  exports.ProtocolV2 = ProtocolV2;
1698
2281
  exports.ProtocolV2FrameAssembler = ProtocolV2FrameAssembler;
2282
+ exports.ProtocolV2LinkError = ProtocolV2LinkError;
2283
+ exports.ProtocolV2LinkManager = ProtocolV2LinkManager;
2284
+ exports.ProtocolV2SequenceCursor = ProtocolV2SequenceCursor;
1699
2285
  exports.ProtocolV2Session = ProtocolV2Session;
2286
+ exports.ProtocolV2UsbTransportBase = ProtocolV2UsbTransportBase;
2287
+ exports.TRANSPORT_EVENT = TRANSPORT_EVENT;
1700
2288
  exports.bytesToHex = bytesToHex;
1701
2289
  exports.concatUint8Arrays = concatUint8Arrays;
2290
+ exports.createTransportCallLog = createTransportCallLog;
1702
2291
  exports["default"] = index;
1703
2292
  exports.getErrorMessage = getErrorMessage;
2293
+ exports.getSafeTransportLogPayload = getSafeTransportLogPayload;
1704
2294
  exports.hexToBytes = hexToBytes;
2295
+ exports.isProtocolV2LinkError = isProtocolV2LinkError;
1705
2296
  exports.probeProtocolV2 = probeProtocolV2;
1706
2297
  exports.protocolV1 = index$1;
1707
2298
  exports.protocolV2 = protocolV2Codec;
2299
+ exports.shouldSuppressHighVolumeCallLog = shouldSuppressHighVolumeCallLog;
1708
2300
  exports.withProtocolTimeout = withProtocolTimeout;
2301
+ exports.writeProtocolV2BleFrame = writeProtocolV2BleFrame;