@fer2809fl/baileys 7.0.2 → 7.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (267) hide show
  1. package/README.md +409 -32
  2. package/lib/Defaults/index.js +2 -1
  3. package/lib/Modded/message_builder.js +2356 -0
  4. package/lib/Signal/libsignal.js +19 -0
  5. package/lib/Socket/business.d.ts +213 -532
  6. package/lib/Socket/business.js +359 -401
  7. package/lib/Socket/chats.d.ts +30 -2
  8. package/lib/Socket/chats.js +295 -40
  9. package/lib/Socket/groups.d.ts +16 -0
  10. package/lib/Socket/groups.js +101 -18
  11. package/lib/Socket/index.d.ts +17 -0
  12. package/lib/Socket/messages-recv.js +18 -1
  13. package/lib/Socket/messages-send.d.ts +18 -0
  14. package/lib/Socket/messages-send.js +50 -2
  15. package/lib/Socket/newsletter.js +3 -3
  16. package/lib/Socket/socket.js +50 -6
  17. package/lib/Types/Newsletter.d.ts +13 -4
  18. package/lib/Types/Newsletter.js +12 -2
  19. package/lib/Utils/anti-ban.d.ts +41 -0
  20. package/lib/Utils/anti-ban.js +182 -0
  21. package/lib/Utils/banner.d.ts +8 -0
  22. package/lib/Utils/banner.js +76 -0
  23. package/lib/Utils/bot-utils.d.ts +57 -0
  24. package/lib/Utils/bot-utils.js +241 -0
  25. package/lib/Utils/chat-utils.d.ts +34 -4
  26. package/lib/Utils/chat-utils.js +80 -20
  27. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  28. package/lib/Utils/companion-reg-client-utils.js +35 -0
  29. package/lib/Utils/enhanced-cache.d.ts +40 -0
  30. package/lib/Utils/enhanced-cache.js +242 -0
  31. package/lib/Utils/enhanced-logger.d.ts +41 -0
  32. package/lib/Utils/enhanced-logger.js +185 -0
  33. package/lib/Utils/event-buffer.js +49 -1
  34. package/lib/Utils/index.d.ts +14 -0
  35. package/lib/Utils/index.js +14 -0
  36. package/lib/Utils/lid-utils.d.ts +139 -0
  37. package/lib/Utils/lid-utils.js +503 -0
  38. package/lib/Utils/message-queue.d.ts +47 -0
  39. package/lib/Utils/message-queue.js +226 -0
  40. package/lib/Utils/message-retry-manager.js +40 -0
  41. package/lib/Utils/rich-message-utils.d.ts +21 -0
  42. package/lib/Utils/rich-message-utils.js +229 -0
  43. package/lib/Utils/rich-messages.d.ts +52 -0
  44. package/lib/Utils/rich-messages.js +185 -0
  45. package/lib/Utils/scheduled-messages.d.ts +122 -0
  46. package/lib/Utils/scheduled-messages.js +289 -0
  47. package/lib/Utils/smart-reconnect.d.ts +48 -0
  48. package/lib/Utils/smart-reconnect.js +207 -0
  49. package/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
  50. package/lib/Utils/use-sqlite-auth-state.js +95 -0
  51. package/lib/VoIP/audio-feeder.d.ts +15 -0
  52. package/lib/VoIP/audio-feeder.js +132 -0
  53. package/lib/VoIP/index.js +277 -0
  54. package/lib/VoIP/relay-transport.d.ts +43 -0
  55. package/lib/VoIP/relay-transport.js +559 -0
  56. package/lib/VoIP/signaling.js +594 -0
  57. package/lib/VoIP/types.d.ts +69 -0
  58. package/lib/VoIP/types.js +17 -0
  59. package/lib/VoIP/wasm-engine.d.ts +103 -0
  60. package/lib/VoIP/wasm-engine.js +1214 -0
  61. package/lib/VoIP/worker-bootstrap.js +1042 -0
  62. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  63. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  64. package/lib/WAUSync/Protocols/index.js +1 -0
  65. package/lib/WAUSync/USyncQuery.js +5 -1
  66. package/lib/assets/wasm/loader.js +5 -0
  67. package/lib/assets/wasm/whatsapp.wasm +0 -0
  68. package/lib/assets/wasm/worker-modules.js +273 -0
  69. package/lib/index.d.ts +41 -0
  70. package/lib/index.js +3 -0
  71. package/package.json +15 -7
  72. package/lib/Defaults/index.d.ts.map +0 -1
  73. package/lib/Defaults/index.js.map +0 -1
  74. package/lib/Signal/Group/ciphertext-message.d.ts.map +0 -1
  75. package/lib/Signal/Group/ciphertext-message.js.map +0 -1
  76. package/lib/Signal/Group/group-session-builder.d.ts.map +0 -1
  77. package/lib/Signal/Group/group-session-builder.js.map +0 -1
  78. package/lib/Signal/Group/group_cipher.d.ts.map +0 -1
  79. package/lib/Signal/Group/group_cipher.js.map +0 -1
  80. package/lib/Signal/Group/index.d.ts.map +0 -1
  81. package/lib/Signal/Group/index.js.map +0 -1
  82. package/lib/Signal/Group/keyhelper.d.ts.map +0 -1
  83. package/lib/Signal/Group/keyhelper.js.map +0 -1
  84. package/lib/Signal/Group/sender-chain-key.d.ts.map +0 -1
  85. package/lib/Signal/Group/sender-chain-key.js.map +0 -1
  86. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +0 -1
  87. package/lib/Signal/Group/sender-key-distribution-message.js.map +0 -1
  88. package/lib/Signal/Group/sender-key-message.d.ts.map +0 -1
  89. package/lib/Signal/Group/sender-key-message.js.map +0 -1
  90. package/lib/Signal/Group/sender-key-name.d.ts.map +0 -1
  91. package/lib/Signal/Group/sender-key-name.js.map +0 -1
  92. package/lib/Signal/Group/sender-key-record.d.ts.map +0 -1
  93. package/lib/Signal/Group/sender-key-record.js.map +0 -1
  94. package/lib/Signal/Group/sender-key-state.d.ts.map +0 -1
  95. package/lib/Signal/Group/sender-key-state.js.map +0 -1
  96. package/lib/Signal/Group/sender-message-key.d.ts.map +0 -1
  97. package/lib/Signal/Group/sender-message-key.js.map +0 -1
  98. package/lib/Signal/libsignal.d.ts.map +0 -1
  99. package/lib/Signal/libsignal.js.map +0 -1
  100. package/lib/Signal/lid-mapping.d.ts.map +0 -1
  101. package/lib/Signal/lid-mapping.js.map +0 -1
  102. package/lib/Socket/Client/index.d.ts.map +0 -1
  103. package/lib/Socket/Client/index.js.map +0 -1
  104. package/lib/Socket/Client/types.d.ts.map +0 -1
  105. package/lib/Socket/Client/types.js.map +0 -1
  106. package/lib/Socket/Client/websocket.d.ts.map +0 -1
  107. package/lib/Socket/Client/websocket.js.map +0 -1
  108. package/lib/Socket/business.d.ts.map +0 -1
  109. package/lib/Socket/business.js.map +0 -1
  110. package/lib/Socket/chats.d.ts.map +0 -1
  111. package/lib/Socket/chats.js.map +0 -1
  112. package/lib/Socket/communities.d.ts.map +0 -1
  113. package/lib/Socket/communities.js.map +0 -1
  114. package/lib/Socket/dugong.d.ts.map +0 -1
  115. package/lib/Socket/dugong.js.map +0 -1
  116. package/lib/Socket/groups.d.ts.map +0 -1
  117. package/lib/Socket/groups.js.map +0 -1
  118. package/lib/Socket/index.d.ts.map +0 -1
  119. package/lib/Socket/index.js.map +0 -1
  120. package/lib/Socket/messages-recv.d.ts.map +0 -1
  121. package/lib/Socket/messages-recv.js.map +0 -1
  122. package/lib/Socket/messages-send.d.ts.map +0 -1
  123. package/lib/Socket/messages-send.js.map +0 -1
  124. package/lib/Socket/mex.d.ts.map +0 -1
  125. package/lib/Socket/mex.js.map +0 -1
  126. package/lib/Socket/newsletter.d.ts.map +0 -1
  127. package/lib/Socket/newsletter.js.map +0 -1
  128. package/lib/Socket/socket.d.ts.map +0 -1
  129. package/lib/Socket/socket.js.map +0 -1
  130. package/lib/Types/Auth.d.ts.map +0 -1
  131. package/lib/Types/Auth.js.map +0 -1
  132. package/lib/Types/Bussines.d.ts.map +0 -1
  133. package/lib/Types/Bussines.js.map +0 -1
  134. package/lib/Types/Call.d.ts.map +0 -1
  135. package/lib/Types/Call.js.map +0 -1
  136. package/lib/Types/Chat.d.ts.map +0 -1
  137. package/lib/Types/Chat.js.map +0 -1
  138. package/lib/Types/Contact.d.ts.map +0 -1
  139. package/lib/Types/Contact.js.map +0 -1
  140. package/lib/Types/Events.d.ts.map +0 -1
  141. package/lib/Types/Events.js.map +0 -1
  142. package/lib/Types/GroupMetadata.d.ts.map +0 -1
  143. package/lib/Types/GroupMetadata.js.map +0 -1
  144. package/lib/Types/Label.d.ts.map +0 -1
  145. package/lib/Types/Label.js.map +0 -1
  146. package/lib/Types/LabelAssociation.d.ts.map +0 -1
  147. package/lib/Types/LabelAssociation.js.map +0 -1
  148. package/lib/Types/Message.d.ts.map +0 -1
  149. package/lib/Types/Message.js.map +0 -1
  150. package/lib/Types/Newsletter.d.ts.map +0 -1
  151. package/lib/Types/Newsletter.js.map +0 -1
  152. package/lib/Types/Product.d.ts.map +0 -1
  153. package/lib/Types/Product.js.map +0 -1
  154. package/lib/Types/Signal.d.ts.map +0 -1
  155. package/lib/Types/Signal.js.map +0 -1
  156. package/lib/Types/Socket.d.ts.map +0 -1
  157. package/lib/Types/Socket.js.map +0 -1
  158. package/lib/Types/State.d.ts.map +0 -1
  159. package/lib/Types/State.js.map +0 -1
  160. package/lib/Types/USync.d.ts.map +0 -1
  161. package/lib/Types/USync.js.map +0 -1
  162. package/lib/Types/index.d.ts.map +0 -1
  163. package/lib/Types/index.js.map +0 -1
  164. package/lib/Utils/auth-utils.d.ts.map +0 -1
  165. package/lib/Utils/auth-utils.js.map +0 -1
  166. package/lib/Utils/browser-utils.d.ts.map +0 -1
  167. package/lib/Utils/browser-utils.js.map +0 -1
  168. package/lib/Utils/business.d.ts.map +0 -1
  169. package/lib/Utils/business.js.map +0 -1
  170. package/lib/Utils/chat-utils.d.ts.map +0 -1
  171. package/lib/Utils/chat-utils.js.map +0 -1
  172. package/lib/Utils/crypto.d.ts.map +0 -1
  173. package/lib/Utils/crypto.js.map +0 -1
  174. package/lib/Utils/decode-wa-message.d.ts.map +0 -1
  175. package/lib/Utils/decode-wa-message.js.map +0 -1
  176. package/lib/Utils/event-buffer.d.ts.map +0 -1
  177. package/lib/Utils/event-buffer.js.map +0 -1
  178. package/lib/Utils/generics.d.ts.map +0 -1
  179. package/lib/Utils/generics.js.map +0 -1
  180. package/lib/Utils/history.d.ts.map +0 -1
  181. package/lib/Utils/history.js.map +0 -1
  182. package/lib/Utils/identity-change-handler.d.ts.map +0 -1
  183. package/lib/Utils/identity-change-handler.js.map +0 -1
  184. package/lib/Utils/index.d.ts.map +0 -1
  185. package/lib/Utils/index.js.map +0 -1
  186. package/lib/Utils/link-preview.d.ts.map +0 -1
  187. package/lib/Utils/link-preview.js.map +0 -1
  188. package/lib/Utils/logger.d.ts.map +0 -1
  189. package/lib/Utils/logger.js.map +0 -1
  190. package/lib/Utils/lt-hash.d.ts.map +0 -1
  191. package/lib/Utils/lt-hash.js.map +0 -1
  192. package/lib/Utils/make-mutex.d.ts.map +0 -1
  193. package/lib/Utils/make-mutex.js.map +0 -1
  194. package/lib/Utils/message-retry-manager.d.ts.map +0 -1
  195. package/lib/Utils/message-retry-manager.js.map +0 -1
  196. package/lib/Utils/messages-media.d.ts.map +0 -1
  197. package/lib/Utils/messages-media.js.map +0 -1
  198. package/lib/Utils/messages.d.ts.map +0 -1
  199. package/lib/Utils/messages.js.map +0 -1
  200. package/lib/Utils/noise-handler.d.ts.map +0 -1
  201. package/lib/Utils/noise-handler.js.map +0 -1
  202. package/lib/Utils/offline-node-processor.d.ts.map +0 -1
  203. package/lib/Utils/offline-node-processor.js.map +0 -1
  204. package/lib/Utils/pre-key-manager.d.ts.map +0 -1
  205. package/lib/Utils/pre-key-manager.js.map +0 -1
  206. package/lib/Utils/process-message.d.ts.map +0 -1
  207. package/lib/Utils/process-message.js.map +0 -1
  208. package/lib/Utils/reporting-utils.d.ts.map +0 -1
  209. package/lib/Utils/reporting-utils.js.map +0 -1
  210. package/lib/Utils/rich-messages.d.ts.map +0 -1
  211. package/lib/Utils/rich-messages.js.map +0 -1
  212. package/lib/Utils/signal.d.ts.map +0 -1
  213. package/lib/Utils/signal.js.map +0 -1
  214. package/lib/Utils/stanza-ack.d.ts.map +0 -1
  215. package/lib/Utils/stanza-ack.js.map +0 -1
  216. package/lib/Utils/sync-action-utils.d.ts.map +0 -1
  217. package/lib/Utils/sync-action-utils.js.map +0 -1
  218. package/lib/Utils/tc-token-utils.d.ts.map +0 -1
  219. package/lib/Utils/tc-token-utils.js.map +0 -1
  220. package/lib/Utils/use-multi-file-auth-state.d.ts.map +0 -1
  221. package/lib/Utils/use-multi-file-auth-state.js.map +0 -1
  222. package/lib/Utils/validate-connection.d.ts.map +0 -1
  223. package/lib/Utils/validate-connection.js.map +0 -1
  224. package/lib/WABinary/constants.d.ts.map +0 -1
  225. package/lib/WABinary/constants.js.map +0 -1
  226. package/lib/WABinary/decode.d.ts.map +0 -1
  227. package/lib/WABinary/decode.js.map +0 -1
  228. package/lib/WABinary/encode.d.ts.map +0 -1
  229. package/lib/WABinary/encode.js.map +0 -1
  230. package/lib/WABinary/generic-utils.d.ts.map +0 -1
  231. package/lib/WABinary/generic-utils.js.map +0 -1
  232. package/lib/WABinary/index.d.ts.map +0 -1
  233. package/lib/WABinary/index.js.map +0 -1
  234. package/lib/WABinary/jid-utils.d.ts.map +0 -1
  235. package/lib/WABinary/jid-utils.js.map +0 -1
  236. package/lib/WABinary/types.d.ts.map +0 -1
  237. package/lib/WABinary/types.js.map +0 -1
  238. package/lib/WAM/BinaryInfo.d.ts.map +0 -1
  239. package/lib/WAM/BinaryInfo.js.map +0 -1
  240. package/lib/WAM/constants.d.ts.map +0 -1
  241. package/lib/WAM/constants.js.map +0 -1
  242. package/lib/WAM/encode.d.ts.map +0 -1
  243. package/lib/WAM/encode.js.map +0 -1
  244. package/lib/WAM/index.d.ts.map +0 -1
  245. package/lib/WAM/index.js.map +0 -1
  246. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +0 -1
  247. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +0 -1
  248. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +0 -1
  249. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +0 -1
  250. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +0 -1
  251. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +0 -1
  252. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +0 -1
  253. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +0 -1
  254. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +0 -1
  255. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +0 -1
  256. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +0 -1
  257. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +0 -1
  258. package/lib/WAUSync/Protocols/index.d.ts.map +0 -1
  259. package/lib/WAUSync/Protocols/index.js.map +0 -1
  260. package/lib/WAUSync/USyncQuery.d.ts.map +0 -1
  261. package/lib/WAUSync/USyncQuery.js.map +0 -1
  262. package/lib/WAUSync/USyncUser.d.ts.map +0 -1
  263. package/lib/WAUSync/USyncUser.js.map +0 -1
  264. package/lib/WAUSync/index.d.ts.map +0 -1
  265. package/lib/WAUSync/index.js.map +0 -1
  266. package/lib/index.d.ts.map +0 -1
  267. package/lib/index.js.map +0 -1
@@ -38,7 +38,7 @@ const to64BitNetworkOrder = (e) => {
38
38
  buff.writeUint32BE(e, 4);
39
39
  return buff;
40
40
  };
41
- const makeLtHashGenerator = ({ indexValueMap, hash }) => {
41
+ export const makeLtHashGenerator = ({ indexValueMap, hash }) => {
42
42
  indexValueMap = { ...indexValueMap };
43
43
  const addBuffs = [];
44
44
  const subBuffs = [];
@@ -48,7 +48,10 @@ const makeLtHashGenerator = ({ indexValueMap, hash }) => {
48
48
  const prevOp = indexValueMap[indexMacBase64];
49
49
  if (operation === proto.SyncdMutation.SyncdOperation.REMOVE) {
50
50
  if (!prevOp) {
51
- throw new Boom('tried remove, but no previous op', { data: { indexMac, valueMac } });
51
+ // WA Web does not throw here it logs a warning and skips the subtract.
52
+ // The missing REMOVE will cause an LTHash mismatch, which is handled
53
+ // by the MAC validation layer (snapshot recovery or retry).
54
+ return;
52
55
  }
53
56
  // remove from index value mac, since this mutation is erased
54
57
  delete indexValueMap[indexMacBase64];
@@ -80,10 +83,33 @@ const generatePatchMac = (snapshotMac, valueMacs, version, type, key) => {
80
83
  return hmacSign(total, key);
81
84
  };
82
85
  export const newLTHashState = () => ({ version: 0, hash: Buffer.alloc(128), indexValueMap: {} });
86
+ export const ensureLTHashStateVersion = (state) => {
87
+ if (typeof state.version !== 'number' || isNaN(state.version)) {
88
+ state.version = 0;
89
+ }
90
+ return state;
91
+ };
92
+ export const MAX_SYNC_ATTEMPTS = 2;
93
+ /**
94
+ * Check if an error is a missing app state sync key.
95
+ * WA Web treats these as "Blocked" (waits for key arrival), not fatal.
96
+ * In Baileys we retry with a snapshot which may use a different key.
97
+ */
98
+ export const isMissingKeyError = (error) => {
99
+ return error?.data?.isMissingKey === true;
100
+ };
101
+ /**
102
+ * Determines if an app state sync error is unrecoverable.
103
+ * TypeError indicates a WASM crash; otherwise we give up after MAX_SYNC_ATTEMPTS.
104
+ * Missing keys are NOT checked here — they are handled separately as "Blocked".
105
+ */
106
+ export const isAppStateSyncIrrecoverable = (error, attempts) => {
107
+ return attempts >= MAX_SYNC_ATTEMPTS || error?.name === 'TypeError';
108
+ };
83
109
  export const encodeSyncdPatch = async ({ type, index, syncAction, apiVersion, operation }, myAppStateKeyId, state, getAppStateSyncKey) => {
84
110
  const key = !!myAppStateKeyId ? await getAppStateSyncKey(myAppStateKeyId) : undefined;
85
111
  if (!key) {
86
- throw new Boom(`myAppStateKey ("${myAppStateKeyId}") not present`, { statusCode: 404 });
112
+ throw new Boom(`myAppStateKey ("${myAppStateKeyId}") not present`, { data: { isMissingKey: true } });
87
113
  }
88
114
  const encKeyId = Buffer.from(myAppStateKeyId, 'base64');
89
115
  state = { ...state, indexValueMap: { ...state.indexValueMap } };
@@ -139,17 +165,36 @@ export const decodeSyncdMutations = async (msgMutations, initialState, getAppSta
139
165
  // otherwise, if it's only a record -- it'll be a SET mutation
140
166
  const operation = 'operation' in msgMutation ? msgMutation.operation : proto.SyncdMutation.SyncdOperation.SET;
141
167
  const record = 'record' in msgMutation && !!msgMutation.record ? msgMutation.record : msgMutation;
142
- const key = await getKey(record.keyId.id);
168
+ let key;
169
+ try {
170
+ key = await getKey(record.keyId.id);
171
+ }
172
+ catch (err) {
173
+ // Missing-key errors must propagate so the orchestrator can park the
174
+ // collection (Blocked) and retry when APP_STATE_SYNC_KEY_SHARE arrives.
175
+ // Other errors → individual record corruption, skip and keep going.
176
+ if (isMissingKeyError(err))
177
+ throw err;
178
+ continue;
179
+ }
143
180
  const content = record.value.blob;
144
181
  const encContent = content.subarray(0, -32);
145
182
  const ogValueMac = content.subarray(-32);
146
183
  if (validateMacs) {
147
184
  const contentHmac = generateMac(operation, encContent, record.keyId.id, key.valueMacKey);
148
185
  if (Buffer.compare(contentHmac, ogValueMac) !== 0) {
149
- throw new Boom('HMAC content verification failed');
186
+ // HMAC verification failed — skip this record
187
+ continue;
150
188
  }
151
189
  }
152
- const result = aesDecrypt(encContent, key.valueEncryptionKey);
190
+ let result;
191
+ try {
192
+ result = aesDecrypt(encContent, key.valueEncryptionKey);
193
+ }
194
+ catch {
195
+ // decrypt failed — skip this record instead of aborting
196
+ continue;
197
+ }
153
198
  const syncAction = proto.SyncActionData.decode(result);
154
199
  if (validateMacs) {
155
200
  const hmac = hmacSign(syncAction.index, key.indexKey);
@@ -175,8 +220,7 @@ export const decodeSyncdMutations = async (msgMutations, initialState, getAppSta
175
220
  const keyEnc = await getAppStateSyncKey(base64Key);
176
221
  if (!keyEnc) {
177
222
  throw new Boom(`failed to find key "${base64Key}" to decode mutation`, {
178
- statusCode: 404,
179
- data: { msgMutations }
223
+ data: { isMissingKey: true, msgMutations }
180
224
  });
181
225
  }
182
226
  const keys = mutationKeys(keyEnc.keyData);
@@ -189,7 +233,7 @@ export const decodeSyncdPatch = async (msg, name, initialState, getAppStateSyncK
189
233
  const base64Key = Buffer.from(msg.keyId.id).toString('base64');
190
234
  const mainKeyObj = await getAppStateSyncKey(base64Key);
191
235
  if (!mainKeyObj) {
192
- throw new Boom(`failed to find key "${base64Key}" to decode patch`, { statusCode: 404, data: { msg } });
236
+ throw new Boom(`failed to find key "${base64Key}" to decode patch`, { data: { isMissingKey: true, msg } });
193
237
  }
194
238
  const mainKey = mutationKeys(mainKeyObj.keyData);
195
239
  const mutationmacs = msg.mutations.map(mutation => mutation.record.value.blob.slice(-32));
@@ -250,7 +294,7 @@ export const downloadExternalPatch = async (blob, options) => {
250
294
  const syncData = proto.SyncdMutations.decode(buffer);
251
295
  return syncData;
252
296
  };
253
- export const decodeSyncdSnapshot = async (name, snapshot, getAppStateSyncKey, minimumVersionNumber, validateMacs = true) => {
297
+ export const decodeSyncdSnapshot = async (name, snapshot, getAppStateSyncKey, minimumVersionNumber, validateMacs = true, logger) => {
254
298
  const newState = newLTHashState();
255
299
  newState.version = toNumber(snapshot.version.version);
256
300
  const mutationMap = {};
@@ -267,12 +311,17 @@ export const decodeSyncdSnapshot = async (name, snapshot, getAppStateSyncKey, mi
267
311
  const base64Key = Buffer.from(snapshot.keyId.id).toString('base64');
268
312
  const keyEnc = await getAppStateSyncKey(base64Key);
269
313
  if (!keyEnc) {
270
- throw new Boom(`failed to find key "${base64Key}" to decode mutation`);
314
+ throw new Boom(`failed to find key "${base64Key}" to decode mutation`, { data: { isMissingKey: true } });
271
315
  }
272
316
  const result = mutationKeys(keyEnc.keyData);
273
317
  const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
274
318
  if (Buffer.compare(snapshot.mac, computedSnapshotMac) !== 0) {
275
- throw new Boom(`failed to verify LTHash at ${newState.version} of ${name} from snapshot`);
319
+ // LTHash verification may fail when decodeSyncdMutations skipped undecryptable
320
+ // records (poisoned server-side snapshot); the aggregate client hash diverges
321
+ // from the server-computed mac. Fall through with a warning so the session stays
322
+ // alive with partial state, symmetric to how decodePatches handles its own
323
+ // LTHash mismatch a few lines below.
324
+ logger?.warn({ name, version: newState.version }, 'LTHash verification failed on snapshot, continuing with partial state');
276
325
  }
277
326
  }
278
327
  return {
@@ -297,24 +346,34 @@ export const decodePatches = async (name, syncds, initial, getAppStateSyncKey, o
297
346
  const patchVersion = toNumber(version.version);
298
347
  newState.version = patchVersion;
299
348
  const shouldMutate = typeof minimumVersionNumber === 'undefined' || patchVersion > minimumVersionNumber;
300
- const decodeResult = await decodeSyncdPatch(syncd, name, newState, getAppStateSyncKey, shouldMutate
301
- ? mutation => {
302
- const index = mutation.syncAction.index?.toString();
303
- mutationMap[index] = mutation;
304
- }
305
- : () => { }, true);
349
+ let decodeResult;
350
+ try {
351
+ decodeResult = await decodeSyncdPatch(syncd, name, newState, getAppStateSyncKey, shouldMutate
352
+ ? mutation => {
353
+ const index = mutation.syncAction.index?.toString();
354
+ mutationMap[index] = mutation;
355
+ }
356
+ : () => { }, validateMacs);
357
+ }
358
+ catch (err) {
359
+ if (isMissingKeyError(err))
360
+ throw err;
361
+ logger?.warn({ name, version: patchVersion, error: err.message }, 'failed to decode patch, skipping');
362
+ continue;
363
+ }
306
364
  newState.hash = decodeResult.hash;
307
365
  newState.indexValueMap = decodeResult.indexValueMap;
308
366
  if (validateMacs) {
309
367
  const base64Key = Buffer.from(keyId.id).toString('base64');
310
368
  const keyEnc = await getAppStateSyncKey(base64Key);
311
369
  if (!keyEnc) {
312
- throw new Boom(`failed to find key "${base64Key}" to decode mutation`);
370
+ throw new Boom(`failed to find key "${base64Key}" to decode mutation`, { data: { isMissingKey: true } });
313
371
  }
314
372
  const result = mutationKeys(keyEnc.keyData);
315
373
  const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
316
374
  if (Buffer.compare(snapshotMac, computedSnapshotMac) !== 0) {
317
- throw new Boom(`failed to verify LTHash at ${newState.version} of ${name}`);
375
+ logger?.warn({ name, version: newState.version }, 'LTHash verification failed, skipping remaining patches');
376
+ break;
318
377
  }
319
378
  }
320
379
  // clear memory used up by the mutations
@@ -779,6 +838,7 @@ export const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) =
779
838
  action.lidContactAction.firstName ||
780
839
  action.lidContactAction.username ||
781
840
  undefined,
841
+ username: action.lidContactAction.username || undefined,
782
842
  lid: id,
783
843
  phoneNumber: undefined
784
844
  }
@@ -0,0 +1,17 @@
1
+ import type { WABrowserDescription } from '../Types/index.js';
2
+ export declare enum CompanionWebClientType {
3
+ UNKNOWN = 0,
4
+ CHROME = 1,
5
+ EDGE = 2,
6
+ FIREFOX = 3,
7
+ IE = 4,
8
+ OPERA = 5,
9
+ SAFARI = 6,
10
+ ELECTRON = 7,
11
+ UWP = 8,
12
+ OTHER_WEB_CLIENT = 9
13
+ }
14
+ export declare const getCompanionWebClientType: ([os, browserName]: WABrowserDescription) => CompanionWebClientType;
15
+ export declare const getCompanionPlatformId: (browser: WABrowserDescription) => string;
16
+ export declare const buildPairingQRData: (ref: string, noiseKeyB64: string, identityKeyB64: string, advB64: string, browser: WABrowserDescription) => string;
17
+ //# sourceMappingURL=companion-reg-client-utils.d.ts.map
@@ -0,0 +1,35 @@
1
+ export var CompanionWebClientType;
2
+ (function (CompanionWebClientType) {
3
+ CompanionWebClientType[CompanionWebClientType["UNKNOWN"] = 0] = "UNKNOWN";
4
+ CompanionWebClientType[CompanionWebClientType["CHROME"] = 1] = "CHROME";
5
+ CompanionWebClientType[CompanionWebClientType["EDGE"] = 2] = "EDGE";
6
+ CompanionWebClientType[CompanionWebClientType["FIREFOX"] = 3] = "FIREFOX";
7
+ CompanionWebClientType[CompanionWebClientType["IE"] = 4] = "IE";
8
+ CompanionWebClientType[CompanionWebClientType["OPERA"] = 5] = "OPERA";
9
+ CompanionWebClientType[CompanionWebClientType["SAFARI"] = 6] = "SAFARI";
10
+ CompanionWebClientType[CompanionWebClientType["ELECTRON"] = 7] = "ELECTRON";
11
+ CompanionWebClientType[CompanionWebClientType["UWP"] = 8] = "UWP";
12
+ CompanionWebClientType[CompanionWebClientType["OTHER_WEB_CLIENT"] = 9] = "OTHER_WEB_CLIENT";
13
+ })(CompanionWebClientType || (CompanionWebClientType = {}));
14
+ const BROWSER_TO_COMPANION_WEB_CLIENT = {
15
+ Chrome: CompanionWebClientType.CHROME,
16
+ Edge: CompanionWebClientType.EDGE,
17
+ Firefox: CompanionWebClientType.FIREFOX,
18
+ IE: CompanionWebClientType.IE,
19
+ Opera: CompanionWebClientType.OPERA,
20
+ Safari: CompanionWebClientType.SAFARI
21
+ };
22
+ export const getCompanionWebClientType = ([os, browserName]) => {
23
+ if (browserName === 'Desktop') {
24
+ return os === 'Windows' ? CompanionWebClientType.UWP : CompanionWebClientType.ELECTRON;
25
+ }
26
+ return BROWSER_TO_COMPANION_WEB_CLIENT[browserName] || CompanionWebClientType.OTHER_WEB_CLIENT;
27
+ };
28
+ export const getCompanionPlatformId = (browser) => {
29
+ return getCompanionWebClientType(browser).toString();
30
+ };
31
+ export const buildPairingQRData = (ref, noiseKeyB64, identityKeyB64, advB64, browser) => {
32
+ return ('https://wa.me/settings/linked_devices#' +
33
+ [ref, noiseKeyB64, identityKeyB64, advB64, getCompanionPlatformId(browser)].join(','));
34
+ };
35
+ //# sourceMappingURL=companion-reg-client-utils.js.map
@@ -0,0 +1,40 @@
1
+ export declare const CACHE_CONFIG: {
2
+ MEMORY: { MAX_SIZE: number; TTL: number; STALE_TTL: number };
3
+ SIGNAL: { MAX_SIZE: number; TTL: number };
4
+ GROUPS: { MAX_SIZE: number; TTL: number };
5
+ PROFILES: { MAX_SIZE: number; TTL: number };
6
+ PERSIST_INTERVAL: number;
7
+ PERSIST_ON_SIZE: number;
8
+ };
9
+
10
+ export declare class EnhancedCache<T = any> {
11
+ constructor(name: string, options?: { MAX_SIZE?: number; TTL?: number; STALE_TTL?: number; persistPath?: string });
12
+ get(key: string): T | undefined;
13
+ set(key: string, value: T, ttl?: number): void;
14
+ delete(key: string): void;
15
+ has(key: string): boolean;
16
+ getMany(keys: string[]): { found: Record<string, T>; missing: string[] };
17
+ setMany(entries: Record<string, T>): void;
18
+ load(): Promise<void>;
19
+ getStats(): {
20
+ hits: number;
21
+ misses: number;
22
+ sets: number;
23
+ deletes: number;
24
+ hitRate: string;
25
+ size: number;
26
+ hotCacheSize: number;
27
+ dirtyKeys: number;
28
+ };
29
+ clear(): void;
30
+ cleanup(): void;
31
+ }
32
+
33
+ export declare class CacheManager {
34
+ constructor(baseDir?: string, logger?: any);
35
+ loadAll(): Promise<void>;
36
+ getCache(name: 'signal' | 'groups' | 'profiles' | 'messages' | 'misc'): EnhancedCache;
37
+ getAllStats(): Record<string, ReturnType<EnhancedCache['getStats']>>;
38
+ clearAll(): void;
39
+ cleanup(): Promise<void>;
40
+ }
@@ -0,0 +1,242 @@
1
+ import { LRUCache } from 'lru-cache';
2
+ import { readFile, writeFile } from 'fs/promises';
3
+ import { join } from 'path';
4
+
5
+ const CACHE_CONFIG = {
6
+ MEMORY: {
7
+ MAX_SIZE: 10000,
8
+ TTL: 30 * 60 * 1000,
9
+ STALE_TTL: 5 * 60 * 1000
10
+ },
11
+ SIGNAL: {
12
+ MAX_SIZE: 5000,
13
+ TTL: 60 * 60 * 1000
14
+ },
15
+ GROUPS: {
16
+ MAX_SIZE: 500,
17
+ TTL: 15 * 60 * 1000
18
+ },
19
+ PROFILES: {
20
+ MAX_SIZE: 1000,
21
+ TTL: 60 * 60 * 1000
22
+ },
23
+ PERSIST_INTERVAL: 5 * 60 * 1000,
24
+ PERSIST_ON_SIZE: 100
25
+ };
26
+
27
+ class EnhancedCache {
28
+ constructor(name, options = {}) {
29
+ this.name = name;
30
+ this.options = { ...CACHE_CONFIG.MEMORY, ...options };
31
+ this.persistPath = options.persistPath;
32
+ this.dirty = new Set();
33
+ this.persistTimer = null;
34
+ this.stats = { hits: 0, misses: 0, sets: 0, deletes: 0 };
35
+ this.cache = new LRUCache({
36
+ max: this.options.MAX_SIZE,
37
+ ttl: this.options.TTL,
38
+ allowStale: true,
39
+ updateAgeOnGet: true,
40
+ updateAgeOnHas: true
41
+ });
42
+ this.hotCache = new Map();
43
+ this.hotCacheMaxSize = Math.floor(this.options.MAX_SIZE * 0.1);
44
+ this.accessCount = new Map();
45
+ if (this.persistPath) this._startPersistence();
46
+ }
47
+
48
+ get(key) {
49
+ if (this.hotCache.has(key)) {
50
+ this.stats.hits++;
51
+ this._trackAccess(key);
52
+ return this.hotCache.get(key);
53
+ }
54
+ const value = this.cache.get(key);
55
+ if (value !== undefined) {
56
+ this.stats.hits++;
57
+ this._trackAccess(key);
58
+ if (this._isHotKey(key)) this._addToHotCache(key, value);
59
+ return value;
60
+ }
61
+ this.stats.misses++;
62
+ return undefined;
63
+ }
64
+
65
+ set(key, value, ttl = undefined) {
66
+ this.cache.set(key, value, { ttl: ttl || this.options.TTL });
67
+ this.stats.sets++;
68
+ if (this.hotCache.has(key)) this.hotCache.set(key, value);
69
+ if (this.persistPath) {
70
+ this.dirty.add(key);
71
+ if (this.dirty.size >= CACHE_CONFIG.PERSIST_ON_SIZE) this._persist();
72
+ }
73
+ }
74
+
75
+ delete(key) {
76
+ this.cache.delete(key);
77
+ this.hotCache.delete(key);
78
+ this.accessCount.delete(key);
79
+ this.dirty.delete(key);
80
+ this.stats.deletes++;
81
+ }
82
+
83
+ has(key) {
84
+ return this.hotCache.has(key) || this.cache.has(key);
85
+ }
86
+
87
+ getMany(keys) {
88
+ const result = {};
89
+ const missing = [];
90
+ for (const key of keys) {
91
+ const value = this.get(key);
92
+ if (value !== undefined) result[key] = value;
93
+ else missing.push(key);
94
+ }
95
+ return { found: result, missing };
96
+ }
97
+
98
+ setMany(entries) {
99
+ for (const [key, value] of Object.entries(entries)) this.set(key, value);
100
+ }
101
+
102
+ _trackAccess(key) {
103
+ const count = (this.accessCount.get(key) || 0) + 1;
104
+ this.accessCount.set(key, count);
105
+ if (this.accessCount.size > this.options.MAX_SIZE) this._cleanupAccessCount();
106
+ }
107
+
108
+ _isHotKey(key) {
109
+ return (this.accessCount.get(key) || 0) >= 3;
110
+ }
111
+
112
+ _addToHotCache(key, value) {
113
+ if (this.hotCache.size >= this.hotCacheMaxSize) {
114
+ let minKey = null;
115
+ let minCount = Infinity;
116
+ for (const [k] of this.hotCache) {
117
+ const count = this.accessCount.get(k) || 0;
118
+ if (count < minCount) { minCount = count; minKey = k; }
119
+ }
120
+ if (minKey) this.hotCache.delete(minKey);
121
+ }
122
+ this.hotCache.set(key, value);
123
+ }
124
+
125
+ _cleanupAccessCount() {
126
+ const entries = [...this.accessCount.entries()];
127
+ entries.sort((a, b) => b[1] - a[1]);
128
+ this.accessCount.clear();
129
+ entries.slice(0, this.options.MAX_SIZE / 2).forEach(([k, v]) => {
130
+ this.accessCount.set(k, Math.floor(v / 2));
131
+ });
132
+ }
133
+
134
+ _startPersistence() {
135
+ this.persistTimer = setInterval(() => {
136
+ if (this.dirty.size > 0) this._persist();
137
+ }, CACHE_CONFIG.PERSIST_INTERVAL);
138
+ }
139
+
140
+ async _persist() {
141
+ if (!this.persistPath || this.dirty.size === 0) return;
142
+ try {
143
+ const data = {};
144
+ for (const key of this.dirty) {
145
+ const value = this.cache.get(key);
146
+ if (value !== undefined) data[key] = value;
147
+ }
148
+ const filePath = join(this.persistPath, `${this.name}-cache.json`);
149
+ let existing = {};
150
+ try {
151
+ const content = await readFile(filePath, 'utf8');
152
+ existing = JSON.parse(content);
153
+ } catch {}
154
+ const merged = { ...existing, ...data };
155
+ await writeFile(filePath, JSON.stringify(merged), 'utf8');
156
+ this.dirty.clear();
157
+ } catch (error) {
158
+ console.error('Cache persist error:', error);
159
+ }
160
+ }
161
+
162
+ async load() {
163
+ if (!this.persistPath) return;
164
+ try {
165
+ const filePath = join(this.persistPath, `${this.name}-cache.json`);
166
+ const content = await readFile(filePath, 'utf8');
167
+ const data = JSON.parse(content);
168
+ for (const [key, value] of Object.entries(data)) this.cache.set(key, value);
169
+ } catch {}
170
+ }
171
+
172
+ getStats() {
173
+ const hitRate = this.stats.hits / (this.stats.hits + this.stats.misses) || 0;
174
+ return {
175
+ ...this.stats,
176
+ hitRate: (hitRate * 100).toFixed(2) + '%',
177
+ size: this.cache.size,
178
+ hotCacheSize: this.hotCache.size,
179
+ dirtyKeys: this.dirty.size
180
+ };
181
+ }
182
+
183
+ clear() {
184
+ this.cache.clear();
185
+ this.hotCache.clear();
186
+ this.accessCount.clear();
187
+ this.dirty.clear();
188
+ }
189
+
190
+ cleanup() {
191
+ if (this.persistTimer) clearInterval(this.persistTimer);
192
+ this._persist();
193
+ this.clear();
194
+ }
195
+ }
196
+
197
+ class CacheManager {
198
+ constructor(baseDir, logger) {
199
+ this.baseDir = baseDir;
200
+ this.logger = logger;
201
+ this.caches = {
202
+ signal: new EnhancedCache('signal', { ...CACHE_CONFIG.SIGNAL, persistPath: baseDir }),
203
+ groups: new EnhancedCache('groups', { ...CACHE_CONFIG.GROUPS, persistPath: baseDir }),
204
+ profiles: new EnhancedCache('profiles', { ...CACHE_CONFIG.PROFILES, persistPath: baseDir }),
205
+ messages: new EnhancedCache('messages', CACHE_CONFIG.MEMORY),
206
+ misc: new EnhancedCache('misc', CACHE_CONFIG.MEMORY)
207
+ };
208
+ }
209
+
210
+ async loadAll() {
211
+ await Promise.all([
212
+ this.caches.signal.load(),
213
+ this.caches.groups.load(),
214
+ this.caches.profiles.load()
215
+ ]);
216
+ this.logger?.info('All caches loaded');
217
+ }
218
+
219
+ getCache(name) {
220
+ return this.caches[name];
221
+ }
222
+
223
+ getAllStats() {
224
+ const stats = {};
225
+ for (const [name, cache] of Object.entries(this.caches)) stats[name] = cache.getStats();
226
+ return stats;
227
+ }
228
+
229
+ clearAll() {
230
+ for (const cache of Object.values(this.caches)) cache.clear();
231
+ }
232
+
233
+ async cleanup() {
234
+ for (const cache of Object.values(this.caches)) cache.cleanup();
235
+ }
236
+ }
237
+
238
+ export {
239
+ CACHE_CONFIG,
240
+ EnhancedCache,
241
+ CacheManager
242
+ };
@@ -0,0 +1,41 @@
1
+ export declare const LOG_LEVELS: {
2
+ fatal: number; error: number; warn: number; info: number; debug: number; trace: number; silent: number;
3
+ };
4
+ export declare const COLORS: Record<string, string>;
5
+ export declare const CATEGORY_ICONS: Record<string, string>;
6
+
7
+ export type LogLevel = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace';
8
+
9
+ export declare class RyzeLogger {
10
+ constructor(options?: {
11
+ level?: LogLevel;
12
+ prettyPrint?: boolean;
13
+ category?: string;
14
+ colors?: boolean;
15
+ timestamps?: boolean;
16
+ filters?: string[];
17
+ maxHistory?: number;
18
+ });
19
+ fatal(messageOrData: string | object, data?: object): void;
20
+ error(messageOrData: string | object, data?: object): void;
21
+ warn(messageOrData: string | object, data?: object): void;
22
+ info(messageOrData: string | object, data?: object): void;
23
+ debug(messageOrData: string | object, data?: object): void;
24
+ trace(messageOrData: string | object, data?: object): void;
25
+ success(message: string, data?: object): void;
26
+ child(bindings: { class?: string; category?: string }): RyzeLogger;
27
+ setLevel(level: LogLevel): void;
28
+ addFilter(pattern: string): void;
29
+ removeFilter(pattern: string): void;
30
+ getHistory(options?: { level?: LogLevel; category?: string; since?: string | number | Date; limit?: number }): Array<{ timestamp: string; level: LogLevel; category: string; message: string; data: any }>;
31
+ clearHistory(): void;
32
+ exportLogs(format?: 'json' | 'text'): string;
33
+ time(label: string): { end: (message?: string) => number };
34
+ if(condition: boolean, level: LogLevel, message: string, data?: object): void;
35
+ throttle(key: string, message: string, data?: object, intervalMs?: number): void;
36
+ }
37
+
38
+ export declare function createLogger(options?: ConstructorParameters<typeof RyzeLogger>[0]): RyzeLogger;
39
+
40
+ declare const defaultLogger: RyzeLogger;
41
+ export default defaultLogger;