@dhilzzkz/baileys 0.0.0-stage → 0.1.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 (241) hide show
  1. package/LICENSE +23 -0
  2. package/NOTICE.md +37 -0
  3. package/README.md +2083 -2
  4. package/WAProto/index.d.ts +22220 -0
  5. package/WAProto/index.js +5 -0
  6. package/lib/Addon/http-error.d.ts +18 -0
  7. package/lib/Addon/http-error.js +40 -0
  8. package/lib/Addon/index.d.ts +3 -0
  9. package/lib/Addon/index.js +4 -0
  10. package/lib/Addon/keyed-db.d.ts +14 -0
  11. package/lib/Addon/keyed-db.js +241 -0
  12. package/lib/Addon/link-preview.d.ts +15 -0
  13. package/lib/Addon/link-preview.js +79 -0
  14. package/lib/Defaults/index.d.ts +188 -0
  15. package/lib/Defaults/index.js +185 -0
  16. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  17. package/lib/Signal/Group/ciphertext-message.js +11 -0
  18. package/lib/Signal/Group/group-cipher.d.ts +10 -0
  19. package/lib/Signal/Group/group-cipher.js +81 -0
  20. package/lib/Signal/Group/group-session-builder.d.ts +7 -0
  21. package/lib/Signal/Group/group-session-builder.js +29 -0
  22. package/lib/Signal/Group/index.d.ts +11 -0
  23. package/lib/Signal/Group/index.js +11 -0
  24. package/lib/Signal/Group/keyhelper.d.ts +6 -0
  25. package/lib/Signal/Group/keyhelper.js +17 -0
  26. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  27. package/lib/Signal/Group/sender-chain-key.js +25 -0
  28. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  29. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  30. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  31. package/lib/Signal/Group/sender-key-message.js +65 -0
  32. package/lib/Signal/Group/sender-key-name.d.ts +11 -0
  33. package/lib/Signal/Group/sender-key-name.js +47 -0
  34. package/lib/Signal/Group/sender-key-record.d.ts +12 -0
  35. package/lib/Signal/Group/sender-key-record.js +40 -0
  36. package/lib/Signal/Group/sender-key-state.d.ts +16 -0
  37. package/lib/Signal/Group/sender-key-state.js +83 -0
  38. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  39. package/lib/Signal/Group/sender-message-key.js +25 -0
  40. package/lib/Signal/Protocol/crypto.d.ts +6 -0
  41. package/lib/Signal/Protocol/crypto.js +61 -0
  42. package/lib/Signal/Protocol/curve.d.ts +8 -0
  43. package/lib/Signal/Protocol/curve.js +61 -0
  44. package/lib/Signal/Protocol/index.d.ts +16 -0
  45. package/lib/Signal/Protocol/index.js +9 -0
  46. package/lib/Signal/Protocol/internals.d.ts +57 -0
  47. package/lib/Signal/Protocol/internals.js +155 -0
  48. package/lib/Signal/Protocol/session-builder.d.ts +40 -0
  49. package/lib/Signal/Protocol/session-builder.js +143 -0
  50. package/lib/Signal/Protocol/session-cipher.d.ts +26 -0
  51. package/lib/Signal/Protocol/session-cipher.js +301 -0
  52. package/lib/Signal/Protocol/session-record.d.ts +55 -0
  53. package/lib/Signal/Protocol/session-record.js +272 -0
  54. package/lib/Signal/libsignal.d.ts +54 -0
  55. package/lib/Signal/libsignal.js +426 -0
  56. package/lib/Signal/lid-mapping.d.ts +20 -0
  57. package/lib/Signal/lid-mapping.js +274 -0
  58. package/lib/Socket/Client/index.d.ts +2 -0
  59. package/lib/Socket/Client/index.js +2 -0
  60. package/lib/Socket/Client/types.d.ts +5 -0
  61. package/lib/Socket/Client/types.js +10 -0
  62. package/lib/Socket/Client/websocket.d.ts +12 -0
  63. package/lib/Socket/Client/websocket.js +119 -0
  64. package/lib/Socket/business.d.ts +387 -0
  65. package/lib/Socket/business.js +380 -0
  66. package/lib/Socket/chats.d.ts +144 -0
  67. package/lib/Socket/chats.js +1216 -0
  68. package/lib/Socket/communities.d.ts +554 -0
  69. package/lib/Socket/communities.js +431 -0
  70. package/lib/Socket/groups.d.ts +286 -0
  71. package/lib/Socket/groups.js +347 -0
  72. package/lib/Socket/index.d.ts +522 -0
  73. package/lib/Socket/index.js +11 -0
  74. package/lib/Socket/messages-recv.d.ts +326 -0
  75. package/lib/Socket/messages-recv.js +1822 -0
  76. package/lib/Socket/messages-send.d.ts +321 -0
  77. package/lib/Socket/messages-send.js +1378 -0
  78. package/lib/Socket/mex.d.ts +1 -0
  79. package/lib/Socket/mex.js +41 -0
  80. package/lib/Socket/newsletter.d.ts +283 -0
  81. package/lib/Socket/newsletter.js +225 -0
  82. package/lib/Socket/socket.d.ts +61 -0
  83. package/lib/Socket/socket.js +992 -0
  84. package/lib/Store/index.d.ts +3 -0
  85. package/lib/Store/index.js +3 -0
  86. package/lib/Store/make-in-memory-store.d.ts +63 -0
  87. package/lib/Store/make-in-memory-store.js +418 -0
  88. package/lib/Store/make-ordered-dictionary.d.ts +12 -0
  89. package/lib/Store/make-ordered-dictionary.js +78 -0
  90. package/lib/Store/object-repository.d.ts +10 -0
  91. package/lib/Store/object-repository.js +23 -0
  92. package/lib/Types/Auth.d.ts +1 -0
  93. package/lib/Types/Auth.js +1 -0
  94. package/lib/Types/Business.d.ts +1 -0
  95. package/lib/Types/Business.js +1 -0
  96. package/lib/Types/Call.d.ts +1 -0
  97. package/lib/Types/Call.js +1 -0
  98. package/lib/Types/Chat.d.ts +1 -0
  99. package/lib/Types/Chat.js +7 -0
  100. package/lib/Types/Contact.d.ts +1 -0
  101. package/lib/Types/Contact.js +1 -0
  102. package/lib/Types/Events.d.ts +1 -0
  103. package/lib/Types/Events.js +1 -0
  104. package/lib/Types/GroupMetadata.d.ts +1 -0
  105. package/lib/Types/GroupMetadata.js +1 -0
  106. package/lib/Types/Label.d.ts +2 -0
  107. package/lib/Types/Label.js +24 -0
  108. package/lib/Types/LabelAssociation.d.ts +2 -0
  109. package/lib/Types/LabelAssociation.js +6 -0
  110. package/lib/Types/Message.d.ts +11 -0
  111. package/lib/Types/Message.js +17 -0
  112. package/lib/Types/Mex.d.ts +2 -0
  113. package/lib/Types/Mex.js +38 -0
  114. package/lib/Types/Product.d.ts +1 -0
  115. package/lib/Types/Product.js +1 -0
  116. package/lib/Types/RichType.d.ts +2 -0
  117. package/lib/Types/RichType.js +22 -0
  118. package/lib/Types/Signal.d.ts +1 -0
  119. package/lib/Types/Signal.js +1 -0
  120. package/lib/Types/Socket.d.ts +1 -0
  121. package/lib/Types/Socket.js +1 -0
  122. package/lib/Types/State.d.ts +5 -0
  123. package/lib/Types/State.js +54 -0
  124. package/lib/Types/USync.d.ts +1 -0
  125. package/lib/Types/USync.js +1 -0
  126. package/lib/Types/index.d.ts +13 -0
  127. package/lib/Types/index.js +25 -0
  128. package/lib/Utils/Auth/auth-utils.d.ts +58 -0
  129. package/lib/Utils/Auth/auth-utils.js +316 -0
  130. package/lib/Utils/Auth/companion-reg-client-utils.d.ts +4 -0
  131. package/lib/Utils/Auth/companion-reg-client-utils.js +39 -0
  132. package/lib/Utils/Auth/pre-key-manager.d.ts +25 -0
  133. package/lib/Utils/Auth/pre-key-manager.js +105 -0
  134. package/lib/Utils/Auth/use-multi-file-auth-state.d.ts +10 -0
  135. package/lib/Utils/Auth/use-multi-file-auth-state.js +116 -0
  136. package/lib/Utils/Auth/use-single-file-auth-state.d.ts +11 -0
  137. package/lib/Utils/Auth/use-single-file-auth-state.js +94 -0
  138. package/lib/Utils/Auth/use-sqlite-auth-state.d.ts +11 -0
  139. package/lib/Utils/Auth/use-sqlite-auth-state.js +109 -0
  140. package/lib/Utils/Auth/validate-connection.d.ts +44 -0
  141. package/lib/Utils/Auth/validate-connection.js +210 -0
  142. package/lib/Utils/Common/browser-utils.d.ts +9 -0
  143. package/lib/Utils/Common/browser-utils.js +28 -0
  144. package/lib/Utils/Common/generics.d.ts +63 -0
  145. package/lib/Utils/Common/generics.js +392 -0
  146. package/lib/Utils/Common/logger.d.ts +12 -0
  147. package/lib/Utils/Common/logger.js +12 -0
  148. package/lib/Utils/Common/make-mutex.d.ts +6 -0
  149. package/lib/Utils/Common/make-mutex.js +32 -0
  150. package/lib/Utils/Crypto/crypto.d.ts +39 -0
  151. package/lib/Utils/Crypto/crypto.js +117 -0
  152. package/lib/Utils/Crypto/lt-hash.d.ts +6 -0
  153. package/lib/Utils/Crypto/lt-hash.js +7 -0
  154. package/lib/Utils/Crypto/noise-handler.d.ts +20 -0
  155. package/lib/Utils/Crypto/noise-handler.js +200 -0
  156. package/lib/Utils/Crypto/signal.d.ts +82 -0
  157. package/lib/Utils/Crypto/signal.js +200 -0
  158. package/lib/Utils/Message/business.d.ts +49 -0
  159. package/lib/Utils/Message/business.js +230 -0
  160. package/lib/Utils/Message/decode-wa-message.d.ts +83 -0
  161. package/lib/Utils/Message/decode-wa-message.js +316 -0
  162. package/lib/Utils/Message/history.d.ts +75 -0
  163. package/lib/Utils/Message/history.js +133 -0
  164. package/lib/Utils/Message/link-preview.d.ts +13 -0
  165. package/lib/Utils/Message/link-preview.js +73 -0
  166. package/lib/Utils/Message/message-retry-manager.d.ts +79 -0
  167. package/lib/Utils/Message/message-retry-manager.js +259 -0
  168. package/lib/Utils/Message/messages-media.d.ts +134 -0
  169. package/lib/Utils/Message/messages-media.js +802 -0
  170. package/lib/Utils/Message/messages.d.ts +47 -0
  171. package/lib/Utils/Message/messages.js +1907 -0
  172. package/lib/Utils/Message/offline-node-processor.d.ts +10 -0
  173. package/lib/Utils/Message/offline-node-processor.js +40 -0
  174. package/lib/Utils/Message/process-message.d.ts +83 -0
  175. package/lib/Utils/Message/process-message.js +748 -0
  176. package/lib/Utils/Message/reporting-utils.d.ts +12 -0
  177. package/lib/Utils/Message/reporting-utils.js +257 -0
  178. package/lib/Utils/Message/rich-message-utils.d.ts +48 -0
  179. package/lib/Utils/Message/rich-message-utils.js +366 -0
  180. package/lib/Utils/Message/stanza-ack.d.ts +16 -0
  181. package/lib/Utils/Message/stanza-ack.js +37 -0
  182. package/lib/Utils/State/chat-utils.d.ts +408 -0
  183. package/lib/Utils/State/chat-utils.js +871 -0
  184. package/lib/Utils/State/event-buffer.d.ts +12 -0
  185. package/lib/Utils/State/event-buffer.js +621 -0
  186. package/lib/Utils/State/identity-change-handler.d.ts +13 -0
  187. package/lib/Utils/State/identity-change-handler.js +48 -0
  188. package/lib/Utils/State/sync-action-utils.d.ts +2 -0
  189. package/lib/Utils/State/sync-action-utils.js +48 -0
  190. package/lib/Utils/State/tc-token-utils.d.ts +29 -0
  191. package/lib/Utils/State/tc-token-utils.js +163 -0
  192. package/lib/Utils/index.d.ts +24 -0
  193. package/lib/Utils/index.js +24 -0
  194. package/lib/WABinary/constants.d.ts +61 -0
  195. package/lib/WABinary/constants.js +1466 -0
  196. package/lib/WABinary/decode.d.ts +9 -0
  197. package/lib/WABinary/decode.js +261 -0
  198. package/lib/WABinary/encode.d.ts +2 -0
  199. package/lib/WABinary/encode.js +219 -0
  200. package/lib/WABinary/generic-utils.d.ts +79 -0
  201. package/lib/WABinary/generic-utils.js +226 -0
  202. package/lib/WABinary/index.d.ts +5 -0
  203. package/lib/WABinary/index.js +5 -0
  204. package/lib/WABinary/jid-utils.d.ts +28 -0
  205. package/lib/WABinary/jid-utils.js +95 -0
  206. package/lib/WABinary/types.d.ts +1 -0
  207. package/lib/WABinary/types.js +1 -0
  208. package/lib/WAM/BinaryInfo.d.ts +7 -0
  209. package/lib/WAM/BinaryInfo.js +9 -0
  210. package/lib/WAM/constants.d.ts +34926 -0
  211. package/lib/WAM/constants.js +22852 -0
  212. package/lib/WAM/encode.d.ts +1 -0
  213. package/lib/WAM/encode.js +149 -0
  214. package/lib/WAM/index.d.ts +3 -0
  215. package/lib/WAM/index.js +3 -0
  216. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.d.ts +38 -0
  217. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +50 -0
  218. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
  219. package/lib/WAUSync/Protocols/USyncContactProtocol.js +51 -0
  220. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  221. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  222. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  223. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  224. package/lib/WAUSync/Protocols/USyncLIDProtocol.d.ts +14 -0
  225. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +28 -0
  226. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  227. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  228. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
  229. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  230. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  231. package/lib/WAUSync/Protocols/index.js +5 -0
  232. package/lib/WAUSync/USyncQuery.d.ts +20 -0
  233. package/lib/WAUSync/USyncQuery.js +97 -0
  234. package/lib/WAUSync/USyncUser.d.ts +16 -0
  235. package/lib/WAUSync/USyncUser.js +30 -0
  236. package/lib/WAUSync/index.d.ts +3 -0
  237. package/lib/WAUSync/index.js +3 -0
  238. package/lib/index.d.ts +11 -0
  239. package/lib/index.js +11 -0
  240. package/package.json +120 -5
  241. package/scripts/engine-requirements.js +16 -0
@@ -0,0 +1,230 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { createWriteStream, promises as fs } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { HttpError } from '../../Addon/index.js';
6
+ import { getBinaryNodeChild, getBinaryNodeChildren, getBinaryNodeChildString } from '../../WABinary/index.js';
7
+ import { generateMessageIDV2 } from '../Common/generics.js';
8
+ import { getStream, getUrlFromDirectPath } from './messages-media.js';
9
+ export const parseCatalogNode = (node) => {
10
+ const catalogNode = getBinaryNodeChild(node, 'product_catalog');
11
+ const products = getBinaryNodeChildren(catalogNode, 'product').map(parseProductNode);
12
+ const paging = getBinaryNodeChild(catalogNode, 'paging');
13
+ return {
14
+ products,
15
+ nextPageCursor: paging ? getBinaryNodeChildString(paging, 'after') : undefined
16
+ };
17
+ };
18
+ export const parseCollectionsNode = (node) => {
19
+ const collectionsNode = getBinaryNodeChild(node, 'collections');
20
+ const collections = getBinaryNodeChildren(collectionsNode, 'collection').map(collectionNode => {
21
+ const id = getBinaryNodeChildString(collectionNode, 'id');
22
+ const name = getBinaryNodeChildString(collectionNode, 'name');
23
+ const products = getBinaryNodeChildren(collectionNode, 'product').map(parseProductNode);
24
+ return {
25
+ id,
26
+ name,
27
+ products,
28
+ status: parseStatusInfo(collectionNode)
29
+ };
30
+ });
31
+ return {
32
+ collections
33
+ };
34
+ };
35
+ export const parseOrderDetailsNode = (node) => {
36
+ const orderNode = getBinaryNodeChild(node, 'order');
37
+ const products = getBinaryNodeChildren(orderNode, 'product').map(productNode => {
38
+ const imageNode = getBinaryNodeChild(productNode, 'image');
39
+ return {
40
+ id: getBinaryNodeChildString(productNode, 'id'),
41
+ name: getBinaryNodeChildString(productNode, 'name'),
42
+ imageUrl: getBinaryNodeChildString(imageNode, 'url'),
43
+ price: +getBinaryNodeChildString(productNode, 'price'),
44
+ currency: getBinaryNodeChildString(productNode, 'currency'),
45
+ quantity: +getBinaryNodeChildString(productNode, 'quantity')
46
+ };
47
+ });
48
+ const priceNode = getBinaryNodeChild(orderNode, 'price');
49
+ const orderDetails = {
50
+ price: {
51
+ total: +getBinaryNodeChildString(priceNode, 'total'),
52
+ currency: getBinaryNodeChildString(priceNode, 'currency')
53
+ },
54
+ products
55
+ };
56
+ return orderDetails;
57
+ };
58
+ export const toProductNode = (productId, product) => {
59
+ const attrs = {};
60
+ const content = [];
61
+ if (typeof productId !== 'undefined') {
62
+ content.push({
63
+ tag: 'id',
64
+ attrs: {},
65
+ content: Buffer.from(productId)
66
+ });
67
+ }
68
+ if (typeof product.name !== 'undefined') {
69
+ content.push({
70
+ tag: 'name',
71
+ attrs: {},
72
+ content: Buffer.from(product.name)
73
+ });
74
+ }
75
+ if (typeof product.description !== 'undefined') {
76
+ content.push({
77
+ tag: 'description',
78
+ attrs: {},
79
+ content: Buffer.from(product.description)
80
+ });
81
+ }
82
+ if (typeof product.retailerId !== 'undefined') {
83
+ content.push({
84
+ tag: 'retailer_id',
85
+ attrs: {},
86
+ content: Buffer.from(product.retailerId)
87
+ });
88
+ }
89
+ if (product.images.length) {
90
+ content.push({
91
+ tag: 'media',
92
+ attrs: {},
93
+ content: product.images.map(img => {
94
+ if (!('url' in img)) {
95
+ throw new HttpError('Expected img for product to already be uploaded', { statusCode: 400 });
96
+ }
97
+ return {
98
+ tag: 'image',
99
+ attrs: {},
100
+ content: [
101
+ {
102
+ tag: 'url',
103
+ attrs: {},
104
+ content: Buffer.from(img.url.toString())
105
+ }
106
+ ]
107
+ };
108
+ })
109
+ });
110
+ }
111
+ if (typeof product.price !== 'undefined') {
112
+ content.push({
113
+ tag: 'price',
114
+ attrs: {},
115
+ content: Buffer.from(product.price.toString())
116
+ });
117
+ }
118
+ if (typeof product.currency !== 'undefined') {
119
+ content.push({
120
+ tag: 'currency',
121
+ attrs: {},
122
+ content: Buffer.from(product.currency)
123
+ });
124
+ }
125
+ if ('originCountryCode' in product) {
126
+ if (typeof product.originCountryCode === 'undefined') {
127
+ attrs['compliance_category'] = 'COUNTRY_ORIGIN_EXEMPT';
128
+ }
129
+ else {
130
+ content.push({
131
+ tag: 'compliance_info',
132
+ attrs: {},
133
+ content: [
134
+ {
135
+ tag: 'country_code_origin',
136
+ attrs: {},
137
+ content: Buffer.from(product.originCountryCode)
138
+ }
139
+ ]
140
+ });
141
+ }
142
+ }
143
+ if (typeof product.isHidden !== 'undefined') {
144
+ attrs['is_hidden'] = product.isHidden.toString();
145
+ }
146
+ const node = {
147
+ tag: 'product',
148
+ attrs,
149
+ content
150
+ };
151
+ return node;
152
+ };
153
+ export const parseProductNode = (productNode) => {
154
+ const isHidden = productNode.attrs.is_hidden === 'true';
155
+ const id = getBinaryNodeChildString(productNode, 'id');
156
+ const mediaNode = getBinaryNodeChild(productNode, 'media');
157
+ const statusInfoNode = getBinaryNodeChild(productNode, 'status_info');
158
+ const product = {
159
+ id,
160
+ imageUrls: parseImageUrls(mediaNode),
161
+ reviewStatus: {
162
+ whatsapp: getBinaryNodeChildString(statusInfoNode, 'status')
163
+ },
164
+ availability: 'in stock',
165
+ name: getBinaryNodeChildString(productNode, 'name'),
166
+ retailerId: getBinaryNodeChildString(productNode, 'retailer_id'),
167
+ url: getBinaryNodeChildString(productNode, 'url'),
168
+ description: getBinaryNodeChildString(productNode, 'description'),
169
+ price: +getBinaryNodeChildString(productNode, 'price'),
170
+ currency: getBinaryNodeChildString(productNode, 'currency'),
171
+ isHidden
172
+ };
173
+ return product;
174
+ };
175
+ /**
176
+ * Uploads images not already uploaded to WA's servers
177
+ */
178
+ export async function uploadingNecessaryImagesOfProduct(product, waUploadToServer, timeoutMs = 30000) {
179
+ product = {
180
+ ...product,
181
+ images: product.images
182
+ ? await uploadingNecessaryImages(product.images, waUploadToServer, timeoutMs)
183
+ : product.images
184
+ };
185
+ return product;
186
+ }
187
+ /**
188
+ * Uploads images not already uploaded to WA's servers
189
+ */
190
+ export const uploadingNecessaryImages = async (images, waUploadToServer, timeoutMs = 30000) => {
191
+ const results = await Promise.all(images.map(async (img) => {
192
+ if ('url' in img) {
193
+ const url = img.url.toString();
194
+ if (url.includes('.whatsapp.net')) {
195
+ return { url };
196
+ }
197
+ }
198
+ const { stream } = await getStream(img);
199
+ const hasher = createHash('sha256');
200
+ const filePath = join(tmpdir(), 'img' + generateMessageIDV2());
201
+ const encFileWriteStream = createWriteStream(filePath);
202
+ for await (const block of stream) {
203
+ hasher.update(block);
204
+ encFileWriteStream.write(block);
205
+ }
206
+ const sha = hasher.digest('base64');
207
+ const { directPath } = await waUploadToServer(filePath, {
208
+ mediaType: 'product-catalog-image',
209
+ fileEncSha256B64: sha,
210
+ timeoutMs
211
+ });
212
+ await fs.unlink(filePath).catch(err => console.log('Error deleting temp file ', err));
213
+ return { url: getUrlFromDirectPath(directPath) };
214
+ }));
215
+ return results;
216
+ };
217
+ const parseImageUrls = (mediaNode) => {
218
+ const imgNode = getBinaryNodeChild(mediaNode, 'image');
219
+ return {
220
+ requested: getBinaryNodeChildString(imgNode, 'request_image_url'),
221
+ original: getBinaryNodeChildString(imgNode, 'original_image_url')
222
+ };
223
+ };
224
+ const parseStatusInfo = (mediaNode) => {
225
+ const node = getBinaryNodeChild(mediaNode, 'status_info');
226
+ return {
227
+ status: getBinaryNodeChildString(node, 'status'),
228
+ canAppeal: getBinaryNodeChildString(node, 'can_appeal') === 'true'
229
+ };
230
+ };
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Decode the received node as a message.
3
+ * @note this will only parse the message, not decrypt it
4
+ */
5
+ export function decodeMessageNode(stanza: any, meId: any, meLid: any): {
6
+ fullMessage: {
7
+ key: {
8
+ server_id?: any;
9
+ remoteJid: any;
10
+ remoteJidAlt: any;
11
+ remoteJidUsername: any;
12
+ fromMe: boolean;
13
+ id: any;
14
+ participant: any;
15
+ participantAlt: any;
16
+ participantUsername: any;
17
+ addressingMode: any;
18
+ };
19
+ category: any;
20
+ messageTimestamp: number;
21
+ pushName: any;
22
+ broadcast: any;
23
+ };
24
+ author: any;
25
+ sender: any;
26
+ };
27
+ export function getDecryptionJid(sender: any, repository: any): Promise<any>;
28
+ export const NO_MESSAGE_FOUND_ERROR_TEXT: "Message absent from node";
29
+ export const MISSING_KEYS_ERROR_TEXT: "Key used already or never filled";
30
+ export const ACCOUNT_RESTRICTED_TEXT: "Your account has been restricted";
31
+ export namespace DECRYPTION_RETRY_CONFIG {
32
+ let maxRetries: number;
33
+ let baseDelayMs: number;
34
+ let sessionRecordErrors: string[];
35
+ }
36
+ export namespace NACK_REASONS {
37
+ let SenderReachoutTimelocked: number;
38
+ let ParsingError: number;
39
+ let UnrecognizedStanza: number;
40
+ let UnrecognizedStanzaClass: number;
41
+ let UnrecognizedStanzaType: number;
42
+ let InvalidProtobuf: number;
43
+ let InvalidHostedCompanionStanza: number;
44
+ let MissingMessageSecret: number;
45
+ let SignalErrorOldCounter: number;
46
+ let MessageDeletedOnPeer: number;
47
+ let UnhandledError: number;
48
+ let UnsupportedAdminRevoke: number;
49
+ let UnsupportedLIDGroup: number;
50
+ let DBOperationFailed: number;
51
+ }
52
+ export namespace SERVER_ERROR_CODES {
53
+ let MessageAccountRestriction: string;
54
+ let SmaxInvalid: string;
55
+ }
56
+ export function extractAddressingContext(stanza: any): {
57
+ addressingMode: any;
58
+ senderAlt: any;
59
+ recipientAlt: any;
60
+ };
61
+ export function decryptMessageNode(stanza: any, meId: any, meLid: any, repository: any, logger: any): {
62
+ fullMessage: {
63
+ key: {
64
+ server_id?: any;
65
+ remoteJid: any;
66
+ remoteJidAlt: any;
67
+ remoteJidUsername: any;
68
+ fromMe: boolean;
69
+ id: any;
70
+ participant: any;
71
+ participantAlt: any;
72
+ participantUsername: any;
73
+ addressingMode: any;
74
+ };
75
+ category: any;
76
+ messageTimestamp: number;
77
+ pushName: any;
78
+ broadcast: any;
79
+ };
80
+ category: any;
81
+ author: any;
82
+ decrypt(): Promise<void>;
83
+ };
@@ -0,0 +1,316 @@
1
+ import { proto } from '../../../WAProto/index.js';
2
+ import { HttpError } from '../../Addon/index.js';
3
+ import { areJidsSameUser, isHostedLidUser, isHostedPnUser, isJidBroadcast, isJidGroup, isJidMetaAI, isJidNewsletter, isJidStatusBroadcast, isLidUser, isPnUser
4
+ // transferDevice
5
+ } from '../../WABinary/index.js';
6
+ import { unpadRandomMax16 } from '../Common/generics.js';
7
+ export const getDecryptionJid = async (sender, repository) => {
8
+ if (isLidUser(sender) || isHostedLidUser(sender)) {
9
+ return sender;
10
+ }
11
+ const mapped = await repository.lidMapping.getLIDForPN(sender);
12
+ return mapped || sender;
13
+ };
14
+ const storeMappingFromEnvelope = async (stanza, sender, repository, decryptionJid, logger) => {
15
+ // TODO: Handle hosted IDs
16
+ const { senderAlt } = extractAddressingContext(stanza);
17
+ if (senderAlt && isLidUser(senderAlt) && isPnUser(sender) && decryptionJid === sender) {
18
+ try {
19
+ await repository.lidMapping.storeLIDPNMappings([{ lid: senderAlt, pn: sender }]);
20
+ await repository.migrateSession(sender, senderAlt);
21
+ logger.debug({ sender, senderAlt }, 'Stored LID mapping from envelope');
22
+ }
23
+ catch (error) {
24
+ logger.warn({ sender, senderAlt, error }, 'Failed to store LID mapping');
25
+ }
26
+ }
27
+ };
28
+ export const NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node';
29
+ export const MISSING_KEYS_ERROR_TEXT = 'Key used already or never filled';
30
+ export const ACCOUNT_RESTRICTED_TEXT = 'Your account has been restricted';
31
+ // Retry configuration for failed decryption
32
+ export const DECRYPTION_RETRY_CONFIG = {
33
+ maxRetries: 3,
34
+ baseDelayMs: 100,
35
+ sessionRecordErrors: ['No session record', 'SessionError: No session record']
36
+ };
37
+ /** NACK reason codes we send to the server (client → server) */
38
+ export const NACK_REASONS = {
39
+ SenderReachoutTimelocked: 463,
40
+ ParsingError: 487,
41
+ UnrecognizedStanza: 488,
42
+ UnrecognizedStanzaClass: 489,
43
+ UnrecognizedStanzaType: 490,
44
+ InvalidProtobuf: 491,
45
+ InvalidHostedCompanionStanza: 493,
46
+ MissingMessageSecret: 495,
47
+ SignalErrorOldCounter: 496,
48
+ MessageDeletedOnPeer: 499,
49
+ UnhandledError: 500,
50
+ UnsupportedAdminRevoke: 550,
51
+ UnsupportedLIDGroup: 551,
52
+ DBOperationFailed: 552
53
+ };
54
+ /**
55
+ * Server-side error codes returned in ack stanzas (server → client) that we
56
+ * currently have dedicated handlers for. Extend as more handlers are added.
57
+ * Distinct from the client-side NackReason enum (WAWebCreateNackFromStanza).
58
+ */
59
+ export const SERVER_ERROR_CODES = {
60
+ /**
61
+ * 1:1 message missing privacy token (tctoken). Usually means the account is
62
+ * restricted: WhatsApp blocks starting new chats but preserves existing ones,
63
+ * since established chats already carry a tctoken.
64
+ */
65
+ MessageAccountRestriction: '463',
66
+ /** Stanza validation failure (SMAX_INVALID) — likely stale device session */
67
+ SmaxInvalid: '479'
68
+ };
69
+ export const extractAddressingContext = (stanza) => {
70
+ let senderAlt;
71
+ let recipientAlt;
72
+ const sender = stanza.attrs.participant || stanza.attrs.from;
73
+ const addressingMode = stanza.attrs.addressing_mode || (sender?.endsWith('lid') ? 'lid' : 'pn');
74
+ if (addressingMode === 'lid') {
75
+ // Message is LID-addressed: sender is LID, extract corresponding PN
76
+ // without device data
77
+ senderAlt = stanza.attrs.participant_pn || stanza.attrs.sender_pn || stanza.attrs.peer_recipient_pn;
78
+ recipientAlt = stanza.attrs.recipient_pn;
79
+ // with device data
80
+ //if (sender && senderAlt) senderAlt = transferDevice(sender, senderAlt)
81
+ }
82
+ else {
83
+ // Message is PN-addressed: sender is PN, extract corresponding LID
84
+ // without device data
85
+ senderAlt = stanza.attrs.participant_lid || stanza.attrs.sender_lid || stanza.attrs.peer_recipient_lid;
86
+ recipientAlt = stanza.attrs.recipient_lid;
87
+ //with device data
88
+ //if (sender && senderAlt) senderAlt = transferDevice(sender, senderAlt)
89
+ }
90
+ return {
91
+ addressingMode,
92
+ senderAlt,
93
+ recipientAlt
94
+ };
95
+ };
96
+ /**
97
+ * Decode the received node as a message.
98
+ * @note this will only parse the message, not decrypt it
99
+ */
100
+ export function decodeMessageNode(stanza, meId, meLid) {
101
+ let msgType;
102
+ let chatId;
103
+ let author;
104
+ let fromMe = false;
105
+ const msgId = stanza.attrs.id;
106
+ const from = stanza.attrs.from;
107
+ const participant = stanza.attrs.participant;
108
+ const recipient = stanza.attrs.recipient;
109
+ if (!msgId) {
110
+ throw new HttpError('Invalid message stanza: missing id attribute', { data: stanza });
111
+ }
112
+ if (!from) {
113
+ throw new HttpError('Invalid message stanza: missing from attribute', { data: stanza });
114
+ }
115
+ const addressingContext = extractAddressingContext(stanza);
116
+ const isMe = (jid) => areJidsSameUser(jid, meId);
117
+ const isMeLid = (jid) => areJidsSameUser(jid, meLid);
118
+ if (isPnUser(from) || isLidUser(from) || isHostedLidUser(from) || isHostedPnUser(from)) {
119
+ if (recipient && !isJidMetaAI(recipient)) {
120
+ if (!isMe(from) && !isMeLid(from)) {
121
+ throw new HttpError('receipient present, but msg not from me', { data: stanza });
122
+ }
123
+ if (isMe(from) || isMeLid(from)) {
124
+ fromMe = true;
125
+ }
126
+ chatId = recipient;
127
+ }
128
+ else {
129
+ // Peer-routed self stanzas (history sync, app-state sync, etc.) arrive
130
+ // with `from` set to our own device but no `recipient` attribute —
131
+ // still mark as fromMe so self-only protocolMessage handlers run.
132
+ if (isMe(from) || isMeLid(from)) {
133
+ fromMe = true;
134
+ }
135
+ chatId = from;
136
+ }
137
+ msgType = 'chat';
138
+ author = from;
139
+ }
140
+ else if (isJidGroup(from)) {
141
+ if (!participant) {
142
+ throw new HttpError('No participant in group message');
143
+ }
144
+ if (isMe(participant) || isMeLid(participant)) {
145
+ fromMe = true;
146
+ }
147
+ msgType = 'group';
148
+ author = participant;
149
+ chatId = from;
150
+ }
151
+ else if (isJidBroadcast(from)) {
152
+ if (!participant) {
153
+ throw new HttpError('No participant in group message');
154
+ }
155
+ const isParticipantMe = isMe(participant);
156
+ if (isJidStatusBroadcast(from)) {
157
+ msgType = isParticipantMe ? 'direct_peer_status' : 'other_status';
158
+ }
159
+ else {
160
+ msgType = isParticipantMe ? 'peer_broadcast' : 'other_broadcast';
161
+ }
162
+ fromMe = isParticipantMe;
163
+ chatId = from;
164
+ author = participant;
165
+ }
166
+ else if (isJidNewsletter(from)) {
167
+ msgType = 'newsletter';
168
+ chatId = from;
169
+ author = from;
170
+ if (isMe(from) || isMeLid(from)) {
171
+ fromMe = true;
172
+ }
173
+ }
174
+ else {
175
+ throw new HttpError('Unknown message type', { data: stanza });
176
+ }
177
+ const pushname = stanza?.attrs?.notify;
178
+ const key = {
179
+ remoteJid: chatId,
180
+ remoteJidAlt: !isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
181
+ remoteJidUsername: !isJidGroup(chatId)
182
+ ? stanza.attrs.peer_recipient_username || stanza.attrs.recipient_username
183
+ : undefined,
184
+ fromMe,
185
+ id: msgId,
186
+ participant,
187
+ participantAlt: isJidGroup(chatId) ? addressingContext.senderAlt : undefined,
188
+ participantUsername: stanza.attrs.participant ? stanza.attrs.participant_username : undefined,
189
+ addressingMode: addressingContext.addressingMode,
190
+ ...(msgType === 'newsletter' && stanza.attrs.server_id ? { server_id: stanza.attrs.server_id } : {})
191
+ };
192
+ const fullMessage = {
193
+ key,
194
+ category: stanza.attrs.category,
195
+ messageTimestamp: +stanza.attrs.t,
196
+ pushName: pushname,
197
+ broadcast: isJidBroadcast(from)
198
+ };
199
+ if (key.fromMe) {
200
+ fullMessage.status = proto.WebMessageInfo.Status.SERVER_ACK;
201
+ }
202
+ return {
203
+ fullMessage,
204
+ author,
205
+ sender: msgType === 'chat' ? author : chatId
206
+ };
207
+ }
208
+ export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
209
+ const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid);
210
+ return {
211
+ fullMessage,
212
+ category: stanza.attrs.category,
213
+ author,
214
+ async decrypt() {
215
+ let decryptables = 0;
216
+ if (Array.isArray(stanza.content)) {
217
+ for (const { tag, attrs, content } of stanza.content) {
218
+ if (tag === 'verified_name' && content instanceof Uint8Array) {
219
+ const cert = proto.VerifiedNameCertificate.decode(content);
220
+ const details = proto.VerifiedNameCertificate.Details.decode(cert.details);
221
+ fullMessage.verifiedBizName = details.verifiedName;
222
+ }
223
+ if (tag === 'unavailable' && attrs.type === 'view_once') {
224
+ fullMessage.key.isViewOnce = true; // TODO: remove from here and add a STUB TYPE
225
+ }
226
+ if (attrs.count && tag === 'enc') {
227
+ fullMessage.retryCount = Number(attrs.count);
228
+ }
229
+ if (tag !== 'enc' && tag !== 'plaintext') {
230
+ continue;
231
+ }
232
+ if (!(content instanceof Uint8Array)) {
233
+ continue;
234
+ }
235
+ decryptables += 1;
236
+ let msgBuffer;
237
+ const decryptionJid = await getDecryptionJid(author, repository);
238
+ if (tag !== 'plaintext') {
239
+ // TODO: Handle hosted devices
240
+ await storeMappingFromEnvelope(stanza, author, repository, decryptionJid, logger);
241
+ }
242
+ try {
243
+ const e2eType = tag === 'plaintext' ? 'plaintext' : attrs.type;
244
+ switch (e2eType) {
245
+ case 'skmsg':
246
+ msgBuffer = await repository.decryptGroupMessage({
247
+ group: sender,
248
+ authorJid: author,
249
+ msg: content
250
+ });
251
+ break;
252
+ case 'pkmsg':
253
+ case 'msg':
254
+ msgBuffer = await repository.decryptMessage({
255
+ jid: decryptionJid,
256
+ type: e2eType,
257
+ ciphertext: content
258
+ });
259
+ break;
260
+ case 'plaintext':
261
+ msgBuffer = content;
262
+ break;
263
+ default:
264
+ throw new Error(`Unknown e2e type: ${e2eType}`);
265
+ }
266
+ let msg = proto.Message.decode(e2eType !== 'plaintext' ? unpadRandomMax16(msgBuffer) : msgBuffer);
267
+ msg = msg.deviceSentMessage?.message || msg;
268
+ if (msg.senderKeyDistributionMessage) {
269
+ //eslint-disable-next-line max-depth
270
+ try {
271
+ await repository.processSenderKeyDistributionMessage({
272
+ authorJid: author,
273
+ item: msg.senderKeyDistributionMessage
274
+ });
275
+ }
276
+ catch (err) {
277
+ logger.error({ key: fullMessage.key, err }, 'failed to process sender key distribution message');
278
+ }
279
+ }
280
+ if (fullMessage.message) {
281
+ Object.assign(fullMessage.message, msg);
282
+ }
283
+ else {
284
+ fullMessage.message = msg;
285
+ }
286
+ }
287
+ catch (err) {
288
+ const errorContext = {
289
+ key: fullMessage.key,
290
+ err,
291
+ messageType: tag === 'plaintext' ? 'plaintext' : attrs.type,
292
+ sender,
293
+ author,
294
+ isSessionRecordError: isSessionRecordError(err)
295
+ };
296
+ logger.error(errorContext, 'failed to decrypt message');
297
+ fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT;
298
+ fullMessage.messageStubParameters = [err.message.toString()];
299
+ }
300
+ }
301
+ }
302
+ // if nothing was found to decrypt
303
+ if (!decryptables && !fullMessage.key?.isViewOnce) {
304
+ fullMessage.messageStubType = proto.WebMessageInfo.StubType.CIPHERTEXT;
305
+ fullMessage.messageStubParameters = [NO_MESSAGE_FOUND_ERROR_TEXT];
306
+ }
307
+ }
308
+ };
309
+ };
310
+ /**
311
+ * Utility function to check if an error is related to missing session record
312
+ */
313
+ function isSessionRecordError(error) {
314
+ const errorMessage = error?.message || error?.toString() || '';
315
+ return DECRYPTION_RETRY_CONFIG.sessionRecordErrors.some(errorPattern => errorMessage.includes(errorPattern));
316
+ }