@fvckerss/baileys 1.0.13 → 1.0.15

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.
@@ -4,6 +4,8 @@ import { randomBytes } from 'crypto';
4
4
  import { proto } from '../../WAProto/index.js';
5
5
  import { BIZ_BOT_SUPPORT_PAYLOAD, DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
6
6
  import { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, decryptMediaRetryData, DEF_MEDIA_HOST, delay, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, generateWAMessageFromContent, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, hasValidAlbumMedia, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, shouldIncludeBizBinaryNode, unixTimestampSeconds } from '../Utils/index.js';
7
+ import { AIRich } from '../Builder/index.js';
8
+ import { sendHtmlApp as sendHtmlAppBuilder } from '../Builder/extras.js';
7
9
  import { AssociationType } from '../Types/index.js';
8
10
  import { getUrlInfo } from '../Utils/link-preview.js';
9
11
  import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex.js';
@@ -1104,6 +1106,60 @@ for (const { user, jid } of devices) {
1104
1106
  return msgId;
1105
1107
  };
1106
1108
 
1109
+ const sendPrivateRelay = async (jid, content, targets = [], options = {}) => {
1110
+ if (!isJidGroup(jid)) {
1111
+ throw new Boom('Private relay hanya bisa digunakan untuk group', {
1112
+ statusCode: 400
1113
+ });
1114
+ }
1115
+
1116
+ if (!Array.isArray(targets) || !targets.length) {
1117
+ throw new Boom('Target kosong', {
1118
+ statusCode: 400
1119
+ });
1120
+ }
1121
+
1122
+ const userJid = authState.creds.me.id;
1123
+
1124
+ const fullMsg = await generateWAMessage(jid, content, {
1125
+ logger,
1126
+ userJid,
1127
+ upload: waUploadToServer,
1128
+ mediaCache: config.mediaCache,
1129
+ options: config.options,
1130
+ ...options,
1131
+ messageId: generateMessageIDV2(userJid)
1132
+ });
1133
+
1134
+ const uniqueTargets = [
1135
+ ...new Set(
1136
+ targets
1137
+ .filter(Boolean)
1138
+ .map(j => jidNormalizedUser(j))
1139
+ )
1140
+ ];
1141
+
1142
+ for (const target of uniqueTargets) {
1143
+ await relayMessage(jid, fullMsg.message, {
1144
+ messageId: fullMsg.key.id,
1145
+
1146
+ participant: {
1147
+ jid: target,
1148
+ count: 0
1149
+ },
1150
+
1151
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1152
+
1153
+ additionalAttributes: options.additionalAttributes,
1154
+ additionalNodes: options.additionalNodes,
1155
+
1156
+ ptcp: false
1157
+ });
1158
+ }
1159
+
1160
+ return fullMsg;
1161
+ };
1162
+
1107
1163
  const getMessageType = (message) => {
1108
1164
  if (!message)
1109
1165
  return 'text';
@@ -1234,11 +1290,11 @@ for (const { user, jid } of devices) {
1234
1290
  issuePrivacyTokens,
1235
1291
  assertSessions,
1236
1292
  relayMessage,
1293
+ sendPrivateRelay,
1237
1294
  sendReceipt,
1238
1295
  sendReceipts,
1239
1296
  readMessages,
1240
1297
  refreshMediaConn,
1241
- // Function (not getter) so the spread in chats.ts preserves the live closure binding.
1242
1298
  getMediaHost: () => mediaHost,
1243
1299
  waUploadToServer,
1244
1300
  fetchPrivacySettings,
@@ -1289,6 +1345,11 @@ for (const { user, jid } of devices) {
1289
1345
  ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
1290
1346
  return message;
1291
1347
  },
1348
+
1349
+ sendHtmlApp: async (jid, html, options = {}) => {
1350
+ const { text, ...rest } = options;
1351
+ return sendHtmlAppBuilder({ ...sock, relayMessage }, jid, html, text !== undefined ? { label: text, ...rest } : rest);
1352
+ },
1292
1353
  // Lia@Changes 30-01-26 --- Add support for modifying additionalNodes and additionalAttributes using "options" in sendMessage()
1293
1354
  sendMessage: async (jid, content, options = {}) => {
1294
1355
  const userJid = authState.creds.me.id;
@@ -0,0 +1,96 @@
1
+
2
+ export const HTML_APP_MESSAGE_CEILING = 1024 * 1024;
3
+
4
+ export const HTML_APP_BYTE_BUDGET = 960 * 1024;
5
+
6
+ export const HTML_APP_BYTE_LIMIT = HTML_APP_BYTE_BUDGET;
7
+
8
+ export const wireBytes = (html) => Buffer.byteLength(
9
+ JSON.stringify(String(html)).replace(/[\u007f-\uffff]/g, (c) => '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0')),
10
+ 'utf-8'
11
+ );
12
+
13
+ const STORAGE_APIS = ['localStorage', 'sessionStorage', 'indexedDB', 'document.cookie', 'caches'];
14
+
15
+ const strip = (html) => html
16
+ .replace(/<!--[\s\S]*?-->/g, '')
17
+ .replace(/data:[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]*;base64,[A-Za-z0-9+/=]+/gi, 'data:');
18
+
19
+ const hasVisibilityGuard = (source) => /document\.(hidden|visibilityState)|visibilitychange|IntersectionObserver|cancelAnimationFrame|clearInterval/.test(source);
20
+
21
+ export const checkHtmlApp = (html, { height, maxBytes = HTML_APP_BYTE_BUDGET } = {}) => {
22
+ if (typeof html !== 'string') {
23
+ throw new TypeError('checkHtmlApp requires an HTML string');
24
+ }
25
+
26
+ const bytes = Buffer.byteLength(html, 'utf-8');
27
+ const wire = wireBytes(html);
28
+ const source = strip(html);
29
+ const problems = [];
30
+ const warnings = [];
31
+
32
+ if (wire > maxBytes) {
33
+ problems.push(`${Math.round(wire / 1024)}KB on the wire, over the ${Math.round(maxBytes / 1024)}KB budget — a message past ${Math.round(HTML_APP_MESSAGE_CEILING / 1024)}KB is dropped by the receiving client, which logs it and renders nothing, so this one would arrive as silence`);
34
+ }
35
+
36
+ if (wire > bytes * 1.15) {
37
+ warnings.push(`escaping inflates this page from ${Math.round(bytes / 1024)}KB to ${Math.round(wire / 1024)}KB — every non-ASCII character is rewritten as \\uXXXX, so emoji and accents cost up to three times their size`);
38
+ }
39
+
40
+ const remote = [...source.matchAll(/\b(?:src|href)\s*=\s*["']?(https?:)?\/\//gi)];
41
+ if (remote.length) {
42
+ problems.push(`${remote.length} remote subresource${remote.length === 1 ? '' : 's'} — the page runs in an opaque origin with no network, so every one of them fails silently; embed as data: URIs instead`);
43
+ }
44
+
45
+ if (/\bfetch\s*\(|XMLHttpRequest|navigator\.sendBeacon|new\s+EventSource/.test(source)) {
46
+ problems.push('a call over the HTTP stack — fetch, XHR, sendBeacon and EventSource were measured dead in this WebView, and no securitypolicyviolation fires to tell the page why');
47
+ }
48
+
49
+ const socket = /new\s+WebSocket/.test(source);
50
+ const peer = /RTCPeerConnection/.test(source);
51
+ if (socket && !/wss:\/\//.test(source)) {
52
+ problems.push('a WebSocket on something other than wss:// — the page is not a secure context, and a cleartext ws:// endpoint sends the room and every move in the open');
53
+ }
54
+ if ((socket || peer) && !hasVisibilityGuard(source)) {
55
+ warnings.push('a live connection with nothing closing it — the bubble outlives the screen, so close or pause the socket on visibilitychange');
56
+ }
57
+
58
+ const storage = STORAGE_APIS.filter(api => source.includes(api));
59
+ if (storage.length) {
60
+ problems.push(`${storage.join(', ')} — every storage API throws SecurityError in an opaque origin, so the catch branch always runs`);
61
+ }
62
+
63
+ if (/crypto\.subtle/.test(source)) {
64
+ problems.push('crypto.subtle needs a secure context and this page is not one');
65
+ }
66
+
67
+ const rafLoop = /requestAnimationFrame/.test(source);
68
+ const interval = /setInterval\s*\(/.test(source);
69
+ if ((rafLoop || interval) && !hasVisibilityGuard(source)) {
70
+ problems.push('an animation or timer loop with nothing to stop it — the bubble stays alive while the chat scrolls, so it keeps burning CPU and battery off-screen; gate it on document.hidden or an IntersectionObserver');
71
+ }
72
+
73
+ const reportsHeight = /AndroidBridge\s*\.\s*updateSize/.test(source);
74
+ if (height === undefined && !reportsHeight) {
75
+ const pinned = /(?:html|body)[^{}]*\{[^{}]*height\s*:\s*\d/i.test(source);
76
+ if (!pinned) {
77
+ warnings.push('no height settled — pass height or autoHeight to sendHtmlApp, or call AndroidBridge.updateSize yourself, or the host and the page measure each other and the card shudders');
78
+ }
79
+ }
80
+
81
+ if (/aspect-ratio\s*:/i.test(source)) {
82
+ warnings.push('aspect-ratio makes the height depend on the width, which is the layout chase the host cannot settle');
83
+ }
84
+
85
+ if (/<canvas[^>]*style\s*=\s*["'][^"']*height\s*:\s*auto/i.test(source)) {
86
+ warnings.push('a canvas at height:auto resizes with the bubble; give it pixel dimensions');
87
+ }
88
+
89
+ const dataUris = [...html.matchAll(/data:[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]*;base64,([A-Za-z0-9+/=]+)/gi)];
90
+ const embedded = dataUris.reduce((total, match) => total + match[1].length, 0);
91
+ if (embedded > bytes * 0.6 && dataUris.length) {
92
+ warnings.push(`${Math.round(embedded / 1024)}KB of the page is embedded media — shrink it before the byte budget forces you to`);
93
+ }
94
+
95
+ return { ok: problems.length === 0, bytes, wireBytes: wire, embeddedBytes: embedded, problems, warnings };
96
+ };
@@ -523,63 +523,162 @@ const isNodeRuntime = () => {
523
523
  typeof process.versions.bun === 'undefined' &&
524
524
  typeof globalThis.Deno === 'undefined');
525
525
  };
526
- export const uploadWithNodeHttp = async ({ url, filePath, headers, timeoutMs, agent }, redirectCount = 0) => {
526
+ export const uploadWithNodeHttp = async (
527
+ { url, filePath, headers, timeoutMs, agent },
528
+ redirectCount = 0
529
+ ) => {
527
530
  if (redirectCount > 5) {
528
531
  throw new Error('Too many redirects');
529
532
  }
533
+
530
534
  const parsedUrl = new URL(url);
531
- const httpModule = parsedUrl.protocol === 'https:' ? await import('https') : await import('http');
532
- // Get file size for Content-Length header (required for Node.js streaming)
533
- const fileStats = await fs.stat(filePath);
534
- const fileSize = fileStats.size;
535
+
536
+ const httpModule =
537
+ parsedUrl.protocol === 'https:'
538
+ ? await import('https')
539
+ : await import('http');
540
+
535
541
  return new Promise((resolve, reject) => {
536
- const req = httpModule.request({
537
- hostname: parsedUrl.hostname,
538
- port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),
539
- path: parsedUrl.pathname + parsedUrl.search,
540
- method: 'POST',
541
- headers: {
542
- ...headers,
543
- 'Content-Length': fileSize
542
+ const req = httpModule.request(
543
+ {
544
+ hostname: parsedUrl.hostname,
545
+ port:
546
+ parsedUrl.port ||
547
+ (parsedUrl.protocol === 'https:' ? 443 : 80),
548
+ path: parsedUrl.pathname + parsedUrl.search,
549
+ method: 'POST',
550
+
551
+ headers: {
552
+ ...headers
553
+ },
554
+
555
+ agent,
556
+ timeout: timeoutMs
544
557
  },
545
- agent,
546
- timeout: timeoutMs
547
- }, res => {
548
- // Handle redirects (3xx)
549
- if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
550
- res.resume(); // Consume response to free resources
551
- const newUrl = new URL(res.headers.location, url).toString();
552
- resolve(uploadWithNodeHttp({
553
- url: newUrl,
554
- filePath,
555
- headers,
556
- timeoutMs,
557
- agent
558
- }, redirectCount + 1));
559
- return;
560
- }
561
- let body = '';
562
- res.on('data', chunk => (body += chunk));
563
- res.on('end', () => {
564
- try {
565
- resolve(JSON.parse(body));
566
- }
567
- catch {
568
- resolve(undefined);
558
+
559
+ res => {
560
+ // Handle redirect
561
+ if (
562
+ res.statusCode >= 300 &&
563
+ res.statusCode < 400 &&
564
+ res.headers.location
565
+ ) {
566
+ res.resume();
567
+
568
+ const newUrl = new URL(
569
+ res.headers.location,
570
+ url
571
+ ).toString();
572
+
573
+ resolve(
574
+ uploadWithNodeHttp(
575
+ {
576
+ url: newUrl,
577
+ filePath,
578
+ headers,
579
+ timeoutMs,
580
+ agent
581
+ },
582
+ redirectCount + 1
583
+ )
584
+ );
585
+
586
+ return;
569
587
  }
570
- });
571
- });
588
+
589
+ let body = '';
590
+
591
+ res.on('data', chunk => {
592
+ body += chunk.toString();
593
+ });
594
+
595
+ res.on('end', () => {
596
+ if (
597
+ res.statusCode < 200 ||
598
+ res.statusCode >= 300
599
+ ) {
600
+ const error = new Error(
601
+ `HTTP ${res.statusCode}: ${body}`
602
+ );
603
+
604
+ error.statusCode = res.statusCode;
605
+ error.responseBody = body;
606
+
607
+ reject(error);
608
+ return;
609
+ }
610
+
611
+ try {
612
+ resolve(JSON.parse(body));
613
+ } catch {
614
+ resolve(undefined);
615
+ }
616
+ });
617
+ }
618
+ );
619
+
572
620
  req.on('error', reject);
621
+
573
622
  req.on('timeout', () => {
574
623
  req.destroy();
575
- reject(new Error('Upload timeout'));
576
- });
577
- const stream = createReadStream(filePath);
578
- stream.pipe(req);
579
- stream.on('error', err => {
580
- req.destroy();
581
- reject(err);
624
+
625
+ reject(
626
+ new Error('Upload timeout')
627
+ );
582
628
  });
629
+
630
+ /*
631
+ * Baileys encryptedStream
632
+ *
633
+ * filePath sebenarnya adalah:
634
+ * encWriteStream
635
+ */
636
+
637
+ if (
638
+ filePath &&
639
+ typeof filePath.pipe === 'function'
640
+ ) {
641
+ filePath.on('error', err => {
642
+ req.destroy(err);
643
+ });
644
+
645
+ filePath.pipe(req);
646
+
647
+ return;
648
+ }
649
+
650
+ /*
651
+ * Fallback kalau ternyata Buffer
652
+ */
653
+
654
+ if (Buffer.isBuffer(filePath)) {
655
+ req.end(filePath);
656
+ return;
657
+ }
658
+
659
+ /*
660
+ * Fallback kalau benar-benar file path
661
+ */
662
+
663
+ if (typeof filePath === 'string') {
664
+ const stream = createReadStream(filePath);
665
+
666
+ stream.on('error', err => {
667
+ req.destroy(err);
668
+ });
669
+
670
+ stream.pipe(req);
671
+
672
+ return;
673
+ }
674
+
675
+ req.destroy();
676
+
677
+ reject(
678
+ new Error(
679
+ 'Invalid upload input: expected stream, Buffer, or file path'
680
+ )
681
+ );
583
682
  });
584
683
  };
585
684
  const uploadWithFetch = async ({ url, filePath, headers, timeoutMs, agent }) => {
@@ -644,18 +743,6 @@ export const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, opt
644
743
  'Content-Type': 'application/octet-stream',
645
744
  Origin: DEFAULT_ORIGIN
646
745
  };
647
- let reqBuffer;
648
- if (Buffer.isBuffer(streamOrPath)) {
649
- reqBuffer = streamOrPath;
650
- }
651
- else if (typeof streamOrPath === 'string') {
652
- reqBuffer = await fs.readFile(streamOrPath);
653
- }
654
- else {
655
- const chunks = [];
656
- for await (const chunk of streamOrPath) chunks.push(chunk);
657
- reqBuffer = Buffer.concat(chunks);
658
- }
659
746
  let mediaPath = MEDIA_PATH_MAP[mediaType];
660
747
  if (newsletter && mediaPath) {
661
748
  mediaPath = mediaPath.replace('/mms/', '/newsletter/newsletter-');
@@ -666,16 +753,14 @@ export const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, opt
666
753
  const url = `https://${hostname}${mediaPath}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`;
667
754
  let result;
668
755
  try {
669
- const axios = (await import('axios')).default;
670
- const body = await axios.post(url, reqBuffer, {
756
+ const body = await uploadMedia({
757
+ url,
758
+ filePath: streamOrPath,
671
759
  headers,
672
- httpsAgent: fetchAgent,
673
- timeout: timeoutMs,
674
- responseType: 'json',
675
- maxBodyLength: Infinity,
676
- maxContentLength: Infinity
677
- });
678
- result = body.data;
760
+ timeoutMs,
761
+ agent: fetchAgent
762
+ }, logger);
763
+ result = body;
679
764
  if (result?.url || result?.direct_path) {
680
765
  urls = {
681
766
  mediaUrl: result.url,
@@ -901,6 +901,8 @@ export const generateWAMessageContent = async (message, options) => {
901
901
  }
902
902
  }
903
903
  };
904
+ } else if (hasNonNullishProperty(message, "orderMessage")) {
905
+ m.orderMessage = proto.Message.OrderMessage.create(message.orderMessage);
904
906
  } else if (hasNonNullishProperty(message, "interactiveMessage")) {
905
907
  const im = { ...message.interactiveMessage }
906
908
 
@@ -0,0 +1,45 @@
1
+ const cache = new Map()
2
+
3
+ const MESSAGES = {
4
+ sharp: 'sharp is an optional dependency. Install it with: npm i sharp',
5
+ 'fluent-ffmpeg': 'fluent-ffmpeg is an optional dependency. Install it with: npm i fluent-ffmpeg'
6
+ }
7
+
8
+ const isMissingModule = (error, name) => {
9
+ const code = error?.code
10
+ if (code !== 'ERR_MODULE_NOT_FOUND' && code !== 'MODULE_NOT_FOUND') {
11
+ return false
12
+ }
13
+ const message = String(error?.message ?? '')
14
+ return message.includes(`'${name}'`) || message.includes(`"${name}"`)
15
+ }
16
+
17
+ const loadOptional = (name) => {
18
+ if (!cache.has(name)) {
19
+ cache.set(name, import(name).then(
20
+ loaded => loaded?.default ?? loaded,
21
+ error => {
22
+ cache.delete(name)
23
+ if (isMissingModule(error, name)) {
24
+ throw new Error(MESSAGES[name] ?? `${name} is an optional dependency. Install it with: npm i ${name}`)
25
+ }
26
+ throw error
27
+ }
28
+ ))
29
+ }
30
+ return cache.get(name)
31
+ }
32
+
33
+ export const loadSharp = () => loadOptional('sharp')
34
+
35
+ export const loadFfmpeg = () => loadOptional('fluent-ffmpeg')
36
+
37
+ export const hasOptionalMedia = async (name) => {
38
+ try {
39
+ await loadOptional(name)
40
+ return true
41
+ }
42
+ catch {
43
+ return false
44
+ }
45
+ }