@synacwave/baileys 0.0.0-stage → 0.4.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 (229) hide show
  1. package/ATTRIBUTION.md +14 -0
  2. package/CHANGELOG.md +35 -0
  3. package/LICENSE +23 -0
  4. package/README.md +493 -2
  5. package/README.upstream.md +2077 -0
  6. package/WAProto/index.d.ts +15942 -0
  7. package/WAProto/index.js +115911 -0
  8. package/engine-requirements.js +13 -0
  9. package/lib/Defaults/index.d.ts +145 -0
  10. package/lib/Defaults/index.js +155 -0
  11. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  12. package/lib/Signal/Group/ciphertext-message.js +12 -0
  13. package/lib/Signal/Group/group-session-builder.d.ts +8 -0
  14. package/lib/Signal/Group/group-session-builder.js +30 -0
  15. package/lib/Signal/Group/group_cipher.d.ts +11 -0
  16. package/lib/Signal/Group/group_cipher.js +82 -0
  17. package/lib/Signal/Group/index.d.ts +12 -0
  18. package/lib/Signal/Group/index.js +12 -0
  19. package/lib/Signal/Group/keyhelper.d.ts +7 -0
  20. package/lib/Signal/Group/keyhelper.js +18 -0
  21. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  22. package/lib/Signal/Group/sender-chain-key.js +26 -0
  23. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  24. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  25. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  26. package/lib/Signal/Group/sender-key-message.js +66 -0
  27. package/lib/Signal/Group/sender-key-name.d.ts +12 -0
  28. package/lib/Signal/Group/sender-key-name.js +48 -0
  29. package/lib/Signal/Group/sender-key-record.d.ts +13 -0
  30. package/lib/Signal/Group/sender-key-record.js +41 -0
  31. package/lib/Signal/Group/sender-key-state.d.ts +17 -0
  32. package/lib/Signal/Group/sender-key-state.js +84 -0
  33. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  34. package/lib/Signal/Group/sender-message-key.js +26 -0
  35. package/lib/Signal/libsignal.d.ts +55 -0
  36. package/lib/Signal/libsignal.js +431 -0
  37. package/lib/Signal/lid-mapping.d.ts +21 -0
  38. package/lib/Signal/lid-mapping.js +277 -0
  39. package/lib/Socket/Client/index.d.ts +3 -0
  40. package/lib/Socket/Client/index.js +3 -0
  41. package/lib/Socket/Client/types.d.ts +6 -0
  42. package/lib/Socket/Client/types.js +11 -0
  43. package/lib/Socket/Client/websocket.d.ts +13 -0
  44. package/lib/Socket/Client/websocket.js +54 -0
  45. package/lib/Socket/business.d.ts +395 -0
  46. package/lib/Socket/business.js +380 -0
  47. package/lib/Socket/chats.d.ts +144 -0
  48. package/lib/Socket/chats.js +1219 -0
  49. package/lib/Socket/communities.d.ts +562 -0
  50. package/lib/Socket/communities.js +432 -0
  51. package/lib/Socket/groups.d.ts +286 -0
  52. package/lib/Socket/groups.js +348 -0
  53. package/lib/Socket/index.d.ts +531 -0
  54. package/lib/Socket/index.js +13 -0
  55. package/lib/Socket/messages-recv.d.ts +334 -0
  56. package/lib/Socket/messages-recv.js +1772 -0
  57. package/lib/Socket/messages-send.d.ts +330 -0
  58. package/lib/Socket/messages-send.js +1372 -0
  59. package/lib/Socket/mex.d.ts +2 -0
  60. package/lib/Socket/mex.js +42 -0
  61. package/lib/Socket/newsletter.d.ts +283 -0
  62. package/lib/Socket/newsletter.js +226 -0
  63. package/lib/Socket/socket.d.ts +61 -0
  64. package/lib/Socket/socket.js +970 -0
  65. package/lib/Store/index.d.ts +4 -0
  66. package/lib/Store/index.js +4 -0
  67. package/lib/Store/make-in-memory-store.d.ts +63 -0
  68. package/lib/Store/make-in-memory-store.js +421 -0
  69. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  70. package/lib/Store/make-ordered-dictionary.js +79 -0
  71. package/lib/Store/object-repository.d.ts +11 -0
  72. package/lib/Store/object-repository.js +24 -0
  73. package/lib/Types/Auth.d.ts +2 -0
  74. package/lib/Types/Auth.js +2 -0
  75. package/lib/Types/Bussines.d.ts +2 -0
  76. package/lib/Types/Bussines.js +2 -0
  77. package/lib/Types/Call.d.ts +2 -0
  78. package/lib/Types/Call.js +2 -0
  79. package/lib/Types/Chat.d.ts +2 -0
  80. package/lib/Types/Chat.js +8 -0
  81. package/lib/Types/Contact.d.ts +2 -0
  82. package/lib/Types/Contact.js +2 -0
  83. package/lib/Types/Events.d.ts +2 -0
  84. package/lib/Types/Events.js +2 -0
  85. package/lib/Types/GroupMetadata.d.ts +2 -0
  86. package/lib/Types/GroupMetadata.js +2 -0
  87. package/lib/Types/Label.d.ts +3 -0
  88. package/lib/Types/Label.js +25 -0
  89. package/lib/Types/LabelAssociation.d.ts +3 -0
  90. package/lib/Types/LabelAssociation.js +7 -0
  91. package/lib/Types/Message.d.ts +12 -0
  92. package/lib/Types/Message.js +18 -0
  93. package/lib/Types/Mex.d.ts +3 -0
  94. package/lib/Types/Mex.js +39 -0
  95. package/lib/Types/Product.d.ts +2 -0
  96. package/lib/Types/Product.js +2 -0
  97. package/lib/Types/RichType.d.ts +3 -0
  98. package/lib/Types/RichType.js +23 -0
  99. package/lib/Types/Signal.d.ts +2 -0
  100. package/lib/Types/Signal.js +2 -0
  101. package/lib/Types/Socket.d.ts +2 -0
  102. package/lib/Types/Socket.js +2 -0
  103. package/lib/Types/State.d.ts +6 -0
  104. package/lib/Types/State.js +56 -0
  105. package/lib/Types/USync.d.ts +2 -0
  106. package/lib/Types/USync.js +2 -0
  107. package/lib/Types/index.d.ts +14 -0
  108. package/lib/Types/index.js +26 -0
  109. package/lib/Utils/api-wrappers.d.ts +70 -0
  110. package/lib/Utils/api-wrappers.js +248 -0
  111. package/lib/Utils/auth-utils.d.ts +58 -0
  112. package/lib/Utils/auth-utils.js +306 -0
  113. package/lib/Utils/browser-utils.d.ts +10 -0
  114. package/lib/Utils/browser-utils.js +29 -0
  115. package/lib/Utils/business.d.ts +50 -0
  116. package/lib/Utils/business.js +231 -0
  117. package/lib/Utils/chat-utils.d.ts +409 -0
  118. package/lib/Utils/chat-utils.js +886 -0
  119. package/lib/Utils/companion-reg-client-utils.d.ts +5 -0
  120. package/lib/Utils/companion-reg-client-utils.js +40 -0
  121. package/lib/Utils/crypto.d.ts +40 -0
  122. package/lib/Utils/crypto.js +118 -0
  123. package/lib/Utils/decode-wa-message.d.ts +84 -0
  124. package/lib/Utils/decode-wa-message.js +317 -0
  125. package/lib/Utils/event-buffer.d.ts +13 -0
  126. package/lib/Utils/event-buffer.js +622 -0
  127. package/lib/Utils/generics.d.ts +64 -0
  128. package/lib/Utils/generics.js +395 -0
  129. package/lib/Utils/history.d.ts +76 -0
  130. package/lib/Utils/history.js +134 -0
  131. package/lib/Utils/identity-change-handler.d.ts +14 -0
  132. package/lib/Utils/identity-change-handler.js +50 -0
  133. package/lib/Utils/index.d.ts +28 -0
  134. package/lib/Utils/index.js +30 -0
  135. package/lib/Utils/link-preview.d.ts +13 -0
  136. package/lib/Utils/link-preview.js +85 -0
  137. package/lib/Utils/logger.d.ts +3 -0
  138. package/lib/Utils/logger.js +3 -0
  139. package/lib/Utils/lt-hash.d.ts +7 -0
  140. package/lib/Utils/lt-hash.js +8 -0
  141. package/lib/Utils/make-mutex.d.ts +7 -0
  142. package/lib/Utils/make-mutex.js +33 -0
  143. package/lib/Utils/message-retry-manager.d.ts +80 -0
  144. package/lib/Utils/message-retry-manager.js +265 -0
  145. package/lib/Utils/messages-media.d.ts +137 -0
  146. package/lib/Utils/messages-media.js +843 -0
  147. package/lib/Utils/messages.d.ts +46 -0
  148. package/lib/Utils/messages.js +1840 -0
  149. package/lib/Utils/noise-handler.d.ts +21 -0
  150. package/lib/Utils/noise-handler.js +201 -0
  151. package/lib/Utils/offline-node-processor.d.ts +10 -0
  152. package/lib/Utils/offline-node-processor.js +40 -0
  153. package/lib/Utils/pre-key-manager.d.ts +26 -0
  154. package/lib/Utils/pre-key-manager.js +106 -0
  155. package/lib/Utils/process-message.d.ts +84 -0
  156. package/lib/Utils/process-message.js +749 -0
  157. package/lib/Utils/reporting-utils.d.ts +13 -0
  158. package/lib/Utils/reporting-utils.js +258 -0
  159. package/lib/Utils/rich-message-utils.d.ts +49 -0
  160. package/lib/Utils/rich-message-utils.js +363 -0
  161. package/lib/Utils/signal.d.ts +83 -0
  162. package/lib/Utils/signal.js +201 -0
  163. package/lib/Utils/stanza-ack.d.ts +17 -0
  164. package/lib/Utils/stanza-ack.js +38 -0
  165. package/lib/Utils/status-utils.js +178 -0
  166. package/lib/Utils/sticker-reaction.js +104 -0
  167. package/lib/Utils/synacwave.d.ts +111 -0
  168. package/lib/Utils/synacwave.js +474 -0
  169. package/lib/Utils/sync-action-utils.d.ts +3 -0
  170. package/lib/Utils/sync-action-utils.js +49 -0
  171. package/lib/Utils/tc-token-utils.d.ts +30 -0
  172. package/lib/Utils/tc-token-utils.js +164 -0
  173. package/lib/Utils/use-multi-file-auth-state.d.ts +11 -0
  174. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  175. package/lib/Utils/use-single-file-auth-state.d.ts +11 -0
  176. package/lib/Utils/use-single-file-auth-state.js +109 -0
  177. package/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
  178. package/lib/Utils/use-sqlite-auth-state.js +109 -0
  179. package/lib/Utils/validate-connection.d.ts +44 -0
  180. package/lib/Utils/validate-connection.js +210 -0
  181. package/lib/Utils/view-once-text.d.ts +32 -0
  182. package/lib/Utils/view-once-text.js +213 -0
  183. package/lib/WABinary/constants.d.ts +62 -0
  184. package/lib/WABinary/constants.js +1467 -0
  185. package/lib/WABinary/decode.d.ts +10 -0
  186. package/lib/WABinary/decode.js +262 -0
  187. package/lib/WABinary/encode.d.ts +3 -0
  188. package/lib/WABinary/encode.js +220 -0
  189. package/lib/WABinary/generic-utils.d.ts +77 -0
  190. package/lib/WABinary/generic-utils.js +226 -0
  191. package/lib/WABinary/index.d.ts +6 -0
  192. package/lib/WABinary/index.js +6 -0
  193. package/lib/WABinary/jid-utils.d.ts +29 -0
  194. package/lib/WABinary/jid-utils.js +96 -0
  195. package/lib/WABinary/types.d.ts +2 -0
  196. package/lib/WABinary/types.js +2 -0
  197. package/lib/WAM/BinaryInfo.d.ts +8 -0
  198. package/lib/WAM/BinaryInfo.js +10 -0
  199. package/lib/WAM/constants.d.ts +34927 -0
  200. package/lib/WAM/constants.js +22853 -0
  201. package/lib/WAM/encode.d.ts +2 -0
  202. package/lib/WAM/encode.js +150 -0
  203. package/lib/WAM/index.d.ts +4 -0
  204. package/lib/WAM/index.js +4 -0
  205. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +37 -0
  206. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  207. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  208. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  209. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  210. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  211. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  212. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  213. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  214. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  215. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +39 -0
  216. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  217. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +15 -0
  218. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  219. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  220. package/lib/WAUSync/Protocols/index.js +6 -0
  221. package/lib/WAUSync/USyncQuery.d.ts +21 -0
  222. package/lib/WAUSync/USyncQuery.js +98 -0
  223. package/lib/WAUSync/USyncUser.d.ts +17 -0
  224. package/lib/WAUSync/USyncUser.js +31 -0
  225. package/lib/WAUSync/index.d.ts +4 -0
  226. package/lib/WAUSync/index.js +4 -0
  227. package/lib/index.d.ts +12 -0
  228. package/lib/index.js +12 -0
  229. package/package.json +118 -5
@@ -0,0 +1,210 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { createHash } from 'crypto';
3
+ import { proto } from '../../WAProto/index.js';
4
+ import { KEY_BUNDLE_TYPE, WA_ADV_ACCOUNT_SIG_PREFIX, WA_ADV_DEVICE_SIG_PREFIX, WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX } from '../Defaults/index.js';
5
+ import { getBinaryNodeChild, jidDecode, S_WHATSAPP_NET } from '../WABinary/index.js';
6
+ import { Curve, hmacSign } from './crypto.js';
7
+ import { encodeBigEndian } from './generics.js';
8
+ import { createSignalIdentity } from './signal.js';
9
+ const getUserAgent = (config) => {
10
+ return {
11
+ appVersion: {
12
+ primary: config.version[0],
13
+ secondary: config.version[1],
14
+ tertiary: config.version[2]
15
+ },
16
+ platform: config.browser[1].toLocaleLowerCase().includes('android')
17
+ ? proto.ClientPayload.UserAgent.Platform.ANDROID
18
+ : proto.ClientPayload.UserAgent.Platform.WEB,
19
+ releaseChannel: proto.ClientPayload.UserAgent.ReleaseChannel.RELEASE,
20
+ osVersion: '0.1',
21
+ device: 'Desktop',
22
+ osBuildNumber: '0.1',
23
+ localeLanguageIso6391: 'en',
24
+ mnc: '000',
25
+ mcc: '000',
26
+ localeCountryIso31661Alpha2: config.countryCode
27
+ };
28
+ };
29
+ const PLATFORM_MAP = {
30
+ 'Mac OS': proto.ClientPayload.WebInfo.WebSubPlatform.DARWIN,
31
+ Windows: proto.ClientPayload.WebInfo.WebSubPlatform.WIN32
32
+ };
33
+ const getWebInfo = (config) => {
34
+ let webSubPlatform = proto.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER;
35
+ if (config.syncFullHistory &&
36
+ PLATFORM_MAP[config.browser[0]] &&
37
+ config.browser[1] === 'Desktop') {
38
+ webSubPlatform = PLATFORM_MAP[config.browser[0]];
39
+ }
40
+ return { webSubPlatform };
41
+ };
42
+ const getClientPayload = (config) => {
43
+ const payload = {
44
+ connectType: proto.ClientPayload.ConnectType.WIFI_UNKNOWN,
45
+ connectReason: proto.ClientPayload.ConnectReason.USER_ACTIVATED,
46
+ userAgent: getUserAgent(config)
47
+ };
48
+ if (!config.browser[1].toLocaleLowerCase().includes('android')) {
49
+ payload.webInfo = getWebInfo(config);
50
+ }
51
+ if (config.pushName) {
52
+ payload.pushName = config.pushName;
53
+ }
54
+ return payload;
55
+ };
56
+ export const generateLoginNode = (userJid, config) => {
57
+ const { user, device } = jidDecode(userJid);
58
+ const payload = {
59
+ ...getClientPayload(config),
60
+ passive: true,
61
+ pull: true,
62
+ username: +user,
63
+ device: device,
64
+ // TODO: investigate (hard set as false atm)
65
+ lidDbMigrated: false
66
+ };
67
+ return proto.ClientPayload.fromObject(payload);
68
+ };
69
+ const getPlatformType = (platform) => {
70
+ const platformType = platform.toUpperCase();
71
+ if (platformType === 'ANDROID') {
72
+ return proto.DeviceProps.PlatformType.ANDROID_PHONE;
73
+ }
74
+ return (proto.DeviceProps.PlatformType[platformType] ||
75
+ proto.DeviceProps.PlatformType.CHROME);
76
+ };
77
+ export const generateRegistrationNode = ({ registrationId, signedPreKey, signedIdentityKey }, config) => {
78
+ // the app version needs to be md5 hashed
79
+ // and passed in
80
+ const appVersionBuf = createHash('md5')
81
+ .update(config.version.join('.')) // join as string
82
+ .digest();
83
+ const companion = {
84
+ os: config.browser[0],
85
+ platformType: getPlatformType(config.browser[1]),
86
+ requireFullSync: config.syncFullHistory,
87
+ historySyncConfig: {
88
+ storageQuotaMb: 10240,
89
+ inlineInitialPayloadInE2EeMsg: true,
90
+ recentSyncDaysLimit: undefined,
91
+ supportCallLogHistory: false,
92
+ supportBotUserAgentChatHistory: true,
93
+ supportCagReactionsAndPolls: true,
94
+ supportBizHostedMsg: true,
95
+ supportRecentSyncChunkMessageCountTuning: true,
96
+ supportHostedGroupMsg: true,
97
+ supportFbidBotChatHistory: true,
98
+ supportAddOnHistorySyncMigration: undefined,
99
+ supportMessageAssociation: true,
100
+ supportGroupHistory: false,
101
+ onDemandReady: undefined,
102
+ supportGuestChat: undefined
103
+ },
104
+ version: {
105
+ primary: 10,
106
+ secondary: 15,
107
+ tertiary: 7
108
+ }
109
+ };
110
+ const companionProto = proto.DeviceProps.encode(companion).finish();
111
+ const registerPayload = {
112
+ ...getClientPayload(config),
113
+ passive: false,
114
+ pull: false,
115
+ devicePairingData: {
116
+ buildHash: appVersionBuf,
117
+ deviceProps: companionProto,
118
+ eRegid: encodeBigEndian(registrationId),
119
+ eKeytype: KEY_BUNDLE_TYPE,
120
+ eIdent: signedIdentityKey.public,
121
+ eSkeyId: encodeBigEndian(signedPreKey.keyId, 3),
122
+ eSkeyVal: signedPreKey.keyPair.public,
123
+ eSkeySig: signedPreKey.signature
124
+ }
125
+ };
126
+ return proto.ClientPayload.fromObject(registerPayload);
127
+ };
128
+ export const configureSuccessfulPairing = (stanza, { advSecretKey, signedIdentityKey, signalIdentities }) => {
129
+ const msgId = stanza.attrs.id;
130
+ const pairSuccessNode = getBinaryNodeChild(stanza, 'pair-success');
131
+ const deviceIdentityNode = getBinaryNodeChild(pairSuccessNode, 'device-identity');
132
+ const platformNode = getBinaryNodeChild(pairSuccessNode, 'platform');
133
+ const deviceNode = getBinaryNodeChild(pairSuccessNode, 'device');
134
+ const businessNode = getBinaryNodeChild(pairSuccessNode, 'biz');
135
+ if (!deviceIdentityNode || !deviceNode) {
136
+ throw new Boom('Missing device-identity or device in pair success node', { data: stanza });
137
+ }
138
+ const bizName = businessNode?.attrs.name;
139
+ const jid = deviceNode.attrs.jid;
140
+ const lid = deviceNode.attrs.lid;
141
+ const { details, hmac, accountType } = proto.ADVSignedDeviceIdentityHMAC.decode(deviceIdentityNode.content);
142
+ let hmacPrefix = Buffer.from([]);
143
+ if (accountType !== undefined && accountType === proto.ADVEncryptionType.HOSTED) {
144
+ hmacPrefix = WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX;
145
+ }
146
+ const advSign = hmacSign(Buffer.concat([hmacPrefix, details]), Buffer.from(advSecretKey, 'base64'));
147
+ if (Buffer.compare(hmac, advSign) !== 0) {
148
+ throw new Boom('Invalid account signature');
149
+ }
150
+ const account = proto.ADVSignedDeviceIdentity.decode(details);
151
+ const { accountSignatureKey, accountSignature, details: deviceDetails } = account;
152
+ const deviceIdentity = proto.ADVDeviceIdentity.decode(deviceDetails);
153
+ const accountSignaturePrefix = deviceIdentity.deviceType === proto.ADVEncryptionType.HOSTED
154
+ ? WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX
155
+ : WA_ADV_ACCOUNT_SIG_PREFIX;
156
+ const accountMsg = Buffer.concat([accountSignaturePrefix, deviceDetails, signedIdentityKey.public]);
157
+ if (!Curve.verify(accountSignatureKey, accountMsg, accountSignature)) {
158
+ throw new Boom('Failed to verify account signature');
159
+ }
160
+ const deviceMsg = Buffer.concat([
161
+ WA_ADV_DEVICE_SIG_PREFIX,
162
+ deviceDetails,
163
+ signedIdentityKey.public,
164
+ accountSignatureKey
165
+ ]);
166
+ account.deviceSignature = Curve.sign(signedIdentityKey.private, deviceMsg);
167
+ const identity = createSignalIdentity(lid, accountSignatureKey);
168
+ const accountEnc = encodeSignedDeviceIdentity(account, false);
169
+ const reply = {
170
+ tag: 'iq',
171
+ attrs: {
172
+ to: S_WHATSAPP_NET,
173
+ type: 'result',
174
+ id: msgId
175
+ },
176
+ content: [
177
+ {
178
+ tag: 'pair-device-sign',
179
+ attrs: {},
180
+ content: [
181
+ {
182
+ tag: 'device-identity',
183
+ attrs: { 'key-index': deviceIdentity.keyIndex.toString() },
184
+ content: accountEnc
185
+ }
186
+ ]
187
+ }
188
+ ]
189
+ };
190
+ const authUpdate = {
191
+ account,
192
+ me: { id: jid, name: bizName, lid },
193
+ signalIdentities: [...(signalIdentities || []), identity],
194
+ platform: platformNode?.attrs.name
195
+ };
196
+ return {
197
+ creds: authUpdate,
198
+ reply
199
+ };
200
+ };
201
+ export const encodeSignedDeviceIdentity = (account, includeSignatureKey) => {
202
+ account = { ...account };
203
+ // set to null if we are not to include the signature key
204
+ // or if we are including the signature key but it is empty
205
+ if (!includeSignatureKey || !account.accountSignatureKey?.length) {
206
+ account.accountSignatureKey = null;
207
+ }
208
+ return proto.ADVSignedDeviceIdentity.encode(account).finish();
209
+ };
210
+ //# sourceMappingURL=validate-connection.js.map
@@ -0,0 +1,32 @@
1
+ import type { proto } from '../../WAProto/index.js';
2
+
3
+ export type ViewOnceTextStrategy = 'inline' | 'lia' | 'viewOnceMessage' | 'viewOnceMessageV2' | 'image';
4
+ export interface ViewOnceTextAttempt { strategy: ViewOnceTextStrategy; ok: boolean; error?: string }
5
+ export interface ViewOnceTextOptions {
6
+ quoted?: proto.IWebMessageInfo | { key: any; message: proto.IMessage };
7
+ messageId?: string;
8
+ ephemeralExpiration?: number;
9
+ timestamp?: Date;
10
+ /** 'auto' (default) tries inline, lia, viewOnceMessage, viewOnceMessageV2, then (if imageFallback) image. */
11
+ strategy?: 'auto' | ViewOnceTextStrategy;
12
+ /** Explicit ordered list; overrides `strategy` and never adds the image fallback on its own. */
13
+ strategies?: ViewOnceTextStrategy[];
14
+ /** Default true. Only used with 'auto'. */
15
+ imageFallback?: boolean;
16
+ /** Default true: encode/decode check before relaying. */
17
+ verify?: boolean;
18
+ relayOptions?: Record<string, any>;
19
+ onAttempt?: (attempt: ViewOnceTextAttempt) => void;
20
+ imageFallbackImage?: Buffer;
21
+ imageFallbackMimetype?: string;
22
+ mediaUploadTimeoutMs?: number;
23
+ }
24
+ export type ViewOnceTextResult = proto.IWebMessageInfo & { readonly viewOnceTextStrategy: ViewOnceTextStrategy; readonly viewOnceTextAttempts: ViewOnceTextAttempt[] };
25
+
26
+ export declare const VIEW_ONCE_TEXT_STRATEGIES: readonly ViewOnceTextStrategy[];
27
+ export declare const makeOnePixelPng: (rgb?: [number, number, number]) => Buffer;
28
+ export declare const buildViewOnceTextMessage: (strategy: 'inline' | 'viewOnceMessage' | 'viewOnceMessageV2', text: string) => proto.IMessage;
29
+ export declare const verifyViewOnceTextWire: (message: proto.IMessage, strategy: ViewOnceTextStrategy, text?: string) => { bytes: Buffer; decoded: proto.IMessage; flagOnWire: boolean };
30
+ export declare const probeViewOnceTextSupport: () => Record<string, { encodes: boolean; error?: string }>;
31
+ export declare const generateViewOnceTextMessage: (sock: any, jid: string, text: string, strategy: ViewOnceTextStrategy, options?: ViewOnceTextOptions) => Promise<proto.IWebMessageInfo>;
32
+ export declare const sendViewOnceTextWithSocket: (sock: any, jid: string, text: string, options?: ViewOnceTextOptions) => Promise<ViewOnceTextResult>;
@@ -0,0 +1,213 @@
1
+ import { deflateSync } from 'zlib';
2
+ import { Boom } from '@hapi/boom';
3
+ import { proto } from '../../WAProto/index.js';
4
+ import { generateMessageIDV2 } from './generics.js';
5
+ import { generateWAMessage, generateWAMessageFromContent } from './messages.js';
6
+
7
+ export const VIEW_ONCE_TEXT_STRATEGIES = Object.freeze([
8
+ 'inline',
9
+ 'lia',
10
+ 'viewOnceMessage',
11
+ 'viewOnceMessageV2',
12
+ 'image'
13
+ ]);
14
+
15
+ const TEXT_STRATEGIES = VIEW_ONCE_TEXT_STRATEGIES.filter(s => s !== 'image');
16
+
17
+ const crcTable = (() => {
18
+ const t = new Uint32Array(256);
19
+ for (let n = 0; n < 256; n++) {
20
+ let c = n;
21
+ for (let k = 0; k < 8; k++) {
22
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
23
+ }
24
+ t[n] = c >>> 0;
25
+ }
26
+ return t;
27
+ })();
28
+ const crc32 = (buf) => {
29
+ let c = 0xffffffff;
30
+ for (const b of buf) {
31
+ c = crcTable[(c ^ b) & 0xff] ^ (c >>> 8);
32
+ }
33
+ return (c ^ 0xffffffff) >>> 0;
34
+ };
35
+ const pngChunk = (type, data) => {
36
+ const body = Buffer.concat([Buffer.from(type, 'ascii'), data]);
37
+ const len = Buffer.alloc(4);
38
+ len.writeUInt32BE(data.length);
39
+ const crc = Buffer.alloc(4);
40
+ crc.writeUInt32BE(crc32(body));
41
+ return Buffer.concat([len, body, crc]);
42
+ };
43
+
44
+ export const makeOnePixelPng = (rgb = [0, 0, 0]) => {
45
+ const ihdr = Buffer.alloc(13);
46
+ ihdr.writeUInt32BE(1, 0);
47
+ ihdr.writeUInt32BE(1, 4);
48
+ ihdr[8] = 8;
49
+ ihdr[9] = 2;
50
+ const raw = Buffer.from([0, rgb[0], rgb[1], rgb[2]]);
51
+ return Buffer.concat([
52
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
53
+ pngChunk('IHDR', ihdr),
54
+ pngChunk('IDAT', deflateSync(raw)),
55
+ pngChunk('IEND', Buffer.alloc(0))
56
+ ]);
57
+ };
58
+
59
+ export const buildViewOnceTextMessage = (strategy, text) => {
60
+ const ext = () => ({ text, viewOnce: true });
61
+ switch (strategy) {
62
+ case 'inline':
63
+ return { extendedTextMessage: ext() };
64
+ case 'viewOnceMessage':
65
+ return { viewOnceMessage: { message: { extendedTextMessage: ext() } } };
66
+ case 'viewOnceMessageV2':
67
+ return { viewOnceMessageV2: { message: { extendedTextMessage: ext() } } };
68
+ default:
69
+ throw new Boom(`No static payload for strategy "${strategy}"`, { statusCode: 400 });
70
+ }
71
+ };
72
+
73
+ const roundTrip = (message) => {
74
+ const bytes = Buffer.from(proto.Message.encode(proto.Message.fromObject(message)).finish());
75
+ return { bytes, decoded: proto.Message.decode(bytes) };
76
+ };
77
+
78
+ export const verifyViewOnceTextWire = (message, strategy, text) => {
79
+ const { bytes, decoded } = roundTrip(message);
80
+ let inner;
81
+ let wrapper = null;
82
+ switch (strategy) {
83
+ case 'inline':
84
+ inner = decoded.extendedTextMessage;
85
+ if (!inner?.viewOnce) {
86
+ throw new Boom('ExtendedTextMessage.viewOnce did not survive encoding', { statusCode: 500 });
87
+ }
88
+ break;
89
+ case 'lia':
90
+ case 'viewOnceMessage':
91
+ wrapper = 'viewOnceMessage';
92
+ inner = decoded.viewOnceMessage?.message?.extendedTextMessage;
93
+ break;
94
+ case 'viewOnceMessageV2':
95
+ wrapper = 'viewOnceMessageV2';
96
+ inner = decoded.viewOnceMessageV2?.message?.extendedTextMessage;
97
+ break;
98
+ case 'image': {
99
+ const w = decoded.viewOnceMessage || decoded.viewOnceMessageV2 || decoded.viewOnceMessageV2Extension;
100
+ inner = (w?.message ?? decoded).imageMessage;
101
+ if (!inner) {
102
+ throw new Boom('image fallback lost its imageMessage', { statusCode: 500 });
103
+ }
104
+ if (!w && !inner.viewOnce) {
105
+ throw new Boom('image fallback is not marked view-once', { statusCode: 500 });
106
+ }
107
+ return { bytes, decoded, flagOnWire: true };
108
+ }
109
+ default:
110
+ throw new Boom(`Unknown view-once text strategy "${strategy}"`, { statusCode: 400 });
111
+ }
112
+ if (!inner) {
113
+ throw new Boom(`Strategy "${strategy}" lost its extendedTextMessage during encoding`, { statusCode: 500 });
114
+ }
115
+ if (text != null && inner.text !== text) {
116
+ throw new Boom(`Strategy "${strategy}" changed the text during encoding`, { statusCode: 500 });
117
+ }
118
+ if (strategy !== 'lia' && strategy !== 'inline' && !inner.viewOnce) {
119
+ throw new Boom(`Strategy "${strategy}" lost the inner viewOnce flag`, { statusCode: 500 });
120
+ }
121
+ return { bytes, decoded, flagOnWire: !!inner.viewOnce || !!wrapper };
122
+ };
123
+
124
+ export const probeViewOnceTextSupport = () => {
125
+ const report = {};
126
+ for (const strategy of TEXT_STRATEGIES) {
127
+ try {
128
+ if (strategy === 'lia') {
129
+
130
+ verifyViewOnceTextWire({ viewOnceMessage: { message: { extendedTextMessage: { text: 'probe' } } } }, 'lia', 'probe');
131
+ }
132
+ else {
133
+ verifyViewOnceTextWire(buildViewOnceTextMessage(strategy, 'probe'), strategy, 'probe');
134
+ }
135
+ report[strategy] = { encodes: true };
136
+ }
137
+ catch (error) {
138
+ report[strategy] = { encodes: false, error: error.message };
139
+ }
140
+ }
141
+ return report;
142
+ };
143
+
144
+ const normalizeStrategies = (options) => {
145
+ const { strategy = 'auto', strategies, imageFallback = true } = options;
146
+ let list;
147
+ if (Array.isArray(strategies) && strategies.length) {
148
+ list = strategies;
149
+ }
150
+ else if (strategy === 'auto') {
151
+ list = TEXT_STRATEGIES.slice();
152
+ }
153
+ else {
154
+ list = [strategy];
155
+ }
156
+ for (const s of list) {
157
+ if (!VIEW_ONCE_TEXT_STRATEGIES.includes(s)) {
158
+ throw new Boom(`Unknown view-once text strategy "${s}"`, { statusCode: 400 });
159
+ }
160
+ }
161
+
162
+ if (imageFallback && !list.includes('image') && strategy === 'auto' && !(Array.isArray(strategies) && strategies.length)) {
163
+ list.push('image');
164
+ }
165
+ return list;
166
+ };
167
+
168
+ export const generateViewOnceTextMessage = async (sock, jid, text, strategy, options = {}) => {
169
+ const base = {
170
+ userJid: sock?.user?.id,
171
+ quoted: options.quoted,
172
+ messageId: options.messageId,
173
+ ephemeralExpiration: options.ephemeralExpiration,
174
+ timestamp: options.timestamp
175
+ };
176
+ if (strategy === 'lia') {
177
+
178
+ return generateWAMessage(jid, { text, viewOnce: true, linkPreview: false }, { ...base, logger: sock?.logger, upload: sock?.waUploadToServer });
179
+ }
180
+ if (strategy === 'image') {
181
+ const image = options.imageFallbackImage ?? makeOnePixelPng();
182
+ return generateWAMessage(jid, { image, caption: text, mimetype: options.imageFallbackMimetype ?? 'image/png', viewOnce: true }, { ...base, logger: sock?.logger, upload: sock?.waUploadToServer, mediaUploadTimeoutMs: options.mediaUploadTimeoutMs });
183
+ }
184
+ return generateWAMessageFromContent(jid, buildViewOnceTextMessage(strategy, text), base);
185
+ };
186
+
187
+ export const sendViewOnceTextWithSocket = async (sock, jid, text, options = {}) => {
188
+ if (typeof text !== 'string' || !text.length) {
189
+ throw new Boom('sendViewOnceText needs a non-empty text string', { statusCode: 400 });
190
+ }
191
+ const strategies = normalizeStrategies(options);
192
+ const messageId = options.messageId || generateMessageIDV2(sock.user?.id);
193
+ const attempts = [];
194
+ for (const strategy of strategies) {
195
+ try {
196
+ const full = await generateViewOnceTextMessage(sock, jid, text, strategy, { ...options, messageId });
197
+ if (options.verify !== false) {
198
+ verifyViewOnceTextWire(full.message, strategy, strategy === 'image' ? undefined : text);
199
+ }
200
+ await sock.relayMessage(jid, full.message, { messageId: full.key.id, ...(options.relayOptions || {}) });
201
+ attempts.push({ strategy, ok: true });
202
+ options.onAttempt?.(attempts[attempts.length - 1]);
203
+ Object.defineProperty(full, 'viewOnceTextStrategy', { value: strategy, enumerable: false });
204
+ Object.defineProperty(full, 'viewOnceTextAttempts', { value: attempts, enumerable: false });
205
+ return full;
206
+ }
207
+ catch (error) {
208
+ attempts.push({ strategy, ok: false, error: error?.message ?? String(error) });
209
+ options.onAttempt?.(attempts[attempts.length - 1]);
210
+ }
211
+ }
212
+ throw new Boom('No view-once text strategy could be built and relayed', { statusCode: 500, data: { attempts } });
213
+ };
@@ -0,0 +1,62 @@
1
+ export namespace TAGS {
2
+ let LIST_EMPTY: number;
3
+ let DICTIONARY_0: number;
4
+ let DICTIONARY_1: number;
5
+ let DICTIONARY_2: number;
6
+ let DICTIONARY_3: number;
7
+ let INTEROP_JID: number;
8
+ let FB_JID: number;
9
+ let AD_JID: number;
10
+ let LIST_8: number;
11
+ let LIST_16: number;
12
+ let JID_PAIR: number;
13
+ let HEX_8: number;
14
+ let BINARY_8: number;
15
+ let BINARY_20: number;
16
+ let BINARY_32: number;
17
+ let NIBBLE_8: number;
18
+ let PACKED_MAX: number;
19
+ }
20
+ export const DOUBLE_BYTE_TOKENS: string[][];
21
+ export const SINGLE_BYTE_TOKENS: string[];
22
+ export const TOKEN_MAP: {};
23
+ export const CPP_KEYWORDS: Set<string>;
24
+ export const CSS_KEYWORDS: Set<string>;
25
+ export const GO_KEYWORDS: Set<string>;
26
+ export const HTML_KEYWORDS: Set<string>;
27
+ export const JS_KEYWORDS: Set<string>;
28
+ export const PYTHON_KEYWORDS: Set<string>;
29
+ export const RUST_KEYWORDS: Set<string>;
30
+ export const C_KEYWORDS: Set<string>;
31
+ export const CSHARP_KEYWORDS: Set<string>;
32
+ export const BASH_KEYWORDS: Set<string>;
33
+ export const CMD_KEYWORDS: Set<string>;
34
+ export const POWERSHELL_KEYWORDS: Set<string>;
35
+ export const LANGUAGE_KEYWORDS: {
36
+ css: Set<string>;
37
+ html: Set<string>;
38
+ javascript: Set<string>;
39
+ typescript: Set<string>;
40
+ js: Set<string>;
41
+ ts: Set<string>;
42
+ python: Set<string>;
43
+ py: Set<string>;
44
+ go: Set<string>;
45
+ golang: Set<string>;
46
+ cpp: Set<string>;
47
+ 'c++': Set<string>;
48
+ rust: Set<string>;
49
+ rs: Set<string>;
50
+ c: Set<string>;
51
+ h: Set<string>;
52
+ csharp: Set<string>;
53
+ cs: Set<string>;
54
+ bash: Set<string>;
55
+ sh: Set<string>;
56
+ zsh: Set<string>;
57
+ cmd: Set<string>;
58
+ bat: Set<string>;
59
+ powershell: Set<string>;
60
+ ps1: Set<string>;
61
+ };
62
+ //# sourceMappingURL=constants.d.ts.map