plogme 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 (154) hide show
  1. package/LICENSE +61 -0
  2. package/README.md +212 -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 +51 -0
  7. package/lib/Defaults/ban-checker.js +44 -0
  8. package/lib/Defaults/index.js +158 -0
  9. package/lib/Signal/Group/ciphertext-message.js +11 -0
  10. package/lib/Signal/Group/group-session-builder.js +29 -0
  11. package/lib/Signal/Group/group_cipher.js +81 -0
  12. package/lib/Signal/Group/index.js +11 -0
  13. package/lib/Signal/Group/keyhelper.js +17 -0
  14. package/lib/Signal/Group/sender-chain-key.js +25 -0
  15. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  16. package/lib/Signal/Group/sender-key-message.js +65 -0
  17. package/lib/Signal/Group/sender-key-name.js +47 -0
  18. package/lib/Signal/Group/sender-key-record.js +40 -0
  19. package/lib/Signal/Group/sender-key-state.js +83 -0
  20. package/lib/Signal/Group/sender-message-key.js +25 -0
  21. package/lib/Signal/libsignal.js +428 -0
  22. package/lib/Signal/lid-mapping.js +280 -0
  23. package/lib/Socket/Client/index.js +2 -0
  24. package/lib/Socket/Client/types.js +10 -0
  25. package/lib/Socket/Client/websocket.js +53 -0
  26. package/lib/Socket/aigroups.js +315 -0
  27. package/lib/Socket/ban-checker.js +153 -0
  28. package/lib/Socket/business.js +407 -0
  29. package/lib/Socket/chats.js +1831 -0
  30. package/lib/Socket/chats.js[old] +1227 -0
  31. package/lib/Socket/communities.js +431 -0
  32. package/lib/Socket/graphql.js +899 -0
  33. package/lib/Socket/groups.js +549 -0
  34. package/lib/Socket/groups.js[old] +347 -0
  35. package/lib/Socket/index.js +71 -0
  36. package/lib/Socket/interactive-handler.js +600 -0
  37. package/lib/Socket/interop.js +563 -0
  38. package/lib/Socket/managed-account.js +208 -0
  39. package/lib/Socket/messages-recv.js +2144 -0
  40. package/lib/Socket/messages-send.js +2650 -0
  41. package/lib/Socket/messages-send.js[latest working] +1759 -0
  42. package/lib/Socket/mex.js +41 -0
  43. package/lib/Socket/newsletter.js +226 -0
  44. package/lib/Socket/privacy.js +446 -0
  45. package/lib/Socket/registration.js +428 -0
  46. package/lib/Socket/socket.js +1050 -0
  47. package/lib/Socket/username.js +229 -0
  48. package/lib/Store/index.js +4 -0
  49. package/lib/Store/make-cache-manager-store.js +89 -0
  50. package/lib/Store/make-in-memory-store.js +420 -0
  51. package/lib/Store/make-ordered-dictionary.js +78 -0
  52. package/lib/Store/object-repository.js +23 -0
  53. package/lib/Types/Auth.js +1 -0
  54. package/lib/Types/Bussines.js +1 -0
  55. package/lib/Types/Call.js +1 -0
  56. package/lib/Types/Chat.js +7 -0
  57. package/lib/Types/Contact.js +1 -0
  58. package/lib/Types/Events.js +1 -0
  59. package/lib/Types/GroupMetadata.js +1 -0
  60. package/lib/Types/Label.js +24 -0
  61. package/lib/Types/LabelAssociation.js +6 -0
  62. package/lib/Types/Message.js +17 -0
  63. package/lib/Types/Mex.js +39 -0
  64. package/lib/Types/Product.js +1 -0
  65. package/lib/Types/RichType.js +22 -0
  66. package/lib/Types/Signal.js +1 -0
  67. package/lib/Types/Socket.js +2 -0
  68. package/lib/Types/State.js +48 -0
  69. package/lib/Types/USync.js +1 -0
  70. package/lib/Types/index.js +25 -0
  71. package/lib/Utils/auth-utils.js +301 -0
  72. package/lib/Utils/bot-planning-replay.js +169 -0
  73. package/lib/Utils/browser-utils.js +28 -0
  74. package/lib/Utils/business.js +230 -0
  75. package/lib/Utils/channel-policy.js +1 -0
  76. package/lib/Utils/chat-utils.js +885 -0
  77. package/lib/Utils/chat-utils.js[old] +871 -0
  78. package/lib/Utils/companion-reg-client-utils.js +32 -0
  79. package/lib/Utils/consumer-application.js +102 -0
  80. package/lib/Utils/crypto.js +117 -0
  81. package/lib/Utils/decode-wa-message.js +484 -0
  82. package/lib/Utils/event-buffer.js +589 -0
  83. package/lib/Utils/games/slot-machine.js +258 -0
  84. package/lib/Utils/games/website-preview.js +293 -0
  85. package/lib/Utils/generics.js +390 -0
  86. package/lib/Utils/generics.js@old +385 -0
  87. package/lib/Utils/group-history.js +56 -0
  88. package/lib/Utils/history.js +130 -0
  89. package/lib/Utils/identity-change-handler.js +48 -0
  90. package/lib/Utils/index.js +35 -0
  91. package/lib/Utils/integrity.js +296 -0
  92. package/lib/Utils/jid-display-normalization.js +209 -0
  93. package/lib/Utils/link-preview.js +84 -0
  94. package/lib/Utils/logger.js +2 -0
  95. package/lib/Utils/lt-hash.js +7 -0
  96. package/lib/Utils/make-mutex.js +32 -0
  97. package/lib/Utils/message-composer.js +467 -0
  98. package/lib/Utils/message-inspect.js +67 -0
  99. package/lib/Utils/message-retry-manager.js +241 -0
  100. package/lib/Utils/messages-media.js +1006 -0
  101. package/lib/Utils/messages-media.js[old] +916 -0
  102. package/lib/Utils/messages.js +1982 -0
  103. package/lib/Utils/messages.js[old] +1902 -0
  104. package/lib/Utils/meta-ai-msmsg.js +130 -0
  105. package/lib/Utils/meta-compositing.js +202 -0
  106. package/lib/Utils/native-flow.js +100 -0
  107. package/lib/Utils/noise-handler.js +200 -0
  108. package/lib/Utils/offline-node-processor.js +39 -0
  109. package/lib/Utils/pre-key-manager.js +105 -0
  110. package/lib/Utils/process-message.js +582 -0
  111. package/lib/Utils/reporting-utils.js +257 -0
  112. package/lib/Utils/rich-message-utils.js +942 -0
  113. package/lib/Utils/rich-message-utils.js[Old] +387 -0
  114. package/lib/Utils/signal.js +200 -0
  115. package/lib/Utils/stanza-ack.js +37 -0
  116. package/lib/Utils/sync-action-utils.js +47 -0
  117. package/lib/Utils/tc-token-utils.js +162 -0
  118. package/lib/Utils/use-multi-file-auth-state.js +120 -0
  119. package/lib/Utils/use-single-file-auth-state.js +96 -0
  120. package/lib/Utils/use-sqlite-auth-state.js +108 -0
  121. package/lib/Utils/validate-connection.js +206 -0
  122. package/lib/Utils/view-once-utils.js +206 -0
  123. package/lib/Utils/voip-rekey.js +20 -0
  124. package/lib/Utils/welcome-flow.js +220 -0
  125. package/lib/WABinary/constants.js +1463 -0
  126. package/lib/WABinary/decode.js +261 -0
  127. package/lib/WABinary/encode.js +219 -0
  128. package/lib/WABinary/generic-utils.js +227 -0
  129. package/lib/WABinary/index.js +5 -0
  130. package/lib/WABinary/jid-utils.js +95 -0
  131. package/lib/WABinary/types.js +1 -0
  132. package/lib/WAM/BinaryInfo.js +9 -0
  133. package/lib/WAM/constants.js +22852 -0
  134. package/lib/WAM/encode.js +149 -0
  135. package/lib/WAM/index.js +3 -0
  136. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +96 -0
  137. package/lib/WAUSync/Protocols/USyncContactProtocol.js +56 -0
  138. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  139. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  140. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +70 -0
  141. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +28 -0
  142. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +25 -0
  143. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  144. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +34 -0
  145. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  146. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
  147. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  148. package/lib/WAUSync/Protocols/index.js +12 -0
  149. package/lib/WAUSync/USyncQuery.js +201 -0
  150. package/lib/WAUSync/USyncUser.js +54 -0
  151. package/lib/WAUSync/index.js +3 -0
  152. package/lib/index.d.ts +406 -0
  153. package/lib/index.js +11 -0
  154. package/package.json +125 -0
@@ -0,0 +1,387 @@
1
+ /**
2
+ * Lia@Changes 09-04-26 [WIP]
3
+ * Adds support for tables and code blocks with richResponseMessage (wrapped inside botForwardedMessage).
4
+ *
5
+ * If you use or copy this code, please credit my name or project.
6
+ * @crysnovax/bailey
7
+ */
8
+ import { getRandomValues, randomUUID, randomBytes } from 'crypto';
9
+ import { BOT_RENDERING_CONFIG_METADATA, DONATE_URL, LEXER_REGEX } from '../Defaults/index.js';
10
+ import { LANGUAGE_KEYWORDS } from '../WABinary/constants.js';
11
+ import { CodeHighlightType, RichSubMessageType } from '../Types/RichType.js';
12
+ import { proto } from '../../WAProto/index.js';
13
+ import { unixTimestampSeconds } from './generics.js';
14
+ const textEncoder = new TextEncoder();
15
+ const NOOP = new Set([]);
16
+ export const tokenizeCode = (code, language = 'javascript') => {
17
+ const keywords = LANGUAGE_KEYWORDS[language] || NOOP;
18
+ const blocks = [];
19
+ LEXER_REGEX.lastIndex = 0;
20
+ let match;
21
+ while ((match = LEXER_REGEX.exec(code)) !== null) {
22
+ if (match[1]) {
23
+ blocks.push({ highlightType: CodeHighlightType.COMMENT, codeContent: match[1] });
24
+ }
25
+ else if (match[2]) {
26
+ blocks.push({ highlightType: CodeHighlightType.STRING, codeContent: match[2] });
27
+ }
28
+ else if (match[3]) {
29
+ blocks.push({
30
+ highlightType: keywords.has(match[3]) ? CodeHighlightType.KEYWORD : CodeHighlightType.METHOD,
31
+ codeContent: match[3],
32
+ });
33
+ }
34
+ else if (match[4]) {
35
+ blocks.push({
36
+ highlightType: keywords.has(match[4]) ? CodeHighlightType.KEYWORD : CodeHighlightType.DEFAULT,
37
+ codeContent: match[4],
38
+ });
39
+ }
40
+ else if (match[5]) {
41
+ blocks.push({ highlightType: CodeHighlightType.NUMBER, codeContent: match[5] });
42
+ }
43
+ else {
44
+ blocks.push({ highlightType: CodeHighlightType.DEFAULT, codeContent: match[6] });
45
+ }
46
+ }
47
+ return blocks;
48
+ };
49
+ // Lia@Changes 09-04-26 --- Inject buffer into unifiedResponse.data to support proper rendering of rich messages (ex: tables and code blocks)
50
+ export const toUnified = (submessages) =>
51
+ ({
52
+ response_id: randomUUID(),
53
+ sections: submessages.map((submessage, index) => {
54
+ switch (submessage.messageType) {
55
+ case RichSubMessageType.CODE:
56
+ const codeMetadata = submessage.codeMetadata;
57
+ return {
58
+ view_model: {
59
+ primitive: {
60
+ language: codeMetadata.codeLanguage,
61
+ code_blocks: codeMetadata.codeBlocks.map((block) => ({ content: block.codeContent, type: CodeHighlightType[block.highlightType] })),
62
+ __typename: 'GenAICodeUXPrimitive'
63
+ },
64
+ __typename: 'GenAISingleLayoutViewModel'
65
+ }
66
+ };
67
+ case RichSubMessageType.CONTENT_ITEMS:
68
+ return {
69
+ view_model: {
70
+ primitives: submessage.contentItemsMetadata.itemsMetadata.map((item) => {
71
+ const reelItem = item.reelItem
72
+ return {
73
+ reels_url: reelItem.videoUrl,
74
+ thumbnail_url: reelItem.thumbnailUrl,
75
+ creator: reelItem.creator || '@crysnovax/bailey',
76
+ avatar_url: reelItem.profileIconUrl,
77
+ reels_title: reelItem.title,
78
+ likes_count: reelItem.likesCount || 0,
79
+ shares_count: reelItem.sharesCount || 0,
80
+ view_count: reelItem.viewCount || 0,
81
+ reel_source: reelItem.reelSource || 'IG',
82
+ is_verified: reelItem.isVerified || false,
83
+ __typename: 'GenAIReelPrimitive'
84
+ }
85
+ }),
86
+ __typename: 'GenAIHScrollLayoutViewModel'
87
+ }
88
+ };
89
+ case RichSubMessageType.LATEX:
90
+ const latexMetadata = submessage.latexMetadata;
91
+ const item = {
92
+ latex_expression: latexMetadata.expressions[0]?.latexExpression,
93
+ font_height: latexMetadata.expressions[0]?.fontHeight,
94
+ padding: 15,
95
+ latex_image: {
96
+ url: latexMetadata.expressions[0]?.url,
97
+ width: latexMetadata.expressions[0]?.width || 388,
98
+ height: latexMetadata.expressions[0]?.height || 160
99
+ }
100
+ };
101
+ return {
102
+ view_model: {
103
+ primitive: {
104
+ item,
105
+ ...item,
106
+ __typename: 'GenAILatexUXPrimitive'
107
+ },
108
+ __typename: 'GenAISingleLayoutViewModel'
109
+ }
110
+ };
111
+ case RichSubMessageType.TABLE:
112
+ const tableMetadata = submessage.tableMetadata;
113
+ return {
114
+ view_model: {
115
+ primitive: {
116
+ title: tableMetadata.title,
117
+ rows: tableMetadata.rows.map((row) => ({ is_header: row.isHeading, cells: row.items, markdown_cells: [] })),
118
+ __typename: 'GenATableUXPrimitive'
119
+ },
120
+ __typename: 'GenAISingleLayoutViewModel'
121
+ }
122
+ };
123
+ case RichSubMessageType.TEXT:
124
+ const shouldAddInlineEntity = index == 0;
125
+ const inlineEntity = [{
126
+ key: 'Crysnovax',
127
+ metadata: {
128
+ reference_id: 1,
129
+ reference_url: DONATE_URL,
130
+ reference_title: 'Official Website',
131
+ reference_display_name: 'Website',
132
+ sources: [{
133
+ source_type: 'THIRD_PARTY',
134
+ source_display_name: 'Website',
135
+ source_subtitle: '',
136
+ source_url: DONATE_URL
137
+ }],
138
+ __typename: 'GenAISearchCitationItem'
139
+ }
140
+ }];
141
+ const textEntity = shouldAddInlineEntity ?
142
+ '{{Crysnovax}}¹{{/Crysnovax}}' :
143
+ '';
144
+ return {
145
+ view_model: {
146
+ primitive: {
147
+ text: submessage.messageText + textEntity,
148
+ inline_entities: shouldAddInlineEntity ?
149
+ inlineEntity :
150
+ [],
151
+ __typename: 'GenAIMarkdownTextUXPrimitive'
152
+ },
153
+ __typename: 'GenAISingleLayoutViewModel'
154
+ }
155
+ };
156
+ }
157
+ return submessage;
158
+ })
159
+ });
160
+ // Lia@Note 17-04-26 --- WIP
161
+ export const buildAdditionalBotMetadataContext = (submessages) => {
162
+ const sources = [];
163
+ const mediaDetailsMetadataList = [];
164
+ for (let i = 0; i < submessages.length; i++) {
165
+ const submessage = submessages[i];
166
+ switch (submessage.messageType) {
167
+ case RichSubMessageType.CONTENT_ITEMS:
168
+ const itemsMetadata = submessage.contentItemsMetadata.itemsMetadata;
169
+ for (let n = 0; n < itemsMetadata.length; n++) {
170
+ const reelItem = itemsMetadata[n].reelItem;
171
+ sources.push({
172
+ provider: 0,
173
+ thumbnailCdnUrl: reelItem.thumbnailUrl,
174
+ sourceProviderUrl: reelItem.videoUrl,
175
+ sourceQuery: '',
176
+ faviconCdnUrl: '',
177
+ citationNumber: i + 1,
178
+ sourceTitle: reelItem.title
179
+ });
180
+ mediaDetailsMetadataList.push({
181
+ id: randomBytes(32).toString('hex'),
182
+ previewMedia: {
183
+ fileSha256: '',
184
+ mediaKey: '',
185
+ fileEncSha256: '',
186
+ directPath: '',
187
+ mediaKeyTimestamp: unixTimestampSeconds(),
188
+ mimetype: 'image/jpeg'
189
+ }
190
+ });
191
+ }
192
+ break;
193
+ case RichSubMessageType.LATEX:
194
+ const expressions = submessage.latexMetadata.expressions;
195
+ for (let n = 0; n < expressions.length; n++) {
196
+ const expression = expressions[n];
197
+ mediaDetailsMetadataList.push({
198
+ id: randomBytes(32).toString('hex'),
199
+ previewMedia: {
200
+ fileSha256: '',
201
+ mediaKey: '',
202
+ fileEncSha256: '',
203
+ directPath: '',
204
+ mediaKeyTimestamp: unixTimestampSeconds(),
205
+ mimetype: 'image/jpeg'
206
+ }
207
+ });
208
+ }
209
+ break;
210
+ }
211
+ }
212
+ return { sources, mediaDetailsMetadataList };
213
+ }
214
+ export const prepareRichResponseMessage = (content) => {
215
+ const { code, contentText, expressions, footerText, headerText, items, language, richResponse, table, text, title } = content;
216
+ let submessages = [];
217
+ if (Array.isArray(richResponse)) {
218
+ submessages = richResponse.map((submessage) => {
219
+ if (submessage.text) {
220
+ return {
221
+ messageType: RichSubMessageType.TEXT,
222
+ messageText: submessage.text
223
+ };
224
+ }
225
+ else if (submessage.code) {
226
+ return {
227
+ messageType: RichSubMessageType.CODE,
228
+ codeMetadata: {
229
+ codeLanguage: submessage.language,
230
+ codeBlocks: submessage.code
231
+ }
232
+ };
233
+ }
234
+ else if (submessage.expressions) {
235
+ return {
236
+ messageType: RichSubMessageType.LATEX,
237
+ latexMetadata: {
238
+ text: submessage.text,
239
+ expressions: submessage.expressions
240
+ }
241
+ };
242
+ }
243
+ else if (submessage.items) {
244
+ return {
245
+ messageType: RichSubMessageType.CONTENT_ITEMS,
246
+ contentItemsMetadata: {
247
+ itemsMetadata: submessage.items
248
+ }
249
+ };
250
+ }
251
+ else if (submessage.table) {
252
+ return {
253
+ messageType: RichSubMessageType.TABLE,
254
+ tableMetadata: {
255
+ title: submessage.title,
256
+ rows: submessage.table
257
+ }
258
+ };
259
+ }
260
+ return submessage;
261
+ });
262
+ }
263
+ else {
264
+ if (headerText) {
265
+ submessages.push({
266
+ messageType: RichSubMessageType.TEXT,
267
+ messageText: headerText
268
+ });
269
+ }
270
+ if (contentText) {
271
+ submessages.push({
272
+ messageType: RichSubMessageType.TEXT,
273
+ messageText: contentText
274
+ });
275
+ }
276
+ if (code) {
277
+ language ??= 'javascript';
278
+ submessages.push({
279
+ messageType: RichSubMessageType.CODE,
280
+ codeMetadata: {
281
+ codeLanguage: language,
282
+ codeBlocks: tokenizeCode(code, language)
283
+ }
284
+ });
285
+ }
286
+ else if (expressions) {
287
+ submessages.push({
288
+ messageType: RichSubMessageType.LATEX,
289
+ latexMetadata: {
290
+ text,
291
+ expressions
292
+ }
293
+ });
294
+ }
295
+ else if (items) {
296
+ submessages.push({
297
+ messageType: RichSubMessageType.CONTENT_ITEMS,
298
+ contentItemsMetadata: {
299
+ itemsMetadata: items.map((item) => ({ reelItem: item })),
300
+ contentType: proto.AIRichResponseContentItemsMetadata.ContentType.CAROUSEL
301
+ }
302
+ });
303
+ }
304
+ else if (table) {
305
+ const tableRows = table.map((items, index) => ({
306
+ isHeading: index == 0,
307
+ items
308
+ }));
309
+ submessages.push({
310
+ messageType: RichSubMessageType.TABLE,
311
+ tableMetadata: {
312
+ title,
313
+ rows: tableRows
314
+ }
315
+ });
316
+ }
317
+ if (footerText) {
318
+ submessages.push({
319
+ messageType: RichSubMessageType.TEXT,
320
+ messageText: footerText
321
+ });
322
+ }
323
+ }
324
+ const unified = toUnified(submessages);
325
+ const message = wrapToBotForwardedMessage({
326
+ submessages,
327
+ messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
328
+ unifiedResponse: {
329
+ data: textEncoder.encode(JSON.stringify(unified))
330
+ },
331
+ contextInfo: {
332
+ isForwarded: true,
333
+ forwardingScore: 1,
334
+ forwardedAiBotMessageInfo: { botJid: '867051314767696@bot' },
335
+ forwardOrigin: 4
336
+ }
337
+ });
338
+ // Lia@Note 17-04-26 --- TODO: Fill mediaDetailsMetadataList and sources field
339
+ const { sources, mediaDetailsMetadataList } = buildAdditionalBotMetadataContext(submessages);
340
+ const botMetadata = message.messageContextInfo.botMetadata;
341
+ if (sources.length > 0) {
342
+ botMetadata.richResponseSourcesMetadata = { sources };
343
+ }
344
+ if (mediaDetailsMetadataList.length > 0) {
345
+ botMetadata.unifiedResponseMutation = { mediaDetailsMetadataList };
346
+ }
347
+ return message;
348
+ }
349
+ // Lia@Note 17-04-26 --- signature and certificateChain for proofs[] field
350
+ export const botMetadataSignature = () => {
351
+ const signature = new Uint8Array(64);
352
+ getRandomValues(signature);
353
+ return signature;
354
+ }
355
+ export const botMetadataCertificate = (length = 700) => {
356
+ const certificate = new Uint8Array(length);
357
+ certificate[0] = 48;
358
+ certificate[1] = 130;
359
+ getRandomValues(certificate.subarray(2));
360
+ return certificate;
361
+ }
362
+ export const wrapToBotForwardedMessage = (richResponseMessage) =>
363
+ ({
364
+ messageContextInfo: {
365
+ botMetadata: {
366
+ pluginMetadata: {},
367
+ // Lia@Note 09-04-26 --- TODO: Fill verificationMetadata field
368
+ verificationMetadata: {
369
+ proofs: [
370
+ {
371
+ certificateChain: [
372
+ botMetadataCertificate(684),
373
+ botMetadataCertificate(892)
374
+ ],
375
+ version: 1,
376
+ useCase: 1,
377
+ signature: botMetadataSignature()
378
+ }
379
+ ]
380
+ },
381
+ botRenderingConfigMetadata: BOT_RENDERING_CONFIG_METADATA
382
+ }
383
+ },
384
+ botForwardedMessage: {
385
+ message: { richResponseMessage }
386
+ }
387
+ });
@@ -0,0 +1,200 @@
1
+ import { KEY_BUNDLE_TYPE } from '../Defaults/index.js';
2
+ import { assertNodeErrorFree, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildUInt, getServerFromDomainType, jidDecode, S_WHATSAPP_NET, WAJIDDomains } from '../WABinary/index.js';
3
+ import { Curve, generateSignalPubKey } from './crypto.js';
4
+ import { encodeBigEndian } from './generics.js';
5
+ function chunk(array, size) {
6
+ const chunks = [];
7
+ for (let i = 0; i < array.length; i += size) {
8
+ chunks.push(array.slice(i, i + size));
9
+ }
10
+ return chunks;
11
+ }
12
+ export const createSignalIdentity = (wid, accountSignatureKey) => {
13
+ return {
14
+ identifier: { name: wid, deviceId: 0 },
15
+ identifierKey: generateSignalPubKey(accountSignatureKey)
16
+ };
17
+ };
18
+ export const getPreKeys = async ({ get }, min, limit) => {
19
+ const idList = [];
20
+ for (let id = min; id < limit; id++) {
21
+ idList.push(id.toString());
22
+ }
23
+ return get('pre-key', idList);
24
+ };
25
+ export const generateOrGetPreKeys = (creds, range) => {
26
+ const avaliable = creds.nextPreKeyId - creds.firstUnuploadedPreKeyId;
27
+ const remaining = range - avaliable;
28
+ const lastPreKeyId = creds.nextPreKeyId + remaining - 1;
29
+ const newPreKeys = {};
30
+ if (remaining > 0) {
31
+ for (let i = creds.nextPreKeyId; i <= lastPreKeyId; i++) {
32
+ newPreKeys[i] = Curve.generateKeyPair();
33
+ }
34
+ }
35
+ return {
36
+ newPreKeys,
37
+ lastPreKeyId,
38
+ preKeysRange: [creds.firstUnuploadedPreKeyId, range]
39
+ };
40
+ };
41
+ export const xmppSignedPreKey = (key) => ({
42
+ tag: 'skey',
43
+ attrs: {},
44
+ content: [
45
+ { tag: 'id', attrs: {}, content: encodeBigEndian(key.keyId, 3) },
46
+ { tag: 'value', attrs: {}, content: key.keyPair.public },
47
+ { tag: 'signature', attrs: {}, content: key.signature }
48
+ ]
49
+ });
50
+ export const xmppPreKey = (pair, id) => ({
51
+ tag: 'key',
52
+ attrs: {},
53
+ content: [
54
+ { tag: 'id', attrs: {}, content: encodeBigEndian(id, 3) },
55
+ { tag: 'value', attrs: {}, content: pair.public }
56
+ ]
57
+ });
58
+ const isValidUInt = (n) => typeof n === 'number' && Number.isInteger(n);
59
+ export const extractE2ESessionFromRetryReceipt = (receipt) => {
60
+ const keysNode = getBinaryNodeChild(receipt, 'keys');
61
+ if (!keysNode)
62
+ return null;
63
+ const typeBuf = getBinaryNodeChildBuffer(keysNode, 'type');
64
+ if (!typeBuf || typeBuf.length !== 1 || typeBuf[0] !== KEY_BUNDLE_TYPE[0])
65
+ return null;
66
+ const identity = getBinaryNodeChildBuffer(keysNode, 'identity');
67
+ const skey = getBinaryNodeChild(keysNode, 'skey');
68
+ if (!identity || identity.length !== 32 || !skey)
69
+ return null;
70
+ const registrationId = getBinaryNodeChildUInt(receipt, 'registration', 4);
71
+ if (!isValidUInt(registrationId))
72
+ return null;
73
+ const signedPubKey = getBinaryNodeChildBuffer(skey, 'value');
74
+ const signedSig = getBinaryNodeChildBuffer(skey, 'signature');
75
+ const signedKeyId = getBinaryNodeChildUInt(skey, 'id', 3);
76
+ if (!signedPubKey || signedPubKey.length !== 32 || !signedSig || !isValidUInt(signedKeyId)) {
77
+ return null;
78
+ }
79
+ const preKeyNode = getBinaryNodeChild(keysNode, 'key');
80
+ let preKey;
81
+ if (preKeyNode) {
82
+ const preKeyPub = getBinaryNodeChildBuffer(preKeyNode, 'value');
83
+ const preKeyId = getBinaryNodeChildUInt(preKeyNode, 'id', 3);
84
+ if (!preKeyPub || preKeyPub.length !== 32 || !isValidUInt(preKeyId)) {
85
+ return null;
86
+ }
87
+ preKey = { keyId: preKeyId, publicKey: generateSignalPubKey(preKeyPub) };
88
+ }
89
+ return {
90
+ registrationId,
91
+ identityKey: generateSignalPubKey(identity),
92
+ signedPreKey: {
93
+ keyId: signedKeyId,
94
+ publicKey: generateSignalPubKey(signedPubKey),
95
+ signature: signedSig
96
+ },
97
+ preKey
98
+ };
99
+ };
100
+ export const parseAndInjectE2ESessions = async (node, repository) => {
101
+ const extractKey = (key) => key
102
+ ? {
103
+ keyId: getBinaryNodeChildUInt(key, 'id', 3),
104
+ publicKey: generateSignalPubKey(getBinaryNodeChildBuffer(key, 'value')),
105
+ signature: getBinaryNodeChildBuffer(key, 'signature')
106
+ }
107
+ : undefined;
108
+ const nodes = getBinaryNodeChildren(getBinaryNodeChild(node, 'list'), 'user');
109
+ for (const node of nodes) {
110
+ assertNodeErrorFree(node);
111
+ }
112
+ // Most of the work in repository.injectE2ESession is CPU intensive, not IO
113
+ // So Promise.all doesn't really help here,
114
+ // but blocks even loop if we're using it inside keys.transaction, and it makes it "sync" actually
115
+ // This way we chunk it in smaller parts and between those parts we can yield to the event loop
116
+ // It's rare case when you need to E2E sessions for so many users, but it's possible
117
+ const chunkSize = 100;
118
+ const chunks = chunk(nodes, chunkSize);
119
+ for (const nodesChunk of chunks) {
120
+ for (const node of nodesChunk) {
121
+ const signedKey = getBinaryNodeChild(node, 'skey');
122
+ const key = getBinaryNodeChild(node, 'key');
123
+ const identity = getBinaryNodeChildBuffer(node, 'identity');
124
+ const jid = node.attrs.jid;
125
+ const registrationId = getBinaryNodeChildUInt(node, 'registration', 4);
126
+ await repository.injectE2ESession({
127
+ jid,
128
+ session: {
129
+ registrationId: registrationId,
130
+ identityKey: generateSignalPubKey(identity),
131
+ signedPreKey: extractKey(signedKey),
132
+ preKey: extractKey(key)
133
+ }
134
+ });
135
+ }
136
+ }
137
+ };
138
+ export const extractDeviceJids = (result, myJid, myLid, excludeZeroDevices) => {
139
+ const { user: myUser, device: myDevice } = jidDecode(myJid);
140
+ const extracted = [];
141
+ for (const userResult of result) {
142
+ const { devices, id } = userResult;
143
+ const decoded = jidDecode(id), { user, server } = decoded;
144
+ let { domainType } = decoded;
145
+ const deviceList = devices?.deviceList;
146
+ if (!Array.isArray(deviceList))
147
+ continue;
148
+ for (const { id: device, keyIndex, isHosted } of deviceList) {
149
+ if ((!excludeZeroDevices || device !== 0) && // if zero devices are not-excluded, or device is non zero
150
+ ((myUser !== user && myLid !== user) || myDevice !== device) && // either different user or if me user, not this device
151
+ (device === 0 || !!keyIndex) // ensure that "key-index" is specified for "non-zero" devices, produces a bad req otherwise
152
+ ) {
153
+ if (isHosted) {
154
+ domainType = domainType === WAJIDDomains.LID ? WAJIDDomains.HOSTED_LID : WAJIDDomains.HOSTED;
155
+ }
156
+ extracted.push({
157
+ user,
158
+ device,
159
+ domainType,
160
+ server: getServerFromDomainType(server, domainType)
161
+ });
162
+ }
163
+ }
164
+ }
165
+ return extracted;
166
+ };
167
+ /**
168
+ * get the next N keys for upload or processing
169
+ * @param count number of pre-keys to get or generate
170
+ */
171
+ export const getNextPreKeys = async ({ creds, keys }, count) => {
172
+ const { newPreKeys, lastPreKeyId, preKeysRange } = generateOrGetPreKeys(creds, count);
173
+ const update = {
174
+ nextPreKeyId: Math.max(lastPreKeyId + 1, creds.nextPreKeyId),
175
+ firstUnuploadedPreKeyId: Math.max(creds.firstUnuploadedPreKeyId, lastPreKeyId + 1)
176
+ };
177
+ await keys.set({ 'pre-key': newPreKeys });
178
+ const preKeys = await getPreKeys(keys, preKeysRange[0], preKeysRange[0] + preKeysRange[1]);
179
+ return { update, preKeys };
180
+ };
181
+ export const getNextPreKeysNode = async (state, count) => {
182
+ const { creds } = state;
183
+ const { update, preKeys } = await getNextPreKeys(state, count);
184
+ const node = {
185
+ tag: 'iq',
186
+ attrs: {
187
+ xmlns: 'encrypt',
188
+ type: 'set',
189
+ to: S_WHATSAPP_NET
190
+ },
191
+ content: [
192
+ { tag: 'registration', attrs: {}, content: encodeBigEndian(creds.registrationId) },
193
+ { tag: 'type', attrs: {}, content: KEY_BUNDLE_TYPE },
194
+ { tag: 'identity', attrs: {}, content: creds.signedIdentityKey.public },
195
+ { tag: 'list', attrs: {}, content: Object.keys(preKeys).map(k => xmppPreKey(preKeys[+k], +k)) },
196
+ xmppSignedPreKey(creds.signedPreKey)
197
+ ]
198
+ };
199
+ return { update, node };
200
+ };
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Builds an ACK stanza for a received node.
3
+ * Pure function -- no I/O, no side effects.
4
+ *
5
+ * Mirrors WhatsApp Web's ACK construction:
6
+ * - WAWebHandleMsgSendAck.sendAck / sendNack
7
+ * - WAWebCreateNackFromStanza.createNackFromStanza
8
+ */
9
+ export function buildAckStanza(node, errorCode, meId) {
10
+ const { tag, attrs } = node;
11
+ const stanza = {
12
+ tag: 'ack',
13
+ attrs: {
14
+ id: attrs.id,
15
+ to: attrs.from,
16
+ class: tag
17
+ }
18
+ };
19
+ if (errorCode) {
20
+ stanza.attrs.error = errorCode.toString();
21
+ }
22
+ if (attrs.participant) {
23
+ stanza.attrs.participant = attrs.participant;
24
+ }
25
+ if (attrs.recipient) {
26
+ stanza.attrs.recipient = attrs.recipient;
27
+ }
28
+ // WA Web always includes type when present: `n.type || DROP_ATTR`
29
+ if (attrs.type) {
30
+ stanza.attrs.type = attrs.type;
31
+ }
32
+ // WA Web WAWebHandleMsgSendAck.sendAck/sendNack always include `from` for message-class ACKs
33
+ if (tag === 'message' && meId) {
34
+ stanza.attrs.from = meId;
35
+ }
36
+ return stanza;
37
+ }
@@ -0,0 +1,47 @@
1
+ import { proto } from '../../WAProto/index.js';
2
+ import { isLidUser, isPnUser } from '../WABinary/index.js';
3
+ /**
4
+ * Process contactAction and return events to emit.
5
+ * Pure function - no side effects.
6
+ */
7
+ export const processContactAction = (action, id, logger) => {
8
+ const results = [];
9
+ if (!id) {
10
+ logger?.warn({ hasFullName: !!action.fullName, hasLidJid: !!action.lidJid, hasPnJid: !!action.pnJid }, 'contactAction sync: missing id in index');
11
+ return results;
12
+ }
13
+ const lidJid = action.lidJid;
14
+ const idIsPn = isPnUser(id);
15
+ // PN is in index[1], not in contactAction.pnJid which is usually null
16
+ const phoneNumber = idIsPn ? id : action.pnJid || undefined;
17
+ // Always emit contacts.upsert
18
+ results.push({
19
+ event: 'contacts.upsert',
20
+ data: [
21
+ {
22
+ id,
23
+ name: action.fullName || action.firstName || action.username || undefined,
24
+ lid: lidJid || undefined,
25
+ phoneNumber
26
+ }
27
+ ]
28
+ });
29
+ // Emit lid-mapping.update if we have valid LID-PN pair
30
+ if (lidJid && isLidUser(lidJid) && idIsPn) {
31
+ results.push({
32
+ event: 'lid-mapping.update',
33
+ data: { lid: lidJid, pn: id }
34
+ });
35
+ }
36
+ return results;
37
+ };
38
+ export const emitSyncActionResults = (ev, results) => {
39
+ for (const result of results) {
40
+ if (result.event === 'contacts.upsert') {
41
+ ev.emit('contacts.upsert', result.data);
42
+ }
43
+ else {
44
+ ev.emit('lid-mapping.update', result.data);
45
+ }
46
+ }
47
+ };