@hiroosy/baileys-lite 0.3.8 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,35 @@
1
1
  import { getNodeChildren, getNodeChildrenByTag, getNodeTextContent } from '../shim/transport.js';
2
2
  import { base64ToBytes, bytesToBase64 } from '../shim/util.js';
3
3
  import { TEXT_DECODER } from '../bytes.js';
4
+ function formatIpv6(bytes) {
5
+ const groups = new Array(8);
6
+ let bestStart = -1;
7
+ let bestLen = 0;
8
+ let runStart = -1;
9
+ let runLen = 0;
10
+ for (let i = 0; i < 8; i++) {
11
+ const value = (bytes[i * 2] << 8) | bytes[i * 2 + 1];
12
+ groups[i] = value.toString(16);
13
+ if (value === 0) {
14
+ if (runStart < 0) {
15
+ runStart = i;
16
+ }
17
+ runLen++;
18
+ if (runLen > bestLen) {
19
+ bestStart = runStart;
20
+ bestLen = runLen;
21
+ }
22
+ }
23
+ else {
24
+ runStart = -1;
25
+ runLen = 0;
26
+ }
27
+ }
28
+ if (bestLen < 2) {
29
+ return groups.join(':');
30
+ }
31
+ return `${groups.slice(0, bestStart).join(':')}::${groups.slice(bestStart + bestLen).join(':')}`;
32
+ }
4
33
  export function parseRelayFromAck(ackNode) {
5
34
  const relays = [];
6
35
  const participantJids = [];
@@ -98,37 +127,49 @@ export function parseRelayFromAck(ackNode) {
98
127
  }
99
128
  }
100
129
  }
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,
130
+ for (const endpointTag of ['te2', 'te']) {
131
+ for (const rcNode of getNodeChildrenByTag(relayNode, endpointTag)) {
132
+ const addrBytes = rcNode.content;
133
+ if (!(addrBytes instanceof Uint8Array)) {
134
+ continue;
135
+ }
136
+ const addrLength = addrBytes.length;
137
+ if (addrLength !== 6 && addrLength !== 18 && addrLength !== 24) {
138
+ continue;
139
+ }
140
+ const tokenId = rcNode.attrs?.token_id || '0';
141
+ const authTokenId = rcNode.attrs?.auth_token_id || '';
142
+ const shared = {
143
+ token: tokens.get(tokenId) || '',
144
+ authToken: authTokenId ? authTokens.get(authTokenId) : undefined,
121
145
  rawAuthToken: authTokenId ? rawAuthTokens.get(authTokenId) : undefined,
122
146
  rawToken: rawTokens.get(tokenId),
123
147
  key: relayKey,
124
148
  relayId: parseInt(rcNode.attrs?.relay_id || '0', 10),
125
- protocol,
149
+ protocol: rcNode.attrs?.protocol ? parseInt(rcNode.attrs.protocol, 10) : 0,
126
150
  c2rRtt: rcNode.attrs?.c2r_rtt ? parseInt(rcNode.attrs.c2r_rtt, 10) : undefined,
127
- relayName,
128
- addressBytes,
151
+ relayName: rcNode.attrs?.relay_name || '',
129
152
  authTokenId: authTokenId || tokenId,
130
- isFna
131
- });
153
+ isFna: rcNode.attrs?.is_fna === '1'
154
+ };
155
+ if (addrLength !== 18) {
156
+ const v4 = addrBytes.subarray(0, 6);
157
+ relays.push({
158
+ ...shared,
159
+ ip: `${v4[0]}.${v4[1]}.${v4[2]}.${v4[3]}`,
160
+ port: (v4[4] << 8) | v4[5],
161
+ addressBytes: new Uint8Array(v4)
162
+ });
163
+ }
164
+ if (addrLength !== 6) {
165
+ const v6 = addrLength === 18 ? addrBytes : addrBytes.subarray(6);
166
+ relays.push({
167
+ ...shared,
168
+ ip: formatIpv6(v6),
169
+ port: (v6[16] << 8) | v6[17],
170
+ addressBytes: new Uint8Array(v6)
171
+ });
172
+ }
132
173
  }
133
174
  }
134
175
  }
@@ -11,6 +11,7 @@ const SEND_WINDOW_SIZE = 32;
11
11
  const MAX_VIDEO_QUEUE_AGE_MS = 400;
12
12
  const MAX_QUEUED_VIDEO_PACKETS = 200;
13
13
  const MAX_QUEUED_AUDIO_FRAMES = 6;
14
+ const inFlightLifetimeMs = 1000;
14
15
  const MAX_VIDEO_IN_FLIGHT = 24;
15
16
  const STALE_GAP_TSN_LIMIT = 512;
16
17
  const videoBurstBytes = 8192;
@@ -193,7 +194,7 @@ export class SctpAssociation extends EventEmitter {
193
194
  const streamSeq = isAudio ? this.#outboundStreamSeq++ : this.#outboundVideoStreamSeq++;
194
195
  const chunk = sctp.buildData({ tsn, streamId: 0, streamSeq, ppid: 53, payload, unordered: isAudio });
195
196
  const packet = sctp.buildPacket({ sourcePort: SCTP_PORT, destinationPort: SCTP_PORT, verificationTag: this.#peerVerificationTag, chunks: [chunk] });
196
- const entry = { packet, timer: null, isAudio, sentAt: performance.now(), retransmitted: false, missing: 0, attempts: 0 };
197
+ const entry = { packet, timer: null, isAudio, createdAt: performance.now(), sentAt: performance.now(), retransmitted: false, missing: 0, attempts: 0 };
197
198
  this.#inFlight.set(tsn, entry);
198
199
  if (!isAudio) this.#videoInFlightCount++;
199
200
  this.#sendDtlsPayload(packet);
@@ -208,6 +209,10 @@ export class SctpAssociation extends EventEmitter {
208
209
  const delayMs = Math.min(RETRANSMIT_TIMEOUT_MS, this.#rtoMs * 2 ** entry.attempts);
209
210
  entry.timer = setTimeout(() => {
210
211
  if (!this.#inFlight.has(tsn)) return;
212
+ if (performance.now() - entry.createdAt > inFlightLifetimeMs) {
213
+ this.#abandonInFlight(tsn, entry);
214
+ return;
215
+ }
211
216
  this.#retransmitCount++;
212
217
  entry.attempts++;
213
218
  entry.retransmitted = true;
@@ -218,6 +223,13 @@ export class SctpAssociation extends EventEmitter {
218
223
  }, delayMs);
219
224
  }
220
225
 
226
+ #abandonInFlight(tsn, entry) {
227
+ clearTimeout(entry.timer);
228
+ this.#inFlight.delete(tsn);
229
+ if (!entry.isAudio) this.#videoInFlightCount--;
230
+ this.#pumpSendQueue();
231
+ }
232
+
221
233
  #refillVideoBudget(now) {
222
234
  this.#videoBudgetBytes = Math.min(videoBurstBytes, this.#videoBudgetBytes + (now - this.#videoBudgetAt) * videoPaceBytesPerMs);
223
235
  this.#videoBudgetAt = now;
@@ -248,6 +260,7 @@ export class SctpAssociation extends EventEmitter {
248
260
  for (const [tsn, entry] of this.#inFlight) {
249
261
  const behind = (highestTsn - tsn) >>> 0;
250
262
  if (behind === 0 || behind >= 0x80000000) continue;
263
+ if (performance.now() - entry.createdAt > inFlightLifetimeMs) continue;
251
264
  if (entry.sentAt + reorderWindowMs >= latestAckedSentAt) continue;
252
265
  entry.missing++;
253
266
  if (entry.missing < 3) continue;
@@ -147,7 +147,7 @@ const WASM_STREAM_DESCRIPTOR_PLAN = [
147
147
  { participant: 2, layer: 2 }
148
148
  ];
149
149
 
150
- export function createWasmStreamDescriptors(streamSsrcs) {
150
+ export function createWasmStreamDescriptors(streamSsrcs, hbhFecSsrcs = []) {
151
151
  const entries = [];
152
152
  for (let i = 0; i < streamSsrcs.length; i++) {
153
153
  const ssrc = streamSsrcs[i];
@@ -162,30 +162,197 @@ export function createWasmStreamDescriptors(streamSsrcs) {
162
162
  parts.push(encodeProtobufVarintField(3, ssrc));
163
163
  entries.push(encodeProtobufLengthDelimited(1, concatBytes(parts)));
164
164
  }
165
+ hbhFecSsrcs.forEach((ssrc, index) => {
166
+ if (ssrc === 0) {
167
+ return;
168
+ }
169
+ entries.push(encodeProtobufLengthDelimited(1, concatBytes([
170
+ encodeProtobufVarintField(1, index + 3),
171
+ encodeProtobufVarintField(2, 3),
172
+ encodeProtobufVarintField(3, ssrc)
173
+ ])));
174
+ });
165
175
  return concatBytes(entries);
166
176
  }
167
- function encodeXorRelayedAddress(ip, port) {
168
- const data = new Uint8Array(8);
169
- data[0] = 0x00;
170
- data[1] = 0x01;
171
- writeUInt16BE(data, port ^ (STUN_MAGIC_COOKIE >>> 16), 2);
172
- const parts = ip.split('.').map(Number);
173
- const ipNum = ((parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]) >>> 0;
174
- writeUInt32BE(data, (ipNum ^ STUN_MAGIC_COOKIE) >>> 0, 4);
177
+ function createGroupSenderSubscription(ssrcs, pids, withVideoLayer) {
178
+ const parts = [encodeProtobufLengthDelimited(1, concatBytes(ssrcs.filter((ssrc) => ssrc !== 0).map(encodeVarint)))];
179
+ for (const pid of pids) {
180
+ const participant = withVideoLayer
181
+ ? concatBytes([encodeProtobufVarintField(1, pid), encodeProtobufVarintField(2, 1)])
182
+ : encodeProtobufVarintField(1, pid);
183
+ parts.push(encodeProtobufLengthDelimited(2, participant));
184
+ }
185
+ return encodeProtobufLengthDelimited(1, encodeProtobufLengthDelimited(1, concatBytes(parts)));
186
+ }
187
+ export function createGroupSenderSubscriptions(streamSsrcs, appDataSsrc, pids) {
188
+ return concatBytes([
189
+ createGroupSenderSubscription(streamSsrcs.slice(3, 6), pids, true),
190
+ createGroupSenderSubscription(streamSsrcs.slice(6, 9), [], false),
191
+ createGroupSenderSubscription(streamSsrcs.slice(0, 3), pids, false),
192
+ createGroupSenderSubscription([appDataSsrc], pids, false)
193
+ ]);
194
+ }
195
+ export function createGroupReceiverSubscriptions(pids) {
196
+ return concatBytes(pids.map((pid) => encodeProtobufLengthDelimited(2, encodeProtobufVarintField(1, pid))));
197
+ }
198
+ function parseIpv4Bytes(ip) {
199
+ const octets = ip.split('.');
200
+ if (octets.length !== 4) {
201
+ return null;
202
+ }
203
+ const out = new Uint8Array(4);
204
+ for (let i = 0; i < 4; i++) {
205
+ if (!/^\d{1,3}$/.test(octets[i]) || Number(octets[i]) > 255) {
206
+ return null;
207
+ }
208
+ out[i] = Number(octets[i]);
209
+ }
210
+ return out;
211
+ }
212
+ function parseIpv6Bytes(text) {
213
+ let ip = text;
214
+ const zone = ip.indexOf('%');
215
+ if (zone >= 0) {
216
+ ip = ip.slice(0, zone);
217
+ }
218
+ if (ip.includes('.')) {
219
+ const split = ip.lastIndexOf(':');
220
+ const tail = split >= 0 ? parseIpv4Bytes(ip.slice(split + 1)) : null;
221
+ if (!tail) {
222
+ return null;
223
+ }
224
+ ip = `${ip.slice(0, split + 1)}${((tail[0] << 8) | tail[1]).toString(16)}:${((tail[2] << 8) | tail[3]).toString(16)}`;
225
+ }
226
+ const halves = ip.split('::');
227
+ if (halves.length > 2) {
228
+ return null;
229
+ }
230
+ const head = halves[0] ? halves[0].split(':') : [];
231
+ const tail = halves.length === 2 && halves[1] ? halves[1].split(':') : [];
232
+ const gap = 8 - head.length - tail.length;
233
+ if (halves.length === 2 ? gap < 1 : gap !== 0) {
234
+ return null;
235
+ }
236
+ const groups = [...head, ...new Array(halves.length === 2 ? gap : 0).fill('0'), ...tail];
237
+ const out = new Uint8Array(16);
238
+ for (let i = 0; i < 8; i++) {
239
+ if (!/^[0-9a-fA-F]{1,4}$/.test(groups[i])) {
240
+ return null;
241
+ }
242
+ const value = parseInt(groups[i], 16);
243
+ out[i * 2] = value >> 8;
244
+ out[i * 2 + 1] = value & 0xff;
245
+ }
246
+ return out;
247
+ }
248
+ function relayXorKey(transactionId) {
249
+ const key = new Uint8Array(16);
250
+ writeUInt32BE(key, STUN_MAGIC_COOKIE, 0);
251
+ for (let i = 0; i < 12; i++) {
252
+ key[4 + i] = transactionId[(i & ~3) + 3 - (i & 3)];
253
+ }
254
+ return key;
255
+ }
256
+ function stripAddressBrackets(text) {
257
+ if (typeof text !== 'string') {
258
+ return '';
259
+ }
260
+ const trimmed = text.trim();
261
+ return trimmed.startsWith('[') && trimmed.endsWith(']') ? trimmed.slice(1, -1) : trimmed;
262
+ }
263
+ function resolveRelayedAddressBytes(ip, form) {
264
+ const bare = stripAddressBrackets(ip);
265
+ if (!bare) {
266
+ return null;
267
+ }
268
+ const ipv4 = bare.includes(':') ? null : parseIpv4Bytes(bare);
269
+ const ipv6 = ipv4 ? null : parseIpv6Bytes(bare);
270
+ if (!ipv4 && !ipv6) {
271
+ return null;
272
+ }
273
+ if (form !== 'mapped') {
274
+ return ipv4 ?? ipv6;
275
+ }
276
+ if (ipv6) {
277
+ return ipv6;
278
+ }
279
+ const mapped = new Uint8Array(16);
280
+ mapped.set([0xff, 0xff], 10);
281
+ mapped.set(ipv4, 12);
282
+ return mapped;
283
+ }
284
+ function encodeXorRelayedAddress(ip, port, transactionId, form = 'exact') {
285
+ const portNumber = Number(port);
286
+ if (!Number.isInteger(portNumber) || portNumber < 1 || portNumber > 65535) {
287
+ return undefined;
288
+ }
289
+ if (!transactionId || transactionId.length !== 12) {
290
+ return undefined;
291
+ }
292
+ const address = resolveRelayedAddressBytes(ip, form);
293
+ if (!address) {
294
+ return undefined;
295
+ }
296
+ const data = new Uint8Array(4 + address.length);
297
+ data[1] = address.length === 16 ? 0x02 : 0x01;
298
+ writeUInt16BE(data, portNumber ^ (STUN_MAGIC_COOKIE >>> 16), 2);
299
+ const key = relayXorKey(transactionId);
300
+ for (let i = 0; i < address.length; i++) {
301
+ data[4 + i] = address[i] ^ key[i];
302
+ }
175
303
  return data;
176
304
  }
177
-
178
- export function buildAllocateForRelay(relayToken, streamDescriptors, hmacKey, relayIp, relayPort, username, transactionId = generateTransactionId()) {
305
+ export function parseRelayedAddressMismatch(reason) {
306
+ if (typeof reason !== 'string') {
307
+ return null;
308
+ }
309
+ const match = /destination address:\s*(.+?)\s+relay address:\s*(.+?)[\s\0]*$/i.exec(reason);
310
+ if (!match) {
311
+ return null;
312
+ }
313
+ const readEndpoint = (text) => {
314
+ const hit = /^\[(.+)\]:(\d{1,5})$/.exec(text) ?? /^([^:\s]+):(\d{1,5})$/.exec(text);
315
+ if (!hit) {
316
+ return null;
317
+ }
318
+ const port = Number(hit[2]);
319
+ return port >= 1 && port <= 65535 ? { ip: hit[1], port } : null;
320
+ };
321
+ return { destination: readEndpoint(match[1]), relay: readEndpoint(match[2]) };
322
+ }
323
+ export function buildAllocateForRelay(relayToken, streamDescriptors, hmacKey, relayIp, relayPort, transactionId = generateTransactionId(), options = {}) {
179
324
  const parts = [];
180
325
  parts.push(encodeAttribute(ATTR_SENDER_SUBSCRIPTIONS, relayToken));
181
326
  parts.push(encodeAttribute(ATTR_SSRC_LIST, streamDescriptors));
182
- parts.push(encodeAttribute(ATTR_REQUESTED_TRANSPORT, new Uint8Array([17, 0, 0, 0])));
183
- if (username && username.length > 0)
184
- parts.push(encodeAttribute(ATTR_USERNAME, username));
185
- parts.push(encodeAttribute(ATTR_XOR_RELAYED_ADDRESS, encodeXorRelayedAddress(relayIp, relayPort)));
327
+ if (relayIp && relayPort && options.relayedAddress !== 'none') {
328
+ const xorRelayedAddress = encodeXorRelayedAddress(relayIp, relayPort, transactionId, options.relayedAddress);
329
+ if (xorRelayedAddress) {
330
+ parts.push(encodeAttribute(ATTR_XOR_RELAYED_ADDRESS, xorRelayedAddress));
331
+ }
332
+ }
186
333
  const attrs = concatBytes(parts);
187
334
  return buildStunMessage(STUN_ALLOCATE_REQUEST, attrs, transactionId, hmacKey, false);
188
335
  }
336
+ export function buildGroupAllocateForRelay(relayToken, group, hmacKey, relayIp, relayPort, transactionId = generateTransactionId(), options = {}) {
337
+ const pids = [...new Set(group.pids)].sort((a, b) => a - b);
338
+ if (pids.length === 0) {
339
+ return buildAllocateForRelay(relayToken, createWasmStreamDescriptors(group.streamSsrcs), hmacKey, relayIp, relayPort, transactionId, options);
340
+ }
341
+ const parts = [
342
+ encodeAttribute(ATTR_SENDER_SUBSCRIPTIONS, relayToken),
343
+ encodeAttribute(0x4025, createGroupSenderSubscriptions(group.streamSsrcs, group.appDataSsrc, pids)),
344
+ encodeAttribute(0x4021, createGroupReceiverSubscriptions(pids)),
345
+ encodeAttribute(ATTR_SSRC_LIST, createWasmStreamDescriptors(group.streamSsrcs, pids.length > 1 ? group.hbhFecSsrcs ?? [] : [])),
346
+ encodeAttribute(0x805a, encodeVarint(pids.length))
347
+ ];
348
+ if (relayIp && relayPort && options.relayedAddress !== 'none') {
349
+ const xorRelayedAddress = encodeXorRelayedAddress(relayIp, relayPort, transactionId, options.relayedAddress);
350
+ if (xorRelayedAddress) {
351
+ parts.push(encodeAttribute(ATTR_XOR_RELAYED_ADDRESS, xorRelayedAddress));
352
+ }
353
+ }
354
+ return buildStunMessage(STUN_ALLOCATE_REQUEST, concatBytes(parts), transactionId, hmacKey, false);
355
+ }
189
356
  export function buildBindingRequest(username, hmacKey, senderSubscriptions, includeIceControllingOrOptions = true) {
190
357
  const options = typeof includeIceControllingOrOptions === 'boolean'
191
358
  ? { iceRole: includeIceControllingOrOptions ? 'controlling' : 'none' }
@@ -193,7 +360,7 @@ export function buildBindingRequest(username, hmacKey, senderSubscriptions, incl
193
360
  const iceRole = options.iceRole ?? 'controlling';
194
361
  const includePriority = options.includePriority ?? true;
195
362
  const includeUsername = options.includeUsername ?? true;
196
- const transactionId = generateTransactionId();
363
+ const transactionId = options.transactionId ?? generateTransactionId();
197
364
  const usernameAttr = includeUsername ? encodeAttribute(ATTR_USERNAME, username) : undefined;
198
365
  const priorityAttr = includePriority
199
366
  ? (() => {
@@ -1,6 +1,7 @@
1
1
  import { createNoopLogger } from '../shim/core.js';
2
2
  import { normalizeDeviceJid } from '../shim/protocol.js';
3
3
  import { buildAckNode, getFirstNodeChild } from '../shim/transport.js';
4
+ import { buildCallControlAckNode } from './signaling.js';
4
5
  import { toError } from '../shim/util.js';
5
6
  const RECEIPT_CALL_TAGS = new Set([
6
7
  'offer',
@@ -18,13 +19,26 @@ export async function routeCallStanza(manager, deps, node, logger) {
18
19
  return null;
19
20
  const tag = inner.tag;
20
21
  const peerJid = node.attrs.from;
21
- await deps.lowLevelCoordinator.sendNode(buildAckNode({
22
+ await deps.lowLevelCoordinator.sendNode(buildCallControlAckNode(node, tag) ?? buildAckNode({
22
23
  kind: 'custom',
23
24
  ackClass: 'call',
24
25
  to: peerJid,
25
26
  id: node.attrs.id,
26
27
  type: tag
27
28
  }));
29
+ switch (tag) {
30
+ case 'group_update':
31
+ await manager.handleGroupUpdate(node);
32
+ return tag;
33
+ case 'enc_rekey':
34
+ await manager.handleGroupEncRekey(node);
35
+ return tag;
36
+ case 'waiting_room_update':
37
+ manager.handleWaitingRoomUpdate(node);
38
+ return tag;
39
+ default:
40
+ break;
41
+ }
28
42
  let normalizedPeerJid;
29
43
  try {
30
44
  normalizedPeerJid = normalizeDeviceJid(peerJid);