sauruspro-bail 0.0.0-stage → 5.0.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 (160) hide show
  1. package/README.md +128 -2
  2. package/WAProto/GenerateStatics.sh +3 -0
  3. package/WAProto/WAProto.proto +6754 -0
  4. package/WAProto/fix-imports.js +85 -0
  5. package/WAProto/index.d.ts +79257 -0
  6. package/WAProto/index.js +242946 -0
  7. package/docs/CHANGELOG.md +43 -0
  8. package/docs/NEWSLETTER-STATUS.md +120 -0
  9. package/docs/SPR.md +51 -0
  10. package/engine-requirements.js +10 -0
  11. package/lib/Defaults/index.js +135 -0
  12. package/lib/Signal/Group/ciphertext-message.js +12 -0
  13. package/lib/Signal/Group/group-session-builder.js +30 -0
  14. package/lib/Signal/Group/group_cipher.js +82 -0
  15. package/lib/Signal/Group/index.js +12 -0
  16. package/lib/Signal/Group/keyhelper.js +18 -0
  17. package/lib/Signal/Group/sender-chain-key.js +26 -0
  18. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  19. package/lib/Signal/Group/sender-key-message.js +66 -0
  20. package/lib/Signal/Group/sender-key-name.js +48 -0
  21. package/lib/Signal/Group/sender-key-record.js +41 -0
  22. package/lib/Signal/Group/sender-key-state.js +84 -0
  23. package/lib/Signal/Group/sender-message-key.js +26 -0
  24. package/lib/Signal/libsignal.js +431 -0
  25. package/lib/Signal/lid-mapping.js +277 -0
  26. package/lib/Socket/Client/index.js +3 -0
  27. package/lib/Socket/Client/types.js +11 -0
  28. package/lib/Socket/Client/websocket.js +54 -0
  29. package/lib/Socket/MessageBuilder.js +3729 -0
  30. package/lib/Socket/business.js +379 -0
  31. package/lib/Socket/chats.js +1198 -0
  32. package/lib/Socket/communities.js +431 -0
  33. package/lib/Socket/dinonic-handler.d.ts +27 -0
  34. package/lib/Socket/dinonic-handler.js +882 -0
  35. package/lib/Socket/graphql.js +716 -0
  36. package/lib/Socket/groups.js +374 -0
  37. package/lib/Socket/index.js +96 -0
  38. package/lib/Socket/interop.js +463 -0
  39. package/lib/Socket/luxu.js +387 -0
  40. package/lib/Socket/message-builder.js +556 -0
  41. package/lib/Socket/messages-recv.js +1942 -0
  42. package/lib/Socket/messages-send.js +1541 -0
  43. package/lib/Socket/mex.js +54 -0
  44. package/lib/Socket/newsletter.js +641 -0
  45. package/lib/Socket/privacy.js +318 -0
  46. package/lib/Socket/socket.js +1115 -0
  47. package/lib/Socket/username.js +236 -0
  48. package/lib/Store/index.js +10 -0
  49. package/lib/Store/keyed-db.js +108 -0
  50. package/lib/Store/make-cache-manager-store.js +85 -0
  51. package/lib/Store/make-in-memory-store.js +244 -0
  52. package/lib/Store/make-ordered-dictionary.js +75 -0
  53. package/lib/Store/object-repository.js +32 -0
  54. package/lib/Types/Auth.js +2 -0
  55. package/lib/Types/Bussines.js +2 -0
  56. package/lib/Types/Call.js +2 -0
  57. package/lib/Types/Chat.js +8 -0
  58. package/lib/Types/Contact.js +2 -0
  59. package/lib/Types/Events.js +2 -0
  60. package/lib/Types/GroupMetadata.js +2 -0
  61. package/lib/Types/Label.js +25 -0
  62. package/lib/Types/LabelAssociation.js +7 -0
  63. package/lib/Types/Message.js +11 -0
  64. package/lib/Types/Mex.js +111 -0
  65. package/lib/Types/Product.js +2 -0
  66. package/lib/Types/Signal.js +2 -0
  67. package/lib/Types/Socket.js +3 -0
  68. package/lib/Types/State.js +56 -0
  69. package/lib/Types/USync.js +2 -0
  70. package/lib/Types/index.js +26 -0
  71. package/lib/Utils/MessageBuilder.d.ts +215 -0
  72. package/lib/Utils/MessageBuilder.js +3991 -0
  73. package/lib/Utils/a2ui.d.ts +202 -0
  74. package/lib/Utils/a2ui.js +732 -0
  75. package/lib/Utils/airich-registry.js +3 -0
  76. package/lib/Utils/auth-utils.js +302 -0
  77. package/lib/Utils/baileys-event-stream.js +58 -0
  78. package/lib/Utils/bot-signature.d.ts +22 -0
  79. package/lib/Utils/bot-signature.js +124 -0
  80. package/lib/Utils/browser-utils.js +48 -0
  81. package/lib/Utils/business.js +231 -0
  82. package/lib/Utils/chat-utils.js +872 -0
  83. package/lib/Utils/companion-reg-client-utils.js +35 -0
  84. package/lib/Utils/crypto.js +118 -0
  85. package/lib/Utils/decode-wa-message.js +350 -0
  86. package/lib/Utils/dinonic-spr.d.ts +26 -0
  87. package/lib/Utils/dinonic-spr.js +521 -0
  88. package/lib/Utils/event-buffer.js +622 -0
  89. package/lib/Utils/extras.d.ts +449 -0
  90. package/lib/Utils/extras.js +1377 -0
  91. package/lib/Utils/generics.js +403 -0
  92. package/lib/Utils/history.js +134 -0
  93. package/lib/Utils/html-app.d.ts +39 -0
  94. package/lib/Utils/html-app.js +291 -0
  95. package/lib/Utils/identity-change-handler.js +50 -0
  96. package/lib/Utils/index.js +38 -0
  97. package/lib/Utils/link-preview.js +85 -0
  98. package/lib/Utils/logger.js +3 -0
  99. package/lib/Utils/lt-hash.js +8 -0
  100. package/lib/Utils/make-mutex.js +33 -0
  101. package/lib/Utils/message-composer.js +273 -0
  102. package/lib/Utils/message-retry-manager.js +265 -0
  103. package/lib/Utils/messages-media.js +870 -0
  104. package/lib/Utils/messages.js +1394 -0
  105. package/lib/Utils/metaai.d.ts +438 -0
  106. package/lib/Utils/metaai.js +911 -0
  107. package/lib/Utils/modern-messages.d.ts +150 -0
  108. package/lib/Utils/modern-messages.js +496 -0
  109. package/lib/Utils/native-flow.d.ts +14 -0
  110. package/lib/Utils/native-flow.js +118 -0
  111. package/lib/Utils/newsletter-status.d.ts +163 -0
  112. package/lib/Utils/newsletter-status.js +694 -0
  113. package/lib/Utils/noise-handler.js +201 -0
  114. package/lib/Utils/offline-node-processor.js +40 -0
  115. package/lib/Utils/payment-messages.d.ts +59 -0
  116. package/lib/Utils/payment-messages.js +156 -0
  117. package/lib/Utils/pre-key-manager.js +106 -0
  118. package/lib/Utils/process-message.js +630 -0
  119. package/lib/Utils/reporting-utils.js +258 -0
  120. package/lib/Utils/scheduled-message.d.ts +82 -0
  121. package/lib/Utils/scheduled-message.js +113 -0
  122. package/lib/Utils/signal.js +201 -0
  123. package/lib/Utils/stanza-ack.js +38 -0
  124. package/lib/Utils/status-stickers.d.ts +78 -0
  125. package/lib/Utils/status-stickers.js +261 -0
  126. package/lib/Utils/sticker.js +133 -0
  127. package/lib/Utils/sync-action-utils.js +49 -0
  128. package/lib/Utils/tc-token-utils.js +163 -0
  129. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  130. package/lib/Utils/use-sqlite-auth-state.js +162 -0
  131. package/lib/Utils/validate-connection.js +203 -0
  132. package/lib/WABinary/constants.js +1301 -0
  133. package/lib/WABinary/decode.js +262 -0
  134. package/lib/WABinary/encode.js +220 -0
  135. package/lib/WABinary/generic-utils.js +204 -0
  136. package/lib/WABinary/index.js +6 -0
  137. package/lib/WABinary/jid-utils.js +98 -0
  138. package/lib/WABinary/types.js +2 -0
  139. package/lib/WAM/BinaryInfo.js +10 -0
  140. package/lib/WAM/constants.js +22853 -0
  141. package/lib/WAM/encode.js +150 -0
  142. package/lib/WAM/index.js +4 -0
  143. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +53 -0
  144. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +43 -0
  145. package/lib/WAUSync/Protocols/USyncContactProtocol.js +54 -0
  146. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  147. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  148. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +58 -0
  149. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +30 -0
  150. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  151. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +28 -0
  152. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -0
  153. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  154. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +27 -0
  155. package/lib/WAUSync/Protocols/index.js +12 -0
  156. package/lib/WAUSync/USyncQuery.js +151 -0
  157. package/lib/WAUSync/USyncUser.js +56 -0
  158. package/lib/WAUSync/index.js +3 -0
  159. package/lib/index.js +67 -0
  160. package/package.json +147 -5
@@ -0,0 +1,78 @@
1
+ import { proto } from "../../WAProto";
2
+ export const StatusLinkType: {
3
+ readonly RASTERIZED_LINK_PREVIEW: 1;
4
+ readonly RASTERIZED_LINK_TRUNCATED: 2;
5
+ readonly RASTERIZED_LINK_FULL_URL: 3;
6
+ };
7
+ export const STICKER_DEFAULT_AREA: {
8
+ readonly x: 0.25;
9
+ readonly y: 0.4;
10
+ readonly width: 0.5;
11
+ readonly height: 0.2;
12
+ };
13
+ export const stickerArea: ({ x, y, width, height }?: {
14
+ x?: number | undefined;
15
+ y?: number | undefined;
16
+ width?: number | undefined;
17
+ height?: number | undefined;
18
+ }) => {
19
+ x: number;
20
+ y: number;
21
+ }[];
22
+ export const locationSticker: ({ latitude, longitude, name, area, skipConfirmation }?: {
23
+ latitude?: any;
24
+ longitude?: any;
25
+ name?: any;
26
+ area?: any;
27
+ skipConfirmation?: any;
28
+ }) => any;
29
+ export const channelSticker: ({ jid, name, serverMessageId, accessibilityText, area }?: {
30
+ jid?: any;
31
+ name?: any;
32
+ serverMessageId?: number | undefined;
33
+ accessibilityText?: any;
34
+ area?: any;
35
+ }) => any;
36
+ export const linkSticker: ({ url, title, area, linkType }?: {
37
+ url?: any;
38
+ title?: any;
39
+ area?: any;
40
+ linkType?: number | undefined;
41
+ }) => any;
42
+ export const musicSticker: ({ songId, title, author, mediaId, artworkDirectPath, artworkSha256, artworkEncSha256, artworkMediaKey, artistAttribution, countryBlocklist, isExplicit, startTimeMs, derivedStartTimeMs, durationMs, area }?: {
43
+ songId?: any;
44
+ title?: any;
45
+ author?: any;
46
+ mediaId?: any;
47
+ artworkDirectPath?: any;
48
+ artworkSha256?: any;
49
+ artworkEncSha256?: any;
50
+ artworkMediaKey?: any;
51
+ artistAttribution?: any;
52
+ countryBlocklist?: any;
53
+ isExplicit?: any;
54
+ startTimeMs?: number | undefined;
55
+ derivedStartTimeMs?: any;
56
+ durationMs?: any;
57
+ area?: any;
58
+ }) => any;
59
+ export const messageSticker: ({ stanzaId, message, area }?: {
60
+ stanzaId?: any;
61
+ message?: any;
62
+ area?: any;
63
+ }) => any;
64
+ export const normalizeStickers: (stickers: any) => proto.InteractiveAnnotation[];
65
+ export const readStickers: (message: any) => any[];
66
+ export const MusicMessageStyle: {
67
+ readonly UNKNOWN: 0;
68
+ readonly VINYL: 1;
69
+ };
70
+ export const MUSIC_ALLOWED_HOSTS: readonly string[];
71
+ export const isMusicHostAllowed: (value: any) => boolean;
72
+ export const buildMusicMessage: ({ songUri, artworkUri, style, contextInfo, ...music }?: {
73
+ songUri?: any;
74
+ artworkUri?: any;
75
+ style?: number | undefined;
76
+ contextInfo?: any;
77
+ }) => any;
78
+ export const readMusicMessage: (msg: any) => any;
@@ -0,0 +1,261 @@
1
+ import * as WAProto_1 from '../../WAProto/index.js';
2
+ const StatusLinkType = Object.freeze({
3
+ RASTERIZED_LINK_PREVIEW: 1,
4
+ RASTERIZED_LINK_TRUNCATED: 2,
5
+ RASTERIZED_LINK_FULL_URL: 3
6
+ });
7
+
8
+ const STICKER_DEFAULT_AREA = Object.freeze({ x: 0.25, y: 0.4, width: 0.5, height: 0.2 });
9
+
10
+ const trimUndefined = (object) => {
11
+ for (const key of Object.keys(object)) {
12
+ if (object[key] === undefined) {
13
+ delete object[key];
14
+ }
15
+ }
16
+ return object;
17
+ };
18
+
19
+ const fraction = (value, name) => {
20
+ const number = Number(value);
21
+ if (!Number.isFinite(number) || number < 0 || number > 1) {
22
+ throw new TypeError(`${name} must be between 0 and 1, the client reads these as a fraction of the media`);
23
+ }
24
+ return number;
25
+ };
26
+
27
+ const stickerArea = ({ x, y, width, height } = STICKER_DEFAULT_AREA) => {
28
+ const left = fraction(x, 'x');
29
+ const top = fraction(y, 'y');
30
+ const right = fraction(left + Number(width), 'x + width');
31
+ const bottom = fraction(top + Number(height), 'y + height');
32
+ if (right <= left || bottom <= top) {
33
+ throw new TypeError('a sticker area needs a positive width and height');
34
+ }
35
+ return [
36
+ { x: left, y: top },
37
+ { x: right, y: top },
38
+ { x: right, y: bottom },
39
+ { x: left, y: bottom }
40
+ ];
41
+ };
42
+
43
+ const annotation = (area, fields) => ({
44
+ polygonVertices: Array.isArray(area) ? area : stickerArea(area),
45
+ ...fields
46
+ });
47
+
48
+ const locationSticker = ({ latitude, longitude, name, area, skipConfirmation } = {}) => {
49
+ const degreesLatitude = Number(latitude);
50
+ const degreesLongitude = Number(longitude);
51
+ if (!Number.isFinite(degreesLatitude) || !Number.isFinite(degreesLongitude)) {
52
+ throw new TypeError('locationSticker needs a numeric latitude and longitude');
53
+ }
54
+ return annotation(area, {
55
+ location: { degreesLatitude, degreesLongitude, ...(name ? { name } : {}) },
56
+ ...(skipConfirmation === undefined ? {} : { shouldSkipConfirmation: !!skipConfirmation })
57
+ });
58
+ };
59
+
60
+ const channelSticker = ({ jid, name, serverMessageId = 0, accessibilityText, area } = {}) => {
61
+ if (typeof jid !== 'string' || !jid.endsWith('@newsletter')) {
62
+ throw new TypeError('channelSticker needs the channel jid, the one ending in @newsletter');
63
+ }
64
+ return annotation(area, {
65
+ newsletter: {
66
+ newsletterJid: jid,
67
+ serverMessageId: Number(serverMessageId),
68
+ ...(name ? { newsletterName: name } : {}),
69
+ ...(accessibilityText ? { accessibilityText } : {})
70
+ }
71
+ });
72
+ };
73
+
74
+ const linkSticker = ({ url, title, area, linkType = StatusLinkType.RASTERIZED_LINK_PREVIEW } = {}) => {
75
+ if (typeof url !== 'string' || !url) {
76
+ throw new TypeError('linkSticker needs a url');
77
+ }
78
+ return annotation(area, {
79
+ tapAction: { tapUrl: url, ...(title ? { title } : {}) },
80
+ statusLinkType: linkType
81
+ });
82
+ };
83
+
84
+ const musicSticker = ({
85
+ songId,
86
+ title,
87
+ author,
88
+ mediaId,
89
+ artworkDirectPath,
90
+ artworkSha256,
91
+ artworkEncSha256,
92
+ artworkMediaKey,
93
+ artistAttribution,
94
+ countryBlocklist,
95
+ isExplicit,
96
+ startTimeMs = 0,
97
+ derivedStartTimeMs,
98
+ durationMs,
99
+ area
100
+ } = {}) => {
101
+ if (!songId && !mediaId) {
102
+ throw new TypeError('musicSticker needs at least a songId or a musicContentMediaId');
103
+ }
104
+ const bytes = value => (value === undefined ? undefined : Buffer.isBuffer(value) ? value : Buffer.from(value, 'base64'));
105
+ const embeddedMusic = {
106
+ ...(songId ? { songId: String(songId) } : {}),
107
+ ...(mediaId ? { musicContentMediaId: String(mediaId) } : {}),
108
+ ...(title ? { title } : {}),
109
+ ...(author ? { author } : {}),
110
+ ...(artistAttribution ? { artistAttribution } : {}),
111
+ ...(artworkDirectPath ? { artworkDirectPath } : {}),
112
+ ...(isExplicit === undefined ? {} : { isExplicit: !!isExplicit }),
113
+ musicSongStartTimeInMs: Number(startTimeMs),
114
+ ...(derivedStartTimeMs === undefined ? {} : { derivedContentStartTimeInMs: Number(derivedStartTimeMs) }),
115
+ ...(durationMs === undefined ? {} : { overlapDurationInMs: Number(durationMs) })
116
+ };
117
+ for (const [key, value] of [
118
+ ['artworkSha256', artworkSha256],
119
+ ['artworkEncSha256', artworkEncSha256],
120
+ ['artworkMediaKey', artworkMediaKey],
121
+ ['countryBlocklist', countryBlocklist]
122
+ ]) {
123
+ const buffer = bytes(value);
124
+ if (buffer) {
125
+ embeddedMusic[key] = buffer;
126
+ }
127
+ }
128
+ return annotation(area, { embeddedContent: { embeddedMusic } });
129
+ };
130
+
131
+ const messageSticker = ({ stanzaId, message, area } = {}) => {
132
+ if (!message) {
133
+ throw new TypeError('messageSticker needs the message it embeds');
134
+ }
135
+ return annotation(area, {
136
+ embeddedContent: { embeddedMessage: { ...(stanzaId ? { stanzaId } : {}), message } }
137
+ });
138
+ };
139
+
140
+ const ACTIONS = ['location', 'newsletter', 'embeddedAction', 'tapAction'];
141
+
142
+ const normalizeStickers = (stickers) => {
143
+ const list = Array.isArray(stickers) ? stickers : [stickers];
144
+ return list.filter(Boolean).map((sticker, index) => {
145
+ const vertices = sticker.polygonVertices;
146
+ if (!Array.isArray(vertices) || vertices.length !== 4) {
147
+ throw new TypeError(`sticker ${index} needs four polygonVertices, the client reads corner 0 and corner 2`);
148
+ }
149
+ const actions = ACTIONS.filter(name => sticker[name] !== undefined && sticker[name] !== null);
150
+ if (actions.length > 1) {
151
+ throw new TypeError(`sticker ${index} sets ${actions.join(' and ')}, but the client reads only one action per sticker`);
152
+ }
153
+ return WAProto_1.proto.InteractiveAnnotation.fromObject(sticker);
154
+ });
155
+ };
156
+
157
+ const readStickers = (message) => {
158
+ const media = message?.imageMessage ?? message?.videoMessage ?? message;
159
+ const annotations = media?.interactiveAnnotations;
160
+ if (!Array.isArray(annotations) || !annotations.length) {
161
+ return [];
162
+ }
163
+ return annotations.map(item => {
164
+ const [topLeft, , bottomRight] = item.polygonVertices ?? [];
165
+ const music = item.embeddedContent?.embeddedMusic;
166
+ return {
167
+ kind: item.location
168
+ ? 'location'
169
+ : item.newsletter
170
+ ? 'channel'
171
+ : item.tapAction
172
+ ? 'link'
173
+ : music
174
+ ? 'music'
175
+ : item.embeddedContent?.embeddedMessage
176
+ ? 'message'
177
+ : 'unknown',
178
+ area: topLeft && bottomRight
179
+ ? { x: topLeft.x, y: topLeft.y, width: bottomRight.x - topLeft.x, height: bottomRight.y - topLeft.y }
180
+ : undefined,
181
+ location: item.location ?? undefined,
182
+ channel: item.newsletter ?? undefined,
183
+ link: item.tapAction ? { url: item.tapAction.tapUrl, title: item.tapAction.title, linkType: item.statusLinkType } : undefined,
184
+ music: music ? { songId: music.songId, title: music.title, author: music.author } : undefined,
185
+ message: item.embeddedContent?.embeddedMessage ?? undefined,
186
+ annotation: item
187
+ };
188
+ });
189
+ };
190
+
191
+ const MusicMessageStyle = Object.freeze({ UNKNOWN: 0, VINYL: 1 });
192
+
193
+ const MUSIC_ALLOWED_HOSTS = Object.freeze([
194
+ '.whatsapp.net',
195
+ '.whatsapp.com',
196
+ '.fbcdn.net',
197
+ '.facebook.com',
198
+ '.instagram.com',
199
+ '.cdninstagram.com'
200
+ ]);
201
+
202
+ const isMusicHostAllowed = (value) => {
203
+ let host;
204
+ try {
205
+ host = new URL(String(value)).hostname.toLowerCase();
206
+ }
207
+ catch {
208
+ return false;
209
+ }
210
+ return MUSIC_ALLOWED_HOSTS.some(suffix => host.endsWith(suffix) || host === suffix.slice(1));
211
+ };
212
+
213
+ const assertMusicHost = (value, label) => {
214
+ if (value === undefined) {
215
+ return undefined;
216
+ }
217
+ if (!isMusicHostAllowed(value)) {
218
+ throw new TypeError(
219
+ `${label} must be hosted on ${MUSIC_ALLOWED_HOSTS.join(', ')} — the client refuses any other host `
220
+ + 'and draws nothing. Both uris come from Meta music catalog entries, so carry them over from a '
221
+ + 'message you received rather than pointing at your own file'
222
+ );
223
+ }
224
+ return value;
225
+ };
226
+
227
+ const embeddedMusicOf = (options) => musicSticker(options).embeddedContent.embeddedMusic;
228
+
229
+ const buildMusicMessage = ({ songUri, artworkUri, style = MusicMessageStyle.VINYL, contextInfo, ...music } = {}) =>
230
+ trimUndefined({
231
+ embeddedMusic: embeddedMusicOf(music),
232
+ songUri: assertMusicHost(songUri, 'songUri'),
233
+ artworkUri: assertMusicHost(artworkUri, 'artworkUri'),
234
+ style,
235
+ contextInfo
236
+ });
237
+
238
+ const readMusicMessage = (msg) => {
239
+ const message = msg?.message ?? msg;
240
+ const music = message?.musicMessage;
241
+ if (!music) {
242
+ return null;
243
+ }
244
+ const embedded = music.embeddedMusic ?? {};
245
+ return {
246
+ songId: embedded.songId,
247
+ mediaId: embedded.musicContentMediaId,
248
+ title: embedded.title,
249
+ author: embedded.author,
250
+ artistAttribution: embedded.artistAttribution,
251
+ isExplicit: embedded.isExplicit,
252
+ startTimeMs: embedded.musicSongStartTimeInMs,
253
+ durationMs: embedded.overlapDurationInMs,
254
+ songUri: music.songUri,
255
+ artworkUri: music.artworkUri,
256
+ style: music.style,
257
+ embeddedMusic: embedded
258
+ };
259
+ };
260
+
261
+ export { StatusLinkType, STICKER_DEFAULT_AREA, stickerArea, locationSticker, channelSticker, linkSticker, musicSticker, messageSticker, normalizeStickers, readStickers, MusicMessageStyle, MUSIC_ALLOWED_HOSTS, isMusicHostAllowed, buildMusicMessage, readMusicMessage };
@@ -0,0 +1,133 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { spawn } from 'child_process';
3
+ import { randomUUID } from 'crypto';
4
+
5
+ const runFfmpeg = (input, args) => new Promise((resolve, reject) => {
6
+ const proc = spawn('ffmpeg', ['-hide_banner', '-loglevel', 'error', '-i', 'pipe:0', ...args, 'pipe:1'], { stdio: ['pipe', 'pipe', 'pipe'] });
7
+ const outChunks = [];
8
+ const errChunks = [];
9
+ proc.stdout.on('data', chunk => outChunks.push(chunk));
10
+ proc.stderr.on('data', chunk => errChunks.push(chunk));
11
+ proc.on('error', err => reject(new Boom(`ffmpeg failed to start: ${err.message}`, { statusCode: 500 })));
12
+ proc.on('close', code => {
13
+ if (code !== 0) {
14
+ reject(new Boom(`ffmpeg exited with code ${code}: ${Buffer.concat(errChunks).toString('utf8').slice(0, 500)}`, { statusCode: 500 }));
15
+ return;
16
+ }
17
+ resolve(Buffer.concat(outChunks));
18
+ });
19
+ proc.stdin.on('error', () => { });
20
+ proc.stdin.end(input);
21
+ });
22
+ export const isLikelyVideoBuffer = (buffer) => {
23
+ if (!Buffer.isBuffer(buffer) || buffer.length < 4) {
24
+ return false;
25
+ }
26
+ const header = buffer.subarray(0, 16).toString('ascii');
27
+ if (header.startsWith('RIFF') && /AVI|WEBM/.test(header)) {
28
+ return true;
29
+ }
30
+ if (buffer.subarray(0, 4).toString('hex') === '1a45dfa3') {
31
+ return true;
32
+ }
33
+ const ftyp = buffer.toString('ascii', 4, 12);
34
+ if (buffer.toString('ascii', 0, 4) === 'ftyp' || /^(ftyp)/.test(buffer.toString('ascii', 0, 8))) {
35
+ return /mp4|isom|M4V|M4A|qt\s/.test(ftyp);
36
+ }
37
+ return false;
38
+ };
39
+ export const convertToWebp = async (buffer, { animated = false, quality = 60 } = {}) => {
40
+ const scalePad = "scale='min(512,iw)':'min(512,ih)':force_original_aspect_ratio=decrease,format=rgba,pad=512:512:-1:-1:color=#00000000";
41
+ const args = animated
42
+ ? ['-vf', `${scalePad},fps=15`, '-loop', '0', '-preset', 'default', '-an', '-vsync', '0', '-vcodec', 'libwebp', '-q:v', String(quality), '-f', 'webp']
43
+ : ['-vf', `${scalePad}`, '-vframes', '1', '-vcodec', 'libwebp', '-q:v', String(quality), '-f', 'webp'];
44
+ return runFfmpeg(buffer, args);
45
+ };
46
+ export const convertToTrayIcon = async (buffer) => {
47
+ const scalePad = "scale='min(96,iw)':'min(96,ih)':force_original_aspect_ratio=decrease,format=rgba,pad=96:96:-1:-1:color=#00000000";
48
+ const args = ['-vf', scalePad, '-vframes', '1', '-vcodec', 'png', '-f', 'image2'];
49
+ return runFfmpeg(buffer, args);
50
+ };
51
+ const readChunks = (buf) => {
52
+ const chunks = [];
53
+ let offset = 12;
54
+ while (offset + 8 <= buf.length) {
55
+ const fourCC = buf.toString('ascii', offset, offset + 4);
56
+ const size = buf.readUInt32LE(offset + 4);
57
+ const dataStart = offset + 8;
58
+ const data = buf.subarray(dataStart, dataStart + size);
59
+ chunks.push({ fourCC, data });
60
+ offset = dataStart + size + (size % 2);
61
+ }
62
+ return chunks;
63
+ };
64
+ const buildChunk = (fourCC, data) => {
65
+ const header = Buffer.alloc(8);
66
+ header.write(fourCC, 0, 4, 'ascii');
67
+ header.writeUInt32LE(data.length, 4);
68
+ const pad = data.length % 2 === 1 ? Buffer.from([0]) : Buffer.alloc(0);
69
+ return Buffer.concat([header, data, pad]);
70
+ };
71
+ const buildExifChunkData = (json) => {
72
+ const header = Buffer.from([0x49, 0x49, 0x2a, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x41, 0x57, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00]);
73
+ const payload = Buffer.from(JSON.stringify(json), 'utf8');
74
+ header.writeUInt32LE(payload.length, 14);
75
+ return Buffer.concat([header, payload]);
76
+ };
77
+ export const writeExifToWebp = (webpBuffer, { packId, packName = '', publisher = '', emojis = [], isAvatar = false } = {}) => {
78
+ if (webpBuffer.toString('ascii', 0, 4) !== 'RIFF' || webpBuffer.toString('ascii', 8, 12) !== 'WEBP') {
79
+ throw new Boom('writeExifToWebp: not a valid webp buffer', { statusCode: 400 });
80
+ }
81
+ const chunks = readChunks(webpBuffer);
82
+ const exifData = buildExifChunkData({
83
+ 'sticker-pack-id': packId || randomUUID(),
84
+ 'sticker-pack-name': packName,
85
+ 'sticker-pack-publisher': publisher,
86
+ emojis: emojis.length ? emojis : ['🤖'],
87
+ 'is-avatar-sticker': isAvatar ? 1 : 0
88
+ });
89
+ let vp8x = chunks.find(c => c.fourCC === 'VP8X');
90
+ const otherChunks = chunks.filter(c => c.fourCC !== 'VP8X' && c.fourCC !== 'EXIF');
91
+ if (!vp8x) {
92
+ const img = otherChunks.find(c => c.fourCC === 'VP8 ' || c.fourCC === 'VP8L');
93
+ if (!img) {
94
+ throw new Boom('writeExifToWebp: no VP8/VP8L image data found', { statusCode: 400 });
95
+ }
96
+ let width;
97
+ let height;
98
+ if (img.fourCC === 'VP8 ') {
99
+ width = (img.data.readUInt16LE(6) & 0x3fff);
100
+ height = (img.data.readUInt16LE(8) & 0x3fff);
101
+ }
102
+ else {
103
+ const b = img.data;
104
+ width = 1 + (((b[2] & 0x3f) << 8) | b[1]);
105
+ height = 1 + (((b[4] & 0xf) << 10) | (b[3] << 2) | ((b[2] & 0xc0) >> 6));
106
+ }
107
+ const flags = Buffer.alloc(4);
108
+ flags[0] = 0x08;
109
+ const dims = Buffer.alloc(6);
110
+ dims.writeUIntLE(width - 1, 0, 3);
111
+ dims.writeUIntLE(height - 1, 3, 3);
112
+ vp8x = { fourCC: 'VP8X', data: Buffer.concat([flags, dims]) };
113
+ }
114
+ else {
115
+ const flagsByte = vp8x.data[0] | 0x08;
116
+ vp8x = { fourCC: 'VP8X', data: Buffer.concat([Buffer.from([flagsByte]), vp8x.data.subarray(1)]) };
117
+ }
118
+ const rebuilt = [vp8x, ...otherChunks, { fourCC: 'EXIF', data: exifData }];
119
+ const chunkBuffers = rebuilt.map(c => buildChunk(c.fourCC, c.data));
120
+ const payload = Buffer.concat(chunkBuffers);
121
+ const riffSize = 4 + payload.length;
122
+ const out = Buffer.alloc(8 + 4 + payload.length);
123
+ out.write('RIFF', 0, 4, 'ascii');
124
+ out.writeUInt32LE(riffSize, 4);
125
+ out.write('WEBP', 8, 4, 'ascii');
126
+ payload.copy(out, 12);
127
+ return out;
128
+ };
129
+ export const makeSticker = async (buffer, { pack = '', author = '', emojis = [], isPrivate = false, animated = false, quality = 60 } = {}) => {
130
+ const shouldAnimate = animated || isLikelyVideoBuffer(buffer);
131
+ const webp = await convertToWebp(buffer, { animated: shouldAnimate, quality });
132
+ return writeExifToWebp(webp, { packName: pack, publisher: author, emojis, isAvatar: isPrivate });
133
+ };
@@ -0,0 +1,49 @@
1
+ import { proto } from '../../WAProto/index.js';
2
+ import { isLidUser, isPnUser } from '../WABinary/index.js';
3
+ /**
4
+ * Process contactAction and return events to emit.
5
+ * Pure function - no side effects.
6
+ */
7
+ export const processContactAction = (action, id, logger) => {
8
+ const results = [];
9
+ if (!id) {
10
+ logger?.warn({ hasFullName: !!action.fullName, hasLidJid: !!action.lidJid, hasPnJid: !!action.pnJid }, 'contactAction sync: missing id in index');
11
+ return results;
12
+ }
13
+ const lidJid = action.lidJid;
14
+ const idIsPn = isPnUser(id);
15
+ // PN is in index[1], not in contactAction.pnJid which is usually null
16
+ const phoneNumber = idIsPn ? id : action.pnJid || undefined;
17
+ // Always emit contacts.upsert
18
+ results.push({
19
+ event: 'contacts.upsert',
20
+ data: [
21
+ {
22
+ id,
23
+ name: action.fullName || action.firstName || action.username || undefined,
24
+ username: action.username || undefined,
25
+ lid: lidJid || undefined,
26
+ phoneNumber
27
+ }
28
+ ]
29
+ });
30
+ // Emit lid-mapping.update if we have valid LID-PN pair
31
+ if (lidJid && isLidUser(lidJid) && idIsPn) {
32
+ results.push({
33
+ event: 'lid-mapping.update',
34
+ data: { lid: lidJid, pn: id }
35
+ });
36
+ }
37
+ return results;
38
+ };
39
+ export const emitSyncActionResults = (ev, results) => {
40
+ for (const result of results) {
41
+ if (result.event === 'contacts.upsert') {
42
+ ev.emit('contacts.upsert', result.data);
43
+ }
44
+ else {
45
+ ev.emit('lid-mapping.update', result.data);
46
+ }
47
+ }
48
+ };
49
+ //# sourceMappingURL=sync-action-utils.js.map
@@ -0,0 +1,163 @@
1
+ import { getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidMetaAI, isLidUser, isPnUser, jidNormalizedUser } from '../WABinary/index.js';
2
+ // Same phone-number pattern as WABinary's isJidBot, applied against the user
3
+ // part so the check is invariant to @c.us ↔ @s.whatsapp.net normalization.
4
+ const BOT_PHONE_REGEX = /^1313555\d{4}$|^131655500\d{2}$/;
5
+ /**
6
+ * Mirrors WA Web's `Wid.isRegularUser()` (user ∧ ¬PSA ∧ ¬Bot). Used to gate tctoken
7
+ * storage against malformed notifications — WA Web filters server-side but we
8
+ * defend here for parity with `WAWebSetTcTokenChatAction.handleIncomingTcToken`.
9
+ * Works for both pre- and post-normalized JIDs (`@c.us` vs `@s.whatsapp.net`).
10
+ */
11
+ function isRegularUser(jid) {
12
+ if (!jid)
13
+ return false;
14
+ const user = jid.split('@')[0] ?? '';
15
+ if (user === '0')
16
+ return false; // PSA
17
+ if (BOT_PHONE_REGEX.test(user))
18
+ return false; // Bot by phone pattern
19
+ if (isJidMetaAI(jid))
20
+ return false; // MetaAI (@bot server)
21
+ return !!(isPnUser(jid) || isLidUser(jid) || isHostedPnUser(jid) || isHostedLidUser(jid) || jid.endsWith('@c.us'));
22
+ }
23
+ const TC_TOKEN_BUCKET_DURATION = 604800; // 7 days
24
+ const TC_TOKEN_NUM_BUCKETS = 4; // ~28-day rolling window
25
+ /** Sentinel key under `tctoken` store holding a JSON array of tracked storage JIDs for cross-session pruning. */
26
+ export const TC_TOKEN_INDEX_KEY = '__index';
27
+ /** Read the persisted tctoken JID index and return its entries (never contains the sentinel key itself). */
28
+ export async function readTcTokenIndex(keys) {
29
+ const data = await keys.get('tctoken', [TC_TOKEN_INDEX_KEY]);
30
+ const entry = data[TC_TOKEN_INDEX_KEY];
31
+ if (!entry?.token?.length)
32
+ return [];
33
+ try {
34
+ const parsed = JSON.parse(Buffer.from(entry.token).toString());
35
+ if (!Array.isArray(parsed))
36
+ return [];
37
+ return parsed.filter((j) => typeof j === 'string' && j.length > 0 && j !== TC_TOKEN_INDEX_KEY);
38
+ }
39
+ catch {
40
+ return [];
41
+ }
42
+ }
43
+ /** Build a SignalDataSet fragment that writes the merged index (persisted ∪ added) under the sentinel key. */
44
+ export async function buildMergedTcTokenIndexWrite(keys, addedJids) {
45
+ const persisted = await readTcTokenIndex(keys);
46
+ const merged = new Set(persisted);
47
+ for (const jid of addedJids) {
48
+ if (jid && jid !== TC_TOKEN_INDEX_KEY)
49
+ merged.add(jid);
50
+ }
51
+ return {
52
+ [TC_TOKEN_INDEX_KEY]: { token: Buffer.from(JSON.stringify([...merged])) }
53
+ };
54
+ }
55
+ // WA Web has separate sender/receiver AB props for these but they're identical today
56
+ export function isTcTokenExpired(timestamp) {
57
+ if (timestamp === null || timestamp === undefined)
58
+ return true;
59
+ const ts = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp;
60
+ if (isNaN(ts))
61
+ return true;
62
+ const now = Math.floor(Date.now() / 1000);
63
+ const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION);
64
+ const cutoffBucket = currentBucket - (TC_TOKEN_NUM_BUCKETS - 1);
65
+ const cutoffTimestamp = cutoffBucket * TC_TOKEN_BUCKET_DURATION;
66
+ return ts < cutoffTimestamp;
67
+ }
68
+ export function shouldSendNewTcToken(senderTimestamp) {
69
+ if (senderTimestamp === undefined)
70
+ return true;
71
+ const now = Math.floor(Date.now() / 1000);
72
+ const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION);
73
+ const senderBucket = Math.floor(senderTimestamp / TC_TOKEN_BUCKET_DURATION);
74
+ return currentBucket > senderBucket;
75
+ }
76
+ /** Resolve JID to LID for tctoken storage (WA Web stores under LID) */
77
+ export async function resolveTcTokenJid(jid, getLIDForPN) {
78
+ if (isLidUser(jid))
79
+ return jid;
80
+ const lid = await getLIDForPN(jid);
81
+ return lid ?? jid;
82
+ }
83
+ /** Resolve target JID for issuing privacy token based on AB prop 14303 */
84
+ export async function resolveIssuanceJid(jid, issueToLid, getLIDForPN, getPNForLID) {
85
+ if (issueToLid) {
86
+ if (isLidUser(jid))
87
+ return jid;
88
+ const lid = await getLIDForPN(jid);
89
+ return lid ?? jid;
90
+ }
91
+ if (!isLidUser(jid))
92
+ return jid;
93
+ if (getPNForLID) {
94
+ const pn = await getPNForLID(jid);
95
+ return pn ?? jid;
96
+ }
97
+ return jid;
98
+ }
99
+ export async function buildTcTokenFromJid({ authState, jid, baseContent = [], getLIDForPN }) {
100
+ try {
101
+ const storageJid = await resolveTcTokenJid(jid, getLIDForPN);
102
+ const tcTokenData = await authState.keys.get('tctoken', [storageJid]);
103
+ const entry = tcTokenData?.[storageJid];
104
+ const tcTokenBuffer = entry?.token;
105
+ if (!tcTokenBuffer?.length || isTcTokenExpired(entry?.timestamp)) {
106
+ if (tcTokenBuffer) {
107
+ // Preserve senderTimestamp so shouldSendNewTcToken() keeps its dedupe state
108
+ // after we drop the unusable peer token. Only wipe the record entirely when
109
+ // there's nothing worth keeping.
110
+ const cleared = entry?.senderTimestamp !== undefined
111
+ ? { token: Buffer.alloc(0), senderTimestamp: entry.senderTimestamp }
112
+ : null;
113
+ await authState.keys.set({ tctoken: { [storageJid]: cleared } });
114
+ }
115
+ return baseContent.length > 0 ? baseContent : undefined;
116
+ }
117
+ baseContent.push({
118
+ tag: 'tctoken',
119
+ attrs: {},
120
+ content: tcTokenBuffer
121
+ });
122
+ return baseContent;
123
+ }
124
+ catch (error) {
125
+ return baseContent.length > 0 ? baseContent : undefined;
126
+ }
127
+ }
128
+ export async function storeTcTokensFromIqResult({ result, fallbackJid, keys, getLIDForPN, onNewJidStored }) {
129
+ const tokensNode = getBinaryNodeChild(result, 'tokens');
130
+ if (!tokensNode)
131
+ return;
132
+ const tokenNodes = getBinaryNodeChildren(tokensNode, 'token');
133
+ for (const tokenNode of tokenNodes) {
134
+ if (tokenNode.attrs.type !== 'trusted_contact' || !(tokenNode.content instanceof Uint8Array)) {
135
+ continue;
136
+ }
137
+ // In notifications tokenNode.attrs.jid is your own device JID, not the sender's
138
+ const rawJid = jidNormalizedUser(fallbackJid || tokenNode.attrs.jid);
139
+ if (!isRegularUser(rawJid))
140
+ continue;
141
+ const storageJid = await resolveTcTokenJid(rawJid, getLIDForPN);
142
+ const existingTcData = await keys.get('tctoken', [storageJid]);
143
+ const existingEntry = existingTcData[storageJid];
144
+ const existingTs = existingEntry?.timestamp ? Number(existingEntry.timestamp) : 0;
145
+ const incomingTs = tokenNode.attrs.t ? Number(tokenNode.attrs.t) : 0;
146
+ // timestamp-less tokens would be immediately expired
147
+ if (!incomingTs)
148
+ continue;
149
+ if (existingTs > 0 && existingTs > incomingTs)
150
+ continue;
151
+ await keys.set({
152
+ tctoken: {
153
+ [storageJid]: {
154
+ ...existingEntry,
155
+ token: Buffer.from(tokenNode.content),
156
+ timestamp: tokenNode.attrs.t
157
+ }
158
+ }
159
+ });
160
+ onNewJidStored?.(storageJid);
161
+ }
162
+ }
163
+ //# sourceMappingURL=tc-token-utils.js.map