@hiroosy/baileys-lite 0.0.4 → 0.3.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.
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 +702 -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,203 @@
1
+ import { CallDirection, CallMediaType, CallState } from '../types.js';
2
+ export class CallInfo {
3
+ callId;
4
+ peerJid;
5
+ callCreator;
6
+ direction;
7
+ mediaType;
8
+ stateData;
9
+ createdAt;
10
+ groupJid;
11
+ isOffline;
12
+ callerPn;
13
+ encryptionKey;
14
+ relayData;
15
+ electedRelayIdx;
16
+ raisedHands = new Set();
17
+ peerScreenShare = null;
18
+ constructor(init) {
19
+ this.callId = init.callId;
20
+ this.peerJid = init.peerJid;
21
+ this.callCreator = init.callCreator;
22
+ this.direction = init.direction;
23
+ this.mediaType = init.mediaType;
24
+ this.stateData = init.stateData;
25
+ this.createdAt = init.createdAt ?? new Date();
26
+ this.groupJid = init.groupJid;
27
+ this.isOffline = init.isOffline ?? false;
28
+ this.callerPn = init.callerPn;
29
+ this.encryptionKey = init.encryptionKey;
30
+ this.relayData = init.relayData;
31
+ this.electedRelayIdx = init.electedRelayIdx;
32
+ }
33
+ static newOutgoing(callId, peerJid, ourJid, mediaType) {
34
+ return new CallInfo({
35
+ callId,
36
+ peerJid,
37
+ callCreator: ourJid,
38
+ direction: CallDirection.Outgoing,
39
+ mediaType,
40
+ stateData: {
41
+ state: CallState.Initiating,
42
+ audioMuted: false,
43
+ videoOff: mediaType !== CallMediaType.Video
44
+ }
45
+ });
46
+ }
47
+ static newIncoming(callId, peerJid, callCreator, callerPn, mediaType) {
48
+ return new CallInfo({
49
+ callId,
50
+ peerJid,
51
+ callCreator,
52
+ direction: CallDirection.Incoming,
53
+ mediaType,
54
+ callerPn,
55
+ stateData: {
56
+ state: CallState.IncomingRinging,
57
+ audioMuted: false,
58
+ videoOff: mediaType !== CallMediaType.Video
59
+ }
60
+ });
61
+ }
62
+ get isInitiator() {
63
+ return this.direction === CallDirection.Outgoing;
64
+ }
65
+ get isActive() {
66
+ return this.stateData.state === CallState.Active;
67
+ }
68
+ get isRinging() {
69
+ return (this.stateData.state === CallState.Ringing ||
70
+ this.stateData.state === CallState.IncomingRinging);
71
+ }
72
+ get isEnded() {
73
+ return this.stateData.state === CallState.Ended;
74
+ }
75
+ get canAccept() {
76
+ return this.stateData.state === CallState.IncomingRinging && !this.stateData.acceptBlocked;
77
+ }
78
+ get isAcceptBlocked() {
79
+ return this.stateData.acceptBlocked === true;
80
+ }
81
+ get canReject() {
82
+ return (this.stateData.state === CallState.IncomingRinging ||
83
+ this.stateData.state === CallState.Ringing);
84
+ }
85
+ applyTransition(transition) {
86
+ const s = this.stateData;
87
+ switch (transition.type) {
88
+ case 'offer_sent':
89
+ if (s.state !== CallState.Initiating) {
90
+ throw new InvalidTransition(s.state, transition.type);
91
+ }
92
+ s.state = CallState.Ringing;
93
+ break;
94
+ case 'offer_received':
95
+ if (s.state !== CallState.Initiating) {
96
+ throw new InvalidTransition(s.state, transition.type);
97
+ }
98
+ s.state = CallState.IncomingRinging;
99
+ s.silenced = transition.silenced;
100
+ break;
101
+ case 'remote_accepted':
102
+ if (s.state !== CallState.Ringing) {
103
+ throw new InvalidTransition(s.state, transition.type);
104
+ }
105
+ s.state = CallState.Connecting;
106
+ s.acceptedAt = new Date();
107
+ break;
108
+ case 'local_accepted':
109
+ if (s.state !== CallState.IncomingRinging) {
110
+ throw new InvalidTransition(s.state, transition.type);
111
+ }
112
+ s.state = CallState.Connecting;
113
+ s.acceptedAt = new Date();
114
+ break;
115
+ case 'remote_rejected':
116
+ if (s.state !== CallState.Ringing) {
117
+ throw new InvalidTransition(s.state, transition.type);
118
+ }
119
+ s.state = CallState.Ended;
120
+ s.endedAt = new Date();
121
+ s.endReason = transition.reason;
122
+ break;
123
+ case 'local_rejected':
124
+ if (s.state !== CallState.IncomingRinging) {
125
+ throw new InvalidTransition(s.state, transition.type);
126
+ }
127
+ s.state = CallState.Ended;
128
+ s.endedAt = new Date();
129
+ s.endReason = transition.reason;
130
+ break;
131
+ case 'media_connected':
132
+ if (s.state !== CallState.Connecting) {
133
+ throw new InvalidTransition(s.state, transition.type);
134
+ }
135
+ s.state = CallState.Active;
136
+ s.connectedAt = new Date();
137
+ s.videoOff = this.mediaType !== CallMediaType.Video;
138
+ break;
139
+ case 'terminated':
140
+ if (s.state === CallState.Ended) {
141
+ throw new InvalidTransition(s.state, transition.type);
142
+ }
143
+ if (s.state === CallState.Active && s.connectedAt) {
144
+ s.durationSecs = Math.floor((Date.now() - s.connectedAt.getTime()) / 1000);
145
+ }
146
+ else if (s.state === CallState.OnHold && s.connectedAt) {
147
+ s.durationSecs = Math.floor((Date.now() - s.connectedAt.getTime()) / 1000);
148
+ }
149
+ s.state = CallState.Ended;
150
+ s.endedAt = new Date();
151
+ s.endReason = transition.reason;
152
+ break;
153
+ case 'hold':
154
+ if (s.state !== CallState.Active) {
155
+ throw new InvalidTransition(s.state, transition.type);
156
+ }
157
+ s.state = CallState.OnHold;
158
+ break;
159
+ case 'resume':
160
+ if (s.state !== CallState.OnHold) {
161
+ throw new InvalidTransition(s.state, transition.type);
162
+ }
163
+ s.state = CallState.Active;
164
+ break;
165
+ case 'audio_mute_changed':
166
+ if (s.state !== CallState.Active) {
167
+ throw new InvalidTransition(s.state, transition.type);
168
+ }
169
+ s.audioMuted = transition.muted;
170
+ break;
171
+ case 'hand_raise_changed':
172
+ if (s.state !== CallState.Active) {
173
+ throw new InvalidTransition(s.state, transition.type);
174
+ }
175
+ s.handRaised = transition.raised;
176
+ break;
177
+ case 'screen_share_changed':
178
+ if (s.state !== CallState.Active) {
179
+ throw new InvalidTransition(s.state, transition.type);
180
+ }
181
+ s.screenSharing = transition.sharing;
182
+ break;
183
+ case 'video_state_changed':
184
+ if (s.state !== CallState.Active) {
185
+ throw new InvalidTransition(s.state, transition.type);
186
+ }
187
+ s.videoOff = transition.off;
188
+ break;
189
+ default:
190
+ throw new InvalidTransition(s.state, transition.type);
191
+ }
192
+ }
193
+ }
194
+ export class InvalidTransition extends Error {
195
+ currentState;
196
+ attempted;
197
+ constructor(currentState, attempted) {
198
+ super(`invalid transition '${attempted}' in state '${currentState}'`);
199
+ this.name = 'InvalidTransition';
200
+ this.currentState = currentState;
201
+ this.attempted = attempted;
202
+ }
203
+ }
@@ -0,0 +1,13 @@
1
+ import { hkdf } from '../shim/crypto.js';
2
+ import { TEXT_ENCODER } from '../bytes.js';
3
+ import { randomBytes } from './primitives.js';
4
+ export function derivePerJidSrtpKey(callKey, deviceJid) {
5
+ const output = hkdf(callKey, null, TEXT_ENCODER.encode(deviceJid), 46);
6
+ return {
7
+ masterKey: output.subarray(0, 16),
8
+ masterSalt: output.subarray(16, 30)
9
+ };
10
+ }
11
+ export function generateCallKey() {
12
+ return randomBytes(32);
13
+ }
@@ -0,0 +1,21 @@
1
+ import { createCipheriv, createHmac, randomBytes as nodeRandomBytes, randomInt as nodeRandomInt } from 'node:crypto';
2
+ import { toBytesView } from '../shim/util.js';
3
+ export function randomBytes(length) {
4
+ return toBytesView(nodeRandomBytes(length));
5
+ }
6
+ export function randomInt(min, max) {
7
+ return nodeRandomInt(min, max);
8
+ }
9
+ export function hmacSha1(key, ...parts) {
10
+ const hmac = createHmac('sha1', key);
11
+ for (const part of parts) {
12
+ hmac.update(part);
13
+ }
14
+ return toBytesView(hmac.digest());
15
+ }
16
+ export function aesCtr128(key, iv, data) {
17
+ const cipher = createCipheriv('aes-128-ctr', key, iv);
18
+ const output = toBytesView(cipher.update(data));
19
+ cipher.final();
20
+ return output;
21
+ }
@@ -0,0 +1,66 @@
1
+ import { writeUInt32BE, writeBigUInt64BE } from '../bytes.js';
2
+ import { aesCtr128, hmacSha1 } from './primitives.js';
3
+ import { RTCP_AUTH_TAG_LEN, SRTCP_LABEL } from '../types.js';
4
+
5
+ const RTCP_HEADER_LEN = 8;
6
+
7
+ function deriveKey(masterKey, masterSalt, label, length) {
8
+ const iv = new Uint8Array(16);
9
+ iv.set(masterSalt.subarray(0, 14), 0);
10
+ iv[7] ^= label;
11
+ const zeros = new Uint8Array(length);
12
+ return aesCtr128(masterKey, iv, zeros);
13
+ }
14
+
15
+ export class SrtcpSendContext {
16
+ #cipherKey;
17
+ #authKey;
18
+ #salt;
19
+ #index = 1;
20
+ #ssrcBuffer = new Uint8Array(4);
21
+ #ivBuffer = new Uint8Array(16);
22
+ #indexBuffer = new Uint8Array(8);
23
+
24
+ constructor(keying) {
25
+ this.#cipherKey = deriveKey(keying.masterKey, keying.masterSalt, SRTCP_LABEL.ENCRYPTION, 16);
26
+ this.#authKey = deriveKey(keying.masterKey, keying.masterSalt, SRTCP_LABEL.AUTH, 20);
27
+ this.#salt = deriveKey(keying.masterKey, keying.masterSalt, SRTCP_LABEL.SALT, 14);
28
+ }
29
+
30
+ #generateIv(ssrc, roc, seq) {
31
+ this.#ivBuffer.fill(0);
32
+ this.#ivBuffer.set(this.#salt.subarray(0, 14), 0);
33
+ writeUInt32BE(this.#ssrcBuffer, ssrc, 0);
34
+ for (let i = 0; i < 4; i++) this.#ivBuffer[4 + i] ^= this.#ssrcBuffer[i];
35
+ const index = (BigInt(roc >>> 0) << 16n) | BigInt(seq & 0xffff);
36
+ writeBigUInt64BE(this.#indexBuffer, index, 0);
37
+ for (let i = 0; i < 6; i++) this.#ivBuffer[8 + i] ^= this.#indexBuffer[2 + i];
38
+ return this.#ivBuffer;
39
+ }
40
+
41
+ protect(senderSsrc, rtcpPacket) {
42
+ const splitAt = Math.min(rtcpPacket.length, RTCP_HEADER_LEN);
43
+ const header = rtcpPacket.subarray(0, splitAt);
44
+ const body = rtcpPacket.subarray(splitAt);
45
+
46
+ const index = this.#index >>> 0;
47
+ this.#index = (this.#index + 1) >>> 0;
48
+
49
+ const roc = index >>> 16;
50
+ const seq = index & 0xffff;
51
+ const iv = this.#generateIv(senderSsrc, roc, seq);
52
+ const encryptedBody = aesCtr128(this.#cipherKey, iv, body);
53
+
54
+ const withIndexWord = new Uint8Array(header.length + encryptedBody.length + 4);
55
+ withIndexWord.set(header, 0);
56
+ withIndexWord.set(encryptedBody, header.length);
57
+ writeUInt32BE(withIndexWord, 0x80000000 | index, header.length + encryptedBody.length);
58
+
59
+ const tag = hmacSha1(this.#authKey, withIndexWord).subarray(0, RTCP_AUTH_TAG_LEN);
60
+
61
+ const out = new Uint8Array(withIndexWord.length + RTCP_AUTH_TAG_LEN);
62
+ out.set(withIndexWord, 0);
63
+ out.set(tag, withIndexWord.length);
64
+ return out;
65
+ }
66
+ }
@@ -0,0 +1,180 @@
1
+ import { uint8TimingSafeEqual } from '../shim/util.js';
2
+ import { writeBigUInt64BE, writeUInt32BE } from '../bytes.js';
3
+ import { RtpHeader, RtpPacket } from '../media/rtp.js';
4
+ import { SRTP_AUTH_TAG_LEN, SRTP_LABEL } from '../types.js';
5
+ import { aesCtr128, hmacSha1 } from './primitives.js';
6
+ const SRTP_REPLAY_WINDOW = 64n;
7
+ const SRTP_INDEX_MASK = (1n << 64n) - 1n;
8
+ export class SrtpContext {
9
+ sessionKey;
10
+ sessionSalt;
11
+ authKey;
12
+ roc = 0;
13
+ lastSeq = 0;
14
+ initialized = false;
15
+ highestIndex = 0n;
16
+ replayMask = 0n;
17
+ authTagLen;
18
+ ivBuffer = new Uint8Array(16);
19
+ ssrcBuffer = new Uint8Array(4);
20
+ indexBuffer = new Uint8Array(8);
21
+ rocBuffer = new Uint8Array(4);
22
+ constructor(keying, authTagLen) {
23
+ this.authTagLen = authTagLen ?? SRTP_AUTH_TAG_LEN;
24
+ this.sessionKey = deriveKey(keying.masterKey, keying.masterSalt, SRTP_LABEL.ENCRYPTION, 16);
25
+ this.authKey = deriveKey(keying.masterKey, keying.masterSalt, SRTP_LABEL.AUTH, 20);
26
+ this.sessionSalt = deriveKey(keying.masterKey, keying.masterSalt, SRTP_LABEL.SALT, 14);
27
+ }
28
+ setAuthKeying(keying) {
29
+ this.authKey = deriveKey(keying.masterKey, keying.masterSalt, SRTP_LABEL.AUTH, 20);
30
+ }
31
+ protect(packet) {
32
+ this.updateRoc(packet.header.sequenceNumber);
33
+ const index = this.packetIndex(packet.header.sequenceNumber);
34
+ const headerSize = packet.header.size();
35
+ const output = new Uint8Array(headerSize + packet.payload.length + this.authTagLen);
36
+ packet.header.encode(output);
37
+ const iv = this.generateIv(packet.header.ssrc, index);
38
+ const encrypted = aesCtr128(this.sessionKey, iv, packet.payload);
39
+ output.set(encrypted, headerSize);
40
+ if (this.authTagLen > 0) {
41
+ const authData = output.subarray(0, headerSize + packet.payload.length);
42
+ const tag = this.computeAuthTag(authData, this.roc, this.authTagLen);
43
+ output.set(tag, headerSize + packet.payload.length);
44
+ }
45
+ return output;
46
+ }
47
+ unprotect(data) {
48
+ if (data.length < 12) {
49
+ throw new SrtpError('packet_too_short', `Packet too short: ${data.length} bytes`);
50
+ }
51
+ const header = RtpHeader.decode(data);
52
+ const headerSize = header.size();
53
+ const payloadLen = data.length - headerSize - this.authTagLen;
54
+ if (payloadLen <= 0) {
55
+ throw new SrtpError('packet_too_short', `No payload: ${data.length}B total, ${headerSize}B header, auth=${this.authTagLen}`);
56
+ }
57
+ const seq = header.sequenceNumber;
58
+ const estimatedRoc = this.estimateRoc(seq);
59
+ const index = (BigInt(estimatedRoc) << 16n) | BigInt(seq);
60
+ if (this.isReplayed(index)) {
61
+ throw new SrtpError('replay', `SRTP replay detected: index ${index}`);
62
+ }
63
+ if (this.authTagLen > 0) {
64
+ const authStart = headerSize + payloadLen;
65
+ const authData = data.subarray(0, authStart);
66
+ const expected = this.computeAuthTag(authData, estimatedRoc, this.authTagLen);
67
+ const received = data.subarray(authStart, authStart + this.authTagLen);
68
+ if (!uint8TimingSafeEqual(expected, received)) {
69
+ throw new SrtpError('auth_failed', 'SRTP auth tag verification failed');
70
+ }
71
+ }
72
+ const iv = this.generateIv(header.ssrc, index);
73
+ const decrypted = aesCtr128(this.sessionKey, iv, data.subarray(headerSize, headerSize + payloadLen));
74
+ this.advanceReplay(index, estimatedRoc, seq);
75
+ return new RtpPacket(header, decrypted);
76
+ }
77
+ updateRoc(seq) {
78
+ if (!this.initialized) {
79
+ this.lastSeq = seq;
80
+ this.initialized = true;
81
+ return;
82
+ }
83
+ const diff = seq - this.lastSeq;
84
+ if (diff < -32768) {
85
+ this.roc = (this.roc + 1) >>> 0;
86
+ }
87
+ this.lastSeq = seq;
88
+ }
89
+ estimateRoc(seq) {
90
+ if (!this.initialized) {
91
+ return this.roc;
92
+ }
93
+ if (this.lastSeq < 32768) {
94
+ return seq - this.lastSeq > 32768 ? (this.roc - 1) >>> 0 : this.roc;
95
+ }
96
+ return this.lastSeq - seq > 32768 ? (this.roc + 1) >>> 0 : this.roc;
97
+ }
98
+ isReplayed(index) {
99
+ if (!this.initialized) {
100
+ return false;
101
+ }
102
+ if (index > this.highestIndex) {
103
+ return false;
104
+ }
105
+ const offset = this.highestIndex - index;
106
+ if (offset >= SRTP_REPLAY_WINDOW) {
107
+ return true;
108
+ }
109
+ return (this.replayMask & (1n << offset)) !== 0n;
110
+ }
111
+ advanceReplay(index, estimatedRoc, seq) {
112
+ if (this.initialized && index <= this.highestIndex) {
113
+ const offset = this.highestIndex - index;
114
+ if (offset < SRTP_REPLAY_WINDOW) {
115
+ this.replayMask |= 1n << offset;
116
+ }
117
+ return;
118
+ }
119
+ const shift = this.initialized ? index - this.highestIndex : SRTP_REPLAY_WINDOW;
120
+ this.replayMask =
121
+ shift >= SRTP_REPLAY_WINDOW ? 1n : ((this.replayMask << shift) | 1n) & SRTP_INDEX_MASK;
122
+ this.highestIndex = index;
123
+ this.roc = estimatedRoc;
124
+ this.lastSeq = seq;
125
+ this.initialized = true;
126
+ }
127
+ packetIndex(seq) {
128
+ return (BigInt(this.roc) << 16n) | BigInt(seq);
129
+ }
130
+ generateIv(ssrc, index) {
131
+ this.ivBuffer.fill(0);
132
+ this.ivBuffer.set(this.sessionSalt.subarray(0, 14), 0);
133
+ writeUInt32BE(this.ssrcBuffer, ssrc, 0);
134
+ for (let i = 0; i < 4; i++) {
135
+ this.ivBuffer[4 + i] ^= this.ssrcBuffer[i];
136
+ }
137
+ writeBigUInt64BE(this.indexBuffer, index, 0);
138
+ for (let i = 0; i < 6; i++) {
139
+ this.ivBuffer[8 + i] ^= this.indexBuffer[2 + i];
140
+ }
141
+ return this.ivBuffer;
142
+ }
143
+ computeAuthTag(data, roc, tagLen = SRTP_AUTH_TAG_LEN) {
144
+ writeUInt32BE(this.rocBuffer, roc, 0);
145
+ const result = hmacSha1(this.authKey, data, this.rocBuffer);
146
+ return result.subarray(0, tagLen);
147
+ }
148
+ }
149
+ export class SrtpSession {
150
+ sendCtx;
151
+ recvCtx;
152
+ constructor(sendKey, recvKey, sendAuthLen, recvAuthLen) {
153
+ this.sendCtx = new SrtpContext(sendKey, sendAuthLen);
154
+ this.recvCtx = new SrtpContext(recvKey, recvAuthLen);
155
+ }
156
+ protect(packet) {
157
+ return this.sendCtx.protect(packet);
158
+ }
159
+ unprotect(data) {
160
+ return this.recvCtx.unprotect(data);
161
+ }
162
+ setSendAuthKeying(keying) {
163
+ this.sendCtx.setAuthKeying(keying);
164
+ }
165
+ }
166
+ function deriveKey(masterKey, masterSalt, label, length) {
167
+ const iv = new Uint8Array(16);
168
+ iv.set(masterSalt.subarray(0, 14), 0);
169
+ iv[7] ^= label;
170
+ const zeros = new Uint8Array(length);
171
+ return aesCtr128(masterKey, iv, zeros);
172
+ }
173
+ export class SrtpError extends Error {
174
+ type;
175
+ constructor(type, message) {
176
+ super(message);
177
+ this.type = type;
178
+ this.name = 'SrtpError';
179
+ }
180
+ }
@@ -0,0 +1,15 @@
1
+ import { hkdf } from '../shim/crypto.js';
2
+ import { readUInt32LE, TEXT_ENCODER, writeUInt32LE } from '../bytes.js';
3
+ export function generateSecureSsrc(callId, selfJid, counter = 0) {
4
+ const key = TEXT_ENCODER.encode(callId);
5
+ const salt = new Uint8Array(4);
6
+ writeUInt32LE(salt, counter, 0);
7
+ const info = TEXT_ENCODER.encode(selfJid);
8
+ const result = hkdf(key, salt, info, 4);
9
+ return readUInt32LE(result, 0);
10
+ }
11
+
12
+ export const WASM_RELAY_STREAM_SLOT_WORDS = [0, 1, 4, 2, 3, 5, 7, 8, 6];
13
+ export function deriveWasmRelayStreamSsrcs(callId, participantId) {
14
+ return WASM_RELAY_STREAM_SLOT_WORDS.map((slotWord) => generateSecureSsrc(callId, participantId, slotWord));
15
+ }