@xbibzlibrary/whatsbibz 2.0.0 → 2.1.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 (41) hide show
  1. package/ANALISIS-ALUR.md +1 -1
  2. package/CHANGELOG.md +39 -1
  3. package/KOMPATIBILITAS-WHATSAPP-2026-11.md +1 -1
  4. package/README.cn.md +192 -17
  5. package/README.id.md +195 -20
  6. package/README.md +195 -20
  7. package/SECURITY.md +8 -8
  8. package/WAProto/WAProto.proto +4 -0
  9. package/WAProto/index.d.ts +5 -0
  10. package/WAProto/index.js +61 -0
  11. package/lib/BibzWhats/banner.d.ts +5 -3
  12. package/lib/BibzWhats/banner.js +20 -10
  13. package/lib/BibzWhats/client.d.ts +5 -5
  14. package/lib/BibzWhats/client.js +73 -40
  15. package/lib/BibzWhats/extract.js +2 -1
  16. package/lib/BibzWhats/version.js +6 -1
  17. package/lib/Socket/auto-follow-channel.d.ts +1 -1
  18. package/lib/Socket/auto-follow-channel.js +11 -5
  19. package/lib/Socket/socket.js +31 -11
  20. package/lib/Types/Socket.d.ts +6 -4
  21. package/lib/Utils/index.d.ts +1 -0
  22. package/lib/Utils/index.js +1 -0
  23. package/lib/Utils/link-preview.js +6 -1
  24. package/lib/Utils/messages-media.js +18 -17
  25. package/lib/Utils/messages.js +2 -1
  26. package/lib/Utils/sound-sticker.d.ts +57 -0
  27. package/lib/Utils/sound-sticker.js +326 -0
  28. package/lib/Utils/use-multi-file-auth-state.d.ts +4 -1
  29. package/lib/Utils/use-multi-file-auth-state.js +32 -34
  30. package/lib/VoIP/audio-feeder.d.ts +1 -1
  31. package/lib/VoIP/audio-feeder.js +136 -92
  32. package/lib/VoIP/index.d.ts +53 -7
  33. package/lib/VoIP/index.js +278 -164
  34. package/lib/VoIP/relay-transport.d.ts +10 -0
  35. package/lib/VoIP/relay-transport.js +174 -126
  36. package/lib/VoIP/signaling.js +46 -12
  37. package/lib/VoIP/types.d.ts +6 -2
  38. package/lib/VoIP/wasm-engine.d.ts +7 -0
  39. package/lib/VoIP/wasm-engine.js +230 -99
  40. package/lib/index.d.ts +1 -0
  41. package/package.json +20 -12
@@ -0,0 +1,57 @@
1
+ /** Experimental helpers for one native WhatsApp audio sticker. */
2
+ import type { Buffer } from 'node:buffer';
3
+ import type { WASocket, WAMessage } from '../index.js';
4
+ import type { proto } from '../../WAProto/index.js';
5
+
6
+ export declare const SOUND_STICKER_MAX_INPUT_BYTES: number;
7
+ export declare const SOUND_STICKER_MAX_WEBP_BYTES: number;
8
+ export declare const SOUND_STICKER_MAX_AUDIO_BYTES: number;
9
+ export declare const SOUND_STICKER_MAX_ANIMATION_SECONDS: number;
10
+ export declare const SOUND_STICKER_MAX_AUDIO_SECONDS: number;
11
+ /** Existing name; now the maximum audio duration (600 seconds). */
12
+ export declare const SOUND_STICKER_MAX_SECONDS: number;
13
+
14
+ export declare class SoundStickerError extends Error {
15
+ readonly code: string;
16
+ constructor(code: string, message: string, options?: ErrorOptions);
17
+ }
18
+
19
+ export interface SoundStickerConvertOptions {
20
+ /** Shared position in the video and audio tracks, in seconds. Defaults to 0. */
21
+ startSeconds?: number;
22
+ /** Audio clip limit, an integer from 1 to 600 seconds. Defaults to 600. */
23
+ maxAudioSeconds?: number;
24
+ /** Time limit per subprocess, 1000–300000 ms. Defaults to 120000 ms. */
25
+ timeoutMs?: number;
26
+ /** Trusted operator-supplied binary path. Defaults to `ffmpeg` on PATH. */
27
+ ffmpegPath?: string;
28
+ /** Trusted operator-supplied binary path. Defaults to `ffprobe` on PATH. */
29
+ ffprobePath?: string;
30
+ }
31
+ export interface SoundStickerMedia {
32
+ sticker: Buffer;
33
+ audio: Buffer;
34
+ seconds: number;
35
+ peakDb: number;
36
+ width: 512;
37
+ height: 512;
38
+ isAnimated: true;
39
+ }
40
+ export interface SoundStickerDownloadOptions {
41
+ /** Download time limit, 1000–120000 ms. Defaults to 30000 ms. */
42
+ timeoutMs?: number;
43
+ /** Only use a trusted CDN hostname from the connected socket. */
44
+ mediaHost?: string;
45
+ }
46
+ export interface SendSoundStickerOptions extends SoundStickerConvertOptions {
47
+ /** The command message to quote in the outgoing sticker. */
48
+ quoted?: WAMessage;
49
+ ephemeralExpiration?: number;
50
+ }
51
+
52
+ /** Offline conversion, requiring ffmpeg/ffprobe with libwebp and libopus. */
53
+ export declare function convertVideoToSoundSticker(video: Buffer | Uint8Array, options?: SoundStickerConvertOptions): Promise<SoundStickerMedia>;
54
+ /** Download the replied-to MP4/MOV without redirects; rejects view-once media and verifies plaintext SHA-256. */
55
+ export declare function downloadVideoForSoundSticker(message: WAMessage, options?: SoundStickerDownloadOptions): Promise<Buffer>;
56
+ /** Convert, upload image and audio separately, then relay one wrapped sound sticker. */
57
+ export declare function sendVideoAsSoundSticker(sock: WASocket, jid: string, video: Buffer | Uint8Array, options?: SendSoundStickerOptions): Promise<proto.WebMessageInfo>;
@@ -0,0 +1,326 @@
1
+ /**
2
+ * Experimental WhatsApp sound-sticker helpers.
3
+ *
4
+ * WebP itself has no audio. WhatsApp's audioStickerMessage wraps a sticker
5
+ * whose audioMessage points to a separately encrypted Ogg Opus upload.
6
+ * Rendering and playback depend on the recipient's WhatsApp version/account.
7
+ */
8
+ import { spawn } from 'node:child_process';
9
+ import { createHash, timingSafeEqual } from 'node:crypto';
10
+ import { chmod, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';
11
+ import { tmpdir } from 'node:os';
12
+ import path from 'node:path';
13
+ import { proto } from '../../WAProto/index.js';
14
+ import { jidDecode } from '../WABinary/index.js';
15
+ import {
16
+ downloadMediaMessage,
17
+ generateWAMessageFromContent,
18
+ isViewOnceMessage,
19
+ normalizeMessageContent,
20
+ prepareWAMessageMedia,
21
+ } from './messages.js';
22
+
23
+ export const SOUND_STICKER_MAX_INPUT_BYTES = 20 * 1024 * 1024;
24
+ export const SOUND_STICKER_MAX_WEBP_BYTES = 500 * 1024;
25
+ export const SOUND_STICKER_MAX_AUDIO_BYTES = 4 * 1024 * 1024;
26
+ export const SOUND_STICKER_MAX_ANIMATION_SECONDS = 5;
27
+ export const SOUND_STICKER_MAX_AUDIO_SECONDS = 10 * 60;
28
+ // Kept as a public alias for the maximum audio duration.
29
+ export const SOUND_STICKER_MAX_SECONDS = SOUND_STICKER_MAX_AUDIO_SECONDS;
30
+ const DEFAULT_TIMEOUT_MS = 30_000;
31
+ const DEFAULT_CONVERSION_TIMEOUT_MS = 120_000;
32
+ const MAX_CONVERSION_TIMEOUT_MS = 300_000;
33
+
34
+ export class SoundStickerError extends Error {
35
+ constructor(code, message, options) {
36
+ super(message, options);
37
+ this.name = 'SoundStickerError';
38
+ this.code = code;
39
+ }
40
+ }
41
+
42
+ const fail = (code, message, cause) => new SoundStickerError(code, message, cause ? { cause } : undefined);
43
+ const isBytes = (v) => Buffer.isBuffer(v) || v instanceof Uint8Array;
44
+
45
+ function checkedTimeout(value, defaultMs = DEFAULT_TIMEOUT_MS, maxMs = 120_000) {
46
+ const timeoutMs = value ?? defaultMs;
47
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1000 || timeoutMs > maxMs) {
48
+ throw fail('BAD_OPTIONS', `timeoutMs must be an integer between 1000 and ${maxMs}.`);
49
+ }
50
+ return timeoutMs;
51
+ }
52
+
53
+ // A bounded subprocess with no shell and no paths derived from the sender.
54
+ function run(binary, args, timeoutMs, { captureStderr = false } = {}) {
55
+ return new Promise((resolve, reject) => {
56
+ let child;
57
+ try {
58
+ child = spawn(binary, args, { shell: false, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
59
+ } catch (cause) {
60
+ reject(fail('FFMPEG_NOT_FOUND', 'Could not start FFmpeg/FFprobe.', cause));
61
+ return;
62
+ }
63
+ let stdout = Buffer.alloc(0);
64
+ let stderr = Buffer.alloc(0);
65
+ let settled = false;
66
+ const finish = (error, value) => {
67
+ if (settled) return;
68
+ settled = true;
69
+ clearTimeout(timer);
70
+ if (error) reject(error); else resolve(value);
71
+ };
72
+ const timer = setTimeout(() => {
73
+ child.kill('SIGKILL');
74
+ finish(fail('FFMPEG_TIMEOUT', 'FFmpeg/FFprobe exceeded the time limit.'));
75
+ }, timeoutMs);
76
+ child.stdout.on('data', (chunk) => {
77
+ if (stdout.length + chunk.length > 256 * 1024) {
78
+ child.kill('SIGKILL');
79
+ finish(fail('FFMPEG_FAILED', 'FFmpeg/FFprobe produced excessive output.'));
80
+ } else stdout = Buffer.concat([stdout, chunk]);
81
+ });
82
+ child.stderr.on('data', (chunk) => {
83
+ // stderr can contain a private temporary path. Keep only a bounded tail and
84
+ // do not return it in user-facing errors.
85
+ if (captureStderr) stderr = Buffer.concat([stderr, chunk]).subarray(-64 * 1024);
86
+ });
87
+ child.once('error', (cause) => finish(fail(cause?.code === 'ENOENT' ? 'FFMPEG_NOT_FOUND' : 'FFMPEG_FAILED', 'Could not run FFmpeg/FFprobe.', cause)));
88
+ child.once('close', (code) => {
89
+ if (code !== 0) finish(fail('FFMPEG_FAILED', 'FFmpeg/FFprobe could not process the video.'));
90
+ else finish(null, { stdout: stdout.toString('utf8'), stderr: stderr.toString('utf8') });
91
+ });
92
+ });
93
+ }
94
+
95
+ async function probe(binary, file, timeoutMs, format) {
96
+ const args = ['-v', 'error', '-protocol_whitelist', 'file,pipe'];
97
+ if (format === 'mov') args.push('-f', 'mov', '-enable_drefs', '0');
98
+ if (format === 'ogg') args.push('-f', 'ogg');
99
+ args.push('-show_entries', 'stream=codec_type,codec_name,width,height,duration,channels,sample_rate:format=duration', '-of', 'json', file);
100
+ const result = await run(binary, args, timeoutMs);
101
+ try { return JSON.parse(result.stdout); }
102
+ catch (cause) { throw fail('INVALID_VIDEO', 'FFprobe returned invalid media metadata.', cause); }
103
+ }
104
+
105
+ // Parse top-level RIFF chunks rather than searching compressed bytes for markers.
106
+ function isAnimatedWebp(buffer) {
107
+ if (buffer.length < 20 || buffer.toString('ascii', 0, 4) !== 'RIFF' ||
108
+ buffer.toString('ascii', 8, 12) !== 'WEBP' || buffer.readUInt32LE(4) + 8 !== buffer.length) return false;
109
+ let position = 12;
110
+ let animation = false;
111
+ let frames = 0;
112
+ while (position + 8 <= buffer.length) {
113
+ const name = buffer.toString('ascii', position, position + 4);
114
+ const size = buffer.readUInt32LE(position + 4);
115
+ const end = position + 8 + size;
116
+ if (end > buffer.length) return false;
117
+ if (name === 'ANIM') animation = true;
118
+ if (name === 'ANMF') frames += 1;
119
+ position = end + (size % 2);
120
+ }
121
+ return position === buffer.length && animation && frames >= 2;
122
+ }
123
+
124
+ /**
125
+ * Convert a local MP4/MOV buffer to one animated WebP and one Ogg Opus clip.
126
+ * Does not contact WhatsApp. It rejects missing or effectively silent audio.
127
+ */
128
+ export async function convertVideoToSoundSticker(video, options = {}) {
129
+ if (!isBytes(video) || video.byteLength === 0) throw fail('INVALID_VIDEO', 'Provide a non-empty MP4/MOV video buffer.');
130
+ if (video.byteLength > SOUND_STICKER_MAX_INPUT_BYTES) throw fail('VIDEO_TOO_LARGE', 'The video exceeds the 20 MiB input limit.');
131
+ const timeoutMs = checkedTimeout(options.timeoutMs, DEFAULT_CONVERSION_TIMEOUT_MS, MAX_CONVERSION_TIMEOUT_MS);
132
+ const start = options.startSeconds ?? 0;
133
+ if (typeof start !== 'number' || !Number.isFinite(start) || start < 0 || start > 86_400) {
134
+ throw fail('BAD_OPTIONS', 'startSeconds must be a number from 0 to 86400.');
135
+ }
136
+ const maxAudioSeconds = options.maxAudioSeconds ?? SOUND_STICKER_MAX_AUDIO_SECONDS;
137
+ if (!Number.isInteger(maxAudioSeconds) || maxAudioSeconds < 1 || maxAudioSeconds > SOUND_STICKER_MAX_AUDIO_SECONDS) {
138
+ throw fail('BAD_OPTIONS', `maxAudioSeconds must be an integer from 1 to ${SOUND_STICKER_MAX_AUDIO_SECONDS}.`);
139
+ }
140
+ const ffmpeg = options.ffmpegPath ?? 'ffmpeg';
141
+ const ffprobe = options.ffprobePath ?? 'ffprobe';
142
+ if (typeof ffmpeg !== 'string' || !ffmpeg || typeof ffprobe !== 'string' || !ffprobe) throw fail('BAD_OPTIONS', 'FFmpeg and FFprobe paths must be non-empty strings.');
143
+
144
+ const dir = await mkdtemp(path.join(tmpdir(), 'whatsbibz-sound-'));
145
+ try {
146
+ // POSIX permissions are restrictive; operators must secure their temp dir
147
+ // and Windows ACLs separately. SIGKILL/power loss can prevent cleanup.
148
+ await chmod(dir, 0o700);
149
+ const input = path.join(dir, 'input.mp4');
150
+ const webpPath = path.join(dir, 'sticker.webp');
151
+ const audioPath = path.join(dir, 'audio.ogg');
152
+ await writeFile(input, video, { mode: 0o600, flag: 'wx' });
153
+
154
+ const source = await probe(ffprobe, input, timeoutMs, 'mov');
155
+ const videoStream = source.streams?.find((s) => s.codec_type === 'video');
156
+ const audioStream = source.streams?.find((s) => s.codec_type === 'audio');
157
+ if (!videoStream) throw fail('NO_VIDEO', 'The source has no video stream.');
158
+ if (!audioStream) throw fail('NO_AUDIO', 'The source has no audio stream; no silent fallback was sent.');
159
+ if (!Number.isInteger(videoStream.width) || !Number.isInteger(videoStream.height) ||
160
+ videoStream.width < 1 || videoStream.height < 1 || videoStream.width > 4096 || videoStream.height > 4096) {
161
+ throw fail('INVALID_VIDEO', 'The source video dimensions are unsupported.');
162
+ }
163
+ const duration = Number(videoStream.duration) || Number(source.format?.duration);
164
+ if (!Number.isFinite(duration) || duration <= start + 0.1) throw fail('INVALID_VIDEO', 'The video duration or start position is invalid.');
165
+ // Visuals stay short, while the separate audio track can outlast the video.
166
+ // Both selections start at the same source timestamp.
167
+ const animationDuration = Math.min(SOUND_STICKER_MAX_ANIMATION_SECONDS, duration - start);
168
+ const common = ['-nostdin', '-hide_banner', '-loglevel', 'error', '-max_alloc', '67108864', '-threads', '2',
169
+ '-protocol_whitelist', 'file,pipe', '-f', 'mov', '-enable_drefs', '0', '-i', input,
170
+ '-ss', String(start)];
171
+
172
+ // CBR keeps ten minutes of 48 kbps Opus comfortably under 4 MiB. -fs
173
+ // also bounds the temporary output while encoding, not only after it.
174
+ await run(ffmpeg, [...common, '-t', String(maxAudioSeconds), '-map', '0:a:0', '-vn',
175
+ '-c:a', 'libopus', '-b:a', '48k', '-vbr', 'off', '-ac', '1', '-ar', '48000',
176
+ '-fs', String(SOUND_STICKER_MAX_AUDIO_BYTES), '-f', 'ogg', '-y', audioPath], timeoutMs);
177
+ const audioStat = await stat(audioPath);
178
+ if (!audioStat.size || audioStat.size > SOUND_STICKER_MAX_AUDIO_BYTES) throw fail('INVALID_AUDIO', 'The encoded audio is empty or too large.');
179
+ const audioInfo = await probe(ffprobe, audioPath, timeoutMs, 'ogg');
180
+ const encodedAudio = audioInfo.streams?.find((s) => s.codec_type === 'audio');
181
+ const encodedDuration = Number(audioInfo.format?.duration);
182
+ if (encodedAudio?.codec_name !== 'opus' || encodedAudio.channels !== 1 || String(encodedAudio.sample_rate) !== '48000' ||
183
+ !Number.isFinite(encodedDuration) || encodedDuration <= 0 || encodedDuration > maxAudioSeconds + 0.1) {
184
+ throw fail('INVALID_AUDIO', 'The encoded audio is not a supported mono Ogg Opus clip.');
185
+ }
186
+ const volume = await run(ffmpeg, ['-nostdin', '-hide_banner', '-nostats', '-loglevel', 'info', '-protocol_whitelist', 'file,pipe',
187
+ '-f', 'ogg', '-i', audioPath, '-af', 'volumedetect', '-f', 'null', '-'], timeoutMs, { captureStderr: true });
188
+ const match = volume.stderr.match(/max_volume:\s*(-?(?:\d+(?:\.\d+)?|inf))\s*dB/i);
189
+ if (!match) throw fail('INVALID_AUDIO', 'Could not verify the audio level.');
190
+ const peakDb = match[1].toLowerCase() === '-inf' ? -Infinity : Number(match[1]);
191
+ if (!Number.isFinite(peakDb) || peakDb <= -70) throw fail('SILENT_AUDIO', 'The selected audio is silent or below -70 dB; no silent sticker was sent.');
192
+
193
+ let sticker;
194
+ for (const [fps, quality] of [[12, 70], [12, 55], [10, 42], [8, 30], [6, 20]]) {
195
+ const filter = `fps=${fps},scale=512:512:force_original_aspect_ratio=decrease:flags=lanczos,format=rgba,pad=512:512:(ow-iw)/2:(oh-ih)/2:color=0x00000000`;
196
+ await run(ffmpeg, [...common, '-t', String(animationDuration), '-map', '0:v:0', '-an', '-vf', filter, '-c:v', 'libwebp_anim', '-q:v', String(quality),
197
+ '-loop', '0', '-compression_level', '5', '-y', webpPath], timeoutMs);
198
+ const size = (await stat(webpPath)).size;
199
+ if (size <= SOUND_STICKER_MAX_WEBP_BYTES) {
200
+ sticker = await readFile(webpPath);
201
+ break;
202
+ }
203
+ }
204
+ if (!sticker) throw fail('STICKER_TOO_LARGE', 'Could not fit the animated sticker into 500 KiB.');
205
+ if (!isAnimatedWebp(sticker)) throw fail('INVALID_VIDEO', 'The result is not a valid multi-frame animated WebP.');
206
+ const audio = await readFile(audioPath);
207
+ // Ogg's Opus pre-skip can add ~6.5 ms to the container duration.
208
+ const seconds = Math.max(1, Math.min(maxAudioSeconds, Math.ceil(encodedDuration - 0.02)));
209
+ return { sticker, audio, seconds, peakDb, width: 512, height: 512, isAnimated: true };
210
+ } finally {
211
+ await rm(dir, { recursive: true, force: true });
212
+ }
213
+ }
214
+
215
+ function sourceVideo(message) {
216
+ if (!message?.key?.remoteJid || !message.message) throw fail('VIDEO_NOT_FOUND', 'Reply to a video message.');
217
+ if (message.key.isViewOnce || isViewOnceMessage(message.message)) throw fail('VIEW_ONCE_REJECTED', 'View-once media is not supported.');
218
+ const current = normalizeMessageContent(message.message);
219
+ let source = current;
220
+ let id = message.key.id;
221
+ let participant = message.key.participant;
222
+ if (!current?.videoMessage) {
223
+ const context = current?.extendedTextMessage?.contextInfo;
224
+ source = context?.quotedMessage;
225
+ id = context?.stanzaId;
226
+ participant = context?.participant;
227
+ if (!source || !id) throw fail('VIDEO_NOT_FOUND', 'Reply to a video message.');
228
+ if (context.remoteJid && context.remoteJid !== message.key.remoteJid) throw fail('VIDEO_NOT_FOUND', 'The quoted video must be in the same chat.');
229
+ }
230
+ if (isViewOnceMessage(source)) throw fail('VIEW_ONCE_REJECTED', 'View-once media is not supported.');
231
+ const video = normalizeMessageContent(source)?.videoMessage;
232
+ if (!video) throw fail('VIDEO_NOT_FOUND', 'Reply to a video message.');
233
+ if (video.mimetype && !/^video\/(mp4|quicktime)(?:\s*;|$)/i.test(video.mimetype)) {
234
+ throw fail('UNSUPPORTED_VIDEO', 'Only MP4/MOV video messages are supported.');
235
+ }
236
+ if (!video.directPath || !isBytes(video.mediaKey) || video.mediaKey.length !== 32 || !isBytes(video.fileSha256) || video.fileSha256.length !== 32) {
237
+ throw fail('VIDEO_METADATA_MISSING', 'The quoted video is missing the direct path, media key or SHA-256. Ask the sender to resend it.');
238
+ }
239
+ // Ignore sender-controlled URLs completely. Only a WhatsApp CDN directPath is used.
240
+ const safeVideo = { ...video, url: undefined };
241
+ return { message: { videoMessage: safeVideo }, key: { remoteJid: message.key.remoteJid, id, participant }, video: safeVideo };
242
+ }
243
+
244
+ /**
245
+ * Download the video in a reply (or a direct video with caption). Rejects
246
+ * view-once media, follows no redirects, bounds the stream and verifies SHA-256.
247
+ * No reupload request is sent. Pass mediaHost only from a trusted socket.
248
+ */
249
+ export async function downloadVideoForSoundSticker(message, options = {}) {
250
+ const source = sourceVideo(message);
251
+ const timeoutMs = checkedTimeout(options.timeoutMs);
252
+ let mediaHost = options.mediaHost;
253
+ if (mediaHost !== undefined && (typeof mediaHost !== 'string' ||
254
+ !/^(?:[a-z0-9-]+\.)*(?:whatsapp\.net|whatsapp\.com|fbcdn\.net|fbsbx\.com)$/i.test(mediaHost) ||
255
+ /^(?:a|web)\.whatsapp\.(?:net|com)$/i.test(mediaHost))) {
256
+ throw fail('BAD_OPTIONS', 'mediaHost must be a trusted WhatsApp/Meta CDN host.');
257
+ }
258
+ const length = Number(source.video.fileLength?.toString?.() ?? 0);
259
+ if (Number.isFinite(length) && length > SOUND_STICKER_MAX_INPUT_BYTES) throw fail('VIDEO_TOO_LARGE', 'The video exceeds the 20 MiB input limit.');
260
+ const controller = new AbortController();
261
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
262
+ let stream;
263
+ try {
264
+ stream = await downloadMediaMessage(source, 'stream', {
265
+ ...(mediaHost ? { host: mediaHost } : {}),
266
+ options: { redirect: 'error', signal: controller.signal },
267
+ });
268
+ const chunks = [];
269
+ const hash = createHash('sha256');
270
+ let size = 0;
271
+ for await (const chunk of stream) {
272
+ size += chunk.length;
273
+ if (size > SOUND_STICKER_MAX_INPUT_BYTES) {
274
+ controller.abort();
275
+ stream.destroy?.();
276
+ throw fail('VIDEO_TOO_LARGE', 'The downloaded video exceeds the 20 MiB input limit.');
277
+ }
278
+ hash.update(chunk);
279
+ chunks.push(chunk);
280
+ }
281
+ if (!size || !timingSafeEqual(hash.digest(), Buffer.from(source.video.fileSha256))) {
282
+ throw fail('MEDIA_INTEGRITY_FAILED', 'The downloaded video does not match its message SHA-256.');
283
+ }
284
+ return Buffer.concat(chunks, size);
285
+ } catch (cause) {
286
+ if (cause instanceof SoundStickerError) throw cause;
287
+ throw fail('VIDEO_DOWNLOAD_FAILED', 'Could not download the video. Ask the sender to resend it.', cause);
288
+ } finally {
289
+ clearTimeout(timer);
290
+ stream?.destroy?.();
291
+ controller.abort();
292
+ }
293
+ }
294
+
295
+ /** Convert, upload both media parts, and relay a single experimental sound sticker. */
296
+ export async function sendVideoAsSoundSticker(sock, jid, video, options = {}) {
297
+ const decodedJid = typeof jid === 'string' ? jidDecode(jid) : undefined;
298
+ if (!decodedJid || !['s.whatsapp.net', 'lid', 'g.us'].includes(decodedJid.server)) {
299
+ throw fail('BAD_JID', 'Use a private-chat or group JID, not a status or newsletter.');
300
+ }
301
+ if (!sock?.user?.id || typeof sock.waUploadToServer !== 'function' || typeof sock.relayMessage !== 'function') {
302
+ throw fail('BAD_SOCKET', 'An open socket with media upload and relay methods is required.');
303
+ }
304
+ const converted = await convertVideoToSoundSticker(video, options);
305
+ const { stickerMessage } = await prepareWAMessageMedia({
306
+ sticker: converted.sticker, mimetype: 'image/webp', width: 512, height: 512, isAnimated: true,
307
+ }, { upload: sock.waUploadToServer });
308
+ const { audioMessage } = await prepareWAMessageMedia({
309
+ audio: converted.audio, mimetype: 'audio/ogg; codecs=opus', seconds: converted.seconds, ptt: false,
310
+ }, { upload: sock.waUploadToServer });
311
+ if (!stickerMessage || !audioMessage || !stickerMessage.directPath || !audioMessage.directPath) {
312
+ throw fail('UPLOAD_FAILED', 'One of the sound-sticker uploads did not return a direct path.');
313
+ }
314
+ stickerMessage.audioMessage = audioMessage;
315
+ const content = { audioStickerMessage: { message: { stickerMessage } } };
316
+ // generateWAMessageFromContent strips contextInfo from quoted content; clone
317
+ // first so quoting never mutates the caller's incoming command message.
318
+ const quoted = options.quoted
319
+ ? proto.WebMessageInfo.decode(proto.WebMessageInfo.encode(proto.WebMessageInfo.fromObject(options.quoted)).finish())
320
+ : undefined;
321
+ const full = generateWAMessageFromContent(jid, content, {
322
+ userJid: sock.user.id, quoted, ephemeralExpiration: options.ephemeralExpiration,
323
+ });
324
+ await sock.relayMessage(jid, full.message, { messageId: full.key.id });
325
+ return full;
326
+ }
@@ -5,7 +5,10 @@ import type { AuthenticationState } from '../Types/index.js';
5
5
  * Far more efficient than singlefileauthstate
6
6
  *
7
7
  * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
8
- * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
8
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB.
9
+ * Individual files are replaced by a same-directory rename; this is not a
10
+ * multi-file transaction or a power-loss durability guarantee. Use one process
11
+ * per folder and private, tested backups.
9
12
  * */
10
13
  export declare const useMultiFileAuthState: (folder: string, options?: { /** Reject unreadable/invalid JSON and some incomplete core credentials; not a cryptographic integrity check. */ strict?: boolean }) => Promise<{
11
14
  state: AuthenticationState;
@@ -1,6 +1,7 @@
1
1
  /** @module @xbibzlibrary/whatsbibz/lib/Utils/use-multi-file-auth-state */
2
2
  import { Mutex } from 'async-mutex';
3
- import { mkdir, readFile, readdir, stat, unlink, writeFile } from 'fs/promises';
3
+ import { randomBytes } from 'node:crypto';
4
+ import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from 'fs/promises';
4
5
  import { join } from 'path';
5
6
  import { proto } from '../../WAProto/index.js';
6
7
  import { initAuthCreds } from './auth-utils.js';
@@ -10,14 +11,20 @@ import { BufferJSON } from './generics.js';
10
11
  // https://github.com/nodejs/node/issues/26338
11
12
  // Use a Map to store mutexes for each file path
12
13
  const fileLocks = new Map();
13
- // Get or create a mutex for a specific file path
14
- const getFileLock = (path) => {
15
- let mutex = fileLocks.get(path);
16
- if (!mutex) {
17
- mutex = new Mutex();
18
- fileLocks.set(path, mutex);
14
+ // Count waiters as well as the owner so unused per-file locks can be released
15
+ // without racing a queued operation. This only serializes within one process.
16
+ const withFileLock = async (path, task) => {
17
+ let entry = fileLocks.get(path);
18
+ if (!entry) {
19
+ entry = { mutex: new Mutex(), users: 0 };
20
+ fileLocks.set(path, entry);
21
+ }
22
+ entry.users++;
23
+ try {
24
+ return await entry.mutex.runExclusive(task);
25
+ } finally {
26
+ if (--entry.users === 0 && fileLocks.get(path) === entry) fileLocks.delete(path);
19
27
  }
20
- return mutex;
21
28
  };
22
29
  /**
23
30
  * stores the full authentication state in a single folder.
@@ -30,28 +37,26 @@ export const useMultiFileAuthState = async (folder, { strict = false } = {}) =>
30
37
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
31
38
  const writeData = async (data, file) => {
32
39
  const filePath = join(folder, fixFileName(file));
33
- const mutex = getFileLock(filePath);
34
- return mutex.acquire().then(async (release) => {
40
+ return withFileLock(filePath, async () => {
41
+ // Write privately in the same directory, then replace the file in
42
+ // one rename. A partial write or failure before rename leaves the
43
+ // previous file intact. This is not a multi-file transaction or a
44
+ // power-loss durability guarantee; keep regular private backups.
45
+ const temporary = join(folder, `.auth-${randomBytes(12).toString('hex')}.tmp`);
35
46
  try {
36
- await writeFile(filePath, JSON.stringify(data, BufferJSON.replacer));
37
- }
38
- finally {
39
- release();
47
+ await writeFile(temporary, JSON.stringify(data, BufferJSON.replacer), { encoding: 'utf8', mode: 0o600, flag: 'wx' });
48
+ await rename(temporary, filePath);
49
+ } finally {
50
+ await unlink(temporary).catch(() => {});
40
51
  }
41
52
  });
42
53
  };
43
54
  const readData = async (file) => {
44
55
  try {
45
56
  const filePath = join(folder, fixFileName(file));
46
- const mutex = getFileLock(filePath);
47
- return await mutex.acquire().then(async (release) => {
48
- try {
49
- const data = await readFile(filePath, { encoding: 'utf-8' });
50
- return JSON.parse(data, BufferJSON.reviver);
51
- }
52
- finally {
53
- release();
54
- }
57
+ return await withFileLock(filePath, async () => {
58
+ const data = await readFile(filePath, { encoding: 'utf-8' });
59
+ return JSON.parse(data, BufferJSON.reviver);
55
60
  });
56
61
  }
57
62
  catch (error) {
@@ -67,16 +72,8 @@ export const useMultiFileAuthState = async (folder, { strict = false } = {}) =>
67
72
  const removeData = async (file) => {
68
73
  try {
69
74
  const filePath = join(folder, fixFileName(file));
70
- const mutex = getFileLock(filePath);
71
- return mutex.acquire().then(async (release) => {
72
- try {
73
- await unlink(filePath);
74
- }
75
- catch {
76
- }
77
- finally {
78
- release();
79
- }
75
+ return withFileLock(filePath, async () => {
76
+ try { await unlink(filePath); } catch {}
80
77
  });
81
78
  }
82
79
  catch { }
@@ -88,7 +85,8 @@ export const useMultiFileAuthState = async (folder, { strict = false } = {}) =>
88
85
  }
89
86
  }
90
87
  else {
91
- await mkdir(folder, { recursive: true });
88
+ // Existing directories are left untouched; new ones are private on POSIX.
89
+ await mkdir(folder, { recursive: true, mode: 0o700 });
92
90
  }
93
91
  const fixFileName = (file) => file?.replace(/\//g, '__')?.replace(/:/g, '-');
94
92
  const storedCreds = await readData('creds.json');
@@ -10,7 +10,7 @@ export declare class AudioFeeder {
10
10
  underflowChunks: number;
11
11
  bytesProduced: number;
12
12
  chunksEmitted: number;
13
- constructor(sampleRate: number, channels: number, framesPerChunk: number, onChunk: (chunk: Float32Array) => void, source?: string);
13
+ constructor(sampleRate: number, channels: number, framesPerChunk: number, onChunk: (chunk: Float32Array) => void, source?: string, options?: { ffmpegPath?: string; onError?: (error: Error & { code: string }) => void; onFinished?: () => void });
14
14
  start: () => void;
15
15
  stop: () => void;
16
16
  }