@onekeyfe/hd-transport 1.2.0-alpha.7 → 1.2.0-alpha.71

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