@hiroosy/baileys-lite 0.0.4 → 0.3.1

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 (116) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +658 -10
  3. package/WAProto/index.js +2 -2558
  4. package/engine-requirements.js +3 -4
  5. package/package.json +8 -3
  6. package/src/binary/wa-binary.js +3 -25
  7. package/src/constants.js +7 -15
  8. package/src/defaults.js +2 -5
  9. package/src/foundation/ai-rich.js +530 -0
  10. package/src/foundation/audio-duration.js +43 -103
  11. package/src/foundation/audio-samples.js +19 -37
  12. package/src/foundation/boom.js +0 -7
  13. package/src/foundation/cache.js +4 -26
  14. package/src/foundation/concurrency.js +1 -19
  15. package/src/foundation/curve25519.js +7 -39
  16. package/src/foundation/link-preview.js +15 -57
  17. package/src/foundation/logger.js +0 -11
  18. package/src/foundation/long.js +4 -14
  19. package/src/foundation/protobuf-minimal.js +21 -53
  20. package/src/foundation/qrcode-terminal.js +273 -0
  21. package/src/foundation/sql-database.js +716 -0
  22. package/src/foundation/wa-crypto.js +2 -31
  23. package/src/foundation/zip.js +25 -41
  24. package/src/index.js +8 -18
  25. package/src/signal/libsignal.js +23 -78
  26. package/src/signal/signal-group.js +0 -35
  27. package/src/signal/signal-repository.js +10 -29
  28. package/src/socket/business-communities.js +12 -31
  29. package/src/socket/chats.js +5 -8
  30. package/src/socket/groups-newsletter.js +18 -17
  31. package/src/socket/messages-recv.js +81 -127
  32. package/src/socket/messages-send.js +372 -139
  33. package/src/socket/socket-core.js +227 -157
  34. package/src/socket/usync.js +2 -6
  35. package/src/socket-client/native-websocket.js +344 -0
  36. package/src/socket-client/websocket-client.js +84 -38
  37. package/src/utils/auth-state-core.js +14 -56
  38. package/src/utils/auth-state-storage.js +7 -42
  39. package/src/utils/chat-sync.js +4 -26
  40. package/src/utils/media.js +15 -71
  41. package/src/utils/message-compose.js +208 -85
  42. package/src/utils/message-processing.js +10 -65
  43. package/src/utils/username.js +19 -0
  44. package/src/utils/wa-protocol-core.js +71 -127
  45. package/src/vendor/jpeg-js/decoder.js +75 -136
  46. package/src/vendor/jpeg-js/encoder.js +179 -264
  47. package/src/vendor/pngjs/bitmapper.js +5 -27
  48. package/src/vendor/pngjs/bitpacker.js +4 -12
  49. package/src/vendor/pngjs/constants.js +3 -11
  50. package/src/vendor/pngjs/crc.js +0 -6
  51. package/src/vendor/pngjs/filter-pack.js +1 -7
  52. package/src/vendor/pngjs/filter-parse-sync.js +0 -6
  53. package/src/vendor/pngjs/filter-parse.js +1 -11
  54. package/src/vendor/pngjs/format-normaliser.js +5 -11
  55. package/src/vendor/pngjs/interlace.js +7 -24
  56. package/src/vendor/pngjs/packer-sync.js +0 -11
  57. package/src/vendor/pngjs/packer.js +7 -15
  58. package/src/vendor/pngjs/paeth-predictor.js +0 -6
  59. package/src/vendor/pngjs/parser-sync.js +0 -8
  60. package/src/vendor/pngjs/parser.js +5 -29
  61. package/src/vendor/pngjs/png-sync.js +0 -7
  62. package/src/vendor/pngjs/sync-inflate.js +7 -16
  63. package/src/vendor/pngjs/sync-reader.js +4 -11
  64. package/src/voip/WaVoipCoordinator.js +158 -0
  65. package/src/voip/app-data/WaAppDataStream.js +193 -0
  66. package/src/voip/app-data/protocol.js +172 -0
  67. package/src/voip/bytes.js +63 -0
  68. package/src/voip/call/WaCallManager.js +442 -0
  69. package/src/voip/call/WaCallMediaSession.js +1705 -0
  70. package/src/voip/call/call-state.js +203 -0
  71. package/src/voip/crypto/encryption.js +13 -0
  72. package/src/voip/crypto/primitives.js +21 -0
  73. package/src/voip/crypto/rtcp.js +66 -0
  74. package/src/voip/crypto/srtp.js +180 -0
  75. package/src/voip/crypto/ssrc.js +15 -0
  76. package/src/voip/index.js +628 -0
  77. package/src/voip/media/WaAudioEngine.js +486 -0
  78. package/src/voip/media/WaVideoEngine.js +275 -0
  79. package/src/voip/media/audio-codec.js +0 -0
  80. package/src/voip/media/audio-reorder.js +107 -0
  81. package/src/voip/media/h264.js +246 -0
  82. package/src/voip/media/mlow-codec.js +465 -0
  83. package/src/voip/media/rtcp.js +68 -0
  84. package/src/voip/media/rtp.js +242 -0
  85. package/src/voip/protobuf.js +30 -0
  86. package/src/voip/relay/WaManualRelay.js +609 -0
  87. package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
  88. package/src/voip/relay/dtls/aead.js +46 -0
  89. package/src/voip/relay/dtls/cert-builder.js +102 -0
  90. package/src/voip/relay/dtls/der.js +98 -0
  91. package/src/voip/relay/dtls/ecdhe.js +37 -0
  92. package/src/voip/relay/dtls/handshake-framing.js +100 -0
  93. package/src/voip/relay/dtls/handshake-messages.js +158 -0
  94. package/src/voip/relay/dtls/handshake.js +582 -0
  95. package/src/voip/relay/dtls/prf.js +39 -0
  96. package/src/voip/relay/dtls/record.js +56 -0
  97. package/src/voip/relay/relay-ack.js +141 -0
  98. package/src/voip/relay/sctp/association.js +434 -0
  99. package/src/voip/relay/sctp/crc32c.js +21 -0
  100. package/src/voip/relay/sctp/wire.js +226 -0
  101. package/src/voip/relay/stun.js +463 -0
  102. package/src/voip/shim/baileys-resolve.js +7 -0
  103. package/src/voip/shim/core.js +66 -0
  104. package/src/voip/shim/crypto.js +6 -0
  105. package/src/voip/shim/proto.js +10 -0
  106. package/src/voip/shim/protocol.js +130 -0
  107. package/src/voip/shim/transport.js +82 -0
  108. package/src/voip/shim/util.js +207 -0
  109. package/src/voip/signaling/bridge.js +102 -0
  110. package/src/voip/signaling/screen-share.js +60 -0
  111. package/src/voip/signaling/signaling.js +491 -0
  112. package/src/voip/types.js +69 -0
  113. package/src/voip/voip-deps.js +243 -0
  114. package/src/voip/voipClient.js +314 -0
  115. package/src/wam/wam-constants.js +0 -1
  116. package/src/wam/wam.js +2 -7
@@ -0,0 +1,141 @@
1
+ import { getNodeChildren, getNodeChildrenByTag, getNodeTextContent } from '../shim/transport.js';
2
+ import { base64ToBytes, bytesToBase64 } from '../shim/util.js';
3
+ import { TEXT_DECODER } from '../bytes.js';
4
+ export function parseRelayFromAck(ackNode) {
5
+ const relays = [];
6
+ const participantJids = [];
7
+ const participantSeen = new Set();
8
+ let uuid = '';
9
+ let selfPid;
10
+ let peerPid;
11
+ let hbhKey;
12
+ if (!ackNode.content || !Array.isArray(ackNode.content)) {
13
+ return { relays, participantJids, uuid };
14
+ }
15
+ for (const child of ackNode.content) {
16
+ if (typeof child !== 'object' || !('tag' in child))
17
+ continue;
18
+ if (child.tag === 'user' && Array.isArray(child.content)) {
19
+ for (const deviceNode of child.content) {
20
+ if (typeof deviceNode === 'object' &&
21
+ 'tag' in deviceNode &&
22
+ deviceNode.tag === 'device' &&
23
+ deviceNode.attrs?.jid) {
24
+ const jid = deviceNode.attrs.jid;
25
+ if (!participantSeen.has(jid)) {
26
+ participantSeen.add(jid);
27
+ participantJids.push(jid);
28
+ }
29
+ }
30
+ }
31
+ }
32
+ if (child.tag !== 'relay')
33
+ continue;
34
+ const relayNode = child;
35
+ uuid = relayNode.attrs?.uuid || '';
36
+ if (relayNode.attrs?.self_pid)
37
+ selfPid = parseInt(relayNode.attrs.self_pid, 10);
38
+ if (relayNode.attrs?.peer_pid)
39
+ peerPid = parseInt(relayNode.attrs.peer_pid, 10);
40
+ const relayContent = getNodeChildren(relayNode);
41
+ for (const rc of getNodeChildrenByTag(relayNode, 'participant')) {
42
+ const jid = rc.attrs?.jid;
43
+ if (jid && !participantSeen.has(jid)) {
44
+ participantSeen.add(jid);
45
+ participantJids.push(jid);
46
+ }
47
+ }
48
+ let relayKey = '';
49
+ const tokens = new Map();
50
+ const authTokens = new Map();
51
+ const rawTokens = new Map();
52
+ const rawAuthTokens = new Map();
53
+ for (const rc of relayContent) {
54
+ if (typeof rc !== 'object' || !('tag' in rc))
55
+ continue;
56
+ const rcNode = rc;
57
+ if (rcNode.tag === 'key' && rcNode.content) {
58
+ relayKey = getNodeTextContent(rcNode) ?? '';
59
+ }
60
+ if (rcNode.tag === 'hbh_key' && rcNode.content) {
61
+ let rawKey;
62
+ if (rcNode.content instanceof Uint8Array) {
63
+ rawKey = rcNode.content;
64
+ }
65
+ else if (typeof rcNode.content === 'string') {
66
+ rawKey = base64ToBytes(rcNode.content);
67
+ }
68
+ if (rawKey) {
69
+ if (rawKey.length === 30) {
70
+ hbhKey = rawKey;
71
+ }
72
+ else if (rawKey.length > 30) {
73
+ const asB64 = TEXT_DECODER.decode(rawKey).trim();
74
+ const decoded = base64ToBytes(asB64);
75
+ if (decoded.length === 30)
76
+ hbhKey = decoded;
77
+ }
78
+ }
79
+ }
80
+ if (rcNode.tag === 'token' && rcNode.content) {
81
+ const tokenId = rcNode.attrs?.id || '0';
82
+ const tokenData = rcNode.content instanceof Uint8Array
83
+ ? bytesToBase64(rcNode.content)
84
+ : String(rcNode.content);
85
+ tokens.set(tokenId, tokenData);
86
+ if (rcNode.content instanceof Uint8Array) {
87
+ rawTokens.set(tokenId, rcNode.content);
88
+ }
89
+ }
90
+ if (rcNode.tag === 'auth_token' && rcNode.content) {
91
+ const authTokenId = rcNode.attrs?.id || '0';
92
+ const authTokenData = rcNode.content instanceof Uint8Array
93
+ ? bytesToBase64(rcNode.content)
94
+ : String(rcNode.content);
95
+ authTokens.set(authTokenId, authTokenData);
96
+ if (rcNode.content instanceof Uint8Array) {
97
+ rawAuthTokens.set(authTokenId, rcNode.content);
98
+ }
99
+ }
100
+ }
101
+ for (const rcNode of getNodeChildrenByTag(relayNode, 'te2')) {
102
+ const tokenId = rcNode.attrs?.token_id || '0';
103
+ const authTokenId = rcNode.attrs?.auth_token_id || '';
104
+ const token = tokens.get(tokenId) || '';
105
+ const authToken = authTokenId ? authTokens.get(authTokenId) : undefined;
106
+ const relayName = rcNode.attrs?.relay_name || '';
107
+ const protocol = rcNode.attrs?.protocol ? parseInt(rcNode.attrs.protocol, 10) : 0;
108
+ const isFna = rcNode.attrs?.is_fna === '1';
109
+ if (!(rcNode.content instanceof Uint8Array) || rcNode.content.length < 6)
110
+ continue;
111
+ const addrBytes = rcNode.content;
112
+ const addressBytes = new Uint8Array(addrBytes);
113
+ if (addrBytes.length === 6) {
114
+ const ip = `${addrBytes[0]}.${addrBytes[1]}.${addrBytes[2]}.${addrBytes[3]}`;
115
+ const port = (addrBytes[4] << 8) | addrBytes[5];
116
+ relays.push({
117
+ ip,
118
+ port,
119
+ token,
120
+ authToken,
121
+ rawAuthToken: authTokenId ? rawAuthTokens.get(authTokenId) : undefined,
122
+ rawToken: rawTokens.get(tokenId),
123
+ key: relayKey,
124
+ relayId: parseInt(rcNode.attrs?.relay_id || '0', 10),
125
+ protocol,
126
+ c2rRtt: rcNode.attrs?.c2r_rtt ? parseInt(rcNode.attrs.c2r_rtt, 10) : undefined,
127
+ relayName,
128
+ addressBytes,
129
+ authTokenId: authTokenId || tokenId,
130
+ isFna
131
+ });
132
+ }
133
+ }
134
+ }
135
+ relays.sort((a, b) => {
136
+ if (!!a.isFna !== !!b.isFna)
137
+ return a.isFna ? 1 : -1;
138
+ return (a.c2rRtt ?? Infinity) - (b.c2rRtt ?? Infinity);
139
+ });
140
+ return { relays, participantJids, uuid, selfPid, peerPid, hbhKey };
141
+ }
@@ -0,0 +1,434 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { EventEmitter } from 'node:events';
3
+ import { createNoopLogger } from '../../shim/core.js';
4
+ import * as sctp from './wire.js';
5
+
6
+ const SCTP_PORT = 5000;
7
+ const RETRANSMIT_TIMEOUT_MS = 1000;
8
+ const MAX_INIT_RETRIES = 5;
9
+ const HEARTBEAT_INTERVAL_MS = 5000;
10
+
11
+ const SEND_WINDOW_SIZE = 32;
12
+ const MAX_VIDEO_QUEUE_AGE_MS = 400;
13
+ const MAX_QUEUED_VIDEO_PACKETS = 200;
14
+ const MAX_QUEUED_AUDIO_FRAMES = 20;
15
+ const MAX_VIDEO_IN_FLIGHT = 24;
16
+ const STALE_GAP_TSN_LIMIT = 512;
17
+
18
+ function randomUint32() {
19
+ return randomBytes(4).readUInt32BE(0);
20
+ }
21
+
22
+ export class SctpAssociation extends EventEmitter {
23
+ #sendDtlsPayload;
24
+ #logger;
25
+ #state = 'idle';
26
+
27
+ #myTag = randomUint32();
28
+ #peerVerificationTag = 0;
29
+ #initialTsn = randomUint32();
30
+ #nextTsn;
31
+ #peerInitialTsn = 0;
32
+ #cumulativeAckReceived = -1;
33
+ #stateCookie = null;
34
+ #retransmitTimer = null;
35
+ #initRetries = 0;
36
+ #heartbeatTimer = null;
37
+ #outboundStreamSeq = 0;
38
+ #outboundVideoStreamSeq = 0;
39
+ #inboundExpectedStreamSeq = 0;
40
+ #reorderBuffer = new Map();
41
+ #inFlight = new Map();
42
+ #videoInFlightCount = 0;
43
+ #videoFlushCount = 0;
44
+ #audioQueue = [];
45
+ #videoQueue = [];
46
+ #inboundCumulativeTsn = -1;
47
+ #inboundReceivedAheadTsns = new Set();
48
+
49
+ constructor({ sendDtlsPayload, logger }) {
50
+ super();
51
+ this.#sendDtlsPayload = sendDtlsPayload;
52
+ this.#logger = logger ?? createNoopLogger();
53
+ this.#nextTsn = this.#initialTsn;
54
+ }
55
+
56
+ start() {
57
+ this.#state = 'wait_init_ack';
58
+ this.#sendInit();
59
+ }
60
+
61
+ close() {
62
+ this.#state = 'closed';
63
+ clearTimeout(this.#retransmitTimer);
64
+ clearInterval(this.#heartbeatTimer);
65
+ for (const entry of this.#inFlight.values()) clearTimeout(entry.timer);
66
+ this.#inFlight.clear();
67
+ this.#videoInFlightCount = 0;
68
+ this.#audioQueue = [];
69
+ this.#videoQueue = [];
70
+ this.#reorderBuffer.clear();
71
+ this.#inboundReceivedAheadTsns.clear();
72
+ }
73
+
74
+ get isConnected() { return this.#state === 'connected'; }
75
+
76
+ getSendBacklog() {
77
+ return {
78
+ queued: this.#audioQueue.length + this.#videoQueue.length,
79
+ queuedAudio: this.#audioQueue.length,
80
+ queuedVideo: this.#videoQueue.length,
81
+ inFlight: this.#inFlight.size,
82
+ retransmits: this.#retransmitCount,
83
+ videoFlushes: this.#videoFlushCount
84
+ };
85
+ }
86
+
87
+ send(payload, isAudio = true) {
88
+ if (this.#state === 'closed') return;
89
+ if (isAudio) {
90
+ this.#audioQueue.push(payload);
91
+ if (this.#audioQueue.length > MAX_QUEUED_AUDIO_FRAMES) {
92
+ this.#audioQueue.splice(0, this.#audioQueue.length - MAX_QUEUED_AUDIO_FRAMES);
93
+ }
94
+ } else {
95
+ const now = Date.now();
96
+ this.#videoQueue.push({ payload, queuedAtMs: now });
97
+ const oldest = this.#videoQueue[0];
98
+ if (this.#videoQueue.length > MAX_QUEUED_VIDEO_PACKETS ||
99
+ now - oldest.queuedAtMs > MAX_VIDEO_QUEUE_AGE_MS) {
100
+ const dropped = this.#videoQueue.length;
101
+ this.#videoQueue = [];
102
+ this.#videoFlushCount++;
103
+ this.#logger.trace('sctp flushed stale video queue to protect audio latency', {
104
+ dropped
105
+ });
106
+ }
107
+ }
108
+ this.#pumpSendQueue();
109
+ }
110
+
111
+ handleDtlsPayload(plaintext) {
112
+ if (this.#state === 'closed') return;
113
+ let header;
114
+ try {
115
+ header = sctp.parsePacketHeader(plaintext);
116
+ } catch (e) {
117
+
118
+ this.#logger.trace('sctp payload failed to parse', {
119
+ message: e.message, bytes: plaintext.length, hex: Buffer.from(plaintext).toString('hex')
120
+ });
121
+ return;
122
+ }
123
+ const chunkTypesForLog = sctp.splitChunks(plaintext, header.chunksStart).map((c) => c.type);
124
+ this.#logger.trace('sctp recv packet', {
125
+ vtag: `0x${header.verificationTag.toString(16)}`,
126
+ expectVtag: `0x${this.#myTag.toString(16)}`,
127
+ chunkTypes: chunkTypesForLog,
128
+ state: this.#state
129
+ });
130
+ if (this.#state !== 'wait_init_ack' && header.verificationTag !== this.#myTag) {
131
+
132
+ return;
133
+ }
134
+ const chunks = sctp.splitChunks(plaintext, header.chunksStart);
135
+ for (const chunk of chunks) this.#handleChunk(chunk, header);
136
+ }
137
+
138
+ #sendInit() {
139
+ const chunk = sctp.buildInit({
140
+ initiateTag: this.#myTag,
141
+ advertisedReceiverWindow: 131072,
142
+
143
+ outboundStreams: 65535,
144
+ inboundStreams: 65535,
145
+ initialTsn: this.#initialTsn,
146
+ });
147
+
148
+ const packet = sctp.buildPacket({ sourcePort: SCTP_PORT, destinationPort: SCTP_PORT, verificationTag: 0, chunks: [chunk] });
149
+ this.#logger.trace('sctp sending INIT', {
150
+ myTag: `0x${this.#myTag.toString(16)}`, initialTsn: this.#initialTsn, attempt: this.#initRetries
151
+ });
152
+ if (this.#initRetries === 0) {
153
+
154
+ this.#logger.trace('sctp INIT packet hex (first attempt only)', { hex: packet.toString('hex') });
155
+ }
156
+ this.#sendDtlsPayload(packet);
157
+ clearTimeout(this.#retransmitTimer);
158
+ this.#retransmitTimer = setTimeout(() => {
159
+ if (this.#state !== 'wait_init_ack') return;
160
+ this.#initRetries += 1;
161
+ if (this.#initRetries > MAX_INIT_RETRIES) {
162
+ this.#fail(new Error('SCTP: INIT retransmit limit exceeded'));
163
+ return;
164
+ }
165
+ this.#sendInit();
166
+ }, RETRANSMIT_TIMEOUT_MS * Math.min(2 ** this.#initRetries, 8));
167
+ }
168
+
169
+ #sendCookieEcho() {
170
+ const chunk = sctp.buildCookieEcho(this.#stateCookie);
171
+ const packet = sctp.buildPacket({ sourcePort: SCTP_PORT, destinationPort: SCTP_PORT, verificationTag: this.#peerVerificationTag, chunks: [chunk] });
172
+ this.#sendDtlsPayload(packet);
173
+ clearTimeout(this.#retransmitTimer);
174
+ this.#retransmitTimer = setTimeout(() => {
175
+ if (this.#state !== 'wait_cookie_ack') return;
176
+ this.#sendCookieEcho();
177
+ }, RETRANSMIT_TIMEOUT_MS);
178
+ }
179
+
180
+ #onConnected() {
181
+ this.#state = 'connected';
182
+ clearTimeout(this.#retransmitTimer);
183
+ this.#heartbeatTimer = setInterval(() => this.#sendHeartbeat(), HEARTBEAT_INTERVAL_MS);
184
+ this.emit('connected');
185
+ this.#pumpSendQueue();
186
+ }
187
+
188
+ #pumpSendQueue() {
189
+ if (this.#state !== 'connected') return;
190
+ while (this.#inFlight.size < SEND_WINDOW_SIZE) {
191
+ let payload, isAudio;
192
+ if (this.#audioQueue.length > 0) {
193
+ payload = this.#audioQueue.shift();
194
+ isAudio = true;
195
+ } else if (this.#videoQueue.length > 0 && this.#videoInFlightCount < MAX_VIDEO_IN_FLIGHT) {
196
+ payload = this.#videoQueue.shift().payload;
197
+ isAudio = false;
198
+ } else {
199
+ break;
200
+ }
201
+ const tsn = this.#nextTsn;
202
+ this.#nextTsn = (this.#nextTsn + 1) >>> 0;
203
+ const streamSeq = isAudio ? this.#outboundStreamSeq++ : this.#outboundVideoStreamSeq++;
204
+ const chunk = sctp.buildData({ tsn, streamId: 0, streamSeq, ppid: 53, payload, unordered: isAudio });
205
+ const packet = sctp.buildPacket({ sourcePort: SCTP_PORT, destinationPort: SCTP_PORT, verificationTag: this.#peerVerificationTag, chunks: [chunk] });
206
+ const entry = { packet, timer: null, isAudio };
207
+ this.#inFlight.set(tsn, entry);
208
+ if (!isAudio) this.#videoInFlightCount++;
209
+ this.#sendDtlsPayload(packet);
210
+ this.#armDataRetransmit(tsn, entry);
211
+ }
212
+ }
213
+
214
+ #retransmitCount = 0;
215
+
216
+ #armDataRetransmit(tsn, entry) {
217
+ clearTimeout(entry.timer);
218
+ entry.timer = setTimeout(() => {
219
+ if (!this.#inFlight.has(tsn)) return;
220
+ this.#retransmitCount++;
221
+ this.#sendDtlsPayload(entry.packet);
222
+ this.#armDataRetransmit(tsn, entry);
223
+ }, RETRANSMIT_TIMEOUT_MS);
224
+ }
225
+
226
+ #handleChunk(chunk, header) {
227
+ switch (chunk.type) {
228
+ case sctp.ChunkType.INIT_ACK: {
229
+ if (this.#state !== 'wait_init_ack') return;
230
+ const parsed = sctp.parseInitOrInitAck(chunk.value);
231
+ if (!parsed.stateCookie) { this.#fail(new Error('SCTP: INIT ACK missing State Cookie')); return; }
232
+ this.#peerVerificationTag = parsed.initiateTag;
233
+ this.#peerInitialTsn = parsed.initialTsn;
234
+ this.#inboundExpectedStreamSeq = 0;
235
+ this.#inboundCumulativeTsn = (parsed.initialTsn - 1) >>> 0;
236
+ this.#inboundReceivedAheadTsns.clear();
237
+ this.#stateCookie = parsed.stateCookie;
238
+ this.#state = 'wait_cookie_ack';
239
+ this.#initRetries = 0;
240
+ this.#sendCookieEcho();
241
+ return;
242
+ }
243
+ case sctp.ChunkType.COOKIE_ACK: {
244
+ if (this.#state !== 'wait_cookie_ack') return;
245
+ this.#onConnected();
246
+ return;
247
+ }
248
+ case sctp.ChunkType.DATA: {
249
+ const parsed = sctp.parseData(chunk.flags, chunk.value);
250
+ this.#handleIncomingData(parsed);
251
+ return;
252
+ }
253
+ case sctp.ChunkType.SACK: {
254
+ const parsed = sctp.parseSack(chunk.value);
255
+ this.#handleSack(parsed);
256
+ return;
257
+ }
258
+ case sctp.ChunkType.HEARTBEAT: {
259
+ const info = sctp.parseHeartbeatInfo(chunk.value);
260
+ const ackChunk = sctp.buildHeartbeatAck(info);
261
+ const packet = sctp.buildPacket({ sourcePort: SCTP_PORT, destinationPort: SCTP_PORT, verificationTag: this.#peerVerificationTag, chunks: [ackChunk] });
262
+ this.#sendDtlsPayload(packet);
263
+ return;
264
+ }
265
+ case sctp.ChunkType.HEARTBEAT_ACK:
266
+ return;
267
+ case sctp.ChunkType.ABORT:
268
+ this.#fail(new Error('SCTP: received ABORT from peer'));
269
+ return;
270
+ case sctp.ChunkType.ERROR:
271
+
272
+ return;
273
+ default:
274
+ return;
275
+ }
276
+ }
277
+
278
+ #handleIncomingData({ tsn, streamId, streamSeq, ppid, payload, unordered }) {
279
+
280
+ this.#recordInboundTsn(tsn);
281
+ this.#buildAndSendSack();
282
+
283
+ if (streamId !== 0 || ppid !== 53) return;
284
+
285
+ if (unordered) {
286
+ this.emit('message', payload);
287
+ return;
288
+ }
289
+
290
+ if (streamSeq === this.#inboundExpectedStreamSeq) {
291
+ this.#inboundExpectedStreamSeq += 1;
292
+ this.emit('message', payload);
293
+
294
+ while (this.#reorderBuffer.has(this.#inboundExpectedStreamSeq)) {
295
+ const buffered = this.#reorderBuffer.get(this.#inboundExpectedStreamSeq);
296
+ this.#reorderBuffer.delete(this.#inboundExpectedStreamSeq);
297
+ this.#inboundExpectedStreamSeq += 1;
298
+ this.emit('message', buffered);
299
+ }
300
+ } else if (streamSeq > this.#inboundExpectedStreamSeq) {
301
+ this.#reorderBuffer.set(streamSeq, payload);
302
+ if (this.#reorderBuffer.size > STALE_GAP_TSN_LIMIT) {
303
+ const bufferedSeqs = [...this.#reorderBuffer.keys()].sort((a, b) => a - b);
304
+ this.#logger.debug('sctp: forcing stream sequence past a stuck gap', {
305
+ from: this.#inboundExpectedStreamSeq, bufferedCount: bufferedSeqs.length
306
+ });
307
+ this.#inboundExpectedStreamSeq = bufferedSeqs[0];
308
+ const buffered = this.#reorderBuffer.get(this.#inboundExpectedStreamSeq);
309
+ this.#reorderBuffer.delete(this.#inboundExpectedStreamSeq);
310
+ this.#inboundExpectedStreamSeq += 1;
311
+ this.emit('message', buffered);
312
+ while (this.#reorderBuffer.has(this.#inboundExpectedStreamSeq)) {
313
+ const next = this.#reorderBuffer.get(this.#inboundExpectedStreamSeq);
314
+ this.#reorderBuffer.delete(this.#inboundExpectedStreamSeq);
315
+ this.#inboundExpectedStreamSeq += 1;
316
+ this.emit('message', next);
317
+ }
318
+ }
319
+ }
320
+
321
+ }
322
+
323
+ #recordInboundTsn(tsn) {
324
+ if (sackAcksTsn(this.#inboundCumulativeTsn, tsn)) {
325
+ return;
326
+ }
327
+ this.#inboundReceivedAheadTsns.add(tsn);
328
+ let next = (this.#inboundCumulativeTsn + 1) >>> 0;
329
+ while (this.#inboundReceivedAheadTsns.has(next)) {
330
+ this.#inboundReceivedAheadTsns.delete(next);
331
+ this.#inboundCumulativeTsn = next;
332
+ next = (this.#inboundCumulativeTsn + 1) >>> 0;
333
+ }
334
+ if (this.#inboundReceivedAheadTsns.size > STALE_GAP_TSN_LIMIT) {
335
+ let maxAheadOffset = 0;
336
+ for (const aheadTsn of this.#inboundReceivedAheadTsns) {
337
+ const offset = (aheadTsn - this.#inboundCumulativeTsn) >>> 0;
338
+ if (offset > maxAheadOffset) maxAheadOffset = offset;
339
+ }
340
+ const jumpTo = (this.#inboundCumulativeTsn + maxAheadOffset) >>> 0;
341
+ this.#logger.debug('sctp: forcing cumulative TSN past a stuck gap', {
342
+ from: this.#inboundCumulativeTsn, to: jumpTo, aheadCount: this.#inboundReceivedAheadTsns.size
343
+ });
344
+ this.#inboundReceivedAheadTsns.delete(jumpTo);
345
+ this.#inboundCumulativeTsn = jumpTo;
346
+ }
347
+ }
348
+
349
+ #buildAndSendSack() {
350
+ const gapAckBlocks = [];
351
+ if (this.#inboundReceivedAheadTsns.size > 0) {
352
+ const sorted = [...this.#inboundReceivedAheadTsns].sort((a, b) => {
353
+ const diffA = (a - this.#inboundCumulativeTsn) >>> 0;
354
+ const diffB = (b - this.#inboundCumulativeTsn) >>> 0;
355
+ return diffA - diffB;
356
+ });
357
+ let blockStart = null;
358
+ let blockEnd = null;
359
+ for (const tsn of sorted) {
360
+ const offset = (tsn - this.#inboundCumulativeTsn) >>> 0;
361
+ if (offset > 0xffff) continue;
362
+ if (blockStart !== null && offset === blockEnd + 1) {
363
+ blockEnd = offset;
364
+ } else {
365
+ if (blockStart !== null) gapAckBlocks.push({ start: blockStart, end: blockEnd });
366
+ blockStart = offset;
367
+ blockEnd = offset;
368
+ }
369
+ }
370
+ if (blockStart !== null) gapAckBlocks.push({ start: blockStart, end: blockEnd });
371
+ }
372
+ const sackChunk = sctp.buildSack({
373
+ cumulativeTsnAck: this.#inboundCumulativeTsn,
374
+ advertisedReceiverWindow: 131072,
375
+ gapAckBlocks
376
+ });
377
+ const sackPacket = sctp.buildPacket({ sourcePort: SCTP_PORT, destinationPort: SCTP_PORT, verificationTag: this.#peerVerificationTag, chunks: [sackChunk] });
378
+ this.#sendDtlsPayload(sackPacket);
379
+ }
380
+
381
+ #handleSack({ cumulativeTsnAck, gapAckBlocks }) {
382
+ if (this.#inFlight.size === 0) return;
383
+ let acked = false;
384
+ for (const [tsn, entry] of this.#inFlight) {
385
+ if (sackAcksTsn(cumulativeTsnAck, tsn)) {
386
+ clearTimeout(entry.timer);
387
+ this.#inFlight.delete(tsn);
388
+ if (!entry.isAudio) this.#videoInFlightCount--;
389
+ acked = true;
390
+ }
391
+ }
392
+ if (gapAckBlocks && gapAckBlocks.length > 0 && this.#inFlight.size > 0) {
393
+ for (const block of gapAckBlocks) {
394
+ for (const [tsn, entry] of this.#inFlight) {
395
+ const offset = (tsn - cumulativeTsnAck) >>> 0;
396
+ if (offset >= block.start && offset <= block.end) {
397
+ clearTimeout(entry.timer);
398
+ this.#inFlight.delete(tsn);
399
+ if (!entry.isAudio) this.#videoInFlightCount--;
400
+ acked = true;
401
+ }
402
+ }
403
+ }
404
+ }
405
+ if (acked) this.#pumpSendQueue();
406
+ }
407
+
408
+ #sendHeartbeat() {
409
+ if (this.#state !== 'connected') return;
410
+ const info = randomBytes(16);
411
+ const chunk = sctp.buildHeartbeat(info);
412
+ const packet = sctp.buildPacket({ sourcePort: SCTP_PORT, destinationPort: SCTP_PORT, verificationTag: this.#peerVerificationTag, chunks: [chunk] });
413
+ this.#sendDtlsPayload(packet);
414
+ }
415
+
416
+ #fail(err) {
417
+ this.#state = 'closed';
418
+ clearTimeout(this.#retransmitTimer);
419
+ clearInterval(this.#heartbeatTimer);
420
+ for (const entry of this.#inFlight.values()) clearTimeout(entry.timer);
421
+ this.#inFlight.clear();
422
+ this.#videoInFlightCount = 0;
423
+ this.#audioQueue = [];
424
+ this.#videoQueue = [];
425
+ this.#reorderBuffer.clear();
426
+ this.#inboundReceivedAheadTsns.clear();
427
+ this.emit('error', err);
428
+ }
429
+ }
430
+
431
+ function sackAcksTsn(cumAck, tsn) {
432
+ const diff = (cumAck - tsn) >>> 0;
433
+ return diff < 0x80000000;
434
+ }
@@ -0,0 +1,21 @@
1
+
2
+ const TABLE = (() => {
3
+ const table = new Uint32Array(256);
4
+ const poly = 0x82f63b78;
5
+ for (let n = 0; n < 256; n++) {
6
+ let c = n;
7
+ for (let k = 0; k < 8; k++) {
8
+ c = c & 1 ? (c >>> 1) ^ poly : c >>> 1;
9
+ }
10
+ table[n] = c >>> 0;
11
+ }
12
+ return table;
13
+ })();
14
+
15
+ export function crc32c(data) {
16
+ let crc = 0xffffffff;
17
+ for (let i = 0; i < data.length; i++) {
18
+ crc = TABLE[(crc ^ data[i]) & 0xff] ^ (crc >>> 8);
19
+ }
20
+ return (crc ^ 0xffffffff) >>> 0;
21
+ }