@homebridge-eufy-security/eufy-security-client 3.8.0-dev.7 → 3.8.0-dev.8

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.
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Normalize a buffer of ADTS audio data by scanning for ADTS frames and splitting
3
+ * any multi-RDB frames into individual single-RDB frames.
4
+ *
5
+ * The input buffer may contain one or more concatenated ADTS frames. Non-ADTS
6
+ * data (or data without a valid sync word) is returned unchanged in a
7
+ * single-element array.
8
+ *
9
+ * For the common case of a single-RDB frame, no allocation occurs — the original
10
+ * buffer region is returned via subarray.
11
+ */
12
+ export declare function normalizeAdtsFrames(data: Buffer): Buffer[];
@@ -0,0 +1,185 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normalizeAdtsFrames = normalizeAdtsFrames;
4
+ const logging_1 = require("../logging");
5
+ // ADTS header: 7 bytes (protection_absent=1) or 9 bytes (protection_absent=0).
6
+ // Byte 6 bits 0-1: number_of_raw_data_blocks_in_frame (0 = 1 RDB, 3 = 4 RDBs).
7
+ // Multi-RDB frames pack several AAC raw data blocks into one ADTS frame.
8
+ // Most decoders (including FFmpeg's native aac) only support single-RDB frames,
9
+ // so we split multi-RDB frames into individual single-RDB ADTS frames.
10
+ const ADTS_SYNC_WORD = 0xfff;
11
+ const ADTS_MIN_HEADER_SIZE = 7;
12
+ /**
13
+ * Returns true when the first two bytes contain an ADTS sync word (0xFFF).
14
+ */
15
+ function hasAdtsSyncWord(buf, offset) {
16
+ if (offset + 1 >= buf.length)
17
+ return false;
18
+ return ((buf[offset] << 4) | (buf[offset + 1] >> 4)) === ADTS_SYNC_WORD;
19
+ }
20
+ /**
21
+ * Extract the 13-bit frame_length field from an ADTS header starting at `offset`.
22
+ * frame_length includes the header itself.
23
+ */
24
+ function getFrameLength(buf, offset) {
25
+ return ((buf[offset + 3] & 0x03) << 11) | (buf[offset + 4] << 3) | ((buf[offset + 5] >> 5) & 0x07);
26
+ }
27
+ /**
28
+ * Extract the 2-bit number_of_raw_data_blocks_in_frame field (0-indexed, so actual
29
+ * count is value + 1).
30
+ */
31
+ function getNumRawDataBlocks(buf, offset) {
32
+ return buf[offset + 6] & 0x03;
33
+ }
34
+ /**
35
+ * Returns true when `protection_absent` is 0 (CRC present).
36
+ */
37
+ function hasCrc(buf, offset) {
38
+ return (buf[offset + 1] & 0x01) === 0;
39
+ }
40
+ /**
41
+ * Build a single-RDB ADTS frame by prepending a rewritten 7-byte header (without
42
+ * CRC) to a raw data block. The template header is cloned from the original
43
+ * multi-RDB frame and patched:
44
+ * - frame_length → 7 + rdbData.length
45
+ * - num_rdb → 0 (meaning 1 block)
46
+ * - protection_absent → 1 (no CRC, since we don't recompute it)
47
+ */
48
+ function buildSingleRdbFrame(templateHeader, headerOffset, rdbData) {
49
+ const newLen = ADTS_MIN_HEADER_SIZE + rdbData.length;
50
+ const out = Buffer.allocUnsafe(newLen);
51
+ // Copy the 7-byte header template.
52
+ templateHeader.copy(out, 0, headerOffset, headerOffset + ADTS_MIN_HEADER_SIZE);
53
+ // Set protection_absent = 1 (bit 0 of byte 1).
54
+ out[1] |= 0x01;
55
+ // Rewrite frame_length (13 bits spanning bytes 3-5).
56
+ out[3] = (out[3] & 0xfc) | ((newLen >> 11) & 0x03);
57
+ out[4] = (newLen >> 3) & 0xff;
58
+ out[5] = ((newLen & 0x07) << 5) | (out[5] & 0x1f);
59
+ // Set number_of_raw_data_blocks_in_frame = 0 (bits 0-1 of byte 6).
60
+ out[6] &= 0xfc;
61
+ // Append the raw data block.
62
+ rdbData.copy(out, ADTS_MIN_HEADER_SIZE);
63
+ return out;
64
+ }
65
+ /**
66
+ * Split a single multi-RDB ADTS frame into individual single-RDB frames.
67
+ *
68
+ * For multi-RDB frames the spec (ISO 14496-3 §1.A.3) places a
69
+ * `raw_data_block_position` table after the header (and CRC when present) that
70
+ * gives the byte offset of each RDB relative to the start of the first RDB.
71
+ *
72
+ * Layout:
73
+ * [7-byte header]
74
+ * [2-byte CRC] ← only if protection_absent=0
75
+ * [2-byte position] × (N) ← N = number_of_raw_data_blocks_in_frame (i.e. num_rdb)
76
+ * [RDB 0 data ...]
77
+ * [RDB 1 data ...]
78
+ * ...
79
+ *
80
+ * The position entries give byte offsets relative to the start of RDB 0.
81
+ * RDB 0 implicitly starts at offset 0. Position[i] gives the start of RDB i+1.
82
+ */
83
+ function splitMultiRdbFrame(buf, offset, frameLength) {
84
+ const numRdbMinusOne = getNumRawDataBlocks(buf, offset); // 1-3
85
+ const numRdb = numRdbMinusOne + 1;
86
+ const crcPresent = hasCrc(buf, offset);
87
+ // Calculate where the position table starts.
88
+ let posTableStart = offset + ADTS_MIN_HEADER_SIZE;
89
+ if (crcPresent) {
90
+ posTableStart += 2; // skip CRC-16
91
+ }
92
+ // We need (numRdb - 1) position entries, each 2 bytes.
93
+ const posTableSize = (numRdb - 1) * 2;
94
+ const rdbDataStart = posTableStart + posTableSize;
95
+ if (rdbDataStart > offset + frameLength) {
96
+ logging_1.rootP2PLogger.warn("ADTS multi-RDB frame too short for position table", {
97
+ frameLength,
98
+ numRdb,
99
+ rdbDataStart: rdbDataStart - offset,
100
+ });
101
+ return [buf.subarray(offset, offset + frameLength)];
102
+ }
103
+ // Read position table: offsets relative to the start of RDB 0.
104
+ const rdbOffsets = [0]; // RDB 0 always starts at relative offset 0
105
+ for (let i = 0; i < numRdb - 1; i++) {
106
+ rdbOffsets.push(buf.readUInt16BE(posTableStart + i * 2));
107
+ }
108
+ const rdbSectionEnd = offset + frameLength;
109
+ const result = [];
110
+ for (let i = 0; i < numRdb; i++) {
111
+ const start = rdbDataStart + rdbOffsets[i];
112
+ const end = i < numRdb - 1 ? rdbDataStart + rdbOffsets[i + 1] : rdbSectionEnd;
113
+ if (start >= end || end > rdbSectionEnd) {
114
+ logging_1.rootP2PLogger.warn("ADTS multi-RDB frame has invalid RDB boundaries", {
115
+ rdbIndex: i,
116
+ start: start - offset,
117
+ end: end - offset,
118
+ frameLength,
119
+ });
120
+ // Return remaining data as a single frame rather than losing it.
121
+ if (start < rdbSectionEnd) {
122
+ result.push(buildSingleRdbFrame(buf, offset, buf.subarray(start, rdbSectionEnd)));
123
+ }
124
+ break;
125
+ }
126
+ result.push(buildSingleRdbFrame(buf, offset, buf.subarray(start, end)));
127
+ }
128
+ return result;
129
+ }
130
+ /**
131
+ * Normalize a buffer of ADTS audio data by scanning for ADTS frames and splitting
132
+ * any multi-RDB frames into individual single-RDB frames.
133
+ *
134
+ * The input buffer may contain one or more concatenated ADTS frames. Non-ADTS
135
+ * data (or data without a valid sync word) is returned unchanged in a
136
+ * single-element array.
137
+ *
138
+ * For the common case of a single-RDB frame, no allocation occurs — the original
139
+ * buffer region is returned via subarray.
140
+ */
141
+ function normalizeAdtsFrames(data) {
142
+ if (data.length < ADTS_MIN_HEADER_SIZE || !hasAdtsSyncWord(data, 0)) {
143
+ // Not ADTS data — return as-is.
144
+ return [data];
145
+ }
146
+ const result = [];
147
+ let pos = 0;
148
+ while (pos + ADTS_MIN_HEADER_SIZE <= data.length) {
149
+ if (!hasAdtsSyncWord(data, pos)) {
150
+ // Lost sync — push remaining bytes and stop.
151
+ logging_1.rootP2PLogger.debug("ADTS sync lost, pushing remaining bytes as-is", {
152
+ offset: pos,
153
+ remaining: data.length - pos,
154
+ });
155
+ result.push(data.subarray(pos));
156
+ break;
157
+ }
158
+ const frameLength = getFrameLength(data, pos);
159
+ if (frameLength < ADTS_MIN_HEADER_SIZE || pos + frameLength > data.length) {
160
+ // Incomplete or invalid frame — push remaining bytes.
161
+ logging_1.rootP2PLogger.debug("ADTS frame length invalid or truncated", {
162
+ offset: pos,
163
+ frameLength,
164
+ available: data.length - pos,
165
+ });
166
+ result.push(data.subarray(pos));
167
+ break;
168
+ }
169
+ const numRdbMinusOne = getNumRawDataBlocks(data, pos);
170
+ if (numRdbMinusOne === 0) {
171
+ // Single RDB — zero-copy, return subarray of original buffer.
172
+ result.push(data.subarray(pos, pos + frameLength));
173
+ }
174
+ else {
175
+ // Multi-RDB — split into individual frames.
176
+ const splitFrames = splitMultiRdbFrame(data, pos, frameLength);
177
+ for (const frame of splitFrames) {
178
+ result.push(frame);
179
+ }
180
+ }
181
+ pos += frameLength;
182
+ }
183
+ return result.length > 0 ? result : [data];
184
+ }
185
+ //# sourceMappingURL=adts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adts.js","sourceRoot":"","sources":["../../src/p2p/adts.ts"],"names":[],"mappings":";;AAgKA,kDAkDC;AAlND,wCAA2C;AAE3C,+EAA+E;AAC/E,+EAA+E;AAC/E,yEAAyE;AACzE,gFAAgF;AAChF,uEAAuE;AAEvE,MAAM,cAAc,GAAG,KAAK,CAAC;AAC7B,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAE/B;;GAEG;AACH,SAAS,eAAe,CAAC,GAAW,EAAE,MAAc;IAClD,IAAI,MAAM,GAAG,CAAC,IAAI,GAAG,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC;IAC3C,OAAO,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,cAAc,CAAC;AAC1E,CAAC;AAED;;;GAGG;AACH,SAAS,cAAc,CAAC,GAAW,EAAE,MAAc;IACjD,OAAO,CAAC,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;AACrG,CAAC;AAED;;;GAGG;AACH,SAAS,mBAAmB,CAAC,GAAW,EAAE,MAAc;IACtD,OAAO,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,GA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IAAI,WAAW,CAAC;IACrB,CAAC;IAED,OAAO,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;AAC7C,CAAC"}
@@ -149,6 +149,15 @@ export interface StreamMetadata {
149
149
  videoHeight: number;
150
150
  audioCodec: AudioCodec;
151
151
  }
152
+ /** Configurable timeout values for P2P streaming. All values in milliseconds. */
153
+ export interface StreamTimeoutOptions {
154
+ /** Max time to wait for stream data before auto-stopping. Default: 5000ms. */
155
+ streamDataWait?: number;
156
+ /** Time to wait for first audio frame before declaring no audio. Default: 650ms. */
157
+ audioCodecAnalyze?: number;
158
+ /** Max time to wait for an expected sequence number. Default: 20000ms. */
159
+ expectedSeqNoWait?: number;
160
+ }
152
161
  export interface DeviceSerial {
153
162
  [index: number]: {
154
163
  sn: string;
@@ -2,7 +2,7 @@ import { TypedEmitter } from "tiny-typed-emitter";
2
2
  import * as NodeRSA from "node-rsa";
3
3
  import { Address, CustomData } from "./models";
4
4
  import { CommandType, P2PDataType, P2PConnectionType } from "./types";
5
- import { P2PClientProtocolEvents, P2PCommand } from "./interfaces";
5
+ import { P2PClientProtocolEvents, P2PCommand, StreamTimeoutOptions } from "./interfaces";
6
6
  import { StationListResponse } from "../http/models";
7
7
  import { HTTPApi } from "../http/api";
8
8
  export declare class P2PClientProtocol extends TypedEmitter<P2PClientProtocolEvents> {
@@ -24,6 +24,7 @@ export declare class P2PClientProtocol extends TypedEmitter<P2PClientProtocolEve
24
24
  private readonly ESD_DISCONNECT_TIMEOUT;
25
25
  private readonly MAX_STREAM_DATA_WAIT;
26
26
  private readonly RESEND_NOT_ACKNOWLEDGED_COMMAND;
27
+ private streamTimeouts;
27
28
  private readonly UDP_RECVBUFFERSIZE_BYTES;
28
29
  private readonly MAX_PAYLOAD_BYTES;
29
30
  private readonly MAX_PACKET_BYTES;
@@ -162,6 +163,7 @@ export declare class P2PClientProtocol extends TypedEmitter<P2PClientProtocolEve
162
163
  private emitStreamStopEvent;
163
164
  isStreaming(channel: number, datatype: P2PDataType): boolean;
164
165
  isLiveStreaming(channel: number): boolean;
166
+ setStreamTimeouts(options: StreamTimeoutOptions): void;
165
167
  private isCurrentlyStreaming;
166
168
  isRTSPLiveStreaming(channel: number): boolean;
167
169
  isDownloading(channel: number): boolean;
@@ -18,6 +18,7 @@ const ble_1 = require("./ble");
18
18
  const http_1 = require("../http");
19
19
  const utils_3 = require("../utils");
20
20
  const logging_1 = require("../logging");
21
+ const adts_1 = require("./adts");
21
22
  class P2PClientProtocol extends tiny_typed_emitter_1.TypedEmitter {
22
23
  MAX_RETRIES = 10;
23
24
  MAX_COMMAND_RESULT_WAIT = 30 * 1000;
@@ -37,6 +38,11 @@ class P2PClientProtocol extends tiny_typed_emitter_1.TypedEmitter {
37
38
  ESD_DISCONNECT_TIMEOUT = 30 * 1000;
38
39
  MAX_STREAM_DATA_WAIT = 5 * 1000;
39
40
  RESEND_NOT_ACKNOWLEDGED_COMMAND = 100;
41
+ streamTimeouts = {
42
+ streamDataWait: this.MAX_STREAM_DATA_WAIT,
43
+ audioCodecAnalyze: this.AUDIO_CODEC_ANALYZE_TIMEOUT,
44
+ expectedSeqNoWait: this.MAX_EXPECTED_SEQNO_WAIT,
45
+ };
40
46
  UDP_RECVBUFFERSIZE_BYTES = 1048576;
41
47
  MAX_PAYLOAD_BYTES = 1028;
42
48
  MAX_PACKET_BYTES = 1024;
@@ -1240,7 +1246,7 @@ class P2PClientProtocol extends tiny_typed_emitter_1.TypedEmitter {
1240
1246
  this.currentMessageState[dataType].waitForSeqNoTimeout = setTimeout(() => {
1241
1247
  this.endStream(dataType, true);
1242
1248
  this.currentMessageState[dataType].waitForSeqNoTimeout = undefined;
1243
- }, this.MAX_EXPECTED_SEQNO_WAIT);
1249
+ }, this.streamTimeouts.expectedSeqNoWait);
1244
1250
  if (!this.currentMessageState[dataType].queuedData.get(message.seqNo)) {
1245
1251
  this.currentMessageState[dataType].queuedData.set(message.seqNo, message);
1246
1252
  logging_1.rootP2PLogger.trace(`Received message - DATA ${types_1.P2PDataType[message.type]} - Received not expected sequence, added to the queue for future processing`, {
@@ -1514,24 +1520,36 @@ class P2PClientProtocol extends tiny_typed_emitter_1.TypedEmitter {
1514
1520
  let return_code = 0;
1515
1521
  let resultData;
1516
1522
  if (message.bytesToRead > 0) {
1517
- if (message.signCode > 0) {
1518
- try {
1519
- message.data = (0, utils_1.decryptP2PData)(message.data, this.p2pKey);
1523
+ if (message.signCode > 0 && message.data.length > 0) {
1524
+ if (message.data.length % 16 === 0) {
1525
+ try {
1526
+ message.data = (0, utils_1.decryptP2PData)(message.data, this.p2pKey);
1527
+ }
1528
+ catch (err) {
1529
+ const error = (0, error_1.ensureError)(err);
1530
+ logging_1.rootP2PLogger.debug(`Handle DATA ${types_1.P2PDataType[message.dataType]} - Decrypt Error`, {
1531
+ error: (0, utils_3.getError)(error),
1532
+ stationSN: this.rawStation.station_sn,
1533
+ message: {
1534
+ seqNo: message.seqNo,
1535
+ channel: message.channel,
1536
+ commandType: types_1.CommandType[message.commandId],
1537
+ signCode: message.signCode,
1538
+ type: message.type,
1539
+ dataType: types_1.P2PDataType[message.dataType],
1540
+ data: message.data.toString("hex"),
1541
+ },
1542
+ });
1543
+ }
1520
1544
  }
1521
- catch (err) {
1522
- const error = (0, error_1.ensureError)(err);
1523
- logging_1.rootP2PLogger.debug(`Handle DATA ${types_1.P2PDataType[message.dataType]} - Decrypt Error`, {
1524
- error: (0, utils_3.getError)(error),
1545
+ else {
1546
+ logging_1.rootP2PLogger.debug(`Handle DATA ${types_1.P2PDataType[message.dataType]} - Skipping decryption, data not block-aligned`, {
1525
1547
  stationSN: this.rawStation.station_sn,
1526
- message: {
1527
- seqNo: message.seqNo,
1528
- channel: message.channel,
1529
- commandType: types_1.CommandType[message.commandId],
1530
- signCode: message.signCode,
1531
- type: message.type,
1532
- dataType: types_1.P2PDataType[message.dataType],
1533
- data: message.data.toString("hex"),
1534
- },
1548
+ seqNo: message.seqNo,
1549
+ commandType: types_1.CommandType[message.commandId],
1550
+ signCode: message.signCode,
1551
+ dataLength: message.data.length,
1552
+ mod16: message.data.length % 16,
1535
1553
  });
1536
1554
  }
1537
1555
  }
@@ -1801,9 +1819,9 @@ class P2PClientProtocol extends tiny_typed_emitter_1.TypedEmitter {
1801
1819
  clearTimeout(this.currentMessageState[dataType].p2pStreamingTimeout);
1802
1820
  }
1803
1821
  this.currentMessageState[dataType].p2pStreamingTimeout = setTimeout(() => {
1804
- logging_1.rootP2PLogger.info(`Stopping the station stream for the device ${this.deviceSNs[this.currentMessageState[dataType].p2pStreamChannel]?.sn}, because we haven't received any data for ${this.MAX_STREAM_DATA_WAIT / 1000} seconds`);
1822
+ logging_1.rootP2PLogger.info(`Stopping the station stream for the device ${this.deviceSNs[this.currentMessageState[dataType].p2pStreamChannel]?.sn}, because we haven't received any data for ${this.streamTimeouts.streamDataWait / 1000} seconds`);
1805
1823
  this.endStream(dataType, sendStopCommand);
1806
- }, this.MAX_STREAM_DATA_WAIT);
1824
+ }, this.streamTimeouts.streamDataWait);
1807
1825
  }
1808
1826
  handleDataBinaryAndVideo(message) {
1809
1827
  if (!this.currentMessageState[message.dataType].invalidStream) {
@@ -1972,7 +1990,7 @@ class P2PClientProtocol extends tiny_typed_emitter_1.TypedEmitter {
1972
1990
  this.currentMessageState[message.dataType].p2pStreamNotStarted) {
1973
1991
  this.emitStreamStartEvent(message.dataType);
1974
1992
  }
1975
- }, this.AUDIO_CODEC_ANALYZE_TIMEOUT);
1993
+ }, this.streamTimeouts.audioCodecAnalyze);
1976
1994
  }
1977
1995
  }
1978
1996
  if (this.currentMessageState[message.dataType].p2pStreamNotStarted) {
@@ -2059,7 +2077,18 @@ class P2PClientProtocol extends tiny_typed_emitter_1.TypedEmitter {
2059
2077
  this.emitStreamStartEvent(message.dataType);
2060
2078
  }
2061
2079
  }
2062
- this.currentMessageState[message.dataType].audioStream?.push(audio_data);
2080
+ {
2081
+ const codec = this.currentMessageState[message.dataType].p2pStreamMetadata.audioCodec;
2082
+ const stream = this.currentMessageState[message.dataType].audioStream;
2083
+ if (stream && (codec === types_1.AudioCodec.AAC || codec === types_1.AudioCodec.AAC_LC)) {
2084
+ for (const frame of (0, adts_1.normalizeAdtsFrames)(audio_data)) {
2085
+ stream.push(frame);
2086
+ }
2087
+ }
2088
+ else {
2089
+ stream?.push(audio_data);
2090
+ }
2091
+ }
2063
2092
  break;
2064
2093
  default:
2065
2094
  logging_1.rootP2PLogger.debug(`Handle DATA ${types_1.P2PDataType[message.dataType]} - Not implemented message`, {
@@ -2433,7 +2462,7 @@ class P2PClientProtocol extends tiny_typed_emitter_1.TypedEmitter {
2433
2462
  device_1.Device.isLockWifiT8502(this.rawStation.devices[0]?.device_type) ||
2434
2463
  device_1.Device.isLockWifiT8510P(this.rawStation.devices[0]?.device_type, this.rawStation.devices[0]?.device_sn) ||
2435
2464
  device_1.Device.isLockWifiT8520P(this.rawStation.devices[0]?.device_type, this.rawStation.devices[0]?.device_sn) ||
2436
- device_1.Device.isLockWifiT85V0(this.rawStation.devices[0]?.device_type, this.rawStation.devices[0]?.device_sn) ||
2465
+ device_1.Device.isLockWifiT85V0(this.rawStation.devices[0]?.device_type) ||
2437
2466
  device_1.Device.isLockWifiT8531(this.rawStation.devices[0]?.device_type) ||
2438
2467
  device_1.Device.isLockWifiT85L0(this.rawStation.devices[0]?.device_type)) {
2439
2468
  this.emit("sequence error", message.channel, types_1.SmartLockCommand[payload.bus_type == types_1.SmartLockFunctionType.TYPE_2
@@ -3230,7 +3259,10 @@ class P2PClientProtocol extends tiny_typed_emitter_1.TypedEmitter {
3230
3259
  data: data.toString("hex"),
3231
3260
  cipherID: cipherID,
3232
3261
  });
3233
- const encryptedKey = (0, utils_1.readNullTerminatedBuffer)(data.subarray(4));
3262
+ // Keep full raw buffer for ECDH — readNullTerminatedBuffer truncates binary ECIES envelopes at 0x00 bytes
3263
+ const rawEncryptedKey = data.subarray(4);
3264
+ const encryptedKey = (0, utils_1.readNullTerminatedBuffer)(rawEncryptedKey);
3265
+ const isECDHDevice = this.rawStation.station_sn.startsWith("T8214") || this.rawStation.station_sn.startsWith("T8425");
3234
3266
  this.api
3235
3267
  .getCipher(/*this.rawStation.station_sn, */ cipherID, this.rawStation.member.admin_user_id)
3236
3268
  .then((cipher) => {
@@ -3242,10 +3274,49 @@ class P2PClientProtocol extends tiny_typed_emitter_1.TypedEmitter {
3242
3274
  cipher: JSON.stringify(cipher),
3243
3275
  });
3244
3276
  if (cipher !== undefined) {
3245
- this.encryption = types_1.EncryptionType.LEVEL_2;
3246
- const rsa = (0, utils_1.getRSAPrivateKey)(cipher.private_key, this.enableEmbeddedPKCS1Support);
3247
- this.p2pKey = rsa.decrypt(encryptedKey);
3248
- logging_1.rootP2PLogger.debug(`Handle DATA ${types_1.P2PDataType[message.dataType]} - CMD_GATEWAYINFO - set encryption level 2`, { stationSN: this.rawStation.station_sn, key: this.p2pKey.toString("hex") });
3277
+ // Try RSA first
3278
+ try {
3279
+ this.encryption = types_1.EncryptionType.LEVEL_2;
3280
+ const rsa = (0, utils_1.getRSAPrivateKey)(cipher.private_key, this.enableEmbeddedPKCS1Support);
3281
+ this.p2pKey = rsa.decrypt(encryptedKey);
3282
+ logging_1.rootP2PLogger.debug(`Handle DATA ${types_1.P2PDataType[message.dataType]} - CMD_GATEWAYINFO - RSA success - set encryption level 2`, { stationSN: this.rawStation.station_sn, key: this.p2pKey.toString("hex") });
3283
+ }
3284
+ catch (rsaErr) {
3285
+ const rsaError = (0, error_1.ensureError)(rsaErr);
3286
+ logging_1.rootP2PLogger.debug(`Handle DATA ${types_1.P2PDataType[message.dataType]} - CMD_GATEWAYINFO - RSA decrypt failed`, {
3287
+ error: (0, utils_3.getError)(rsaError),
3288
+ stationSN: this.rawStation.station_sn,
3289
+ isECDHDevice: isECDHDevice,
3290
+ hasEccKey: !!cipher.ecc_private_key,
3291
+ });
3292
+ // Try ECDH only for known ECDH devices (T8214/T8425)
3293
+ if (isECDHDevice && cipher.ecc_private_key) {
3294
+ try {
3295
+ this.encryption = types_1.EncryptionType.LEVEL_2;
3296
+ this.p2pKey = (0, utils_1.decryptP2PKeyECDH)(rawEncryptedKey, cipher.ecc_private_key);
3297
+ logging_1.rootP2PLogger.debug(`Handle DATA ${types_1.P2PDataType[message.dataType]} - CMD_GATEWAYINFO - ECDH success - set encryption level 2`, {
3298
+ stationSN: this.rawStation.station_sn,
3299
+ key: this.p2pKey.toString("hex"),
3300
+ keyLength: this.p2pKey.length,
3301
+ });
3302
+ }
3303
+ catch (ecdhErr) {
3304
+ const ecdhError = (0, error_1.ensureError)(ecdhErr);
3305
+ logging_1.rootP2PLogger.debug(`Handle DATA ${types_1.P2PDataType[message.dataType]} - CMD_GATEWAYINFO - ECDH also failed, falling back to Level 1`, {
3306
+ error: (0, utils_3.getError)(ecdhError),
3307
+ stationSN: this.rawStation.station_sn,
3308
+ });
3309
+ this.encryption = types_1.EncryptionType.LEVEL_1;
3310
+ this.p2pKey = Buffer.from((0, utils_1.getP2PCommandEncryptionKey)(this.rawStation.station_sn, this.rawStation.p2p_did));
3311
+ }
3312
+ }
3313
+ else {
3314
+ // Non-ECDH device or no ECC key — fall back to Level 1
3315
+ this.encryption = types_1.EncryptionType.LEVEL_1;
3316
+ this.p2pKey = Buffer.from((0, utils_1.getP2PCommandEncryptionKey)(this.rawStation.station_sn, this.rawStation.p2p_did));
3317
+ logging_1.rootP2PLogger.debug(`Handle DATA ${types_1.P2PDataType[message.dataType]} - CMD_GATEWAYINFO - RSA failed, set encryption level 1`, { stationSN: this.rawStation.station_sn, key: this.p2pKey.toString("hex") });
3318
+ }
3319
+ }
3249
3320
  }
3250
3321
  else {
3251
3322
  this.encryption = types_1.EncryptionType.LEVEL_1;
@@ -3537,6 +3608,9 @@ class P2PClientProtocol extends tiny_typed_emitter_1.TypedEmitter {
3537
3608
  isLiveStreaming(channel) {
3538
3609
  return this.isStreaming(channel, types_1.P2PDataType.VIDEO);
3539
3610
  }
3611
+ setStreamTimeouts(options) {
3612
+ this.streamTimeouts = { ...this.streamTimeouts, ...options };
3613
+ }
3540
3614
  isCurrentlyStreaming() {
3541
3615
  for (const element of Object.values(this.currentMessageState)) {
3542
3616
  if (element.p2pStreaming || element.p2pTalkback)