@vinzsocket/baileys 3.3.0 → 3.3.1

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 (228) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1337 -2685
  3. package/WAProto/WAProto.proto +916 -360
  4. package/WAProto/fix-imports.js +18 -22
  5. package/WAProto/index.d.ts +0 -14015
  6. package/WAProto/index.js +80576 -45941
  7. package/lib/Defaults/index.d.ts +14 -15
  8. package/lib/Defaults/index.d.ts.map +1 -1
  9. package/lib/Defaults/index.js +109 -98
  10. package/lib/Defaults/index.js.map +1 -1
  11. package/lib/Modded/message_builder.js +2330 -0
  12. package/lib/Signal/Group/group_cipher.js.map +1 -1
  13. package/lib/Signal/Group/keyhelper.d.ts.map +1 -1
  14. package/lib/Signal/Group/keyhelper.js.map +1 -1
  15. package/lib/Signal/Group/sender-chain-key.js.map +1 -1
  16. package/lib/Signal/Group/sender-key-message.js.map +1 -1
  17. package/lib/Signal/Group/sender-message-key.js.map +1 -1
  18. package/lib/Signal/libsignal.d.ts.map +1 -1
  19. package/lib/Signal/libsignal.js +17 -45
  20. package/lib/Signal/libsignal.js.map +1 -1
  21. package/lib/Signal/lid-mapping.d.ts +0 -4
  22. package/lib/Signal/lid-mapping.d.ts.map +1 -1
  23. package/lib/Signal/lid-mapping.js +0 -6
  24. package/lib/Signal/lid-mapping.js.map +1 -1
  25. package/lib/Socket/business.d.ts +532 -213
  26. package/lib/Socket/business.d.ts.map +1 -1
  27. package/lib/Socket/business.js +401 -358
  28. package/lib/Socket/chats.d.ts +2 -15
  29. package/lib/Socket/chats.d.ts.map +1 -1
  30. package/lib/Socket/chats.js +40 -247
  31. package/lib/Socket/chats.js.map +1 -1
  32. package/lib/Socket/communities.d.ts +641 -269
  33. package/lib/Socket/communities.d.ts.map +1 -1
  34. package/lib/Socket/dugong.d.ts +127 -315
  35. package/lib/Socket/dugong.d.ts.map +1 -0
  36. package/lib/Socket/dugong.js +749 -623
  37. package/lib/Socket/dugong.js.map +1 -0
  38. package/lib/Socket/groups.d.ts +2 -13
  39. package/lib/Socket/groups.d.ts.map +1 -1
  40. package/lib/Socket/groups.js +1 -21
  41. package/lib/Socket/groups.js.map +1 -1
  42. package/lib/Socket/index.d.ts +631 -256
  43. package/lib/Socket/index.d.ts.map +1 -1
  44. package/lib/Socket/index.js +12 -9
  45. package/lib/Socket/index.js.map +1 -1
  46. package/lib/Socket/messages-recv.d.ts +58 -23
  47. package/lib/Socket/messages-recv.d.ts.map +1 -1
  48. package/lib/Socket/messages-recv.js +181 -645
  49. package/lib/Socket/messages-recv.js.map +1 -1
  50. package/lib/Socket/messages-send.d.ts +575 -201
  51. package/lib/Socket/messages-send.d.ts.map +1 -1
  52. package/lib/Socket/messages-send.js +1552 -1185
  53. package/lib/Socket/messages-send.js.map +1 -1
  54. package/lib/Socket/mex.d.ts.map +1 -1
  55. package/lib/Socket/mex.js +8 -2
  56. package/lib/Socket/mex.js.map +1 -1
  57. package/lib/Socket/newsletter.d.ts +18 -11
  58. package/lib/Socket/newsletter.d.ts.map +1 -1
  59. package/lib/Socket/newsletter.js +440 -165
  60. package/lib/Socket/newsletter.js.map +1 -1
  61. package/lib/Socket/socket.d.ts +2 -6
  62. package/lib/Socket/socket.d.ts.map +1 -1
  63. package/lib/Socket/socket.js +25 -59
  64. package/lib/Socket/socket.js.map +1 -1
  65. package/lib/Types/Auth.d.ts +0 -1
  66. package/lib/Types/Auth.d.ts.map +1 -1
  67. package/lib/Types/Bussines.d.ts +34 -22
  68. package/lib/Types/Call.d.ts +1 -1
  69. package/lib/Types/Call.d.ts.map +1 -1
  70. package/lib/Types/Chat.d.ts +0 -1
  71. package/lib/Types/Chat.d.ts.map +1 -1
  72. package/lib/Types/Contact.d.ts +0 -2
  73. package/lib/Types/Contact.d.ts.map +1 -1
  74. package/lib/Types/Events.d.ts +1 -20
  75. package/lib/Types/Events.d.ts.map +1 -1
  76. package/lib/Types/GroupMetadata.d.ts +1 -4
  77. package/lib/Types/GroupMetadata.d.ts.map +1 -1
  78. package/lib/Types/Message.d.ts +348 -294
  79. package/lib/Types/Message.d.ts.map +1 -1
  80. package/lib/Types/Message.js.map +1 -1
  81. package/lib/Types/{Mex.d.ts → Newsletter.d.ts} +5 -11
  82. package/lib/Types/Newsletter.d.ts.map +1 -0
  83. package/lib/Types/{Mex.js → Newsletter.js} +3 -9
  84. package/lib/Types/Newsletter.js.map +1 -0
  85. package/lib/Types/Signal.d.ts +1 -12
  86. package/lib/Types/Signal.d.ts.map +1 -1
  87. package/lib/Types/Socket.d.ts +148 -126
  88. package/lib/Types/Socket.d.ts.map +1 -1
  89. package/lib/Types/State.d.ts +0 -58
  90. package/lib/Types/State.d.ts.map +1 -1
  91. package/lib/Types/State.js +0 -43
  92. package/lib/Types/State.js.map +1 -1
  93. package/lib/Types/index.d.ts +52 -52
  94. package/lib/Types/index.d.ts.map +1 -1
  95. package/lib/Types/index.js +30 -23
  96. package/lib/Types/index.js.map +1 -1
  97. package/lib/Utils/auth-utils.d.ts +0 -5
  98. package/lib/Utils/auth-utils.d.ts.map +1 -1
  99. package/lib/Utils/auth-utils.js +0 -12
  100. package/lib/Utils/auth-utils.js.map +1 -1
  101. package/lib/Utils/browser-utils.js +0 -1
  102. package/lib/Utils/chat-utils.d.ts +4 -34
  103. package/lib/Utils/chat-utils.d.ts.map +1 -1
  104. package/lib/Utils/chat-utils.js +20 -80
  105. package/lib/Utils/chat-utils.js.map +1 -1
  106. package/lib/Utils/crypto.d.ts +12 -12
  107. package/lib/Utils/crypto.d.ts.map +1 -1
  108. package/lib/Utils/crypto.js.map +1 -1
  109. package/lib/Utils/decode-wa-message.d.ts +0 -18
  110. package/lib/Utils/decode-wa-message.d.ts.map +1 -1
  111. package/lib/Utils/decode-wa-message.js +0 -34
  112. package/lib/Utils/decode-wa-message.js.map +1 -1
  113. package/lib/Utils/event-buffer.d.ts +0 -2
  114. package/lib/Utils/event-buffer.d.ts.map +1 -1
  115. package/lib/Utils/event-buffer.js +1 -49
  116. package/lib/Utils/event-buffer.js.map +1 -1
  117. package/lib/Utils/generics.d.ts +2 -2
  118. package/lib/Utils/generics.d.ts.map +1 -1
  119. package/lib/Utils/generics.js +1 -10
  120. package/lib/Utils/generics.js.map +1 -1
  121. package/lib/Utils/history.d.ts +0 -2
  122. package/lib/Utils/history.d.ts.map +1 -1
  123. package/lib/Utils/history.js +9 -12
  124. package/lib/Utils/history.js.map +1 -1
  125. package/lib/Utils/identity-change-handler.d.ts +0 -7
  126. package/lib/Utils/identity-change-handler.d.ts.map +1 -1
  127. package/lib/Utils/identity-change-handler.js +0 -1
  128. package/lib/Utils/identity-change-handler.js.map +1 -1
  129. package/lib/Utils/index.d.ts +23 -23
  130. package/lib/Utils/index.d.ts.map +1 -1
  131. package/lib/Utils/index.js +2 -3
  132. package/lib/Utils/index.js.map +1 -1
  133. package/lib/Utils/link-preview.js +2 -2
  134. package/lib/Utils/link-preview.js.map +1 -1
  135. package/lib/Utils/logger.d.ts +2 -1
  136. package/lib/Utils/logger.d.ts.map +1 -1
  137. package/lib/Utils/message-retry-manager.d.ts +0 -5
  138. package/lib/Utils/message-retry-manager.d.ts.map +1 -1
  139. package/lib/Utils/message-retry-manager.js +0 -40
  140. package/lib/Utils/message-retry-manager.js.map +1 -1
  141. package/lib/Utils/messages-media.d.ts +13 -16
  142. package/lib/Utils/messages-media.d.ts.map +1 -1
  143. package/lib/Utils/messages-media.js +79 -85
  144. package/lib/Utils/messages-media.js.map +1 -1
  145. package/lib/Utils/messages.d.ts +1 -16
  146. package/lib/Utils/messages.d.ts.map +1 -1
  147. package/lib/Utils/messages.js +1121 -1021
  148. package/lib/Utils/messages.js.map +1 -1
  149. package/lib/Utils/noise-handler.d.ts +1 -1
  150. package/lib/Utils/process-message.d.ts.map +1 -1
  151. package/lib/Utils/process-message.js +1 -103
  152. package/lib/Utils/process-message.js.map +1 -1
  153. package/lib/Utils/rich-messages.d.ts +277 -0
  154. package/lib/Utils/rich-messages.d.ts.map +1 -0
  155. package/lib/Utils/rich-messages.js +1144 -0
  156. package/lib/Utils/rich-messages.js.map +1 -0
  157. package/lib/Utils/signal.d.ts +0 -13
  158. package/lib/Utils/signal.d.ts.map +1 -1
  159. package/lib/Utils/signal.js +0 -42
  160. package/lib/Utils/signal.js.map +1 -1
  161. package/lib/Utils/sticker-pack.d.ts +10 -0
  162. package/lib/Utils/sticker-pack.js +111 -0
  163. package/lib/Utils/sync-action-utils.d.ts.map +1 -1
  164. package/lib/Utils/sync-action-utils.js +0 -1
  165. package/lib/Utils/sync-action-utils.js.map +1 -1
  166. package/lib/Utils/tc-token-utils.d.ts +1 -26
  167. package/lib/Utils/tc-token-utils.d.ts.map +1 -1
  168. package/lib/Utils/tc-token-utils.js +5 -151
  169. package/lib/Utils/tc-token-utils.js.map +1 -1
  170. package/lib/Utils/validate-connection.d.ts.map +1 -1
  171. package/lib/Utils/validate-connection.js +2 -12
  172. package/lib/Utils/validate-connection.js.map +1 -1
  173. package/lib/VoIP/audio-feeder.d.ts +15 -0
  174. package/lib/VoIP/audio-feeder.js +132 -0
  175. package/lib/VoIP/index.js +277 -0
  176. package/lib/VoIP/relay-transport.d.ts +43 -0
  177. package/lib/VoIP/relay-transport.js +559 -0
  178. package/lib/VoIP/signaling.js +594 -0
  179. package/lib/VoIP/types.d.ts +69 -0
  180. package/lib/VoIP/types.js +17 -0
  181. package/lib/VoIP/wasm-engine.d.ts +103 -0
  182. package/lib/VoIP/wasm-engine.js +1214 -0
  183. package/lib/VoIP/worker-bootstrap.js +1042 -0
  184. package/lib/WABinary/decode.d.ts +1 -1
  185. package/lib/WABinary/decode.d.ts.map +1 -1
  186. package/lib/WABinary/generic-utils.d.ts +3 -1
  187. package/lib/WABinary/generic-utils.d.ts.map +1 -1
  188. package/lib/WABinary/generic-utils.js +78 -0
  189. package/lib/WABinary/generic-utils.js.map +1 -1
  190. package/lib/WAM/encode.d.ts +1 -1
  191. package/lib/WAM/encode.d.ts.map +1 -1
  192. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -1
  193. package/lib/WAUSync/Protocols/USyncContactProtocol.js +3 -26
  194. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -1
  195. package/lib/WAUSync/Protocols/index.d.ts +0 -1
  196. package/lib/WAUSync/Protocols/index.d.ts.map +1 -1
  197. package/lib/WAUSync/Protocols/index.js +0 -1
  198. package/lib/WAUSync/Protocols/index.js.map +1 -1
  199. package/lib/WAUSync/USyncQuery.d.ts +0 -1
  200. package/lib/WAUSync/USyncQuery.d.ts.map +1 -1
  201. package/lib/WAUSync/USyncQuery.js +2 -6
  202. package/lib/WAUSync/USyncQuery.js.map +1 -1
  203. package/lib/WAUSync/USyncUser.d.ts +0 -4
  204. package/lib/WAUSync/USyncUser.d.ts.map +1 -1
  205. package/lib/WAUSync/USyncUser.js +0 -8
  206. package/lib/WAUSync/USyncUser.js.map +1 -1
  207. package/lib/assets/wasm/loader.js +5 -0
  208. package/lib/assets/wasm/whatsapp.wasm +0 -0
  209. package/lib/assets/wasm/worker-modules.js +273 -0
  210. package/lib/index.d.ts +1 -0
  211. package/lib/index.d.ts.map +1 -1
  212. package/lib/index.js +3 -0
  213. package/lib/index.js.map +1 -1
  214. package/package.json +29 -92
  215. package/engine-requirements.js +0 -27
  216. package/lib/Types/Mex.d.ts.map +0 -1
  217. package/lib/Types/Mex.js.map +0 -1
  218. package/lib/Utils/companion-reg-client-utils.d.ts +0 -17
  219. package/lib/Utils/companion-reg-client-utils.d.ts.map +0 -1
  220. package/lib/Utils/companion-reg-client-utils.js +0 -35
  221. package/lib/Utils/companion-reg-client-utils.js.map +0 -1
  222. package/lib/Utils/mention.d.ts +0 -14
  223. package/lib/Utils/mention.js +0 -138
  224. package/lib/Utils/story-card.js +0 -107
  225. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +0 -10
  226. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +0 -1
  227. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +0 -25
  228. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +0 -1
@@ -1,19 +1,11 @@
1
1
  import { Boom } from '@hapi/boom';
2
2
  import { proto } from '../../WAProto/index.js';
3
- import type { BotListInfo, CacheStore, ChatModification, MessageUpsertType, SocketConfig, WABusinessProfile, WAMediaUpload, WAMessage, WAPatchCreate, WAPresence, WAPrivacyCallValue, WAPrivacyGroupAddValue, WAPrivacyMessagesValue, WAPrivacyOnlineValue, WAPrivacyValue, WAReadReceiptsValue } from '../Types/index.js';
3
+ import type { BotListInfo, ChatModification, MessageUpsertType, SocketConfig, WABusinessProfile, WAMediaUpload, WAMessage, WAPatchCreate, WAPresence, WAPrivacyCallValue, WAPrivacyGroupAddValue, WAPrivacyMessagesValue, WAPrivacyOnlineValue, WAPrivacyValue, WAReadReceiptsValue } from '../Types/index.js';
4
4
  import type { QuickReplyAction } from '../Types/Bussines.js';
5
5
  import type { LabelActionBody } from '../Types/Label.js';
6
6
  import { type BinaryNode } from '../WABinary/index.js';
7
7
  import { USyncQuery } from '../WAUSync/index.js';
8
8
  export declare const makeChatsSocket: (config: SocketConfig) => {
9
- serverProps: {
10
- /** AB prop 10518: gate tctoken on 1:1 messages. Default true (safe: avoids 463). */
11
- privacyTokenOn1to1: boolean;
12
- /** AB prop 9666: gate tctoken on profile picture IQs. WA Web default: true. */
13
- profilePicPrivacyToken: boolean;
14
- /** AB prop 14303: issue tctokens to LID instead of PN. WA Web default: false. */
15
- lidTrustedTokenIssueToLid: boolean;
16
- };
17
9
  createCallLink: (type: "audio" | "video", event?: {
18
10
  startTime: number;
19
11
  }, timeoutMs?: number) => Promise<string | undefined>;
@@ -65,7 +57,6 @@ export declare const makeChatsSocket: (config: SocketConfig) => {
65
57
  cleanDirtyBits: (type: "account_sync" | "groups", fromTimestamp?: number | string) => Promise<void>;
66
58
  addOrEditContact: (jid: string, contact: proto.SyncActionValue.IContactAction) => Promise<void>;
67
59
  removeContact: (jid: string) => Promise<void>;
68
- placeholderResendCache: CacheStore;
69
60
  addLabel: (jid: string, labels: LabelActionBody) => Promise<void>;
70
61
  addChatLabel: (jid: string, labelId: string) => Promise<void>;
71
62
  removeChatLabel: (jid: string, labelId: string) => Promise<void>;
@@ -85,7 +76,6 @@ export declare const makeChatsSocket: (config: SocketConfig) => {
85
76
  createBufferedFunction<A extends any[], T>(work: (...args: A) => Promise<T>): (...args: A) => Promise<T>;
86
77
  flush(): boolean;
87
78
  isBuffering(): boolean;
88
- destroy(): void;
89
79
  };
90
80
  authState: {
91
81
  creds: import("../Types/index.js").AuthenticationCreds;
@@ -101,9 +91,8 @@ export declare const makeChatsSocket: (config: SocketConfig) => {
101
91
  sendNode: (frame: BinaryNode) => Promise<void>;
102
92
  logout: (msg?: string) => Promise<void>;
103
93
  end: (error: Error | undefined) => Promise<void>;
104
- registerSocketEndHandler: (handler: (error: Error | undefined) => void | Promise<void>) => void;
105
94
  onUnexpectedError: (err: Error | Boom, msg: string) => void;
106
- uploadPreKeys: (count?: number) => Promise<void>;
95
+ uploadPreKeys: (count?: number, retryCount?: number) => Promise<void>;
107
96
  uploadPreKeysToServerIfRequired: () => Promise<void>;
108
97
  digestKeyBundle: () => Promise<void>;
109
98
  rotateSignedPreKey: () => Promise<void>;
@@ -118,7 +107,5 @@ export declare const makeChatsSocket: (config: SocketConfig) => {
118
107
  jid: string;
119
108
  exists: boolean;
120
109
  }[] | undefined>;
121
- fetchAccountReachoutTimelock: () => Promise<import("../Types/index.js").ReachoutTimelockState>;
122
- fetchNewChatMessageCap: () => Promise<import("../Types/index.js").NewChatMessageCapInfo>;
123
110
  };
124
111
  //# sourceMappingURL=chats.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"chats.d.ts","sourceRoot":"","sources":["../../src/Socket/chats.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAA;AACjC,OAAO,EAAE,KAAK,EAAE,MAAM,wBAAwB,CAAA;AAE9C,OAAO,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api/boom';
3
3
  import { proto } from '../../WAProto/index.js';
4
- import { DEFAULT_CACHE_TTLS, HISTORY_SYNC_PAUSED_TIMEOUT_MS, PROCESSABLE_HISTORY_TYPES } from '../Defaults/index.js';
4
+ import { DEFAULT_CACHE_TTLS, PROCESSABLE_HISTORY_TYPES } from '../Defaults/index.js';
5
5
  import { ALL_WA_PATCH_NAMES } from '../Types/index.js';
6
6
  import { SyncState } from '../Types/State.js';
7
- import { chatModificationToAppPatch, decodePatches, decodeSyncdSnapshot, encodeSyncdPatch, ensureLTHashStateVersion, extractSyncdPatches, generateProfilePicture, getHistoryMsg, isAppStateSyncIrrecoverable, isMissingKeyError, MAX_SYNC_ATTEMPTS, newLTHashState, processSyncAction } from '../Utils/index.js';
7
+ import { chatModificationToAppPatch, decodePatches, decodeSyncdSnapshot, encodeSyncdPatch, extractSyncdPatches, generateProfilePicture, getHistoryMsg, newLTHashState, processSyncAction } from '../Utils/index.js';
8
8
  import { makeMutex } from '../Utils/make-mutex.js';
9
9
  import processMessage from '../Utils/process-message.js';
10
10
  import { buildTcTokenFromJid } from '../Utils/tc-token-utils.js';
11
- import { getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isLidUser, isPnUser, jidDecode, jidNormalizedUser, reduceBinaryNodeToDictionary, S_WHATSAPP_NET } from '../WABinary/index.js';
11
+ import { getBinaryNodeChild, getBinaryNodeChildren, jidDecode, jidNormalizedUser, reduceBinaryNodeToDictionary, S_WHATSAPP_NET } from '../WABinary/index.js';
12
12
  import { USyncQuery, USyncUser } from '../WAUSync/index.js';
13
13
  import { makeSocket } from './socket.js';
14
- export const buildProfilePictureQueryContent = (type, tcTokenContent) => {
15
- const picture = { tag: 'picture', attrs: { type, query: 'url' } };
16
- if (tcTokenContent?.length) {
17
- picture.content = tcTokenContent;
18
- }
19
- return [picture];
20
- };
14
+ const MAX_SYNC_ATTEMPTS = 2;
21
15
  export const makeChatsSocket = (config) => {
22
16
  const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, getMessage } = config;
23
17
  const sock = makeSocket(config);
24
- const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, sendUnifiedSession, registerSocketEndHandler } = sock;
25
- const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
18
+ const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, sendUnifiedSession } = sock;
26
19
  let privacySettings;
27
- /** Server-assigned AB props for protocol behavior. */
28
- const serverProps = {
29
- /** AB prop 10518: gate tctoken on 1:1 messages. Default true (safe: avoids 463). */
30
- privacyTokenOn1to1: true,
31
- /** AB prop 9666: gate tctoken on profile picture IQs. WA Web default: true. */
32
- profilePicPrivacyToken: true,
33
- /** AB prop 14303: issue tctokens to LID instead of PN. WA Web default: false. */
34
- lidTrustedTokenIssueToLid: false
35
- };
36
20
  let syncState = SyncState.Connecting;
37
21
  /** this mutex ensures that messages are processed in order */
38
22
  const messageMutex = makeMutex();
@@ -44,20 +28,14 @@ export const makeChatsSocket = (config) => {
44
28
  const notificationMutex = makeMutex();
45
29
  // Timeout for AwaitingInitialSync state
46
30
  let awaitingSyncTimeout;
47
- // In-memory history sync completion tracking (resets on reconnection)
48
- const historySyncStatus = {
49
- initialBootstrapComplete: false,
50
- recentSyncComplete: false
51
- };
52
- let historySyncPausedTimeout;
53
- // Collections blocked on missing app state sync keys (mirrors WA Web's "Blocked" state).
54
- // When a key arrives via APP_STATE_SYNC_KEY_SHARE, these are re-synced.
55
- const blockedCollections = new Set();
56
31
  const placeholderResendCache = config.placeholderResendCache ||
57
32
  new NodeCache({
58
33
  stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
59
34
  useClones: false
60
35
  });
36
+ if (!config.placeholderResendCache) {
37
+ config.placeholderResendCache = placeholderResendCache;
38
+ }
61
39
  /** helper function to fetch the given app state sync key */
62
40
  const getAppStateSyncKey = async (keyId) => {
63
41
  const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
@@ -280,42 +258,6 @@ export const makeChatsSocket = (config) => {
280
258
  return getBinaryNodeChildren(listNode, 'item').map(n => n.attrs.jid);
281
259
  };
282
260
  const updateBlockStatus = async (jid, action) => {
283
- const normalizedJid = jidNormalizedUser(jid);
284
- let lid;
285
- let pn_jid;
286
- if (isLidUser(normalizedJid) || isHostedLidUser(normalizedJid)) {
287
- lid = normalizedJid;
288
- if (action === 'block') {
289
- const pn = await signalRepository.lidMapping.getPNForLID(normalizedJid);
290
- if (!pn) {
291
- throw new Boom(`Unable to resolve PN JID for LID: ${jid}`, { statusCode: 400 });
292
- }
293
- pn_jid = jidNormalizedUser(pn);
294
- }
295
- }
296
- else if (isPnUser(normalizedJid) || isHostedPnUser(normalizedJid)) {
297
- const mapped = await signalRepository.lidMapping.getLIDForPN(normalizedJid);
298
- if (!mapped) {
299
- throw new Boom(`Unable to resolve LID for PN JID: ${jid}`, { statusCode: 400 });
300
- }
301
- lid = mapped;
302
- if (action === 'block') {
303
- pn_jid = jidNormalizedUser(normalizedJid);
304
- }
305
- }
306
- else {
307
- throw new Boom(`Invalid jid: ${jid}`, { statusCode: 400 });
308
- }
309
- const itemAttrs = {
310
- action,
311
- jid: lid
312
- };
313
- if (action === 'block') {
314
- if (!pn_jid) {
315
- throw new Boom(`pn_jid required for block: ${jid}`, { statusCode: 400 });
316
- }
317
- itemAttrs.pn_jid = pn_jid;
318
- }
319
261
  await query({
320
262
  tag: 'iq',
321
263
  attrs: {
@@ -326,7 +268,10 @@ export const makeChatsSocket = (config) => {
326
268
  content: [
327
269
  {
328
270
  tag: 'item',
329
- attrs: itemAttrs
271
+ attrs: {
272
+ action,
273
+ jid
274
+ }
330
275
  }
331
276
  ]
332
277
  });
@@ -425,9 +370,6 @@ export const makeChatsSocket = (config) => {
425
370
  const collectionsToHandle = new Set(collections);
426
371
  // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
427
372
  const attemptsMap = {};
428
- // collections that failed and need a full snapshot on retry
429
- // mirrors WA Web's ErrorFatal -> force snapshot behavior
430
- const forceSnapshotCollections = new Set();
431
373
  // keep executing till all collections are done
432
374
  // sometimes a single patch request will not return all the patches (God knows why)
433
375
  // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
@@ -438,7 +380,6 @@ export const makeChatsSocket = (config) => {
438
380
  const result = await authState.keys.get('app-state-sync-version', [name]);
439
381
  let state = result[name];
440
382
  if (state) {
441
- state = ensureLTHashStateVersion(state);
442
383
  if (typeof initialVersionMap[name] === 'undefined') {
443
384
  initialVersionMap[name] = state.version;
444
385
  }
@@ -447,18 +388,14 @@ export const makeChatsSocket = (config) => {
447
388
  state = newLTHashState();
448
389
  }
449
390
  states[name] = state;
450
- const shouldForceSnapshot = forceSnapshotCollections.has(name);
451
- if (shouldForceSnapshot) {
452
- forceSnapshotCollections.delete(name);
453
- }
454
- logger.info(`resyncing ${name} from v${state.version}${shouldForceSnapshot ? ' (forcing snapshot)' : ''}`);
391
+ logger.info(`resyncing ${name} from v${state.version}`);
455
392
  nodes.push({
456
393
  tag: 'collection',
457
394
  attrs: {
458
395
  name,
459
396
  version: state.version.toString(),
460
- // return snapshot if syncing from scratch or forcing after a failed attempt
461
- return_snapshot: (shouldForceSnapshot || !state.version).toString()
397
+ // return snapshot if being synced from scratch
398
+ return_snapshot: (!state.version).toString()
462
399
  }
463
400
  });
464
401
  }
@@ -484,7 +421,7 @@ export const makeChatsSocket = (config) => {
484
421
  const { patches, hasMorePatches, snapshot } = decoded[name];
485
422
  try {
486
423
  if (snapshot) {
487
- const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getCachedAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot, logger);
424
+ const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getCachedAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot);
488
425
  states[name] = newState;
489
426
  Object.assign(globalMutationMap, mutationMap);
490
427
  logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
@@ -507,37 +444,19 @@ export const makeChatsSocket = (config) => {
507
444
  }
508
445
  }
509
446
  catch (error) {
447
+ // if retry attempts overshoot
448
+ // or key not found
449
+ const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS ||
450
+ error.output?.statusCode === 404 ||
451
+ error.name === 'TypeError';
452
+ logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`);
453
+ await authState.keys.set({ 'app-state-sync-version': { [name]: null } });
454
+ // increment number of retries
510
455
  attemptsMap[name] = (attemptsMap[name] || 0) + 1;
511
- const logData = {
512
- name,
513
- attempt: attemptsMap[name],
514
- version: states[name].version,
515
- statusCode: error.output?.statusCode,
516
- errorType: error.name,
517
- error: error.stack
518
- };
519
- if (isMissingKeyError(error) && attemptsMap[name] >= MAX_SYNC_ATTEMPTS) {
520
- // WA Web treats missing keys as "Blocked" — park the collection
521
- // until the key arrives via APP_STATE_SYNC_KEY_SHARE.
522
- logger.warn(logData, `${name} blocked on missing key from v${states[name].version}, parking after ${attemptsMap[name]} attempts`);
523
- blockedCollections.add(name);
524
- collectionsToHandle.delete(name);
525
- }
526
- else if (isMissingKeyError(error)) {
527
- // Retry with a snapshot which may use a different key.
528
- logger.info(logData, `${name} blocked on missing key from v${states[name].version}, retrying with snapshot`);
529
- forceSnapshotCollections.add(name);
530
- }
531
- else if (isAppStateSyncIrrecoverable(error, attemptsMap[name])) {
532
- logger.warn(logData, `failed to sync ${name} from v${states[name].version}, giving up`);
456
+ if (isIrrecoverableError) {
457
+ // stop retrying
533
458
  collectionsToHandle.delete(name);
534
459
  }
535
- else {
536
- logger.info(logData, `failed to sync ${name} from v${states[name].version}, forcing snapshot retry`);
537
- // force a full snapshot on retry to recover from
538
- // corrupted local state (e.g. LTHash MAC mismatch)
539
- forceSnapshotCollections.add(name);
540
- }
541
460
  }
542
461
  }
543
462
  }
@@ -553,21 +472,8 @@ export const makeChatsSocket = (config) => {
553
472
  * type = "image for the high res picture"
554
473
  */
555
474
  const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
556
- // WA Web only includes tctoken for user JIDs (not groups/newsletters)
557
- // and never for own profile pic (Chat model for self has no tcToken).
558
- // Including tctoken for own JID causes the server to never respond.
559
- const normalizedJid = jidNormalizedUser(jid);
560
- const isUserJid = isPnUser(normalizedJid) || isLidUser(normalizedJid);
561
- const me = authState.creds.me;
562
- const isSelf = me && (normalizedJid === jidNormalizedUser(me.id) || (me.lid && normalizedJid === jidNormalizedUser(me.lid)));
563
- let tcTokenContent;
564
- if (serverProps.profilePicPrivacyToken && isUserJid && !isSelf) {
565
- tcTokenContent = await buildTcTokenFromJid({
566
- authState,
567
- jid: normalizedJid,
568
- getLIDForPN
569
- });
570
- }
475
+ const baseContent = [{ tag: 'picture', attrs: { type, query: 'url' } }];
476
+ const tcTokenContent = await buildTcTokenFromJid({ authState, jid, baseContent });
571
477
  jid = jidNormalizedUser(jid);
572
478
  const result = await query({
573
479
  tag: 'iq',
@@ -577,7 +483,7 @@ export const makeChatsSocket = (config) => {
577
483
  type: 'get',
578
484
  xmlns: 'w:profile:picture'
579
485
  },
580
- content: buildProfilePictureQueryContent(type, tcTokenContent)
486
+ content: tcTokenContent
581
487
  }, timeoutMs);
582
488
  const child = getBinaryNodeChild(result, 'picture');
583
489
  return child?.attrs?.url;
@@ -643,12 +549,7 @@ export const makeChatsSocket = (config) => {
643
549
  * @param tcToken token for subscription, use if present
644
550
  */
645
551
  const presenceSubscribe = async (toJid) => {
646
- // Only include tctoken for user JIDs — groups/newsletters don't use tctokens
647
- const normalizedToJid = jidNormalizedUser(toJid);
648
- const isUserJid = isPnUser(normalizedToJid) || isLidUser(normalizedToJid);
649
- const tcTokenContent = isUserJid
650
- ? await buildTcTokenFromJid({ authState, jid: normalizedToJid, getLIDForPN })
651
- : undefined;
552
+ const tcTokenContent = await buildTcTokenFromJid({ authState, jid: toJid });
652
553
  return sendNode({
653
554
  tag: 'presence',
654
555
  attrs: {
@@ -669,8 +570,7 @@ export const makeChatsSocket = (config) => {
669
570
  if (tag === 'presence') {
670
571
  presence = {
671
572
  lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
672
- lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined,
673
- groupOnlineCount: attrs.count ? +attrs.count : undefined
573
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
674
574
  };
675
575
  }
676
576
  else if (Array.isArray(content)) {
@@ -704,7 +604,7 @@ export const makeChatsSocket = (config) => {
704
604
  logger.debug({ patch: patchCreate }, 'applying app patch');
705
605
  await resyncAppState([name], false);
706
606
  const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
707
- initial = currentSyncVersion ? ensureLTHashStateVersion(currentSyncVersion) : newLTHashState();
607
+ initial = currentSyncVersion || newLTHashState();
708
608
  encodeResult = await encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
709
609
  const { patch, state } = encodeResult;
710
610
  const node = {
@@ -750,21 +650,22 @@ export const makeChatsSocket = (config) => {
750
650
  }
751
651
  }
752
652
  };
753
- /** fetch AB props */
653
+ /** sending non-abt props may fix QR scan fail if server expects */
754
654
  const fetchProps = async () => {
655
+ //TODO: implement both protocol 1 and protocol 2 prop fetching, specially for abKey for WM
755
656
  const resultNode = await query({
756
657
  tag: 'iq',
757
658
  attrs: {
758
659
  to: S_WHATSAPP_NET,
759
- xmlns: 'abt',
660
+ xmlns: 'w',
760
661
  type: 'get'
761
662
  },
762
663
  content: [
763
664
  {
764
665
  tag: 'props',
765
666
  attrs: {
766
- protocol: '1',
767
- ...(authState?.creds?.lastPropHash ? { hash: authState.creds.lastPropHash } : {})
667
+ protocol: '2',
668
+ hash: authState?.creds?.lastPropHash || ''
768
669
  }
769
670
  }
770
671
  ]
@@ -779,20 +680,7 @@ export const makeChatsSocket = (config) => {
779
680
  }
780
681
  props = reduceBinaryNodeToDictionary(propsNode, 'prop');
781
682
  }
782
- // Extract protocol-relevant AB props (only the ones we need)
783
- const privacyTokenProp = props['10518'] ?? props['privacy_token_sending_on_all_1_on_1_messages'];
784
- if (privacyTokenProp !== undefined) {
785
- serverProps.privacyTokenOn1to1 = privacyTokenProp === 'true' || privacyTokenProp === '1';
786
- }
787
- const profilePicProp = props['9666'] ?? props['profile_scraping_privacy_token_in_photo_iq'];
788
- if (profilePicProp !== undefined) {
789
- serverProps.profilePicPrivacyToken = profilePicProp === 'true' || profilePicProp === '1';
790
- }
791
- const lidIssueProp = props['14303'] ?? props['lid_trusted_token_issue_to_lid'];
792
- if (lidIssueProp !== undefined) {
793
- serverProps.lidTrustedTokenIssueToLid = lidIssueProp === 'true' || lidIssueProp === '1';
794
- }
795
- logger.debug({ serverProps }, 'fetched props');
683
+ logger.debug('fetched props');
796
684
  return props;
797
685
  };
798
686
  /**
@@ -932,47 +820,6 @@ export const makeChatsSocket = (config) => {
932
820
  ? shouldSyncHistoryMessage(historyMsg) &&
933
821
  PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
934
822
  : false;
935
- if (historyMsg && shouldProcessHistoryMsg) {
936
- const syncType = historyMsg.syncType;
937
- // INITIAL_BOOTSTRAP — fire immediately, no progress check (same as WA Web K function)
938
- if (syncType === proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP &&
939
- !historySyncStatus.initialBootstrapComplete) {
940
- historySyncStatus.initialBootstrapComplete = true;
941
- ev.emit('messaging-history.status', {
942
- syncType,
943
- status: 'complete',
944
- explicit: true
945
- });
946
- }
947
- // RECENT with progress === 100 — explicit completion
948
- if (syncType === proto.HistorySync.HistorySyncType.RECENT &&
949
- historyMsg.progress === 100 &&
950
- !historySyncStatus.recentSyncComplete) {
951
- historySyncStatus.recentSyncComplete = true;
952
- clearTimeout(historySyncPausedTimeout);
953
- historySyncPausedTimeout = undefined;
954
- ev.emit('messaging-history.status', {
955
- syncType,
956
- status: 'complete',
957
- explicit: true
958
- });
959
- }
960
- // Reset 120s paused timeout on any RECENT chunk (like WA Web's handleChunkProgress)
961
- if (syncType === proto.HistorySync.HistorySyncType.RECENT && !historySyncStatus.recentSyncComplete) {
962
- clearTimeout(historySyncPausedTimeout);
963
- historySyncPausedTimeout = setTimeout(() => {
964
- if (!historySyncStatus.recentSyncComplete) {
965
- historySyncStatus.recentSyncComplete = true;
966
- ev.emit('messaging-history.status', {
967
- syncType: proto.HistorySync.HistorySyncType.RECENT,
968
- status: 'paused',
969
- explicit: false
970
- });
971
- }
972
- historySyncPausedTimeout = undefined;
973
- }, HISTORY_SYNC_PAUSED_TIMEOUT_MS);
974
- }
975
- }
976
823
  // State machine: decide on sync and flush
977
824
  if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
978
825
  if (awaitingSyncTimeout) {
@@ -992,8 +839,6 @@ export const makeChatsSocket = (config) => {
992
839
  }
993
840
  const doAppStateSync = async () => {
994
841
  if (syncState === SyncState.Syncing) {
995
- // All collections will be synced, so clear any blocked ones
996
- blockedCollections.clear();
997
842
  logger.info('Doing app state sync');
998
843
  await resyncAppState(ALL_WA_PATCH_NAMES, true);
999
844
  // Sync is complete, go online and flush everything
@@ -1053,11 +898,6 @@ export const makeChatsSocket = (config) => {
1053
898
  }
1054
899
  });
1055
900
  ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
1056
- if (connection === 'close') {
1057
- blockedCollections.clear();
1058
- clearTimeout(historySyncPausedTimeout);
1059
- historySyncPausedTimeout = undefined;
1060
- }
1061
901
  if (connection === 'open') {
1062
902
  if (fireInitQueries) {
1063
903
  executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'));
@@ -1067,10 +907,6 @@ export const makeChatsSocket = (config) => {
1067
907
  if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
1068
908
  return;
1069
909
  }
1070
- historySyncStatus.initialBootstrapComplete = false;
1071
- historySyncStatus.recentSyncComplete = false;
1072
- clearTimeout(historySyncPausedTimeout);
1073
- historySyncPausedTimeout = undefined;
1074
910
  syncState = SyncState.AwaitingInitialSync;
1075
911
  logger.info('Connection is now AwaitingInitialSync, buffering events');
1076
912
  ev.buffer();
@@ -1083,49 +919,19 @@ export const makeChatsSocket = (config) => {
1083
919
  setTimeout(() => ev.flush(), 0);
1084
920
  return;
1085
921
  }
1086
- // On reconnection (accountSyncCounter > 0), the server does not push
1087
- // history sync notifications — the device already has its data.
1088
- // Skip the 20s wait and go online immediately.
1089
- if (authState.creds.accountSyncCounter > 0) {
1090
- logger.info('Reconnection with existing sync data, skipping history sync wait. Transitioning to Online.');
1091
- syncState = SyncState.Online;
1092
- setTimeout(() => ev.flush(), 0);
1093
- return;
1094
- }
1095
- logger.info('First connection, awaiting history sync notification with a 20s timeout.');
922
+ logger.info('History sync is enabled, awaiting notification with a 20s timeout.');
1096
923
  if (awaitingSyncTimeout) {
1097
924
  clearTimeout(awaitingSyncTimeout);
1098
925
  }
1099
926
  awaitingSyncTimeout = setTimeout(() => {
1100
927
  if (syncState === SyncState.AwaitingInitialSync) {
928
+ // TODO: investigate
1101
929
  logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer');
1102
930
  syncState = SyncState.Online;
1103
931
  ev.flush();
1104
- // Increment so subsequent reconnections skip the 20s wait.
1105
- // Late-arriving history is still processed via processMessage
1106
- // regardless of the state machine phase.
1107
- const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
1108
- ev.emit('creds.update', { accountSyncCounter });
1109
932
  }
1110
933
  }, 20000);
1111
934
  });
1112
- // When an app state sync key arrives (myAppStateKeyId is set) and there are
1113
- // collections blocked on a missing key, trigger a re-sync for just those collections.
1114
- // This mirrors WA Web's Blocked → retry-on-key-arrival behavior.
1115
- ev.on('creds.update', ({ myAppStateKeyId }) => {
1116
- if (!myAppStateKeyId || blockedCollections.size === 0) {
1117
- return;
1118
- }
1119
- // If we're in the middle of a full sync, doAppStateSync handles all collections
1120
- if (syncState === SyncState.Syncing) {
1121
- blockedCollections.clear();
1122
- return;
1123
- }
1124
- const collections = [...blockedCollections];
1125
- blockedCollections.clear();
1126
- logger.info({ collections }, 'app state sync key arrived, re-syncing blocked collections');
1127
- resyncAppState(collections, false).catch(error => onUnexpectedError(error, 'blocked collections resync'));
1128
- });
1129
935
  ev.on('lid-mapping.update', async ({ lid, pn }) => {
1130
936
  try {
1131
937
  await signalRepository.lidMapping.storeLIDPNMappings([{ lid, pn }]);
@@ -1134,20 +940,8 @@ export const makeChatsSocket = (config) => {
1134
940
  logger.warn({ lid, pn, error }, 'Failed to store LID-PN mapping');
1135
941
  }
1136
942
  });
1137
- registerSocketEndHandler(() => {
1138
- if (awaitingSyncTimeout) {
1139
- clearTimeout(awaitingSyncTimeout);
1140
- awaitingSyncTimeout = undefined;
1141
- }
1142
- if (!config.placeholderResendCache && placeholderResendCache.close) {
1143
- placeholderResendCache.close();
1144
- }
1145
- syncState = SyncState.Connecting;
1146
- privacySettings = undefined;
1147
- });
1148
943
  return {
1149
944
  ...sock,
1150
- serverProps,
1151
945
  createCallLink,
1152
946
  getBotListV2,
1153
947
  messageMutex,
@@ -1184,7 +978,6 @@ export const makeChatsSocket = (config) => {
1184
978
  cleanDirtyBits,
1185
979
  addOrEditContact,
1186
980
  removeContact,
1187
- placeholderResendCache,
1188
981
  addLabel,
1189
982
  addChatLabel,
1190
983
  removeChatLabel,