savage-baileys 2.0.0 → 2.0.3

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.
package/README.md CHANGED
@@ -1,6 +1,8 @@
1
1
  <div align="center">
2
+ <img src="https://raw.githubusercontent.com/tysavage163/savage-baileys/main/assets/logo.jpg" alt="Savage Baileys Logo" width="250" />
2
3
  <h1>Savage Baileys</h1>
3
4
  <p>A WebSocket-based JavaScript library for interacting with the WhatsApp Web API</p>
5
+ <p>Created and maintained by <strong>Spencer (Savage Tech)</strong></p>
4
6
 
5
7
  [![npm version](https://img.shields.io/npm/v/savage-baileys.svg)](https://www.npmjs.com/package/savage-baileys)
6
8
  [![npm downloads](https://img.shields.io/npm/dm/savage-baileys.svg)](https://www.npmjs.com/package/savage-baileys)
@@ -9,6 +11,13 @@
9
11
 
10
12
  ---
11
13
 
14
+ ## Author & Credits
15
+
16
+ Created with 💻 and ☕ by **Spencer (Savage Tech)**.
17
+ Check out the repository at [github.com/tysavage163/savage-baileys](https://github.com/tysavage163/savage-baileys).
18
+
19
+ ---
20
+
12
21
  ## Disclaimer
13
22
 
14
23
  This project is not affiliated, associated, authorized, endorsed by, or in any way officially
@@ -24,6 +33,7 @@ Do not spam people with this. We discourage any stalkerware, bulk or automated m
24
33
  - Full WhatsApp Web API support
25
34
  - Multi-device support with QR code and pairing code authentication
26
35
  - LID (Link ID) addressing for personal chats and groups
36
+ - Phone-number lookup on LID chats: message keys carry `remoteJidAlt` (DMs) and `participantAlt` (groups) with the sender's real number when known
27
37
  - Group status / story sending
28
38
  - View-once: send view-once text/media (V1, V2, V2Extension), detect and unwrap incoming view-once, recover blank view-once stubs, and download the media
29
39
  - Session management and restoration
@@ -48,37 +58,3 @@ using the public API this library exposes:
48
58
  ```javascript
49
59
  await sock.groupAcceptInvite(inviteCode)
50
60
  await sock.newsletterFollow(channelJid)
51
-
52
- ---
53
-
54
- ## View-once
55
-
56
- ```javascript
57
- const { downloadViewOnceMessage, extractViewOnceMedia, isViewOnceMessage } = require('savage-baileys')
58
-
59
- // send view-once (V2 is required for view-once text)
60
- await sock.sendMessage(jid, { text: 'hi', viewOnceV2: true })
61
- await sock.sendMessage(jid, { image: { url: './pic.jpg' }, viewOnceV2: true })
62
- // voice-note capable variant
63
- await sock.sendMessage(jid, { audio: { url: './a.ogg' }, ptt: true, viewOnceV2Extension: true })
64
-
65
- // receive + download
66
- sock.ev.on('messages.upsert', async ({ messages }) => {
67
- for (const m of messages) {
68
- if (extractViewOnceMedia(m.message)?.isViewOnce) {
69
- const buf = await downloadViewOnceMessage(m, 'buffer', {}, {
70
- logger: sock.logger,
71
- reuploadRequest: sock.updateMediaMessage
72
- })
73
- }
74
- }
75
- })
76
- ```
77
-
78
- Notes:
79
- - A view-once sent from a phone can first arrive as an empty stub (`key.isViewOnce === true`).
80
- The library asks your phone and the sender to resend it, and the real message follows
81
- through `messages.upsert` / `messages.update`.
82
- - Don't open the view-once on your phone first, or it may no longer be served.
83
- - If view-onces only ever arrive as empty stubs, link with an Android browser identity
84
- (`browser: Browsers.android('Chrome')`) instead of Mac/Chrome.
@@ -66,15 +66,24 @@ function makeLibSignalRepository(auth) {
66
66
  const addr = jidToSignalProtocolAddress(jid);
67
67
  const session = new libsignal.SessionCipher(storage, addr);
68
68
  let result;
69
- switch (type) {
70
- case 'pkmsg':
71
- result = await session.decryptPreKeyWhisperMessage(ciphertext);
72
- break;
73
- case 'msg':
74
- result = await session.decryptWhisperMessage(ciphertext);
75
- break;
76
- default:
77
- throw new Error(`Unknown message type: ${type}`);
69
+ try {
70
+ switch (type) {
71
+ case 'pkmsg':
72
+ result = await session.decryptPreKeyWhisperMessage(ciphertext);
73
+ break;
74
+ case 'msg':
75
+ result = await session.decryptWhisperMessage(ciphertext);
76
+ break;
77
+ default:
78
+ throw new Error(`Unknown message type: ${type}`);
79
+ }
80
+ } catch (error) {
81
+ const msg = error.message || '';
82
+ if (msg.includes('Bad MAC') || msg.includes('No matching session') || msg.includes('Invalid PreKey ID')) {
83
+ const addrStr = addr.toString();
84
+ await auth.keys.set({ session: { [addrStr]: null } });
85
+ }
86
+ throw error;
78
87
  }
79
88
  return result;
80
89
  },
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ const { proto } = require("../../WAProto");
3
+ const REVOKE = proto.WebMessageInfo.StubType.REVOKE;
4
+
5
+ class AntiDelete {
6
+ constructor(config, sock) {
7
+ this.config = config;
8
+ this.sock = sock;
9
+ this.cache = new Map();
10
+ this.deleted = new Map();
11
+ this.enabled = false;
12
+ this.ttlMs = 30 * 60 * 1000;
13
+ this.maxEntries = 200;
14
+ this._upsertHandler = null;
15
+ this._updateHandler = null;
16
+ this._cleanupTimer = null;
17
+ }
18
+
19
+ enable(options = {}) {
20
+ if (this.enabled) return this;
21
+ this.ttlMs = options.ttlMs ?? 30 * 60 * 1000;
22
+ this.maxEntries = options.maxEntries ?? 200;
23
+
24
+ this._upsertHandler = ({ messages, type }) => {
25
+ if (type !== "notify") return;
26
+ for (const msg of messages) {
27
+ if (!msg.message || !msg.key?.id) continue;
28
+ if (msg.key.fromMe) continue;
29
+ this.cache.set(msg.key.id, { message: msg, ts: Date.now() });
30
+ }
31
+ this._trim();
32
+ };
33
+
34
+ this._updateHandler = (updates) => {
35
+ for (const u of updates) {
36
+ if (u.update?.messageStubType !== REVOKE) continue;
37
+ const id = u.key?.id;
38
+ const original = this.cache.get(id);
39
+ if (!original) continue;
40
+ const payload = {
41
+ key: u.key,
42
+ original: original.message,
43
+ revokedBy: u.update?.key?.participant || u.update?.key?.remoteJid,
44
+ };
45
+ this.deleted.set(id, { ...payload, ts: Date.now() });
46
+ this.sock.ev.emit("messages.deleted", payload);
47
+ this.config.logger?.debug?.({ id }, "anti-delete: recovered revoked message");
48
+ }
49
+ };
50
+
51
+ this.sock.ev.on("messages.upsert", this._upsertHandler);
52
+ this.sock.ev.on("messages.update", this._updateHandler);
53
+ this._cleanupTimer = setInterval(() => this._cleanup(), 60_000);
54
+ if (this._cleanupTimer.unref) this._cleanupTimer.unref();
55
+ this.enabled = true;
56
+ this.config.logger?.info?.(
57
+ { ttlMs: this.ttlMs, maxEntries: this.maxEntries },
58
+ "anti-delete enabled"
59
+ );
60
+ return this;
61
+ }
62
+
63
+ disable() {
64
+ if (!this.enabled) return;
65
+ if (this._upsertHandler) this.sock.ev.off("messages.upsert", this._upsertHandler);
66
+ if (this._updateHandler) this.sock.ev.off("messages.update", this._updateHandler);
67
+ if (this._cleanupTimer) clearInterval(this._cleanupTimer);
68
+ this._upsertHandler = null;
69
+ this._updateHandler = null;
70
+ this._cleanupTimer = null;
71
+ this.enabled = false;
72
+ }
73
+
74
+ _trim() {
75
+ while (this.cache.size > this.maxEntries) {
76
+ this.cache.delete(this.cache.keys().next().value);
77
+ }
78
+ }
79
+
80
+ _cleanup() {
81
+ const now = Date.now();
82
+ for (const [id, e] of this.cache) {
83
+ if (now - e.ts > this.ttlMs) this.cache.delete(id);
84
+ }
85
+ for (const [id, e] of this.deleted) {
86
+ if (now - e.ts > this.ttlMs) this.deleted.delete(id);
87
+ }
88
+ }
89
+
90
+ get(id) {
91
+ const hit = this.deleted.get(id);
92
+ return hit || null;
93
+ }
94
+
95
+ stats() {
96
+ return {
97
+ enabled: this.enabled,
98
+ cached: this.cache.size,
99
+ recovered: this.deleted.size,
100
+ };
101
+ }
102
+ }
103
+
104
+ module.exports = AntiDelete;
@@ -0,0 +1,99 @@
1
+ "use strict";
2
+
3
+ class Automation {
4
+ constructor(config, sock) {
5
+ this.config = config;
6
+ this.sock = sock;
7
+ this.enabled = false;
8
+ this.options = {};
9
+ this._callHandler = null;
10
+ this._statusHandler = null;
11
+ }
12
+
13
+ enable(options = {}) {
14
+ this.updateOptions(options);
15
+
16
+ if (this.enabled) return this;
17
+
18
+ // --- Anti-Call Logic ---
19
+ this._callHandler = async (calls) => {
20
+ if (this.options.antiCallMode === 'off') return;
21
+
22
+ for (const call of calls) {
23
+ try {
24
+ await this.sock.rejectCall(call.id, call.from);
25
+
26
+ if (this.options.antiCallMode === 'block') {
27
+ await this.sock.updateBlockStatus(call.from, 'block');
28
+ }
29
+
30
+ // Resolve the message dynamically (supports both strings and functions)
31
+ let msg = this.options.antiCallMessage;
32
+ if (typeof msg === 'function') msg = msg(call);
33
+
34
+ if (msg && typeof msg === 'string' && msg.trim() !== "") {
35
+ await this.sock.sendMessage(call.from, { text: msg });
36
+ }
37
+ } catch (err) {
38
+ this.config.logger?.warn?.({ err }, 'Automation: Anti-call failed');
39
+ }
40
+ }
41
+ };
42
+ this.sock.ev.on('call', this._callHandler);
43
+
44
+ // --- Auto-Status Logic ---
45
+ this._statusHandler = async ({ messages, type }) => {
46
+ if (type !== 'notify') return;
47
+ if (!this.options.autoViewStatus && !this.options.autoReactStatus) return;
48
+
49
+ for (const msg of messages) {
50
+ if (msg.key.remoteJid !== 'status@broadcast' || msg.key.fromMe) continue;
51
+
52
+ try {
53
+ if (this.options.autoViewStatus) {
54
+ await this.sock.readMessages([msg.key]);
55
+ }
56
+ if (this.options.autoReactStatus && msg.key.participant) {
57
+ let emoji = this.options.statusEmoji || '💚';
58
+ if (typeof emoji === 'function') emoji = emoji(msg);
59
+
60
+ await this.sock.sendMessage('status@broadcast', {
61
+ react: { text: emoji, key: msg.key }
62
+ }, {
63
+ statusJidList: [msg.key.participant]
64
+ });
65
+ }
66
+ } catch (err) {
67
+ this.config.logger?.warn?.({ err }, 'Automation: Auto-status failed');
68
+ }
69
+ }
70
+ };
71
+ this.sock.ev.on('messages.upsert', this._statusHandler);
72
+
73
+ this.enabled = true;
74
+ this.config.logger?.info?.({ ...this.options }, 'automation enabled');
75
+ return this;
76
+ }
77
+
78
+ // Expose this so developers can change the message later (e.g., from a command)
79
+ updateOptions(newOptions) {
80
+ this.options = {
81
+ antiCallMode: 'off',
82
+ antiCallMessage: 'I am a bot, please text me instead.',
83
+ autoViewStatus: false,
84
+ autoReactStatus: false,
85
+ statusEmoji: '💚',
86
+ ...this.options,
87
+ ...newOptions
88
+ };
89
+ }
90
+
91
+ disable() {
92
+ if (!this.enabled) return;
93
+ if (this._callHandler) this.sock.ev.off('call', this._callHandler);
94
+ if (this._statusHandler) this.sock.ev.off('messages.upsert', this._statusHandler);
95
+ this.enabled = false;
96
+ }
97
+ }
98
+
99
+ module.exports = Automation;
@@ -2,9 +2,21 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const Defaults_1 = require("../Defaults");
4
4
  const business_1 = require("./business");
5
+ const MessageStore = require("../Utils/msg-store");
5
6
  // export the last socket layer
6
- const makeWASocket = (config) => (0, business_1.makeBusinessSocket)({
7
- ...Defaults_1.DEFAULT_CONNECTION_CONFIG,
8
- ...config
9
- });
7
+ const makeWASocket = (config) => {
8
+ const msgStore = new MessageStore(2000);
9
+ return (0, business_1.makeBusinessSocket)({
10
+ ...Defaults_1.DEFAULT_CONNECTION_CONFIG,
11
+ ...config,
12
+ msgStore,
13
+ getMessage: async (key) => {
14
+ if (config.getMessage && typeof config.getMessage === 'function') {
15
+ const custom = await config.getMessage(key);
16
+ if (custom) return custom;
17
+ }
18
+ return msgStore.get(key.id);
19
+ }
20
+ });
21
+ };
10
22
  exports.default = makeWASocket;
@@ -0,0 +1,169 @@
1
+ "use strict";
2
+ const crypto = require("crypto");
3
+ const { proto } = require("../../WAProto");
4
+
5
+ class MessageEdit {
6
+ constructor(config, sock) {
7
+ this.config = config;
8
+ this.sock = sock;
9
+ this.messageCache = new Map(); // id -> { msg, secret }
10
+ this.timestamps = new Map(); // id -> ts (for TTL)
11
+ this.enabled = false;
12
+ this.ttlMs = 10 * 60 * 1000;
13
+ this.maxEntries = 500;
14
+ this._upsertHandler = null;
15
+ }
16
+
17
+ enable(options = {}) {
18
+ if (this.enabled) return this;
19
+ this.ttlMs = options.ttlMs ?? 10 * 60 * 1000;
20
+ this.maxEntries = options.maxEntries ?? 500;
21
+
22
+ this._upsertHandler = ({ messages }) => {
23
+ for (const msg of messages) {
24
+ if (!msg.key?.id) continue;
25
+ const id = msg.key.id;
26
+
27
+ const secret = msg.message?.messageContextInfo?.messageSecret;
28
+ if (secret) {
29
+ this.messageCache.set(id, { msg, secret: toBuffer(secret) });
30
+ this.timestamps.set(id, Date.now());
31
+ }
32
+
33
+ // Old-style plaintext edit
34
+ const protocolMsg = msg.message?.protocolMessage;
35
+ const isPlaintextEdit = protocolMsg && (
36
+ protocolMsg.type === "MESSAGE_EDIT" ||
37
+ protocolMsg.type === proto.Message.ProtocolMessage.Type.MESSAGE_EDIT ||
38
+ protocolMsg.type === 14
39
+ );
40
+ if (isPlaintextEdit) {
41
+ const targetId = protocolMsg.key?.id;
42
+ const original = this.messageCache.get(targetId);
43
+ this.sock.ev.emit("messages.edited", {
44
+ key: msg.key,
45
+ targetId,
46
+ original: original?.msg || null,
47
+ edited: protocolMsg.editedMessage || null,
48
+ source: "plaintext",
49
+ });
50
+ continue;
51
+ }
52
+
53
+ // New-style encrypted edit
54
+ const envelope = msg.message?.secretEncryptedMessage;
55
+ const isEncryptedEdit = envelope && (
56
+ envelope.secretEncType === "MESSAGE_EDIT" ||
57
+ envelope.secretEncType === proto.Message.SecretEncryptedMessage.SecretEncType.MESSAGE_EDIT ||
58
+ envelope.secretEncType === 2 ||
59
+ envelope.secretEncType === "2"
60
+ );
61
+ if (isEncryptedEdit) {
62
+ this._handleEncryptedEdit(msg, envelope).catch(err => {
63
+ this.config.logger?.warn?.({ err: err.message }, "anti-edit decrypt failed");
64
+ });
65
+ }
66
+ }
67
+ this._trimCache();
68
+ };
69
+
70
+ this.sock.ev.on("messages.upsert", this._upsertHandler);
71
+ this.enabled = true;
72
+ this.config.logger?.info?.({ ttlMs: this.ttlMs }, "anti-edit enabled");
73
+ return this;
74
+ }
75
+
76
+ disable() {
77
+ if (!this.enabled) return;
78
+ if (this._upsertHandler) this.sock.ev.off("messages.upsert", this._upsertHandler);
79
+ this._upsertHandler = null;
80
+ this.enabled = false;
81
+ }
82
+
83
+ async _handleEncryptedEdit(msg, envelope) {
84
+ const targetId = envelope.targetMessageKey?.id;
85
+ if (!targetId) return;
86
+
87
+ const cached = this.messageCache.get(targetId);
88
+ if (!cached) {
89
+ this.config.logger?.debug?.({ targetId }, "anti-edit: original not cached");
90
+ return;
91
+ }
92
+
93
+ const originalSenderJid = cached.msg.key.participant || cached.msg.key.remoteJid;
94
+ const editorJid = msg.key.participant || msg.key.remoteJid;
95
+
96
+ const edited = this._decrypt(envelope, cached.secret, targetId, originalSenderJid, editorJid);
97
+ if (!edited) {
98
+ this.config.logger?.warn?.({ targetId }, "anti-edit: decryption returned null");
99
+ return;
100
+ }
101
+
102
+ this.sock.ev.emit("messages.edited", {
103
+ key: msg.key,
104
+ targetId,
105
+ original: cached.msg,
106
+ edited,
107
+ source: "encrypted",
108
+ });
109
+ }
110
+
111
+ _decrypt(envelope, messageSecret, originalMsgId, originalSenderJid, editorJid) {
112
+ try {
113
+ const info = Buffer.concat([
114
+ Buffer.from(originalMsgId, "utf8"),
115
+ Buffer.from(originalSenderJid || "", "utf8"),
116
+ Buffer.from(editorJid || "", "utf8"),
117
+ Buffer.from("Message Edit", "utf8"),
118
+ ]);
119
+
120
+ const salt = Buffer.alloc(32, 0);
121
+ const key = Buffer.from(crypto.hkdfSync("sha256", messageSecret, salt, info, 32));
122
+
123
+ const encPayload = toBuffer(envelope.encPayload);
124
+ const encIv = toBuffer(envelope.encIv);
125
+ if (encIv.length !== 12) return null;
126
+
127
+ const authTag = encPayload.slice(-16);
128
+ const ciphertext = encPayload.slice(0, -16);
129
+ const decipher = crypto.createDecipheriv("aes-256-gcm", key, encIv);
130
+ decipher.setAuthTag(authTag);
131
+ decipher.setAAD(Buffer.alloc(0));
132
+
133
+ const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
134
+ const parsed = proto.Message.decode(decrypted);
135
+ return parsed.protocolMessage?.editedMessage || null;
136
+ } catch (err) {
137
+ return null;
138
+ }
139
+ }
140
+
141
+ _trimCache() {
142
+ const now = Date.now();
143
+ for (const [id, ts] of this.timestamps) {
144
+ if (now - ts > this.ttlMs) {
145
+ this.messageCache.delete(id);
146
+ this.timestamps.delete(id);
147
+ }
148
+ }
149
+ while (this.messageCache.size > this.maxEntries) {
150
+ const first = this.messageCache.keys().next().value;
151
+ this.messageCache.delete(first);
152
+ this.timestamps.delete(first);
153
+ }
154
+ }
155
+
156
+ stats() {
157
+ return { enabled: this.enabled, cached: this.messageCache.size };
158
+ }
159
+ }
160
+
161
+ function toBuffer(x) {
162
+ if (!x) return Buffer.alloc(0);
163
+ if (Buffer.isBuffer(x)) return x;
164
+ if (x instanceof Uint8Array) return Buffer.from(x);
165
+ if (typeof x === "string") return Buffer.from(x, "base64");
166
+ return Buffer.alloc(0);
167
+ }
168
+
169
+ module.exports = MessageEdit;
@@ -17,10 +17,25 @@ const WAUSync_1 = require("../WAUSync");
17
17
  const groups_1 = require("./groups");
18
18
  const newsletter_1 = require("./newsletter");
19
19
  const SavageStatus = require("./gcstatus");
20
+ const ViewOnceCache = require("./view-once");
21
+ const AntiDelete = require("./anti-delete");
22
+ const MessageEdit = require("./message-edit");
23
+ const Automation = require("./automation");
20
24
  // Permanently blacklist device JIDs that WhatsApp rejects with not-acceptable.
21
25
  // These are typically stale companion devices. Avoids repeated failed IQ queries.
22
26
  const _deadDeviceJids = new Set();
23
27
 
28
+
29
+ async function resolveJidToLid(sock, jid) {
30
+ try {
31
+ if (!jid || jid.endsWith('@lid') || jid.endsWith('@g.us')) return jid;
32
+ const lid = await sock.signalRepository?.lidMapping?.getLIDForPN(jid);
33
+ return lid || jid;
34
+ } catch (e) {
35
+ return jid;
36
+ }
37
+ }
38
+
24
39
  const makeMessagesSocket = (config) => {
25
40
  const {
26
41
  logger,
@@ -774,6 +789,9 @@ const makeMessagesSocket = (config) => {
774
789
  );
775
790
  await sendNode(stanza);
776
791
  });
792
+ if (config.msgStore) {
793
+ config.msgStore.set(msgId, message);
794
+ }
777
795
  return msgId;
778
796
  };
779
797
  const getMessageType = (message) => {
@@ -857,6 +875,10 @@ const makeMessagesSocket = (config) => {
857
875
  refreshMediaConn,
858
876
  );
859
877
  const savageStatus = new SavageStatus(Utils_1, waUploadToServer, relayMessage, config, sock);
878
+ const viewOnceCache = new ViewOnceCache(config, sock);
879
+ const antiDelete = new AntiDelete(config, sock);
880
+ const messageEdit = new MessageEdit(config, sock);
881
+ const automation = new Automation(config, sock);
860
882
  const waitForMsgMediaUpdate = (0, Utils_1.bindWaitForEvent)(
861
883
  ev,
862
884
  "messages.media-update",
@@ -873,6 +895,28 @@ const makeMessagesSocket = (config) => {
873
895
  waUploadToServer,
874
896
  savageStatus,
875
897
  spencerStatus: savageStatus, // backwards-compatible alias
898
+ viewOnceCache,
899
+ enableViewOnceCache: (opts = {}) => {
900
+ viewOnceCache.enable(opts);
901
+ return viewOnceCache;
902
+ },
903
+ downloadViewOnce: (id) => viewOnceCache.get(id),
904
+ viewOnceStats: () => viewOnceCache.stats(),
905
+ antiDelete,
906
+ enableAntiDelete: (opts = {}) => {
907
+ antiDelete.enable(opts);
908
+ return antiDelete;
909
+ },
910
+ getDeletedMessage: (id) => antiDelete.get(id),
911
+ antiDeleteStats: () => antiDelete.stats(),
912
+ messageEdit,
913
+ enableAntiEdit: (opts = {}) => {
914
+ messageEdit.enable(opts);
915
+ return messageEdit;
916
+ },
917
+ antiEditStats: () => messageEdit.stats(),
918
+ automation,
919
+ enableAutomation: (opts = {}) => automation.enable(opts),
876
920
  fetchPrivacySettings,
877
921
  sendPeerDataOperationMessage,
878
922
  createParticipantNodes,
@@ -952,6 +996,7 @@ const makeMessagesSocket = (config) => {
952
996
  return message;
953
997
  },
954
998
  sendMessage: async (jid, content, options = {}) => {
999
+ jid = await resolveJidToLid(sock, jid);
955
1000
  var _a, _b, _c;
956
1001
  const userJid = authState.creds.me.id;
957
1002
  if (
package/lib/Socket/mex.js CHANGED
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.executeWMexQuery = void 0;
4
4
  const boom_1 = require("@hapi/boom");
5
5
  const WABinary_1 = require("../WABinary");
6
+
6
7
  const wMexQuery = (variables, queryId, query, generateMessageTag) => {
7
8
  return query({
8
9
  tag: 'iq',
@@ -21,26 +22,52 @@ const wMexQuery = (variables, queryId, query, generateMessageTag) => {
21
22
  ]
22
23
  });
23
24
  };
25
+
24
26
  const executeWMexQuery = async (variables, queryId, dataPath, query, generateMessageTag) => {
25
- var _a, _b;
26
27
  const result = await wMexQuery(variables, queryId, query, generateMessageTag);
27
28
  const child = (0, WABinary_1.getBinaryNodeChild)(result, 'result');
28
- if (child === null || child === void 0 ? void 0 : child.content) {
29
- const data = JSON.parse(child.content.toString());
29
+
30
+ if (child?.content) {
31
+ let data;
32
+ const rawStr = Buffer.isBuffer(child.content) ? child.content.toString('utf8') : String(child.content);
33
+
34
+ try {
35
+ // 1. Try standard JSON first
36
+ data = JSON.parse(rawStr);
37
+ } catch (e) {
38
+ // 2. If JSON fails, WhatsApp sent binary data. Extract the JID using regex.
39
+ const jidMatch = rawStr.match(/(\d{10,})@newsletter/);
40
+ if (jidMatch && dataPath?.includes('newsletter')) {
41
+ // Create a mocked response so the library continues smoothly
42
+ data = { data: { [dataPath]: { id: jidMatch[0], state: 'ACTIVE', thread_metadata: { name: { text: 'Channel' } } } } };
43
+ } else {
44
+ // 3. Fallback: try to find any JSON object buried in the binary string
45
+ const jsonMatch = rawStr.match(/\{[\s\S]*\}/);
46
+ if (jsonMatch) {
47
+ try { data = JSON.parse(jsonMatch[0]); } catch(e2) {}
48
+ }
49
+ if (!data) {
50
+ throw new boom_1.Boom(`Failed to decode WMex response: ${e.message}`, { statusCode: 500, data: result });
51
+ }
52
+ }
53
+ }
54
+
30
55
  if (data.errors && data.errors.length > 0) {
31
56
  const errorMessages = data.errors.map((err) => err.message || 'Unknown error').join(', ');
32
57
  const firstError = data.errors[0];
33
- const errorCode = ((_a = firstError.extensions) === null || _a === void 0 ? void 0 : _a.error_code) || 400;
58
+ const errorCode = firstError.extensions?.error_code || 400;
34
59
  throw new boom_1.Boom(`GraphQL server error: ${errorMessages}`, { statusCode: errorCode, data: firstError });
35
60
  }
36
- const response = dataPath ? (_b = data === null || data === void 0 ? void 0 : data.data) === null || _b === void 0 ? void 0 : _b[dataPath] : data === null || data === void 0 ? void 0 : data.data;
61
+
62
+ const response = dataPath ? data?.data?.[dataPath] : data?.data;
37
63
  if (typeof response !== 'undefined') {
38
64
  return response;
39
65
  }
40
66
  }
67
+
41
68
  const action = (dataPath || '').startsWith('xwa2_')
42
69
  ? dataPath.substring(5).replace(/_/g, ' ')
43
- : dataPath === null || dataPath === void 0 ? void 0 : dataPath.replace(/_/g, ' ');
70
+ : dataPath?.replace(/_/g, ' ') || 'query';
44
71
  throw new boom_1.Boom(`Failed to ${action}, unexpected response structure.`, { statusCode: 400, data: result });
45
72
  };
46
73
  exports.executeWMexQuery = executeWMexQuery;
@@ -0,0 +1,214 @@
1
+ "use strict";
2
+ const fs = require("fs");
3
+ const path = require("path");
4
+ const {
5
+ downloadMediaMessage,
6
+ getContentType,
7
+ normalizeMessageContent,
8
+ } = require("../Utils/messages");
9
+ const { proto } = require("../../WAProto");
10
+
11
+ const VIEW_ONCE_TYPES = [
12
+ "imageMessage",
13
+ "videoMessage",
14
+ "audioMessage",
15
+ "ptvMessage",
16
+ ];
17
+ const CIPHERTEXT = proto.WebMessageInfo.StubType.CIPHERTEXT;
18
+
19
+ class ViewOnceCache {
20
+ constructor(config, sock) {
21
+ this.config = config;
22
+ this.sock = sock;
23
+ this.cache = new Map();
24
+ this.stubs = new Map();
25
+ this.fails = new Map();
26
+ this.inflight = new Set();
27
+ this.enabled = false;
28
+ this.ttlMs = 30 * 60 * 1000;
29
+ this.maxEntries = 100;
30
+ this.cacheDir = null;
31
+ this._upsertHandler = null;
32
+ this._cleanupTimer = null;
33
+ }
34
+
35
+ enable(options = {}) {
36
+ if (this.enabled) return this;
37
+ this.ttlMs = options.ttlMs ?? 30 * 60 * 1000;
38
+ this.maxEntries = options.maxEntries ?? 100;
39
+ this.cacheDir = options.cacheDir || null;
40
+ if (this.cacheDir) {
41
+ fs.mkdirSync(this.cacheDir, { recursive: true });
42
+ }
43
+ this._upsertHandler = ({ messages, type }) => {
44
+ if (type !== "notify") return;
45
+ for (const msg of messages) this._handle(msg);
46
+ };
47
+ this.sock.ev.on("messages.upsert", this._upsertHandler);
48
+ this._cleanupTimer = setInterval(() => this._cleanup(), 60_000);
49
+ if (this._cleanupTimer.unref) this._cleanupTimer.unref();
50
+ this.enabled = true;
51
+ this.config.logger?.info?.(
52
+ { ttlMs: this.ttlMs, maxEntries: this.maxEntries, disk: !!this.cacheDir },
53
+ "view-once cache enabled"
54
+ );
55
+ return this;
56
+ }
57
+
58
+ disable() {
59
+ if (!this.enabled) return;
60
+ if (this._upsertHandler) {
61
+ this.sock.ev.off("messages.upsert", this._upsertHandler);
62
+ }
63
+ if (this._cleanupTimer) clearInterval(this._cleanupTimer);
64
+ this._upsertHandler = null;
65
+ this._cleanupTimer = null;
66
+ this.enabled = false;
67
+ }
68
+
69
+ async _handle(msg) {
70
+ const id = msg.key?.id;
71
+ if (!id) return;
72
+
73
+ if (!msg.message) {
74
+ if (msg.messageStubType === CIPHERTEXT) {
75
+ if (!this.stubs.has(id) && !this.cache.has(id)) {
76
+ this.stubs.set(id, { ts: Date.now() });
77
+ }
78
+ }
79
+ return;
80
+ }
81
+
82
+ const normalized = normalizeMessageContent(msg.message);
83
+ const contentType = getContentType(normalized);
84
+ if (!contentType || !VIEW_ONCE_TYPES.includes(contentType)) return;
85
+ const inner = normalized[contentType];
86
+ if (!inner || !inner.viewOnce) return;
87
+ if (this.cache.has(id) || this.inflight.has(id)) return;
88
+
89
+ this.inflight.add(id);
90
+ try {
91
+ const buffer = await downloadMediaMessage(
92
+ { ...msg, message: normalized },
93
+ "buffer",
94
+ {},
95
+ {
96
+ logger: this.config.logger,
97
+ reuploadRequest: this.sock.updateMediaMessage,
98
+ }
99
+ );
100
+ if (!buffer || buffer.length === 0) {
101
+ throw new Error("empty buffer");
102
+ }
103
+
104
+ const entry = {
105
+ type: contentType.replace("Message", ""),
106
+ mimetype: inner.mimetype || null,
107
+ caption: inner.caption || null,
108
+ ts: Date.now(),
109
+ };
110
+
111
+ if (this.cacheDir) {
112
+ const ext = mimeToExt(entry.mimetype);
113
+ const file = path.join(this.cacheDir, `${id}${ext}`);
114
+ await fs.promises.writeFile(file, buffer);
115
+ entry.path = file;
116
+ } else {
117
+ entry.buffer = buffer;
118
+ }
119
+
120
+ this.cache.set(id, entry);
121
+ this.stubs.delete(id);
122
+ this.fails.delete(id);
123
+
124
+ this.sock.ev.emit("messages.view-once", {
125
+ key: msg.key,
126
+ type: entry.type,
127
+ mimetype: entry.mimetype,
128
+ caption: entry.caption,
129
+ buffer: entry.buffer,
130
+ path: entry.path,
131
+ });
132
+ } catch (err) {
133
+ this.fails.set(id, {
134
+ ts: Date.now(),
135
+ error: (err && err.message) || "download failed",
136
+ });
137
+ this.config.logger?.warn?.({ err, id }, "view-once download failed");
138
+ } finally {
139
+ this.inflight.delete(id);
140
+ }
141
+ }
142
+
143
+ _cleanup() {
144
+ const now = Date.now();
145
+ for (const [id, e] of this.cache) {
146
+ if (now - e.ts > this.ttlMs) {
147
+ this._dropCacheEntry(id, e);
148
+ }
149
+ }
150
+ while (this.cache.size > this.maxEntries) {
151
+ const oldestId = this.cache.keys().next().value;
152
+ this._dropCacheEntry(oldestId, this.cache.get(oldestId));
153
+ }
154
+ for (const [id, e] of this.stubs) {
155
+ if (now - e.ts > this.ttlMs) this.stubs.delete(id);
156
+ }
157
+ for (const [id, e] of this.fails) {
158
+ if (now - e.ts > this.ttlMs) this.fails.delete(id);
159
+ }
160
+ }
161
+
162
+ _dropCacheEntry(id, e) {
163
+ this.cache.delete(id);
164
+ if (e && e.path) fs.promises.unlink(e.path).catch(() => {});
165
+ }
166
+
167
+ get(id) {
168
+ const hit = this.cache.get(id);
169
+ if (hit) {
170
+ if (hit.path && !hit.buffer) {
171
+ try {
172
+ return {
173
+ state: "cached",
174
+ ...hit,
175
+ buffer: fs.readFileSync(hit.path),
176
+ };
177
+ } catch (err) {
178
+ this.cache.delete(id);
179
+ }
180
+ } else {
181
+ return { state: "cached", ...hit };
182
+ }
183
+ }
184
+ const stub = this.stubs.get(id);
185
+ if (stub) return { state: "stub", ...stub };
186
+ const fail = this.fails.get(id);
187
+ if (fail) return { state: "fail", ...fail };
188
+ return { state: "missing" };
189
+ }
190
+
191
+ stats() {
192
+ return {
193
+ enabled: this.enabled,
194
+ cache: this.cache.size,
195
+ stubs: this.stubs.size,
196
+ fails: this.fails.size,
197
+ inflight: this.inflight.size,
198
+ };
199
+ }
200
+ }
201
+
202
+ function mimeToExt(mimetype) {
203
+ if (!mimetype) return ".bin";
204
+ if (mimetype.includes("jpeg")) return ".jpg";
205
+ if (mimetype.includes("png")) return ".png";
206
+ if (mimetype.includes("webp")) return ".webp";
207
+ if (mimetype.includes("mp4")) return ".mp4";
208
+ if (mimetype.includes("ogg")) return ".ogg";
209
+ if (mimetype.includes("mpeg")) return ".mp3";
210
+ if (mimetype.includes("pdf")) return ".pdf";
211
+ return ".bin";
212
+ }
213
+
214
+ module.exports = ViewOnceCache;
@@ -178,6 +178,8 @@ function decodeMessageNode(stanza, meId, meLid) {
178
178
  ...(senderPnValue ? { senderPn: senderPnValue } : {}),
179
179
  ...(participant ? { participant } : {}),
180
180
  ...(participantPnValue ? { participantPn: participantPnValue } : {}),
181
+ ...(senderPnValue && (0, WABinary_1.isLidUser)(chatId) ? { remoteJidAlt: senderPnValue } : {}),
182
+ ...(participantPnValue && participant && (0, WABinary_1.isLidUser)(participant) ? { participantAlt: participantPnValue } : {}),
181
183
  ...(participantLidValue ? { participantLid: participantLidValue } : {}),
182
184
  ...(msgType === 'newsletter' && stanza.attrs.server_id ? { server_id: stanza.attrs.server_id } : {})
183
185
  };
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+
3
+ class MessageStore {
4
+ constructor(maxSize = 2000) {
5
+ this.maxSize = maxSize;
6
+ this.cache = new Map();
7
+ }
8
+
9
+ set(id, message) {
10
+ if (!id || !message) return;
11
+ if (this.cache.has(id)) {
12
+ this.cache.delete(id);
13
+ }
14
+ this.cache.set(id, message);
15
+ if (this.cache.size > this.maxSize) {
16
+ const first = this.cache.keys().next().value;
17
+ this.cache.delete(first);
18
+ }
19
+ }
20
+
21
+ get(id) {
22
+ return this.cache.get(id);
23
+ }
24
+
25
+ clear() {
26
+ this.cache.clear();
27
+ }
28
+ }
29
+
30
+ module.exports = MessageStore;
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ const { initAuthCreds } = require("./auth-utils");
3
+ const { BufferJSON } = require("./generics");
4
+ const { proto } = require("../../WAProto");
5
+
6
+ const useRedisAuthState = async (redisClient, prefix = "baileys") => {
7
+ const credsKey = `${prefix}:creds`;
8
+
9
+ const credsRaw = await redisClient.get(credsKey);
10
+ const creds = credsRaw ? JSON.parse(credsRaw, BufferJSON.reviver) : initAuthCreds();
11
+
12
+ return {
13
+ state: {
14
+ creds,
15
+ keys: {
16
+ get: async (type, ids) => {
17
+ if (!ids.length) return {};
18
+ const data = {};
19
+ const hashKey = `${prefix}:${type}`;
20
+ const values = await redisClient.hmGet(hashKey, ids);
21
+
22
+ ids.forEach((id, index) => {
23
+ if (values[index]) {
24
+ let value = JSON.parse(values[index], BufferJSON.reviver);
25
+ if (type === "app-state-sync-key") value = proto.Message.AppStateSyncKeyData.fromObject(value);
26
+ data[id] = value;
27
+ }
28
+ });
29
+ return data;
30
+ },
31
+ set: async (data) => {
32
+ const pipeline = redisClient.multi();
33
+ for (const category in data) {
34
+ const hashKey = `${prefix}:${category}`;
35
+ for (const id in data[category]) {
36
+ const value = data[category][id];
37
+ if (value) {
38
+ pipeline.hSet(hashKey, id, JSON.stringify(value, BufferJSON.replacer));
39
+ } else {
40
+ pipeline.hDel(hashKey, id);
41
+ }
42
+ }
43
+ }
44
+ await pipeline.exec();
45
+ },
46
+ },
47
+ },
48
+ saveCreds: async () => {
49
+ await redisClient.set(credsKey, JSON.stringify(creds, BufferJSON.replacer));
50
+ },
51
+ };
52
+ };
53
+
54
+ module.exports = { useRedisAuthState };
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ const { initAuthCreds } = require("./auth-utils");
3
+ const { BufferJSON } = require("./generics");
4
+
5
+ const useSQLAuthState = async ({ driver = "sqlite", config, tablePrefix = "baileys" }) => {
6
+ let db;
7
+ if (driver === "sqlite") {
8
+ const Database = require("better-sqlite3");
9
+ db = new Database(config.database);
10
+ db.pragma("journal_mode = WAL");
11
+ } else if (driver === "pg") {
12
+ const { Pool } = require("pg");
13
+ db = new Pool(config);
14
+ } else if (driver === "mysql") {
15
+ db = require("mysql2/promise").createPool(config);
16
+ } else {
17
+ throw new Error("Unsupported driver. Use sqlite, pg, or mysql.");
18
+ }
19
+
20
+ const credsTable = `${tablePrefix}_creds`;
21
+ const keysTable = `${tablePrefix}_keys`;
22
+
23
+ // --- Table Initialization ---
24
+ const initQuery = `
25
+ CREATE TABLE IF NOT EXISTS ${credsTable} (
26
+ key TEXT PRIMARY KEY,
27
+ value TEXT
28
+ );
29
+ CREATE TABLE IF NOT EXISTS ${keysTable} (
30
+ type TEXT,
31
+ id TEXT,
32
+ value TEXT,
33
+ PRIMARY KEY (type, id)
34
+ );
35
+ `;
36
+
37
+ if (driver === "sqlite") {
38
+ db.exec(initQuery);
39
+ } else {
40
+ await db.query(initQuery);
41
+ }
42
+
43
+ const readData = async (table, condition = "", params = []) => {
44
+ const query = `SELECT * FROM ${table} ${condition}`;
45
+ const result = driver === "sqlite" ? db.prepare(query).all(...params) : (await db.query(query, params)).rows;
46
+ return result;
47
+ };
48
+
49
+ const writeData = async (table, data, isDelete = false) => {
50
+ if (isDelete) {
51
+ const query = `DELETE FROM ${table} WHERE key = ? OR (type = ? AND id = ?)`;
52
+ if (driver === "sqlite") db.prepare(query).run(data.key, data.type, data.id);
53
+ else await db.query(query, [data.key, data.type, data.id]);
54
+ return;
55
+ }
56
+
57
+ const query = table === credsTable
58
+ ? `INSERT INTO ${credsTable} (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = EXCLUDED.value`
59
+ : `INSERT INTO ${keysTable} (type, id, value) VALUES (?, ?, ?) ON CONFLICT(type, id) DO UPDATE SET value = EXCLUDED.value`;
60
+
61
+ const params = table === credsTable ? [data.key, data.value] : [data.type, data.id, data.value];
62
+
63
+ if (driver === "sqlite") db.prepare(query).run(...params);
64
+ else await db.query(query, params);
65
+ };
66
+
67
+ const credsRow = await readData(credsTable);
68
+ const creds = credsRow.length ? JSON.parse(credsRow[0].value, BufferJSON.reviver) : initAuthCreds();
69
+
70
+ return {
71
+ state: {
72
+ creds,
73
+ keys: {
74
+ get: async (type, ids) => {
75
+ if (!ids.length) return {};
76
+ const placeholders = ids.map(() => "?").join(",");
77
+ const query = `SELECT id, value FROM ${keysTable} WHERE type = ? AND id IN (${placeholders})`;
78
+ const rows = driver === "sqlite" ? db.prepare(query).all(type, ...ids) : (await db.query(query, [type, ...ids])).rows;
79
+
80
+ const data = {};
81
+ for (const row of rows) {
82
+ let value = JSON.parse(row.value, BufferJSON.reviver);
83
+ if (type === "app-state-sync-key") value = require("../../WAProto").proto.Message.AppStateSyncKeyData.fromObject(value);
84
+ data[row.id] = value;
85
+ }
86
+ return data;
87
+ },
88
+ set: async (data) => {
89
+ const tasks = [];
90
+ for (const category in data) {
91
+ for (const id in data[category]) {
92
+ const value = data[category][id];
93
+ const valStr = value ? JSON.stringify(value, BufferJSON.replacer) : null;
94
+ if (valStr) tasks.push(writeData(keysTable, { type: category, id, value: valStr }));
95
+ else tasks.push(writeData(keysTable, { type: category, id }, true));
96
+ }
97
+ }
98
+ await Promise.all(tasks);
99
+ },
100
+ },
101
+ },
102
+ saveCreds: async () => {
103
+ await writeData(credsTable, { key: "creds", value: JSON.stringify(creds, BufferJSON.replacer) });
104
+ },
105
+ };
106
+ };
107
+
108
+ module.exports = { useSQLAuthState };
package/lib/index.js CHANGED
@@ -18,7 +18,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
18
18
  };
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
20
  exports.makeWASocket = void 0;
21
+
22
+
21
23
  const Socket_1 = __importDefault(require("./Socket"));
24
+ const { useSQLAuthState } = require("./Utils/use-sql-auth-state");
25
+ const { useRedisAuthState } = require("./Utils/use-redis-auth-state");
22
26
  exports.makeWASocket = Socket_1.default;
23
27
  __exportStar(require("../WAProto"), exports);
24
28
  __exportStar(require("./Utils"), exports);
@@ -27,4 +31,6 @@ __exportStar(require("./Defaults"), exports);
27
31
  __exportStar(require("./WABinary"), exports);
28
32
  __exportStar(require("./WAM"), exports);
29
33
  __exportStar(require("./WAUSync"), exports);
34
+ exports.useSQLAuthState = useSQLAuthState;
35
+ exports.useRedisAuthState = useRedisAuthState;
30
36
  exports.default = Socket_1.default;
package/package.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "name": "savage-baileys",
3
- "version": "2.0.0",
3
+ "version": "2.0.3",
4
4
  "description": "Savage Baileys — WhatsApp Web API WebSocket library with full view-once support. No telemetry, no auto-follow, no automatic remote calls.",
5
+ "icon": "https://raw.githubusercontent.com/tysavage163/savage-baileys/main/assets/logo.jpg",
5
6
  "main": "lib/index.js",
6
7
  "types": "lib/index.d.ts",
7
8
  "homepage": "https://github.com/tysavage163/savage-baileys#readme",