@x4r1s3/baileys 0.0.0-stage → 1.0.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 (183) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1262 -2
  3. package/SECURITY.md +47 -0
  4. package/WAProto/V +1 -0
  5. package/WAProto/WAProto.proto +8892 -0
  6. package/WAProto/index.d.ts +104128 -0
  7. package/WAProto/index.js +334920 -0
  8. package/assets/rolling-circle.svg +133 -0
  9. package/assets/x4r1s3-banner.svg +32 -0
  10. package/engine-requirements.js +27 -0
  11. package/lib/Builders/A2UI.js +245 -0
  12. package/lib/Builders/AIRich.js +179 -0
  13. package/lib/Builders/Button.js +108 -0
  14. package/lib/Builders/CFC.js +284 -0
  15. package/lib/Builders/Carousel.js +81 -0
  16. package/lib/Call/THIRD_PARTY_LICENSE.txt +21 -0
  17. package/lib/Call/audio-feeder.mjs +179 -0
  18. package/lib/Call/audio-recorder.mjs +250 -0
  19. package/lib/Call/fetch-wasm-resources.mjs +104 -0
  20. package/lib/Call/index.mjs +680 -0
  21. package/lib/Call/relay-transport.mjs +563 -0
  22. package/lib/Call/signaling.mjs +641 -0
  23. package/lib/Call/types.mjs +17 -0
  24. package/lib/Call/video-feeder.mjs +94 -0
  25. package/lib/Call/wasm-engine.mjs +1372 -0
  26. package/lib/Call/worker-bootstrap.mjs +1042 -0
  27. package/lib/Defaults/ban-checker.js +56 -0
  28. package/lib/Defaults/index.js +170 -0
  29. package/lib/Signal/Group/ciphertext-message.js +23 -0
  30. package/lib/Signal/Group/group-session-builder.js +41 -0
  31. package/lib/Signal/Group/group_cipher.js +93 -0
  32. package/lib/Signal/Group/index.js +23 -0
  33. package/lib/Signal/Group/keyhelper.js +29 -0
  34. package/lib/Signal/Group/sender-chain-key.js +37 -0
  35. package/lib/Signal/Group/sender-key-distribution-message.js +74 -0
  36. package/lib/Signal/Group/sender-key-message.js +77 -0
  37. package/lib/Signal/Group/sender-key-name.js +59 -0
  38. package/lib/Signal/Group/sender-key-record.js +52 -0
  39. package/lib/Signal/Group/sender-key-state.js +95 -0
  40. package/lib/Signal/Group/sender-message-key.js +37 -0
  41. package/lib/Signal/libsignal.js +440 -0
  42. package/lib/Signal/lid-mapping.js +292 -0
  43. package/lib/Socket/Client/index.js +14 -0
  44. package/lib/Socket/Client/types.js +22 -0
  45. package/lib/Socket/Client/websocket.js +65 -0
  46. package/lib/Socket/aigroups.js +327 -0
  47. package/lib/Socket/ban-checker.js +165 -0
  48. package/lib/Socket/business.js +419 -0
  49. package/lib/Socket/chats.js +1921 -0
  50. package/lib/Socket/communities.js +443 -0
  51. package/lib/Socket/graphql.js +911 -0
  52. package/lib/Socket/groups.js +561 -0
  53. package/lib/Socket/index.js +49 -0
  54. package/lib/Socket/interactive-handler.js +612 -0
  55. package/lib/Socket/interop.js +575 -0
  56. package/lib/Socket/managed-account.js +220 -0
  57. package/lib/Socket/messages-recv.js +2191 -0
  58. package/lib/Socket/messages-send.js +4104 -0
  59. package/lib/Socket/mex.js +53 -0
  60. package/lib/Socket/newsletter.js +291 -0
  61. package/lib/Socket/privacy.js +458 -0
  62. package/lib/Socket/registration.js +440 -0
  63. package/lib/Socket/socket.js +1029 -0
  64. package/lib/Socket/status-actions.js +287 -0
  65. package/lib/Socket/username.js +241 -0
  66. package/lib/Store/index.js +16 -0
  67. package/lib/Store/make-cache-manager-store.js +101 -0
  68. package/lib/Store/make-in-memory-store.js +432 -0
  69. package/lib/Store/make-ordered-dictionary.js +90 -0
  70. package/lib/Store/object-repository.js +35 -0
  71. package/lib/Types/Auth.js +13 -0
  72. package/lib/Types/Bussines.js +13 -0
  73. package/lib/Types/Call.js +13 -0
  74. package/lib/Types/Chat.js +19 -0
  75. package/lib/Types/Contact.js +13 -0
  76. package/lib/Types/Events.js +13 -0
  77. package/lib/Types/GroupMetadata.js +13 -0
  78. package/lib/Types/Label.js +36 -0
  79. package/lib/Types/LabelAssociation.js +18 -0
  80. package/lib/Types/Message.js +30 -0
  81. package/lib/Types/Mex.js +53 -0
  82. package/lib/Types/Product.js +13 -0
  83. package/lib/Types/RichType.js +34 -0
  84. package/lib/Types/Signal.js +13 -0
  85. package/lib/Types/Socket.js +14 -0
  86. package/lib/Types/State.js +60 -0
  87. package/lib/Types/USync.js +13 -0
  88. package/lib/Types/index.js +37 -0
  89. package/lib/Utils/auth-utils.js +313 -0
  90. package/lib/Utils/ban-checker.js +48 -0
  91. package/lib/Utils/bot-capabilities.js +96 -0
  92. package/lib/Utils/bot-planning-replay.js +177 -0
  93. package/lib/Utils/browser-utils.js +40 -0
  94. package/lib/Utils/business.js +242 -0
  95. package/lib/Utils/c2582.js +147 -0
  96. package/lib/Utils/chat-utils.js +905 -0
  97. package/lib/Utils/companion-reg-client-utils.js +44 -0
  98. package/lib/Utils/consumer-application.js +114 -0
  99. package/lib/Utils/crypto.js +129 -0
  100. package/lib/Utils/decode-wa-message.js +496 -0
  101. package/lib/Utils/direct-chat-theme.js +164 -0
  102. package/lib/Utils/event-buffer.js +601 -0
  103. package/lib/Utils/experimental-proto.js +206 -0
  104. package/lib/Utils/games/miniapp.js +17 -0
  105. package/lib/Utils/games/slot-machine.js +270 -0
  106. package/lib/Utils/games/website-preview.js +306 -0
  107. package/lib/Utils/generics.js +402 -0
  108. package/lib/Utils/group-history.js +68 -0
  109. package/lib/Utils/group-wallpaper.js +168 -0
  110. package/lib/Utils/history.js +162 -0
  111. package/lib/Utils/identity-change-handler.js +60 -0
  112. package/lib/Utils/index.js +61 -0
  113. package/lib/Utils/jid-display-normalization.js +221 -0
  114. package/lib/Utils/link-preview.js +96 -0
  115. package/lib/Utils/logger.js +14 -0
  116. package/lib/Utils/lt-hash.js +19 -0
  117. package/lib/Utils/make-mutex.js +44 -0
  118. package/lib/Utils/message-composer.js +709 -0
  119. package/lib/Utils/message-inspect.js +79 -0
  120. package/lib/Utils/message-retry-manager.js +253 -0
  121. package/lib/Utils/message-security.js +167 -0
  122. package/lib/Utils/messages-media.js +1027 -0
  123. package/lib/Utils/messages.js +2467 -0
  124. package/lib/Utils/meta-ai-msmsg.js +215 -0
  125. package/lib/Utils/meta-compositing.js +239 -0
  126. package/lib/Utils/native-flow.js +158 -0
  127. package/lib/Utils/newsletter-live-update-utils.js +74 -0
  128. package/lib/Utils/newsletter-status-utils.js +152 -0
  129. package/lib/Utils/noise-handler.js +212 -0
  130. package/lib/Utils/offline-node-processor.js +51 -0
  131. package/lib/Utils/poll-manager.js +206 -0
  132. package/lib/Utils/portable-compat.js +12 -0
  133. package/lib/Utils/pre-key-manager.js +117 -0
  134. package/lib/Utils/process-message.js +610 -0
  135. package/lib/Utils/reporting-utils.js +269 -0
  136. package/lib/Utils/rich-message-utils.js +2841 -0
  137. package/lib/Utils/scheduled-message.js +107 -0
  138. package/lib/Utils/signal.js +212 -0
  139. package/lib/Utils/source-grep.js +57 -0
  140. package/lib/Utils/stanza-ack.js +49 -0
  141. package/lib/Utils/sticker-annotation.js +87 -0
  142. package/lib/Utils/sync-action-utils.js +59 -0
  143. package/lib/Utils/tc-token-utils.js +174 -0
  144. package/lib/Utils/use-multi-file-auth-state.js +132 -0
  145. package/lib/Utils/use-single-file-auth-state.js +108 -0
  146. package/lib/Utils/use-sqlite-auth-state.js +120 -0
  147. package/lib/Utils/validate-connection.js +220 -0
  148. package/lib/Utils/view-once-utils.js +218 -0
  149. package/lib/Utils/voip-rekey.js +32 -0
  150. package/lib/Utils/website-preview.js +27 -0
  151. package/lib/Utils/welcome-flow.js +228 -0
  152. package/lib/Utils/x4r1s3.js +144 -0
  153. package/lib/WABinary/constants.js +1475 -0
  154. package/lib/WABinary/decode.js +273 -0
  155. package/lib/WABinary/encode.js +231 -0
  156. package/lib/WABinary/generic-utils.js +242 -0
  157. package/lib/WABinary/index.js +17 -0
  158. package/lib/WABinary/jid-utils.js +107 -0
  159. package/lib/WABinary/types.js +13 -0
  160. package/lib/WAM/BinaryInfo.js +21 -0
  161. package/lib/WAM/constants.js +22864 -0
  162. package/lib/WAM/encode.js +161 -0
  163. package/lib/WAM/index.js +15 -0
  164. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +108 -0
  165. package/lib/WAUSync/Protocols/USyncContactProtocol.js +68 -0
  166. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +65 -0
  167. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +38 -0
  168. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +82 -0
  169. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +40 -0
  170. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +37 -0
  171. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +49 -0
  172. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +46 -0
  173. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +36 -0
  174. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +62 -0
  175. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +40 -0
  176. package/lib/WAUSync/Protocols/index.js +24 -0
  177. package/lib/WAUSync/USyncQuery.js +213 -0
  178. package/lib/WAUSync/USyncUser.js +66 -0
  179. package/lib/WAUSync/index.js +15 -0
  180. package/lib/antiban.cjs +4726 -0
  181. package/lib/index.d.ts +1285 -0
  182. package/lib/index.js +30 -0
  183. package/package.json +125 -4
@@ -0,0 +1,152 @@
1
+ import { randomBytes } from 'crypto';
2
+ import { proto } from '../../WAProto/index.js';
3
+ import { isJidNewsletter } from '../WABinary/index.js';
4
+ import { encodeNewsletterMessage } from './generics.js';
5
+ import { normalizeMessageContent } from './messages.js';
6
+
7
+ const NEWSLETTER_STATUS_MEDIA_TYPES = new Set(['image', 'video', 'audio']);
8
+ const DEFAULT_NEWSLETTER_STATUS_AUDIO_BACKGROUND = 0xff1e88e5;
9
+
10
+ export const withNewsletterStatusAttribution = content => {
11
+ if (!content || typeof content !== 'object' || Array.isArray(content)) {
12
+ throw new TypeError('Newsletter status content must be an object');
13
+ }
14
+ if (content.contextInfo != null && (typeof content.contextInfo !== 'object' || Array.isArray(content.contextInfo))) {
15
+ throw new TypeError('Newsletter status contextInfo must be an object');
16
+ }
17
+ if (content.messageContextInfo != null && (typeof content.messageContextInfo !== 'object' || Array.isArray(content.messageContextInfo))) {
18
+ throw new TypeError('Newsletter status messageContextInfo must be an object');
19
+ }
20
+
21
+ return {
22
+ ...content,
23
+ messageContextInfo: {
24
+ ...(content.messageContextInfo || {}),
25
+ messageSecret: content.messageContextInfo?.messageSecret ?? randomBytes(32)
26
+ },
27
+ contextInfo: {
28
+ ...(content.contextInfo || {}),
29
+ statusAttributions: [{ type: proto.StatusAttribution.Type.NEWSLETTER_STATUS }],
30
+ featureEligibilities: {
31
+ ...(content.contextInfo?.featureEligibilities || {}),
32
+ canBeReshared: true
33
+ }
34
+ }
35
+ };
36
+ };
37
+
38
+ export const withNewsletterStatusAudioMetadata = (message, backgroundArgb) => {
39
+ const normalized = normalizeMessageContent(message);
40
+ const audio = normalized?.audioMessage;
41
+ if (!audio?.ptt) {
42
+ throw new TypeError('Newsletter audio status requires a push-to-talk voice note');
43
+ }
44
+ const resolvedBackgroundArgb = backgroundArgb ?? DEFAULT_NEWSLETTER_STATUS_AUDIO_BACKGROUND;
45
+ if (!Number.isInteger(resolvedBackgroundArgb) || resolvedBackgroundArgb < 0 || resolvedBackgroundArgb > 0xffffffff) {
46
+ throw new TypeError('Newsletter voice-note backgroundArgb must be an unsigned 32-bit integer');
47
+ }
48
+ audio.backgroundArgb = resolvedBackgroundArgb >>> 0;
49
+ audio.contextInfo = {
50
+ ...(audio.contextInfo || {}),
51
+ statusSourceType: proto.ContextInfo.StatusSourceType.AUDIO
52
+ };
53
+ return message;
54
+ };
55
+ export const getNewsletterStatusMediaType = message => {
56
+ const normalized = normalizeMessageContent(message);
57
+ if (normalized?.imageMessage) return 'image';
58
+ if (normalized?.videoMessage) return normalized.videoMessage.gifPlayback ? 'gif' : 'video';
59
+ if (normalized?.audioMessage?.ptt) return 'audio';
60
+ return undefined;
61
+ };
62
+
63
+ export const waitForNewsletterStatusServerId = (sock, { jid, messageId }) => {
64
+ if (!sock?.ws || typeof sock.ws.on !== 'function' || typeof sock.ws.off !== 'function') {
65
+ throw new TypeError('Newsletter status server-ID lookup requires a socket event emitter');
66
+ }
67
+
68
+ let settle;
69
+ let timer;
70
+ let finished = false;
71
+ let resolvePromise;
72
+ const promise = new Promise(resolve => {
73
+ resolvePromise = resolve;
74
+ });
75
+ const finish = value => {
76
+ if (finished) return;
77
+ finished = true;
78
+ if (timer) clearTimeout(timer);
79
+ sock.ws.off('CB:status', onStatus);
80
+ resolvePromise(value);
81
+ };
82
+ const onStatus = node => {
83
+ if (node?.tag !== 'status') return;
84
+ const attrs = node.attrs || {};
85
+ if (attrs.from && attrs.from !== jid) return;
86
+ if (attrs.id && attrs.id !== messageId) return;
87
+ const serverId = Number.parseInt(String(attrs.server_id), 10);
88
+ if (Number.isFinite(serverId)) finish(serverId);
89
+ };
90
+ sock.ws.on('CB:status', onStatus);
91
+ settle = finish;
92
+
93
+ return {
94
+ promise,
95
+ startTimeout: (timeoutMs = 8000) => {
96
+ if (finished) return;
97
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
98
+ throw new TypeError('Newsletter status server-ID timeout must be a positive number');
99
+ }
100
+ if (timer) clearTimeout(timer);
101
+ timer = setTimeout(() => finish(undefined), timeoutMs);
102
+ },
103
+ cancel: () => settle?.(undefined)
104
+ };
105
+ };
106
+
107
+ export const buildNewsletterStatusNode = ({ jid, message, messageId, mediaType, mediaHandle }) => {
108
+ if (!isJidNewsletter(jid)) {
109
+ throw new TypeError('Newsletter status target must be a @newsletter JID');
110
+ }
111
+ if (typeof messageId !== 'string' || !messageId) {
112
+ throw new TypeError('Newsletter status messageId is required');
113
+ }
114
+ if (!message || typeof message !== 'object' || Array.isArray(message)) {
115
+ throw new TypeError('Newsletter status message is required');
116
+ }
117
+ if (mediaType !== undefined && !NEWSLETTER_STATUS_MEDIA_TYPES.has(mediaType)) {
118
+ throw new TypeError(`Unsupported newsletter status media type: ${mediaType}`);
119
+ }
120
+
121
+ const normalized = normalizeMessageContent(message);
122
+ const detectedMediaType = getNewsletterStatusMediaType(message);
123
+ if (mediaType !== detectedMediaType) {
124
+ throw new TypeError('Newsletter status media type does not match the encoded message');
125
+ }
126
+ if (!mediaType && typeof normalized?.conversation !== 'string' && typeof normalized?.extendedTextMessage?.text !== 'string') {
127
+ throw new TypeError('Newsletter status supports text, image, video, and push-to-talk voice-note content');
128
+ }
129
+ if (mediaType && (mediaHandle === undefined || mediaHandle === null || mediaHandle === '')) {
130
+ throw new TypeError('Media newsletter status requires the handle returned by the newsletter upload');
131
+ }
132
+ if (!mediaType && mediaHandle !== undefined && mediaHandle !== null && mediaHandle !== '') {
133
+ throw new TypeError('A media handle can only be used with an image or video newsletter status');
134
+ }
135
+
136
+ const attrs = {
137
+ to: jid,
138
+ id: messageId,
139
+ type: mediaType === 'audio' ? 'text' : mediaType ? 'media' : 'text'
140
+ };
141
+ if (mediaType && mediaType !== 'audio') attrs.media_id = String(mediaHandle);
142
+
143
+ return {
144
+ tag: 'status',
145
+ attrs,
146
+ content: [{
147
+ tag: 'plaintext',
148
+ attrs: mediaType && mediaType !== 'audio' ? { mediatype: mediaType } : {},
149
+ content: encodeNewsletterMessage(message)
150
+ }]
151
+ };
152
+ };
@@ -0,0 +1,212 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Utils/noise-handler.js
5
+ * About: Noise handler module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: makeNoiseHandler
7
+ * Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
8
+ *
9
+ * Copyright and attribution notice.
10
+ * Do not copy, reproduce, redistribute, modify, or create derivative works
11
+ * from this source without explicit written permission.
12
+ */
13
+ import { Boom } from '@hapi/boom';
14
+ import { proto } from '../../WAProto/index.js';
15
+ import { NOISE_MODE, WA_CERT_DETAILS } from '../Defaults/index.js';
16
+ import { decodeBinaryNode } from '../WABinary/index.js';
17
+ import { aesDecryptGCM, aesEncryptGCM, Curve, hkdf, sha256 } from './crypto.js';
18
+ const IV_LENGTH = 12;
19
+ const EMPTY_BUFFER = Buffer.alloc(0);
20
+ const generateIV = (counter) => {
21
+ const iv = new ArrayBuffer(IV_LENGTH);
22
+ new DataView(iv).setUint32(8, counter);
23
+ return new Uint8Array(iv);
24
+ };
25
+ class TransportState {
26
+ constructor(encKey, decKey) {
27
+ this.encKey = encKey;
28
+ this.decKey = decKey;
29
+ this.readCounter = 0;
30
+ this.writeCounter = 0;
31
+ this.iv = new Uint8Array(IV_LENGTH);
32
+ }
33
+ encrypt(plaintext) {
34
+ const c = this.writeCounter++;
35
+ this.iv[8] = (c >>> 24) & 0xff;
36
+ this.iv[9] = (c >>> 16) & 0xff;
37
+ this.iv[10] = (c >>> 8) & 0xff;
38
+ this.iv[11] = c & 0xff;
39
+ return aesEncryptGCM(plaintext, this.encKey, this.iv, EMPTY_BUFFER);
40
+ }
41
+ decrypt(ciphertext) {
42
+ const c = this.readCounter++;
43
+ this.iv[8] = (c >>> 24) & 0xff;
44
+ this.iv[9] = (c >>> 16) & 0xff;
45
+ this.iv[10] = (c >>> 8) & 0xff;
46
+ this.iv[11] = c & 0xff;
47
+ return aesDecryptGCM(ciphertext, this.decKey, this.iv, EMPTY_BUFFER);
48
+ }
49
+ }
50
+ export const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, logger, routingInfo }) => {
51
+ logger = logger.child({ class: 'ns' });
52
+ const data = Buffer.from(NOISE_MODE);
53
+ let hash = data.byteLength === 32 ? data : sha256(data);
54
+ let salt = hash;
55
+ let encKey = hash;
56
+ let decKey = hash;
57
+ let counter = 0;
58
+ let sentIntro = false;
59
+ let inBytes = Buffer.alloc(0);
60
+ let transport = null;
61
+ let isWaitingForTransport = false;
62
+ let pendingOnFrame = null;
63
+ let introHeader;
64
+ if (routingInfo) {
65
+ introHeader = Buffer.alloc(7 + routingInfo.byteLength + NOISE_HEADER.length);
66
+ introHeader.write('ED', 0, 'utf8');
67
+ introHeader.writeUint8(0, 2);
68
+ introHeader.writeUint8(1, 3);
69
+ introHeader.writeUint8(routingInfo.byteLength >> 16, 4);
70
+ introHeader.writeUint16BE(routingInfo.byteLength & 65535, 5);
71
+ introHeader.set(routingInfo, 7);
72
+ introHeader.set(NOISE_HEADER, 7 + routingInfo.byteLength);
73
+ }
74
+ else {
75
+ introHeader = Buffer.from(NOISE_HEADER);
76
+ }
77
+ const authenticate = (data) => {
78
+ if (!transport) {
79
+ hash = sha256(Buffer.concat([hash, data]));
80
+ }
81
+ };
82
+ const encrypt = (plaintext) => {
83
+ if (transport) {
84
+ return transport.encrypt(plaintext);
85
+ }
86
+ const result = aesEncryptGCM(plaintext, encKey, generateIV(counter++), hash);
87
+ authenticate(result);
88
+ return result;
89
+ };
90
+ const decrypt = (ciphertext) => {
91
+ if (transport) {
92
+ return transport.decrypt(ciphertext);
93
+ }
94
+ const result = aesDecryptGCM(ciphertext, decKey, generateIV(counter++), hash);
95
+ authenticate(ciphertext);
96
+ return result;
97
+ };
98
+ const localHKDF = (data) => {
99
+ const key = hkdf(Buffer.from(data), 64, { salt, info: '' });
100
+ return [key.subarray(0, 32), key.subarray(32)];
101
+ };
102
+ const mixIntoKey = (data) => {
103
+ const [write, read] = localHKDF(data);
104
+ salt = write;
105
+ encKey = read;
106
+ decKey = read;
107
+ counter = 0;
108
+ };
109
+ const finishInit = async () => {
110
+ isWaitingForTransport = true;
111
+ const [write, read] = localHKDF(new Uint8Array(0));
112
+ transport = new TransportState(write, read);
113
+ isWaitingForTransport = false;
114
+ logger.trace('Noise handler transitioned to Transport state');
115
+ if (pendingOnFrame) {
116
+ logger.trace({ length: inBytes.length }, 'Flushing buffered frames after transport ready');
117
+ await processData(pendingOnFrame);
118
+ pendingOnFrame = null;
119
+ }
120
+ };
121
+ const processData = async (onFrame) => {
122
+ let size;
123
+ while (true) {
124
+ if (inBytes.length < 3)
125
+ return;
126
+ size = (inBytes[0] << 16) | (inBytes[1] << 8) | inBytes[2];
127
+ if (inBytes.length < size + 3)
128
+ return;
129
+ let frame = inBytes.subarray(3, size + 3);
130
+ inBytes = inBytes.subarray(size + 3);
131
+ if (transport) {
132
+ const result = transport.decrypt(frame);
133
+ frame = await decodeBinaryNode(result);
134
+ }
135
+ if (logger.level === 'trace') {
136
+ logger.trace({ msg: frame?.attrs?.id }, 'recv frame');
137
+ }
138
+ onFrame(frame);
139
+ }
140
+ };
141
+ authenticate(NOISE_HEADER);
142
+ authenticate(publicKey);
143
+ return {
144
+ encrypt,
145
+ decrypt,
146
+ authenticate,
147
+ mixIntoKey,
148
+ finishInit,
149
+ processHandshake: ({ serverHello }, noiseKey) => {
150
+ authenticate(serverHello.ephemeral);
151
+ mixIntoKey(Curve.sharedKey(privateKey, serverHello.ephemeral));
152
+ const decStaticContent = decrypt(serverHello.static);
153
+ mixIntoKey(Curve.sharedKey(privateKey, decStaticContent));
154
+ const certDecoded = decrypt(serverHello.payload);
155
+ const { intermediate: certIntermediate, leaf } = proto.CertChain.decode(certDecoded);
156
+ // leaf
157
+ if (!leaf?.details || !leaf?.signature) {
158
+ throw new Boom('invalid noise leaf certificate', { statusCode: 400 });
159
+ }
160
+ if (!certIntermediate?.details || !certIntermediate?.signature) {
161
+ throw new Boom('invalid noise intermediate certificate', { statusCode: 400 });
162
+ }
163
+ const details = proto.CertChain.NoiseCertificate.Details.decode(certIntermediate.details);
164
+ const { issuerSerial } = details;
165
+ const verify = Curve.verify(details.key, leaf.details, leaf.signature);
166
+ const verifyIntermediate = Curve.verify(WA_CERT_DETAILS.PUBLIC_KEY, certIntermediate.details, certIntermediate.signature);
167
+ if (!verify) {
168
+ throw new Boom('noise certificate signature invalid', { statusCode: 400 });
169
+ }
170
+ if (!verifyIntermediate) {
171
+ throw new Boom('noise intermediate certificate signature invalid', { statusCode: 400 });
172
+ }
173
+ if (issuerSerial !== WA_CERT_DETAILS.SERIAL) {
174
+ throw new Boom('certification match failed', { statusCode: 400 });
175
+ }
176
+ const keyEnc = encrypt(noiseKey.public);
177
+ mixIntoKey(Curve.sharedKey(noiseKey.private, serverHello.ephemeral));
178
+ return keyEnc;
179
+ },
180
+ encodeFrame: (data) => {
181
+ if (transport) {
182
+ data = transport.encrypt(data);
183
+ }
184
+ const dataLen = data.byteLength;
185
+ const introSize = sentIntro ? 0 : introHeader.length;
186
+ const frame = Buffer.allocUnsafe(introSize + 3 + dataLen);
187
+ if (!sentIntro) {
188
+ frame.set(introHeader);
189
+ sentIntro = true;
190
+ }
191
+ frame[introSize] = (dataLen >>> 16) & 0xff;
192
+ frame[introSize + 1] = (dataLen >>> 8) & 0xff;
193
+ frame[introSize + 2] = dataLen & 0xff;
194
+ frame.set(data, introSize + 3);
195
+ return frame;
196
+ },
197
+ decodeFrame: async (newData, onFrame) => {
198
+ if (isWaitingForTransport) {
199
+ inBytes = Buffer.concat([inBytes, newData]);
200
+ pendingOnFrame = onFrame;
201
+ return;
202
+ }
203
+ if (inBytes.length === 0) {
204
+ inBytes = Buffer.from(newData);
205
+ }
206
+ else {
207
+ inBytes = Buffer.concat([inBytes, newData]);
208
+ }
209
+ await processData(onFrame);
210
+ }
211
+ };
212
+ };
@@ -0,0 +1,51 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Utils/offline-node-processor.js
5
+ * About: Offline node processor module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: makeOfflineNodeProcessor
7
+ * Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
8
+ *
9
+ * Copyright and attribution notice.
10
+ * Do not copy, reproduce, redistribute, modify, or create derivative works
11
+ * from this source without explicit written permission.
12
+ */
13
+ /**
14
+ * Creates a processor for offline stanza nodes that:
15
+ * - Queues nodes for sequential processing
16
+ * - Yields to the event loop periodically to avoid blocking
17
+ * - Catches handler errors to prevent the processing loop from crashing
18
+ */
19
+ export function makeOfflineNodeProcessor(nodeProcessorMap, deps, batchSize = 10) {
20
+ const nodes = [];
21
+ let isProcessing = false;
22
+ const enqueue = (type, node) => {
23
+ nodes.push({ type, node });
24
+ if (isProcessing) {
25
+ return;
26
+ }
27
+ isProcessing = true;
28
+ const promise = async () => {
29
+ let processedInBatch = 0;
30
+ while (nodes.length && deps.isWsOpen()) {
31
+ const { type, node } = nodes.shift();
32
+ const nodeProcessor = nodeProcessorMap.get(type);
33
+ if (!nodeProcessor) {
34
+ deps.onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node');
35
+ continue;
36
+ }
37
+ await nodeProcessor(node).catch(err => deps.onUnexpectedError(err, `processing offline ${type}`));
38
+ processedInBatch++;
39
+ // Yield to event loop after processing a batch
40
+ // This prevents blocking the event loop for too long when there are many offline nodes
41
+ if (processedInBatch >= batchSize) {
42
+ processedInBatch = 0;
43
+ await deps.yieldToEventLoop();
44
+ }
45
+ }
46
+ isProcessing = false;
47
+ };
48
+ promise().catch(error => deps.onUnexpectedError(error, 'processing offline nodes'));
49
+ };
50
+ return { enqueue };
51
+ }
@@ -0,0 +1,206 @@
1
+ /**
2
+ * Copyright (c) 2026 X4R1S3x — @X4R1S3/baileys
3
+ */
4
+ import { createHash } from 'crypto';
5
+ import { getKeyAuthor } from './generics.js';
6
+
7
+ const hashName = name => createHash('sha256').update(Buffer.from(String(name ?? ''))).digest('hex');
8
+
9
+ const toHashHex = value => {
10
+ if (value === null || value === undefined) return null;
11
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array) return Buffer.from(value).toString('hex');
12
+ const text = String(value);
13
+ if (/^[0-9a-f]{64}$/i.test(text)) return text.toLowerCase();
14
+ return hashName(text);
15
+ };
16
+
17
+ const unwrapMessage = message => {
18
+ let current = message;
19
+ const wrappers = [
20
+ 'ephemeralMessage',
21
+ 'viewOnceMessage',
22
+ 'viewOnceMessageV2',
23
+ 'viewOnceMessageV2Extension',
24
+ 'documentWithCaptionMessage',
25
+ 'editedMessage'
26
+ ];
27
+ for (let depth = 0; depth < 8 && current; depth++) {
28
+ const wrapper = wrappers.find(key => current[key]?.message);
29
+ if (!wrapper) break;
30
+ current = current[wrapper].message;
31
+ }
32
+ return current;
33
+ };
34
+
35
+ const extractOptions = source => {
36
+ const message = unwrapMessage(source?.message || source);
37
+ const creation = message?.pollCreationMessage
38
+ || message?.pollCreationMessageV2
39
+ || message?.pollCreationMessageV3
40
+ || message?.pollCreationMessageV4
41
+ || message?.pollCreationMessageV5
42
+ || message?.pollCreationMessageV6
43
+ || source?.pollCreationMessage
44
+ || null;
45
+ if (creation) {
46
+ return {
47
+ names: (creation.options || []).map(option => option?.optionName || ''),
48
+ selectableCount: creation.selectableOptionsCount ?? 0
49
+ };
50
+ }
51
+ const names = source?.options || source?.values || [];
52
+ return {
53
+ names: Array.isArray(names) ? [...names] : [],
54
+ selectableCount: source?.selectableCount ?? source?.selectableOptionsCount ?? 0
55
+ };
56
+ };
57
+
58
+ const resolvePollId = idOrMessage => typeof idOrMessage === 'string'
59
+ ? idOrMessage
60
+ : idOrMessage?.key?.id || idOrMessage?.id || null;
61
+
62
+ /**
63
+ * Create an in-memory poll tracker. Register poll-creation messages, then call
64
+ * applyVote/applyUpdate with decrypted poll selections. Each voter is counted
65
+ * once and a new selection replaces their previous one.
66
+ */
67
+ export const createPollManager = ({ meId = 'me' } = {}) => {
68
+ const polls = new Map();
69
+
70
+ const getPoll = idOrMessage => polls.get(resolvePollId(idOrMessage));
71
+ const tallyPoll = poll => {
72
+ if (!poll) return [];
73
+ const rows = poll.options.map(option => ({ name: option.name, hash: option.hash, count: 0, voters: [] }));
74
+ const byName = new Map(rows.map(row => [row.name, row]));
75
+ for (const [voter, names] of poll.votes) {
76
+ for (const name of names) {
77
+ const row = byName.get(name);
78
+ if (row) {
79
+ row.count += 1;
80
+ row.voters.push(voter);
81
+ }
82
+ }
83
+ }
84
+ return rows;
85
+ };
86
+
87
+ const manager = {
88
+ register(pollMessage, extra = {}) {
89
+ const id = extra.id || pollMessage?.key?.id || pollMessage?.id;
90
+ const { names, selectableCount } = extractOptions(pollMessage);
91
+ if (!id || !names.length) return null;
92
+ const key = pollMessage?.key;
93
+ const creator = extra.creator || (key
94
+ ? (key.fromMe ? meId : (key.participant || key.remoteJid))
95
+ : undefined);
96
+ polls.set(id, {
97
+ id,
98
+ options: names.map(name => ({ name, hash: hashName(name) })),
99
+ selectableCount: extra.selectableCount ?? selectableCount ?? 0,
100
+ creator,
101
+ createdAt: extra.at ?? Date.now(),
102
+ closed: false,
103
+ votes: new Map()
104
+ });
105
+ return id;
106
+ },
107
+
108
+ has(idOrMessage) {
109
+ return polls.has(resolvePollId(idOrMessage));
110
+ },
111
+
112
+ applyVote(idOrMessage, voterJid, selection = []) {
113
+ const poll = getPoll(idOrMessage);
114
+ if (!poll || !voterJid) return null;
115
+ if (poll.closed) return tallyPoll(poll);
116
+ const wanted = (Array.isArray(selection) ? selection : [selection])
117
+ .map(toHashHex)
118
+ .filter(Boolean);
119
+ let names = poll.options.filter(option => wanted.includes(option.hash)).map(option => option.name);
120
+ if (poll.selectableCount > 0 && names.length > poll.selectableCount) {
121
+ names = names.slice(0, poll.selectableCount);
122
+ }
123
+ if (!names.length) poll.votes.delete(voterJid);
124
+ else poll.votes.set(voterJid, names);
125
+ return tallyPoll(poll);
126
+ },
127
+
128
+ applyUpdate(idOrMessage, update) {
129
+ const voter = update?.voterJid || getKeyAuthor(update?.pollUpdateMessageKey, meId);
130
+ const selected = update?.vote?.selectedOptions || update?.selectedOptions || [];
131
+ return manager.applyVote(idOrMessage, voter, selected);
132
+ },
133
+
134
+ getVoterChoice(idOrMessage, voterJid) {
135
+ return getPoll(idOrMessage)?.votes.get(voterJid)?.slice() || [];
136
+ },
137
+
138
+ totalVoters(idOrMessage) {
139
+ return getPoll(idOrMessage)?.votes.size || 0;
140
+ },
141
+
142
+ tally(idOrMessage) {
143
+ return tallyPoll(getPoll(idOrMessage));
144
+ },
145
+
146
+ winner(idOrMessage) {
147
+ const rows = manager.tally(idOrMessage);
148
+ const count = rows.reduce((max, row) => Math.max(max, row.count), 0);
149
+ return count === 0 ? null : { winners: rows.filter(row => row.count === count).map(row => row.name), count };
150
+ },
151
+
152
+ render(idOrMessage, { width = 16 } = {}) {
153
+ const rows = manager.tally(idOrMessage);
154
+ const total = rows.reduce((sum, row) => sum + row.count, 0);
155
+ const barWidth = Math.max(0, Math.min(80, Math.floor(Number(width) || 0)));
156
+ return rows.map(row => {
157
+ const percentage = total ? row.count / total : 0;
158
+ const filled = Math.round(percentage * barWidth);
159
+ const bar = '█'.repeat(filled) + '░'.repeat(Math.max(0, barWidth - filled));
160
+ return `${row.name}\n${bar} ${row.count} (${Math.round(percentage * 100)}%)`;
161
+ }).join('\n');
162
+ },
163
+
164
+ getVotersFor(idOrMessage, option) {
165
+ const poll = getPoll(idOrMessage);
166
+ if (!poll) return [];
167
+ const name = typeof option === 'number' ? poll.options[option]?.name : option;
168
+ if (name === undefined) return [];
169
+ const voters = [];
170
+ for (const [voter, names] of poll.votes) {
171
+ if (names.includes(name)) voters.push(voter);
172
+ }
173
+ return voters;
174
+ },
175
+
176
+ close(idOrMessage) {
177
+ const poll = getPoll(idOrMessage);
178
+ if (!poll) return false;
179
+ poll.closed = true;
180
+ return true;
181
+ },
182
+
183
+ reopen(idOrMessage) {
184
+ const poll = getPoll(idOrMessage);
185
+ if (!poll) return false;
186
+ poll.closed = false;
187
+ return true;
188
+ },
189
+
190
+ isOpen(idOrMessage) {
191
+ const poll = getPoll(idOrMessage);
192
+ return !!poll && !poll.closed;
193
+ },
194
+
195
+ list() {
196
+ return [...polls.keys()];
197
+ },
198
+
199
+ reset(idOrMessage) {
200
+ if (idOrMessage === undefined) polls.clear();
201
+ else polls.delete(resolvePollId(idOrMessage));
202
+ }
203
+ };
204
+
205
+ return manager;
206
+ };
@@ -0,0 +1,12 @@
1
+ import { generateRichMenuContent } from './message-composer.js';
2
+ import { prepareRichResponseMessage } from './rich-message-utils.js';
3
+
4
+ /** Build a prepared rich-menu payload for direct message generation. */
5
+ export const prepareRichMenuMessage = (content = {}, quoted, options = {}) => generateRichMenuContent(content, quoted, options);
6
+
7
+ /** Convert unsupported premium content to a safe plain-text rich response. */
8
+ export const downgradePremiumContent = (content = {}) => {
9
+ if (typeof content === 'string') return prepareRichResponseMessage({ contentText: content, noDonation: true });
10
+ const text = content.text || content.contentText || content.caption || '';
11
+ return prepareRichResponseMessage({ contentText: String(text), noDonation: true });
12
+ };