@codexverified/baileys 2.7.5

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 (139) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +233 -0
  3. package/WAProto/V +1 -0
  4. package/WAProto/WAProto.proto +8051 -0
  5. package/WAProto/index.js +289292 -0
  6. package/engine-requirements.js +13 -0
  7. package/lib/Defaults/index.js +158 -0
  8. package/lib/Signal/Group/ciphertext-message.js +11 -0
  9. package/lib/Signal/Group/group-session-builder.js +29 -0
  10. package/lib/Signal/Group/group_cipher.js +81 -0
  11. package/lib/Signal/Group/index.js +11 -0
  12. package/lib/Signal/Group/keyhelper.js +17 -0
  13. package/lib/Signal/Group/sender-chain-key.js +25 -0
  14. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  15. package/lib/Signal/Group/sender-key-message.js +65 -0
  16. package/lib/Signal/Group/sender-key-name.js +47 -0
  17. package/lib/Signal/Group/sender-key-record.js +40 -0
  18. package/lib/Signal/Group/sender-key-state.js +83 -0
  19. package/lib/Signal/Group/sender-message-key.js +25 -0
  20. package/lib/Signal/libsignal.js +428 -0
  21. package/lib/Signal/lid-mapping.js +280 -0
  22. package/lib/Socket/Client/index.js +2 -0
  23. package/lib/Socket/Client/types.js +10 -0
  24. package/lib/Socket/Client/websocket.js +53 -0
  25. package/lib/Socket/aigroups.js +315 -0
  26. package/lib/Socket/business.js +407 -0
  27. package/lib/Socket/chats.js +1831 -0
  28. package/lib/Socket/communities.js +431 -0
  29. package/lib/Socket/graphql.js +899 -0
  30. package/lib/Socket/groups.js +549 -0
  31. package/lib/Socket/index.js +79 -0
  32. package/lib/Socket/interactive-handler.js +600 -0
  33. package/lib/Socket/interop.js +563 -0
  34. package/lib/Socket/managed-account.js +208 -0
  35. package/lib/Socket/messages-recv.js +2144 -0
  36. package/lib/Socket/messages-send.js +2030 -0
  37. package/lib/Socket/mex.js +41 -0
  38. package/lib/Socket/newsletter.js +226 -0
  39. package/lib/Socket/privacy.js +446 -0
  40. package/lib/Socket/registration.js +428 -0
  41. package/lib/Socket/socket.js +1017 -0
  42. package/lib/Socket/username.js +229 -0
  43. package/lib/Store/index.js +4 -0
  44. package/lib/Store/make-cache-manager-store.js +89 -0
  45. package/lib/Store/make-in-memory-store.js +420 -0
  46. package/lib/Store/make-ordered-dictionary.js +78 -0
  47. package/lib/Store/object-repository.js +23 -0
  48. package/lib/Types/Auth.js +1 -0
  49. package/lib/Types/Bussines.js +1 -0
  50. package/lib/Types/Call.js +1 -0
  51. package/lib/Types/Chat.js +7 -0
  52. package/lib/Types/Contact.js +1 -0
  53. package/lib/Types/Events.js +1 -0
  54. package/lib/Types/GroupMetadata.js +1 -0
  55. package/lib/Types/Label.js +24 -0
  56. package/lib/Types/LabelAssociation.js +6 -0
  57. package/lib/Types/Message.js +17 -0
  58. package/lib/Types/Mex.js +39 -0
  59. package/lib/Types/Product.js +1 -0
  60. package/lib/Types/RichType.js +22 -0
  61. package/lib/Types/Signal.js +1 -0
  62. package/lib/Types/Socket.js +2 -0
  63. package/lib/Types/State.js +48 -0
  64. package/lib/Types/USync.js +1 -0
  65. package/lib/Types/index.js +25 -0
  66. package/lib/Utils/auth-utils.js +301 -0
  67. package/lib/Utils/bot-planning-replay.js +169 -0
  68. package/lib/Utils/browser-utils.js +28 -0
  69. package/lib/Utils/business.js +230 -0
  70. package/lib/Utils/chat-utils.js +885 -0
  71. package/lib/Utils/companion-reg-client-utils.js +32 -0
  72. package/lib/Utils/consumer-application.js +102 -0
  73. package/lib/Utils/crypto.js +117 -0
  74. package/lib/Utils/decode-wa-message.js +484 -0
  75. package/lib/Utils/event-buffer.js +589 -0
  76. package/lib/Utils/generics.js +388 -0
  77. package/lib/Utils/group-history.js +56 -0
  78. package/lib/Utils/history.js +130 -0
  79. package/lib/Utils/identity-change-handler.js +48 -0
  80. package/lib/Utils/index.js +34 -0
  81. package/lib/Utils/jid-display-normalization.js +209 -0
  82. package/lib/Utils/link-preview.js +84 -0
  83. package/lib/Utils/logger.js +2 -0
  84. package/lib/Utils/lt-hash.js +7 -0
  85. package/lib/Utils/make-mutex.js +32 -0
  86. package/lib/Utils/message-composer.js +467 -0
  87. package/lib/Utils/message-inspect.js +67 -0
  88. package/lib/Utils/message-retry-manager.js +241 -0
  89. package/lib/Utils/messages-media.js +1006 -0
  90. package/lib/Utils/messages.js +1851 -0
  91. package/lib/Utils/meta-ai-msmsg.js +130 -0
  92. package/lib/Utils/meta-compositing.js +194 -0
  93. package/lib/Utils/noise-handler.js +200 -0
  94. package/lib/Utils/offline-node-processor.js +39 -0
  95. package/lib/Utils/pre-key-manager.js +105 -0
  96. package/lib/Utils/process-message.js +527 -0
  97. package/lib/Utils/reporting-utils.js +257 -0
  98. package/lib/Utils/rich-message-utils.js +439 -0
  99. package/lib/Utils/signal.js +200 -0
  100. package/lib/Utils/stanza-ack.js +37 -0
  101. package/lib/Utils/sync-action-utils.js +47 -0
  102. package/lib/Utils/tc-token-utils.js +162 -0
  103. package/lib/Utils/use-multi-file-auth-state.js +120 -0
  104. package/lib/Utils/use-single-file-auth-state.js +96 -0
  105. package/lib/Utils/use-sqlite-auth-state.js +108 -0
  106. package/lib/Utils/validate-connection.js +206 -0
  107. package/lib/Utils/voip-rekey.js +20 -0
  108. package/lib/Utils/welcome-flow.js +217 -0
  109. package/lib/WABinary/constants.js +1463 -0
  110. package/lib/WABinary/decode.js +261 -0
  111. package/lib/WABinary/encode.js +219 -0
  112. package/lib/WABinary/generic-utils.js +227 -0
  113. package/lib/WABinary/index.js +5 -0
  114. package/lib/WABinary/jid-utils.js +95 -0
  115. package/lib/WABinary/types.js +1 -0
  116. package/lib/WAM/BinaryInfo.js +9 -0
  117. package/lib/WAM/constants.js +22852 -0
  118. package/lib/WAM/encode.js +149 -0
  119. package/lib/WAM/index.js +3 -0
  120. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +96 -0
  121. package/lib/WAUSync/Protocols/USyncContactProtocol.js +56 -0
  122. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  123. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  124. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +70 -0
  125. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +28 -0
  126. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +25 -0
  127. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  128. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +34 -0
  129. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  130. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
  131. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  132. package/lib/WAUSync/Protocols/index.js +12 -0
  133. package/lib/WAUSync/USyncQuery.js +201 -0
  134. package/lib/WAUSync/USyncUser.js +54 -0
  135. package/lib/WAUSync/index.js +3 -0
  136. package/lib/antiban.cjs +4726 -0
  137. package/lib/index.d.ts +286 -0
  138. package/lib/index.js +18 -0
  139. package/package.json +121 -0
@@ -0,0 +1,130 @@
1
+ import { proto } from '../../WAProto/index.js';
2
+ import { aesDecryptGCM, hkdf } from './crypto.js';
3
+
4
+ const BOT_MESSAGE_INFO = 'Bot Message';
5
+ const KEY_LENGTH = 32;
6
+
7
+ const unpadRandomMax16 = (value) => {
8
+ const bytes = new Uint8Array(value);
9
+ if (!bytes.length) {
10
+ throw new Error('unpadPkcs7 given empty bytes');
11
+ }
12
+ const padLength = bytes[bytes.length - 1];
13
+ if (padLength > bytes.length) {
14
+ throw new Error(`unpad given ${bytes.length} bytes, but pad is ${padLength}`);
15
+ }
16
+ return new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.length - padLength);
17
+ };
18
+
19
+ const toBuffer = (value) => {
20
+ if (Buffer.isBuffer(value)) return value;
21
+ if (value instanceof Uint8Array) return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
22
+ return Buffer.from(value);
23
+ };
24
+
25
+ // Strips device suffix from LID JIDs: "user:device@lid" "user@lid".
26
+ // jidEncode includes ":0" even for device=0 (user/non-AD form), so normalize both meId and meLid.
27
+ const normalizeLidJid = (jid) => {
28
+ if (!jid || !jid.endsWith('@lid') || !jid.includes(':')) return jid;
29
+ return `${jid.split(':')[0]}@lid`;
30
+ };
31
+
32
+ // Ordered msgId candidates per the Rust BotMessageContext:
33
+ // botEditTargetId when editing, stanzaId for the normal full response, metaTargetId as fallback.
34
+ const selectMsgIdCandidates = (messageKey) => {
35
+ const seen = new Set();
36
+ const result = [];
37
+ for (const id of [messageKey?.botEditTargetId, messageKey?.stanzaId, messageKey?.metaTargetId]) {
38
+ const s = id ? String(id) : '';
39
+ if (s && !seen.has(s)) {
40
+ seen.add(s);
41
+ result.push(s);
42
+ }
43
+ }
44
+ return result;
45
+ };
46
+
47
+ // Ordered target_sender_user_jid candidates per Rust spec (non-AD user JID = no device suffix).
48
+ // jidEncode produces "user:0@lid" for device=0 LID JIDs, so normalize both meId and meLid.
49
+ const selectTargetJidCandidates = (messageKey) => {
50
+ const seen = new Set();
51
+ const result = [];
52
+ for (const jid of [normalizeLidJid(messageKey?.meId), normalizeLidJid(messageKey?.meLid)]) {
53
+ const s = jid ? String(jid) : '';
54
+ if (s && !seen.has(s)) {
55
+ seen.add(s);
56
+ result.push(s);
57
+ }
58
+ }
59
+ return result;
60
+ };
61
+
62
+ const decodeDecryptedMsmsgMessage = (decrypted) => {
63
+ const buf = toBuffer(decrypted);
64
+ try {
65
+ const unpadded = Buffer.from(unpadRandomMax16(buf));
66
+ const decoded = proto.Message.decode(unpadded);
67
+ const hasContent = Object.keys(decoded).some(k => k !== 'messageContextInfo' && decoded[k] != null);
68
+ if (hasContent) return decoded;
69
+ }
70
+ catch {}
71
+ return proto.Message.decode(buf);
72
+ };
73
+
74
+ /**
75
+ * Decrypts <enc type="msmsg"> bot messages.
76
+ *
77
+ * Two-pass HKDF algorithm from bot_message.rs (BotMessageContext):
78
+ * k1 = HKDF(messageSecret, salt=, info="Bot Message", 32)
79
+ * k2 = HKDF(k1, salt=, info=msgID||target_sender_jid||bot_jid, 32)
80
+ * AAD = msgID || 0x00 || bot_user_jid
81
+ * plain = AES-256-GCM.Decrypt(k2, encIv, encPayload, AAD)
82
+ *
83
+ * k1 is shared across all candidates and derived once.
84
+ * AAD always uses bot_user_jid, never target_sender_jid.
85
+ */
86
+ export const decryptMsmsgBotMessage = async (messageSecret, messageKey, msMsg) => {
87
+ if (!messageSecret || (messageSecret instanceof Uint8Array && !messageSecret.byteLength)) {
88
+ throw new Error('Missing required messageSecret for msmsg decryption');
89
+ }
90
+ if (!messageKey?.participant) throw new Error('Missing required participant for msmsg decryption');
91
+ if (!messageKey?.meId) throw new Error('Missing required meId for msmsg decryption');
92
+ if (!msMsg?.encIv) throw new Error('Missing required encIv for msmsg decryption');
93
+ if (!msMsg?.encPayload) throw new Error('Missing required encPayload for msmsg decryption');
94
+
95
+ const msgIdCandidates = selectMsgIdCandidates(messageKey);
96
+ if (!msgIdCandidates.length) throw new Error('Missing required target message id for msmsg decryption');
97
+
98
+ const targetJidCandidates = selectTargetJidCandidates(messageKey);
99
+ if (!targetJidCandidates.length) throw new Error('Missing required target JID for msmsg decryption');
100
+
101
+ const botJidBuf = Buffer.from(String(messageKey.participant));
102
+ const payload = toBuffer(msMsg.encPayload);
103
+ const iv = toBuffer(msMsg.encIv);
104
+
105
+ // k1 depends only on messageSecret derive once and reuse across all candidates
106
+ const baseKey = Buffer.from(hkdf(toBuffer(messageSecret), KEY_LENGTH, { info: BOT_MESSAGE_INFO }));
107
+
108
+ let lastError;
109
+ for (const msgId of msgIdCandidates) {
110
+ // msg_id is always passed as ASCII bytes per Rust spec (msg_id.as_bytes())
111
+ const idBuf = Buffer.from(msgId);
112
+ for (const targetJid of targetJidCandidates) {
113
+ const info = Buffer.concat([idBuf, Buffer.from(targetJid), botJidBuf]);
114
+ const key = Buffer.from(hkdf(baseKey, KEY_LENGTH, { info }));
115
+ const aad = Buffer.concat([idBuf, Buffer.from([0x00]), botJidBuf]);
116
+ try {
117
+ return Buffer.from(aesDecryptGCM(payload, key, iv, aad));
118
+ }
119
+ catch (e) {
120
+ lastError = e;
121
+ }
122
+ }
123
+ }
124
+
125
+ const err = new Error('msmsg decryption failed: all key derivation candidates exhausted');
126
+ err.cause = lastError;
127
+ throw err;
128
+ };
129
+
130
+ export { decodeDecryptedMsmsgMessage };
@@ -0,0 +1,194 @@
1
+ /**
2
+ * Lia@Changes [WIP]
3
+ * Meta Compositing send rich messages with Meta AI-style progress indicator.
4
+ *
5
+ * UNIVERSAL VERSION: Works on ALL WhatsApp clients.
6
+ * - Native Meta AI rendering for compatible clients (Beta, AI-enabled)
7
+ * - Plain text fallback for regular clients (no "Update WhatsApp")
8
+ *
9
+ * metaTyping() shows the "typing..." / planning steps indicator.
10
+ * sendMetaComposited() full flow: typing delete final message.
11
+ *
12
+ * If you use or copy this code, please credit @codexverified/baileys.
13
+ */
14
+
15
+ import { proto } from '../../WAProto/index.js';
16
+ import { prepareRichResponseMessage, wrapToBotForwardedMessage, botMetadataSignature, botMetadataCertificate } from './rich-message-utils.js';
17
+ import { BOT_RENDERING_CONFIG_METADATA } from '../Defaults/index.js';
18
+ import { generateWAMessageFromContent } from './messages.js';
19
+ import { unixTimestampSeconds, delay } from './generics.js';
20
+
21
+ // Step status enum
22
+ export const PlanningStepStatus = {
23
+ IN_PROGRESS: 0,
24
+ DONE: 1,
25
+ FAILED: 2
26
+ };
27
+
28
+ /**
29
+ * Check whether the socket explicitly allows native Meta AI progress rendering.
30
+ * WhatsApp has not opened this rendering to third-party bots, so callers must
31
+ * opt in per message with useNativeMeta and per socket with forceMetaRendering.
32
+ */
33
+ export const supportsMetaRendering = (_jid, config = {}) => {
34
+ return config.forceMetaRendering === true;
35
+ };
36
+
37
+ /**
38
+ * Build a BotProgressIndicatorMetadata object.
39
+ */
40
+ export const buildProgressIndicator = (description, steps = [], estimatedMs) => {
41
+ const stepsMetadata = steps.map(step => {
42
+ const s = {
43
+ statusTitle: step.title,
44
+ status: step.status ?? PlanningStepStatus.IN_PROGRESS
45
+ };
46
+ if (step.body) s.statusBody = step.body;
47
+ if (step.isReasoning) s.isReasoning = true;
48
+ if (step.isEnhancedSearch) s.isEnhancedSearch = true;
49
+ return s;
50
+ });
51
+
52
+ const indicator = { stepsMetadata };
53
+ if (description) indicator.progressDescription = description;
54
+ if (estimatedMs != null) indicator.estimatedCompletionTime = estimatedMs;
55
+ return indicator;
56
+ };
57
+
58
+ /**
59
+ * Build the native Meta AI compositing placeholder (for compatible clients only).
60
+ */
61
+ export const buildCompositingPlaceholder = ({
62
+ description = 'Thinking',
63
+ steps = [],
64
+ estimatedMs,
65
+ placeholderText = ''
66
+ } = {}) => {
67
+ const progressIndicatorMetadata = buildProgressIndicator(description, steps, estimatedMs);
68
+
69
+ const textEncoder = new TextEncoder();
70
+ const unifiedData = textEncoder.encode(JSON.stringify({
71
+ response_id: crypto.randomUUID(),
72
+ sections: placeholderText ? [{
73
+ view_model: {
74
+ primitive: {
75
+ text: placeholderText,
76
+ inline_entities: [],
77
+ __typename: 'GenAIMarkdownTextUXPrimitive'
78
+ },
79
+ __typename: 'GenAISingleLayoutViewModel'
80
+ }
81
+ }] : []
82
+ }));
83
+
84
+ const richResponseMessage = {
85
+ messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
86
+ unifiedResponse: { data: unifiedData },
87
+ submessages: []
88
+ };
89
+
90
+ return {
91
+ messageContextInfo: {
92
+ botMetadata: {
93
+ pluginMetadata: {},
94
+ progressIndicatorMetadata,
95
+ verificationMetadata: {
96
+ proofs: [{
97
+ certificateChain: [
98
+ botMetadataCertificate(684),
99
+ botMetadataCertificate(892)
100
+ ],
101
+ version: 1,
102
+ useCase: 1,
103
+ signature: botMetadataSignature()
104
+ }]
105
+ },
106
+ botRenderingConfigMetadata: BOT_RENDERING_CONFIG_METADATA
107
+ }
108
+ },
109
+ botForwardedMessage: {
110
+ message: { richResponseMessage }
111
+ }
112
+ };
113
+ };
114
+
115
+ /**
116
+ * Build a plain-text placeholder that works on ALL WhatsApp clients.
117
+ */
118
+ export const buildPlainPlaceholder = (description = 'Thinking', steps = [], placeholderText = '') => {
119
+ const stepLines = steps.map(step => {
120
+ const icon = step.status === PlanningStepStatus.DONE ? '' :
121
+ step.status === PlanningStepStatus.FAILED ? '' : '';
122
+ return `${icon} ${step.title}`;
123
+ }).join('\n');
124
+
125
+ let text = `_${description}_`;
126
+ if (stepLines) text += `\n\n${stepLines}`;
127
+ if (placeholderText) text += `\n\n${placeholderText}`;
128
+
129
+ return { text };
130
+ };
131
+
132
+ /**
133
+ * metaTyping sends the progress/compositing indicator.
134
+ * UNIVERSAL: plain text is the default. Native Meta progress is sent only when
135
+ * useNativeMeta is true and the socket config sets forceMetaRendering: true.
136
+ */
137
+ export const metaTyping = async (sock, jid, {
138
+ description = 'Thinking',
139
+ steps = [],
140
+ estimatedMs,
141
+ placeholderText = '',
142
+ useNativeMeta = false
143
+ } = {}) => {
144
+ // Show typing indicator
145
+ await sock.sendPresenceUpdate('composing', jid);
146
+
147
+ if (useNativeMeta && supportsMetaRendering(jid, sock.config)) {
148
+ const placeholder = buildCompositingPlaceholder({
149
+ description, steps, estimatedMs, placeholderText
150
+ });
151
+ return sock.sendMessage(jid, { raw: true, ...placeholder });
152
+ }
153
+
154
+ // Universal fallback: plain text placeholder
155
+ const plainSteps = steps.map(s => ({ ...s, status: PlanningStepStatus.IN_PROGRESS }));
156
+ const placeholder = buildPlainPlaceholder(description, plainSteps, placeholderText);
157
+ return sock.sendMessage(jid, placeholder);
158
+ };
159
+
160
+ /**
161
+ * sendMetaComposited full Meta AI flow (UNIVERSAL).
162
+ * 1. Send progress indicator
163
+ * 2. Wait thinkingMs
164
+ * 3. Delete placeholder
165
+ * 4. Send final message fresh
166
+ */
167
+ export const sendMetaComposited = async (sock, jid, content, {
168
+ thinkingMs = 2000,
169
+ description = 'Thinking',
170
+ steps = [],
171
+ placeholderText = '',
172
+ sendOptions = {},
173
+ useNativeMeta = false
174
+ } = {}) => {
175
+ const placeholder = await metaTyping(sock, jid, {
176
+ description, steps, estimatedMs: thinkingMs, placeholderText, useNativeMeta
177
+ });
178
+
179
+ try {
180
+ await delay(thinkingMs);
181
+ if (placeholder?.key) {
182
+ await sock.sendMessage(jid, { delete: placeholder.key });
183
+ }
184
+ } catch (_) {}
185
+
186
+ await sock.sendPresenceUpdate('paused', jid);
187
+ return sock.sendMessage(jid, content, sendOptions);
188
+ };
189
+
190
+ /**
191
+ * Convenience: build a steps array from plain strings.
192
+ */
193
+ export const buildSteps = (titles, status = PlanningStepStatus.IN_PROGRESS) =>
194
+ titles.map(title => ({ title, status }));
@@ -0,0 +1,200 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { proto } from '../../WAProto/index.js';
3
+ import { NOISE_MODE, WA_CERT_DETAILS } from '../Defaults/index.js';
4
+ import { decodeBinaryNode } from '../WABinary/index.js';
5
+ import { aesDecryptGCM, aesEncryptGCM, Curve, hkdf, sha256 } from './crypto.js';
6
+ const IV_LENGTH = 12;
7
+ const EMPTY_BUFFER = Buffer.alloc(0);
8
+ const generateIV = (counter) => {
9
+ const iv = new ArrayBuffer(IV_LENGTH);
10
+ new DataView(iv).setUint32(8, counter);
11
+ return new Uint8Array(iv);
12
+ };
13
+ class TransportState {
14
+ constructor(encKey, decKey) {
15
+ this.encKey = encKey;
16
+ this.decKey = decKey;
17
+ this.readCounter = 0;
18
+ this.writeCounter = 0;
19
+ this.iv = new Uint8Array(IV_LENGTH);
20
+ }
21
+ encrypt(plaintext) {
22
+ const c = this.writeCounter++;
23
+ this.iv[8] = (c >>> 24) & 0xff;
24
+ this.iv[9] = (c >>> 16) & 0xff;
25
+ this.iv[10] = (c >>> 8) & 0xff;
26
+ this.iv[11] = c & 0xff;
27
+ return aesEncryptGCM(plaintext, this.encKey, this.iv, EMPTY_BUFFER);
28
+ }
29
+ decrypt(ciphertext) {
30
+ const c = this.readCounter++;
31
+ this.iv[8] = (c >>> 24) & 0xff;
32
+ this.iv[9] = (c >>> 16) & 0xff;
33
+ this.iv[10] = (c >>> 8) & 0xff;
34
+ this.iv[11] = c & 0xff;
35
+ return aesDecryptGCM(ciphertext, this.decKey, this.iv, EMPTY_BUFFER);
36
+ }
37
+ }
38
+ export const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, logger, routingInfo }) => {
39
+ logger = logger.child({ class: 'ns' });
40
+ const data = Buffer.from(NOISE_MODE);
41
+ let hash = data.byteLength === 32 ? data : sha256(data);
42
+ let salt = hash;
43
+ let encKey = hash;
44
+ let decKey = hash;
45
+ let counter = 0;
46
+ let sentIntro = false;
47
+ let inBytes = Buffer.alloc(0);
48
+ let transport = null;
49
+ let isWaitingForTransport = false;
50
+ let pendingOnFrame = null;
51
+ let introHeader;
52
+ if (routingInfo) {
53
+ introHeader = Buffer.alloc(7 + routingInfo.byteLength + NOISE_HEADER.length);
54
+ introHeader.write('ED', 0, 'utf8');
55
+ introHeader.writeUint8(0, 2);
56
+ introHeader.writeUint8(1, 3);
57
+ introHeader.writeUint8(routingInfo.byteLength >> 16, 4);
58
+ introHeader.writeUint16BE(routingInfo.byteLength & 65535, 5);
59
+ introHeader.set(routingInfo, 7);
60
+ introHeader.set(NOISE_HEADER, 7 + routingInfo.byteLength);
61
+ }
62
+ else {
63
+ introHeader = Buffer.from(NOISE_HEADER);
64
+ }
65
+ const authenticate = (data) => {
66
+ if (!transport) {
67
+ hash = sha256(Buffer.concat([hash, data]));
68
+ }
69
+ };
70
+ const encrypt = (plaintext) => {
71
+ if (transport) {
72
+ return transport.encrypt(plaintext);
73
+ }
74
+ const result = aesEncryptGCM(plaintext, encKey, generateIV(counter++), hash);
75
+ authenticate(result);
76
+ return result;
77
+ };
78
+ const decrypt = (ciphertext) => {
79
+ if (transport) {
80
+ return transport.decrypt(ciphertext);
81
+ }
82
+ const result = aesDecryptGCM(ciphertext, decKey, generateIV(counter++), hash);
83
+ authenticate(ciphertext);
84
+ return result;
85
+ };
86
+ const localHKDF = (data) => {
87
+ const key = hkdf(Buffer.from(data), 64, { salt, info: '' });
88
+ return [key.subarray(0, 32), key.subarray(32)];
89
+ };
90
+ const mixIntoKey = (data) => {
91
+ const [write, read] = localHKDF(data);
92
+ salt = write;
93
+ encKey = read;
94
+ decKey = read;
95
+ counter = 0;
96
+ };
97
+ const finishInit = async () => {
98
+ isWaitingForTransport = true;
99
+ const [write, read] = localHKDF(new Uint8Array(0));
100
+ transport = new TransportState(write, read);
101
+ isWaitingForTransport = false;
102
+ logger.trace('Noise handler transitioned to Transport state');
103
+ if (pendingOnFrame) {
104
+ logger.trace({ length: inBytes.length }, 'Flushing buffered frames after transport ready');
105
+ await processData(pendingOnFrame);
106
+ pendingOnFrame = null;
107
+ }
108
+ };
109
+ const processData = async (onFrame) => {
110
+ let size;
111
+ while (true) {
112
+ if (inBytes.length < 3)
113
+ return;
114
+ size = (inBytes[0] << 16) | (inBytes[1] << 8) | inBytes[2];
115
+ if (inBytes.length < size + 3)
116
+ return;
117
+ let frame = inBytes.subarray(3, size + 3);
118
+ inBytes = inBytes.subarray(size + 3);
119
+ if (transport) {
120
+ const result = transport.decrypt(frame);
121
+ frame = await decodeBinaryNode(result);
122
+ }
123
+ if (logger.level === 'trace') {
124
+ logger.trace({ msg: frame?.attrs?.id }, 'recv frame');
125
+ }
126
+ onFrame(frame);
127
+ }
128
+ };
129
+ authenticate(NOISE_HEADER);
130
+ authenticate(publicKey);
131
+ return {
132
+ encrypt,
133
+ decrypt,
134
+ authenticate,
135
+ mixIntoKey,
136
+ finishInit,
137
+ processHandshake: ({ serverHello }, noiseKey) => {
138
+ authenticate(serverHello.ephemeral);
139
+ mixIntoKey(Curve.sharedKey(privateKey, serverHello.ephemeral));
140
+ const decStaticContent = decrypt(serverHello.static);
141
+ mixIntoKey(Curve.sharedKey(privateKey, decStaticContent));
142
+ const certDecoded = decrypt(serverHello.payload);
143
+ const { intermediate: certIntermediate, leaf } = proto.CertChain.decode(certDecoded);
144
+ // leaf
145
+ if (!leaf?.details || !leaf?.signature) {
146
+ throw new Boom('invalid noise leaf certificate', { statusCode: 400 });
147
+ }
148
+ if (!certIntermediate?.details || !certIntermediate?.signature) {
149
+ throw new Boom('invalid noise intermediate certificate', { statusCode: 400 });
150
+ }
151
+ const details = proto.CertChain.NoiseCertificate.Details.decode(certIntermediate.details);
152
+ const { issuerSerial } = details;
153
+ const verify = Curve.verify(details.key, leaf.details, leaf.signature);
154
+ const verifyIntermediate = Curve.verify(WA_CERT_DETAILS.PUBLIC_KEY, certIntermediate.details, certIntermediate.signature);
155
+ if (!verify) {
156
+ throw new Boom('noise certificate signature invalid', { statusCode: 400 });
157
+ }
158
+ if (!verifyIntermediate) {
159
+ throw new Boom('noise intermediate certificate signature invalid', { statusCode: 400 });
160
+ }
161
+ if (issuerSerial !== WA_CERT_DETAILS.SERIAL) {
162
+ throw new Boom('certification match failed', { statusCode: 400 });
163
+ }
164
+ const keyEnc = encrypt(noiseKey.public);
165
+ mixIntoKey(Curve.sharedKey(noiseKey.private, serverHello.ephemeral));
166
+ return keyEnc;
167
+ },
168
+ encodeFrame: (data) => {
169
+ if (transport) {
170
+ data = transport.encrypt(data);
171
+ }
172
+ const dataLen = data.byteLength;
173
+ const introSize = sentIntro ? 0 : introHeader.length;
174
+ const frame = Buffer.allocUnsafe(introSize + 3 + dataLen);
175
+ if (!sentIntro) {
176
+ frame.set(introHeader);
177
+ sentIntro = true;
178
+ }
179
+ frame[introSize] = (dataLen >>> 16) & 0xff;
180
+ frame[introSize + 1] = (dataLen >>> 8) & 0xff;
181
+ frame[introSize + 2] = dataLen & 0xff;
182
+ frame.set(data, introSize + 3);
183
+ return frame;
184
+ },
185
+ decodeFrame: async (newData, onFrame) => {
186
+ if (isWaitingForTransport) {
187
+ inBytes = Buffer.concat([inBytes, newData]);
188
+ pendingOnFrame = onFrame;
189
+ return;
190
+ }
191
+ if (inBytes.length === 0) {
192
+ inBytes = Buffer.from(newData);
193
+ }
194
+ else {
195
+ inBytes = Buffer.concat([inBytes, newData]);
196
+ }
197
+ await processData(onFrame);
198
+ }
199
+ };
200
+ };
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Creates a processor for offline stanza nodes that:
3
+ * - Queues nodes for sequential processing
4
+ * - Yields to the event loop periodically to avoid blocking
5
+ * - Catches handler errors to prevent the processing loop from crashing
6
+ */
7
+ export function makeOfflineNodeProcessor(nodeProcessorMap, deps, batchSize = 10) {
8
+ const nodes = [];
9
+ let isProcessing = false;
10
+ const enqueue = (type, node) => {
11
+ nodes.push({ type, node });
12
+ if (isProcessing) {
13
+ return;
14
+ }
15
+ isProcessing = true;
16
+ const promise = async () => {
17
+ let processedInBatch = 0;
18
+ while (nodes.length && deps.isWsOpen()) {
19
+ const { type, node } = nodes.shift();
20
+ const nodeProcessor = nodeProcessorMap.get(type);
21
+ if (!nodeProcessor) {
22
+ deps.onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node');
23
+ continue;
24
+ }
25
+ await nodeProcessor(node).catch(err => deps.onUnexpectedError(err, `processing offline ${type}`));
26
+ processedInBatch++;
27
+ // Yield to event loop after processing a batch
28
+ // This prevents blocking the event loop for too long when there are many offline nodes
29
+ if (processedInBatch >= batchSize) {
30
+ processedInBatch = 0;
31
+ await deps.yieldToEventLoop();
32
+ }
33
+ }
34
+ isProcessing = false;
35
+ };
36
+ promise().catch(error => deps.onUnexpectedError(error, 'processing offline nodes'));
37
+ };
38
+ return { enqueue };
39
+ }
@@ -0,0 +1,105 @@
1
+ import PQueue from 'p-queue';
2
+ /**
3
+ * Manages pre-key operations with proper concurrency control
4
+ */
5
+ export class PreKeyManager {
6
+ constructor(store, logger) {
7
+ this.store = store;
8
+ this.logger = logger;
9
+ this.queues = new Map();
10
+ }
11
+ /**
12
+ * Get or create a queue for a specific key type
13
+ */
14
+ getQueue(keyType) {
15
+ if (!this.queues.has(keyType)) {
16
+ this.queues.set(keyType, new PQueue({ concurrency: 1 }));
17
+ }
18
+ return this.queues.get(keyType);
19
+ }
20
+ /**
21
+ * Process pre-key operations (updates and deletions)
22
+ */
23
+ async processOperations(data, keyType, transactionCache, mutations, isInTransaction) {
24
+ const keyData = data[keyType];
25
+ if (!keyData)
26
+ return;
27
+ return this.getQueue(keyType).add(async () => {
28
+ // Ensure structures exist
29
+ transactionCache[keyType] = transactionCache[keyType] || {};
30
+ mutations[keyType] = mutations[keyType] || {};
31
+ // Separate deletions from updates
32
+ const deletions = [];
33
+ const updates = {};
34
+ for (const keyId in keyData) {
35
+ if (keyData[keyId] === null) {
36
+ deletions.push(keyId);
37
+ }
38
+ else {
39
+ updates[keyId] = keyData[keyId];
40
+ }
41
+ }
42
+ // Process updates (no validation needed)
43
+ if (Object.keys(updates).length > 0) {
44
+ Object.assign(transactionCache[keyType], updates);
45
+ Object.assign(mutations[keyType], updates);
46
+ }
47
+ // Process deletions with validation
48
+ if (deletions.length > 0) {
49
+ await this.processDeletions(keyType, deletions, transactionCache, mutations, isInTransaction);
50
+ }
51
+ });
52
+ }
53
+ /**
54
+ * Process deletions with validation
55
+ */
56
+ async processDeletions(keyType, ids, transactionCache, mutations, isInTransaction) {
57
+ if (isInTransaction) {
58
+ // In transaction, only allow deletion if key exists in cache
59
+ for (const keyId of ids) {
60
+ if (transactionCache[keyType]?.[keyId]) {
61
+ transactionCache[keyType][keyId] = null;
62
+ mutations[keyType][keyId] = null;
63
+ }
64
+ else {
65
+ this.logger.warn(`Skipping deletion of non-existent ${keyType} in transaction: ${keyId}`);
66
+ }
67
+ }
68
+ }
69
+ else {
70
+ // Outside transaction, validate against store
71
+ const existingKeys = await this.store.get(keyType, ids);
72
+ for (const keyId of ids) {
73
+ if (existingKeys[keyId]) {
74
+ transactionCache[keyType][keyId] = null;
75
+ mutations[keyType][keyId] = null;
76
+ }
77
+ else {
78
+ this.logger.warn(`Skipping deletion of non-existent ${keyType}: ${keyId}`);
79
+ }
80
+ }
81
+ }
82
+ }
83
+ /**
84
+ * Validate and process pre-key deletions outside transactions
85
+ */
86
+ async validateDeletions(data, keyType) {
87
+ const keyData = data[keyType];
88
+ if (!keyData)
89
+ return;
90
+ return this.getQueue(keyType).add(async () => {
91
+ // Find all deletion requests
92
+ const deletionIds = Object.keys(keyData).filter(id => keyData[id] === null);
93
+ if (deletionIds.length === 0)
94
+ return;
95
+ // Validate deletions
96
+ const existingKeys = await this.store.get(keyType, deletionIds);
97
+ for (const keyId of deletionIds) {
98
+ if (!existingKeys[keyId]) {
99
+ this.logger.warn(`Skipping deletion of non-existent ${keyType}: ${keyId}`);
100
+ delete data[keyType][keyId];
101
+ }
102
+ }
103
+ });
104
+ }
105
+ }