@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,107 @@
1
+ import { createCipheriv, randomBytes } from 'crypto';
2
+ import { proto } from '../../WAProto/index.js';
3
+
4
+ const isFiniteNumber = value => typeof value === 'number' && Number.isFinite(value);
5
+
6
+ /** Attach the native parent-key association to a generated paired child message. */
7
+ export const associateScheduledMessages = (parent, child, associationType = proto.MessageAssociation.AssociationType.MOTION_PHOTO) => {
8
+ if (!parent?.key || !child?.message) {
9
+ throw new TypeError('A generated parent and child message are required');
10
+ }
11
+ child.message.messageContextInfo = {
12
+ ...(child.message.messageContextInfo || {}),
13
+ messageAssociation: {
14
+ associationType,
15
+ parentMessageKey: parent.key
16
+ }
17
+ };
18
+ return { parent, child };
19
+ };
20
+
21
+ /**
22
+ * Normalize an explicit schedule time to Unix seconds.
23
+ * Numeric values below 1e11 are interpreted as Unix seconds; larger values are
24
+ * interpreted as Unix milliseconds. Date and ISO-8601 strings are also accepted.
25
+ */
26
+ export const normalizeScheduledTime = (scheduledAt, now = Date.now()) => {
27
+ let timestampMs;
28
+
29
+ if (scheduledAt instanceof Date) {
30
+ timestampMs = scheduledAt.getTime();
31
+ }
32
+ else if (isFiniteNumber(scheduledAt)) {
33
+ timestampMs = Math.abs(scheduledAt) < 1e11 ? scheduledAt * 1000 : scheduledAt;
34
+ }
35
+ else if (typeof scheduledAt === 'string' && scheduledAt.trim()) {
36
+ const value = scheduledAt.trim();
37
+ if (/^-?\d+(?:\.\d+)?$/.test(value)) {
38
+ const numeric = Number(value);
39
+ timestampMs = Math.abs(numeric) < 1e11 ? numeric * 1000 : numeric;
40
+ }
41
+ else {
42
+ timestampMs = Date.parse(value);
43
+ }
44
+ }
45
+ else {
46
+ throw new TypeError('scheduledAt must be a Date, an ISO-8601 string, or a Unix timestamp in seconds/milliseconds');
47
+ }
48
+
49
+ if (!Number.isFinite(timestampMs) || Math.abs(timestampMs) > 8.64e15) {
50
+ throw new RangeError('scheduledAt is not a valid timestamp');
51
+ }
52
+
53
+ const scheduledTime = Math.floor(timestampMs / 1000);
54
+ if (!Number.isSafeInteger(scheduledTime)) {
55
+ throw new RangeError('scheduledAt is outside the supported timestamp range');
56
+ }
57
+ if (scheduledTime <= Math.floor(now / 1000)) {
58
+ throw new RangeError('scheduledAt must be in the future');
59
+ }
60
+
61
+ return scheduledTime;
62
+ };
63
+
64
+ /**
65
+ * Encrypt a generated WhatsApp Message for the native conditional-reveal
66
+ * scheduled-message envelope. The matching reveal key is carried separately in
67
+ * the scheduled-message metadata node and in the sender-side WebMessageInfo.
68
+ */
69
+ export const createScheduledMessageEnvelope = (message, scheduledAt, { now = Date.now() } = {}) => {
70
+ const scheduledTime = normalizeScheduledTime(scheduledAt, now);
71
+ const revealKey = randomBytes(32);
72
+ const encIv = randomBytes(12);
73
+ const revealKeyId = randomBytes(16).toString('hex').toUpperCase();
74
+ const plaintext = proto.Message.encode(message).finish();
75
+ const cipher = createCipheriv('aes-256-gcm', revealKey, encIv);
76
+ const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]);
77
+
78
+ const content = proto.Message.create({
79
+ conditionalRevealMessage: {
80
+ encPayload: ciphertext,
81
+ encIv,
82
+ conditionalRevealMessageType: proto.Message.ConditionalRevealMessage.ConditionalRevealMessageType.SCHEDULED_MESSAGE,
83
+ revealKeyId
84
+ }
85
+ });
86
+
87
+ const additionalNode = {
88
+ tag: 'meta',
89
+ attrs: {
90
+ type: 'scheduled_message',
91
+ st: String(scheduledTime)
92
+ },
93
+ content: [{
94
+ tag: 'key',
95
+ attrs: { rkid: revealKeyId },
96
+ content: revealKey
97
+ }]
98
+ };
99
+
100
+ return {
101
+ content,
102
+ scheduledTime,
103
+ revealKey,
104
+ revealKeyId,
105
+ additionalNode
106
+ };
107
+ };
@@ -0,0 +1,212 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Utils/signal.js
5
+ * About: Signal module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: createSignalIdentity, getPreKeys, generateOrGetPreKeys, xmppSignedPreKey, xmppPreKey, extractE2ESessionFromRetryReceipt, parseAndInjectE2ESessions, extractDeviceJids; …
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 { KEY_BUNDLE_TYPE } from '../Defaults/index.js';
14
+ import { assertNodeErrorFree, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildUInt, getServerFromDomainType, jidDecode, S_WHATSAPP_NET, WAJIDDomains } from '../WABinary/index.js';
15
+ import { Curve, generateSignalPubKey } from './crypto.js';
16
+ import { encodeBigEndian } from './generics.js';
17
+ function chunk(array, size) {
18
+ const chunks = [];
19
+ for (let i = 0; i < array.length; i += size) {
20
+ chunks.push(array.slice(i, i + size));
21
+ }
22
+ return chunks;
23
+ }
24
+ export const createSignalIdentity = (wid, accountSignatureKey) => {
25
+ return {
26
+ identifier: { name: wid, deviceId: 0 },
27
+ identifierKey: generateSignalPubKey(accountSignatureKey)
28
+ };
29
+ };
30
+ export const getPreKeys = async ({ get }, min, limit) => {
31
+ const idList = [];
32
+ for (let id = min; id < limit; id++) {
33
+ idList.push(id.toString());
34
+ }
35
+ return get('pre-key', idList);
36
+ };
37
+ export const generateOrGetPreKeys = (creds, range) => {
38
+ const avaliable = creds.nextPreKeyId - creds.firstUnuploadedPreKeyId;
39
+ const remaining = range - avaliable;
40
+ const lastPreKeyId = creds.nextPreKeyId + remaining - 1;
41
+ const newPreKeys = {};
42
+ if (remaining > 0) {
43
+ for (let i = creds.nextPreKeyId; i <= lastPreKeyId; i++) {
44
+ newPreKeys[i] = Curve.generateKeyPair();
45
+ }
46
+ }
47
+ return {
48
+ newPreKeys,
49
+ lastPreKeyId,
50
+ preKeysRange: [creds.firstUnuploadedPreKeyId, range]
51
+ };
52
+ };
53
+ export const xmppSignedPreKey = (key) => ({
54
+ tag: 'skey',
55
+ attrs: {},
56
+ content: [
57
+ { tag: 'id', attrs: {}, content: encodeBigEndian(key.keyId, 3) },
58
+ { tag: 'value', attrs: {}, content: key.keyPair.public },
59
+ { tag: 'signature', attrs: {}, content: key.signature }
60
+ ]
61
+ });
62
+ export const xmppPreKey = (pair, id) => ({
63
+ tag: 'key',
64
+ attrs: {},
65
+ content: [
66
+ { tag: 'id', attrs: {}, content: encodeBigEndian(id, 3) },
67
+ { tag: 'value', attrs: {}, content: pair.public }
68
+ ]
69
+ });
70
+ const isValidUInt = (n) => typeof n === 'number' && Number.isInteger(n);
71
+ export const extractE2ESessionFromRetryReceipt = (receipt) => {
72
+ const keysNode = getBinaryNodeChild(receipt, 'keys');
73
+ if (!keysNode)
74
+ return null;
75
+ const typeBuf = getBinaryNodeChildBuffer(keysNode, 'type');
76
+ if (!typeBuf || typeBuf.length !== 1 || typeBuf[0] !== KEY_BUNDLE_TYPE[0])
77
+ return null;
78
+ const identity = getBinaryNodeChildBuffer(keysNode, 'identity');
79
+ const skey = getBinaryNodeChild(keysNode, 'skey');
80
+ if (!identity || identity.length !== 32 || !skey)
81
+ return null;
82
+ const registrationId = getBinaryNodeChildUInt(receipt, 'registration', 4);
83
+ if (!isValidUInt(registrationId))
84
+ return null;
85
+ const signedPubKey = getBinaryNodeChildBuffer(skey, 'value');
86
+ const signedSig = getBinaryNodeChildBuffer(skey, 'signature');
87
+ const signedKeyId = getBinaryNodeChildUInt(skey, 'id', 3);
88
+ if (!signedPubKey || signedPubKey.length !== 32 || !signedSig || !isValidUInt(signedKeyId)) {
89
+ return null;
90
+ }
91
+ const preKeyNode = getBinaryNodeChild(keysNode, 'key');
92
+ let preKey;
93
+ if (preKeyNode) {
94
+ const preKeyPub = getBinaryNodeChildBuffer(preKeyNode, 'value');
95
+ const preKeyId = getBinaryNodeChildUInt(preKeyNode, 'id', 3);
96
+ if (!preKeyPub || preKeyPub.length !== 32 || !isValidUInt(preKeyId)) {
97
+ return null;
98
+ }
99
+ preKey = { keyId: preKeyId, publicKey: generateSignalPubKey(preKeyPub) };
100
+ }
101
+ return {
102
+ registrationId,
103
+ identityKey: generateSignalPubKey(identity),
104
+ signedPreKey: {
105
+ keyId: signedKeyId,
106
+ publicKey: generateSignalPubKey(signedPubKey),
107
+ signature: signedSig
108
+ },
109
+ preKey
110
+ };
111
+ };
112
+ export const parseAndInjectE2ESessions = async (node, repository) => {
113
+ const extractKey = (key) => key
114
+ ? {
115
+ keyId: getBinaryNodeChildUInt(key, 'id', 3),
116
+ publicKey: generateSignalPubKey(getBinaryNodeChildBuffer(key, 'value')),
117
+ signature: getBinaryNodeChildBuffer(key, 'signature')
118
+ }
119
+ : undefined;
120
+ const nodes = getBinaryNodeChildren(getBinaryNodeChild(node, 'list'), 'user');
121
+ for (const node of nodes) {
122
+ assertNodeErrorFree(node);
123
+ }
124
+ // Most of the work in repository.injectE2ESession is CPU intensive, not IO
125
+ // So Promise.all doesn't really help here,
126
+ // but blocks even loop if we're using it inside keys.transaction, and it makes it "sync" actually
127
+ // This way we chunk it in smaller parts and between those parts we can yield to the event loop
128
+ // It's rare case when you need to E2E sessions for so many users, but it's possible
129
+ const chunkSize = 100;
130
+ const chunks = chunk(nodes, chunkSize);
131
+ for (const nodesChunk of chunks) {
132
+ for (const node of nodesChunk) {
133
+ const signedKey = getBinaryNodeChild(node, 'skey');
134
+ const key = getBinaryNodeChild(node, 'key');
135
+ const identity = getBinaryNodeChildBuffer(node, 'identity');
136
+ const jid = node.attrs.jid;
137
+ const registrationId = getBinaryNodeChildUInt(node, 'registration', 4);
138
+ await repository.injectE2ESession({
139
+ jid,
140
+ session: {
141
+ registrationId: registrationId,
142
+ identityKey: generateSignalPubKey(identity),
143
+ signedPreKey: extractKey(signedKey),
144
+ preKey: extractKey(key)
145
+ }
146
+ });
147
+ }
148
+ }
149
+ };
150
+ export const extractDeviceJids = (result, myJid, myLid, excludeZeroDevices) => {
151
+ const { user: myUser, device: myDevice } = jidDecode(myJid);
152
+ const extracted = [];
153
+ for (const userResult of result) {
154
+ const { devices, id } = userResult;
155
+ const decoded = jidDecode(id), { user, server } = decoded;
156
+ let { domainType } = decoded;
157
+ const deviceList = devices?.deviceList;
158
+ if (!Array.isArray(deviceList))
159
+ continue;
160
+ for (const { id: device, keyIndex, isHosted } of deviceList) {
161
+ if ((!excludeZeroDevices || device !== 0) && // if zero devices are not-excluded, or device is non zero
162
+ ((myUser !== user && myLid !== user) || myDevice !== device) && // either different user or if me user, not this device
163
+ (device === 0 || !!keyIndex) // ensure that "key-index" is specified for "non-zero" devices, produces a bad req otherwise
164
+ ) {
165
+ if (isHosted) {
166
+ domainType = domainType === WAJIDDomains.LID ? WAJIDDomains.HOSTED_LID : WAJIDDomains.HOSTED;
167
+ }
168
+ extracted.push({
169
+ user,
170
+ device,
171
+ domainType,
172
+ server: getServerFromDomainType(server, domainType)
173
+ });
174
+ }
175
+ }
176
+ }
177
+ return extracted;
178
+ };
179
+ /**
180
+ * get the next N keys for upload or processing
181
+ * @param count number of pre-keys to get or generate
182
+ */
183
+ export const getNextPreKeys = async ({ creds, keys }, count) => {
184
+ const { newPreKeys, lastPreKeyId, preKeysRange } = generateOrGetPreKeys(creds, count);
185
+ const update = {
186
+ nextPreKeyId: Math.max(lastPreKeyId + 1, creds.nextPreKeyId),
187
+ firstUnuploadedPreKeyId: Math.max(creds.firstUnuploadedPreKeyId, lastPreKeyId + 1)
188
+ };
189
+ await keys.set({ 'pre-key': newPreKeys });
190
+ const preKeys = await getPreKeys(keys, preKeysRange[0], preKeysRange[0] + preKeysRange[1]);
191
+ return { update, preKeys };
192
+ };
193
+ export const getNextPreKeysNode = async (state, count) => {
194
+ const { creds } = state;
195
+ const { update, preKeys } = await getNextPreKeys(state, count);
196
+ const node = {
197
+ tag: 'iq',
198
+ attrs: {
199
+ xmlns: 'encrypt',
200
+ type: 'set',
201
+ to: S_WHATSAPP_NET
202
+ },
203
+ content: [
204
+ { tag: 'registration', attrs: {}, content: encodeBigEndian(creds.registrationId) },
205
+ { tag: 'type', attrs: {}, content: KEY_BUNDLE_TYPE },
206
+ { tag: 'identity', attrs: {}, content: creds.signedIdentityKey.public },
207
+ { tag: 'list', attrs: {}, content: Object.keys(preKeys).map(k => xmppPreKey(preKeys[+k], +k)) },
208
+ xmppSignedPreKey(creds.signedPreKey)
209
+ ]
210
+ };
211
+ return { update, node };
212
+ };
@@ -0,0 +1,57 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Utils/source-grep.js
5
+ * About: Source grep module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: grepSource
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 fs from 'node:fs';
14
+ import path from 'node:path';
15
+ import { fileURLToPath } from 'node:url';
16
+
17
+ const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
18
+ const DEFAULT_DIRS = ['lib', 'WAProto'];
19
+ const DEFAULT_EXTENSIONS = new Set(['.js', '.mjs', '.cjs', '.ts', '.d.ts', '.proto', '.md', '.json']);
20
+
21
+ const walk = (directory, files) => {
22
+ if (!fs.existsSync(directory)) return;
23
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
24
+ if (entry.name === 'node_modules' || entry.name.startsWith('.')) continue;
25
+ const fullPath = path.join(directory, entry.name);
26
+ if (entry.isDirectory()) walk(fullPath, files);
27
+ else if (DEFAULT_EXTENSIONS.has(path.extname(entry.name))) files.push(fullPath);
28
+ }
29
+ };
30
+
31
+ /**
32
+ * Find a literal or regular-expression pattern in package source.
33
+ * Returns exact relative file, line, column, and matching source line.
34
+ */
35
+ export const grepSource = (pattern, options = {}) => {
36
+ if (typeof pattern !== 'string' || !pattern.trim()) {
37
+ throw new TypeError('grepSource requires a non-empty search string');
38
+ }
39
+ const expression = options.regex ? new RegExp(pattern, options.flags || 'i') : null;
40
+ const needle = options.caseSensitive ? pattern : pattern.toLowerCase();
41
+ const files = [];
42
+ for (const relativeDir of options.dirs || DEFAULT_DIRS) walk(path.resolve(PACKAGE_ROOT, relativeDir), files);
43
+ if (options.includeReadme) files.push(path.resolve(PACKAGE_ROOT, 'README.md'));
44
+ const matches = [];
45
+ for (const file of files.sort()) {
46
+ const lines = fs.readFileSync(file, 'utf8').split(/\r?\n/);
47
+ lines.forEach((line, index) => {
48
+ const found = expression ? expression.test(line) : (options.caseSensitive ? line.includes(pattern) : line.toLowerCase().includes(needle));
49
+ if (found) {
50
+ const column = expression ? Math.max(0, line.search(expression)) : (options.caseSensitive ? line.indexOf(pattern) : line.toLowerCase().indexOf(needle));
51
+ matches.push({ file: path.relative(PACKAGE_ROOT, file), line: index + 1, column: column + 1, text: line.trim() });
52
+ }
53
+ if (expression) expression.lastIndex = 0;
54
+ });
55
+ }
56
+ return matches.slice(0, Math.max(1, options.maxResults || 200));
57
+ };
@@ -0,0 +1,49 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Utils/stanza-ack.js
5
+ * About: Stanza ack module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: buildAckStanza
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
+ * Builds an ACK stanza for a received node.
15
+ * Pure function -- no I/O, no side effects.
16
+ *
17
+ * Mirrors WhatsApp Web's ACK construction:
18
+ * - WAWebHandleMsgSendAck.sendAck / sendNack
19
+ * - WAWebCreateNackFromStanza.createNackFromStanza
20
+ */
21
+ export function buildAckStanza(node, errorCode, meId) {
22
+ const { tag, attrs } = node;
23
+ const stanza = {
24
+ tag: 'ack',
25
+ attrs: {
26
+ id: attrs.id,
27
+ to: attrs.from,
28
+ class: tag
29
+ }
30
+ };
31
+ if (errorCode) {
32
+ stanza.attrs.error = errorCode.toString();
33
+ }
34
+ if (attrs.participant) {
35
+ stanza.attrs.participant = attrs.participant;
36
+ }
37
+ if (attrs.recipient) {
38
+ stanza.attrs.recipient = attrs.recipient;
39
+ }
40
+ // WA Web always includes type when present: `n.type || DROP_ATTR`
41
+ if (attrs.type) {
42
+ stanza.attrs.type = attrs.type;
43
+ }
44
+ // WA Web WAWebHandleMsgSendAck.sendAck/sendNack always include `from` for message-class ACKs
45
+ if (tag === 'message' && meId) {
46
+ stanza.attrs.from = meId;
47
+ }
48
+ return stanza;
49
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Copyright (c) 2026 X4R1S3x — @X4R1S3/baileys
3
+ */
4
+ import { Boom } from '@hapi/boom';
5
+ import { proto } from '../../WAProto/index.js';
6
+
7
+ const MAX_STICKER_ANNOTATION_COUNT = 20;
8
+ const MAX_STICKER_ANNOTATION_INTERVAL_MS = 60_000;
9
+
10
+ export const normalizeStickerAnnotationOptions = ({ count = 1, intervalMs = 1000 } = {}) => {
11
+ if (!Number.isInteger(count) || count < 1 || count > MAX_STICKER_ANNOTATION_COUNT) {
12
+ throw new Boom(`sticker annotation count must be an integer between 1 and ${MAX_STICKER_ANNOTATION_COUNT}`, { statusCode: 400 });
13
+ }
14
+ if (!Number.isInteger(intervalMs) || intervalMs < 0 || intervalMs > MAX_STICKER_ANNOTATION_INTERVAL_MS) {
15
+ throw new Boom(`sticker annotation intervalMs must be an integer between 0 and ${MAX_STICKER_ANNOTATION_INTERVAL_MS}`, { statusCode: 400 });
16
+ }
17
+ return { count, intervalMs };
18
+ };
19
+
20
+ export const prepareStickerAnnotationMessage = ({ parentMessageKey, stickerMessage } = {}, { now = Date.now() } = {}) => {
21
+ if (!parentMessageKey || typeof parentMessageKey !== 'object' || typeof parentMessageKey.id !== 'string' || !parentMessageKey.id.trim()) {
22
+ throw new Boom('sendStickerAnnotation requires a parentMessageKey with a message id', { statusCode: 400 });
23
+ }
24
+ if (!stickerMessage || typeof stickerMessage !== 'object' || Array.isArray(stickerMessage)) {
25
+ throw new Boom('sendStickerAnnotation requires a stickerMessage payload', { statusCode: 400 });
26
+ }
27
+ if (!(typeof stickerMessage.url === 'string' && stickerMessage.url) && !(typeof stickerMessage.directPath === 'string' && stickerMessage.directPath)) {
28
+ throw new Boom('stickerMessage requires a media url or directPath', { statusCode: 400 });
29
+ }
30
+ if (!Number.isFinite(now) || now < 0) {
31
+ throw new Boom('sticker annotation timestamp must be a non-negative number', { statusCode: 400 });
32
+ }
33
+
34
+ return proto.Message.fromObject({
35
+ messageContextInfo: {
36
+ messageAssociation: {
37
+ associationType: proto.MessageAssociation.AssociationType.STICKER_ANNOTATION,
38
+ parentMessageKey
39
+ }
40
+ },
41
+ stickerMessage: {
42
+ ...stickerMessage,
43
+ isAnimated: stickerMessage.isAnimated ?? true,
44
+ stickerSentTs: stickerMessage.stickerSentTs ?? now
45
+ }
46
+ });
47
+ };
48
+
49
+ /** Relay one associated sticker repeatedly, using an independent message id for every send. */
50
+ export const sendStickerAnnotationBatch = async ({
51
+ jid,
52
+ parentMessageKey,
53
+ stickerMessage,
54
+ count = 1,
55
+ intervalMs = 1000,
56
+ relay,
57
+ createMessageId,
58
+ relayOptions = {},
59
+ sleep = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds))
60
+ } = {}) => {
61
+ if (!jid || typeof jid !== 'string') {
62
+ throw new Boom('sendStickerAnnotation requires a target JID', { statusCode: 400 });
63
+ }
64
+ if (typeof relay !== 'function' || typeof createMessageId !== 'function' || typeof sleep !== 'function') {
65
+ throw new Boom('sendStickerAnnotation requires relay and message-id functions', { statusCode: 400 });
66
+ }
67
+ const normalized = normalizeStickerAnnotationOptions({ count, intervalMs });
68
+ const messageIds = [];
69
+
70
+ for (let index = 0; index < normalized.count; index += 1) {
71
+ const messageId = index === 0 && typeof relayOptions.messageId === 'string' && relayOptions.messageId
72
+ ? relayOptions.messageId
73
+ : createMessageId();
74
+ if (typeof messageId !== 'string' || !messageId) {
75
+ throw new Boom('sendStickerAnnotation could not create a message id', { statusCode: 500 });
76
+ }
77
+ const message = prepareStickerAnnotationMessage({ parentMessageKey, stickerMessage });
78
+ await relay(jid, message, { ...relayOptions, messageId });
79
+ messageIds.push(messageId);
80
+
81
+ if (index + 1 < normalized.count && normalized.intervalMs > 0) {
82
+ await sleep(normalized.intervalMs);
83
+ }
84
+ }
85
+
86
+ return { sent: messageIds.length, messageIds };
87
+ };
@@ -0,0 +1,59 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Utils/sync-action-utils.js
5
+ * About: Sync action utils module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: processContactAction, emitSyncActionResults
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 { proto } from '../../WAProto/index.js';
14
+ import { isLidUser, isPnUser } from '../WABinary/index.js';
15
+ /**
16
+ * Process contactAction and return events to emit.
17
+ * Pure function - no side effects.
18
+ */
19
+ export const processContactAction = (action, id, logger) => {
20
+ const results = [];
21
+ if (!id) {
22
+ logger?.warn({ hasFullName: !!action.fullName, hasLidJid: !!action.lidJid, hasPnJid: !!action.pnJid }, 'contactAction sync: missing id in index');
23
+ return results;
24
+ }
25
+ const lidJid = action.lidJid;
26
+ const idIsPn = isPnUser(id);
27
+ // PN is in index[1], not in contactAction.pnJid which is usually null
28
+ const phoneNumber = idIsPn ? id : action.pnJid || undefined;
29
+ // Always emit contacts.upsert
30
+ results.push({
31
+ event: 'contacts.upsert',
32
+ data: [
33
+ {
34
+ id,
35
+ name: action.fullName || action.firstName || action.username || undefined,
36
+ lid: lidJid || undefined,
37
+ phoneNumber
38
+ }
39
+ ]
40
+ });
41
+ // Emit lid-mapping.update if we have valid LID-PN pair
42
+ if (lidJid && isLidUser(lidJid) && idIsPn) {
43
+ results.push({
44
+ event: 'lid-mapping.update',
45
+ data: { lid: lidJid, pn: id }
46
+ });
47
+ }
48
+ return results;
49
+ };
50
+ export const emitSyncActionResults = (ev, results) => {
51
+ for (const result of results) {
52
+ if (result.event === 'contacts.upsert') {
53
+ ev.emit('contacts.upsert', result.data);
54
+ }
55
+ else {
56
+ ev.emit('lid-mapping.update', result.data);
57
+ }
58
+ }
59
+ };