@ryuu-reinzz/baileys 3.5.1 → 5.0.2

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/README.md +30 -25
  2. package/WAProto/fix-imports.js +22 -18
  3. package/WAProto/index.js +22 -18
  4. package/lib/Defaults/index.js +10 -9
  5. package/lib/Signal/libsignal.js +45 -17
  6. package/lib/Signal/lid-mapping.js +6 -0
  7. package/lib/Socket/chats.js +241 -39
  8. package/lib/Socket/groups.js +20 -0
  9. package/lib/Socket/messages-recv.js +736 -314
  10. package/lib/Socket/messages-send.js +279 -129
  11. package/lib/Socket/newsletter.js +2 -2
  12. package/lib/Socket/socket.js +56 -25
  13. package/lib/Types/{Newsletter.js → Mex.js} +9 -3
  14. package/lib/Types/State.js +43 -0
  15. package/lib/Types/index.js +1 -1
  16. package/lib/Utils/auth-utils.js +12 -0
  17. package/lib/Utils/chat-utils.js +80 -20
  18. package/lib/Utils/companion-reg-client-utils.js +35 -0
  19. package/lib/Utils/decode-wa-message.js +34 -0
  20. package/lib/Utils/event-buffer.js +49 -1
  21. package/lib/Utils/generics.js +12 -3
  22. package/lib/Utils/history.js +12 -9
  23. package/lib/Utils/identity-change-handler.js +1 -0
  24. package/lib/Utils/index.js +3 -1
  25. package/lib/Utils/link-preview.js +2 -2
  26. package/lib/Utils/message-retry-manager.js +40 -0
  27. package/lib/Utils/messages-media.js +21 -7
  28. package/lib/Utils/messages.js +28 -5
  29. package/lib/Utils/offline-node-processor.js +40 -0
  30. package/lib/Utils/process-message.js +103 -1
  31. package/lib/Utils/signal.js +42 -0
  32. package/lib/Utils/stanza-ack.js +38 -0
  33. package/lib/Utils/sync-action-utils.js +1 -0
  34. package/lib/Utils/tc-token-utils.js +149 -4
  35. package/lib/Utils/validate-connection.js +3 -0
  36. package/lib/WAUSync/Protocols/USyncContactProtocol.js +26 -3
  37. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  38. package/lib/WAUSync/Protocols/index.js +1 -0
  39. package/lib/WAUSync/USyncQuery.js +6 -2
  40. package/lib/WAUSync/USyncUser.js +8 -0
  41. package/package.json +39 -12
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Builds an ACK stanza for a received node.
3
+ * Pure function -- no I/O, no side effects.
4
+ *
5
+ * Mirrors WhatsApp Web's ACK construction:
6
+ * - WAWebHandleMsgSendAck.sendAck / sendNack
7
+ * - WAWebCreateNackFromStanza.createNackFromStanza
8
+ */
9
+ export function buildAckStanza(node, errorCode, meId) {
10
+ const { tag, attrs } = node;
11
+ const stanza = {
12
+ tag: 'ack',
13
+ attrs: {
14
+ id: attrs.id,
15
+ to: attrs.from,
16
+ class: tag
17
+ }
18
+ };
19
+ if (errorCode) {
20
+ stanza.attrs.error = errorCode.toString();
21
+ }
22
+ if (attrs.participant) {
23
+ stanza.attrs.participant = attrs.participant;
24
+ }
25
+ if (attrs.recipient) {
26
+ stanza.attrs.recipient = attrs.recipient;
27
+ }
28
+ // WA Web always includes type when present: `n.type || DROP_ATTR`
29
+ if (attrs.type) {
30
+ stanza.attrs.type = attrs.type;
31
+ }
32
+ // WA Web WAWebHandleMsgSendAck.sendAck/sendNack always include `from` for message-class ACKs
33
+ if (tag === 'message' && meId) {
34
+ stanza.attrs.from = meId;
35
+ }
36
+ return stanza;
37
+ }
38
+ //# sourceMappingURL=stanza-ack.js.map
@@ -21,6 +21,7 @@ export const processContactAction = (action, id, logger) => {
21
21
  {
22
22
  id,
23
23
  name: action.fullName || action.firstName || action.username || undefined,
24
+ username: action.username || undefined,
24
25
  lid: lidJid || undefined,
25
26
  phoneNumber
26
27
  }
@@ -1,9 +1,119 @@
1
- export async function buildTcTokenFromJid({ authState, jid, baseContent = [] }) {
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 }) {
2
100
  try {
3
- const tcTokenData = await authState.keys.get('tctoken', [jid]);
4
- const tcTokenBuffer = tcTokenData?.[jid]?.token;
5
- if (!tcTokenBuffer)
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
+ }
6
115
  return baseContent.length > 0 ? baseContent : undefined;
116
+ }
7
117
  baseContent.push({
8
118
  tag: 'tctoken',
9
119
  attrs: {},
@@ -15,4 +125,39 @@ export async function buildTcTokenFromJid({ authState, jid, baseContent = [] })
15
125
  return baseContent.length > 0 ? baseContent : undefined;
16
126
  }
17
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
+ }
18
163
  //# sourceMappingURL=tc-token-utils.js.map
@@ -44,6 +44,9 @@ const getClientPayload = (config) => {
44
44
  userAgent: getUserAgent(config)
45
45
  };
46
46
  payload.webInfo = getWebInfo(config);
47
+ if (config.pushName) {
48
+ payload.pushName = config.pushName;
49
+ }
47
50
  return payload;
48
51
  };
49
52
  export const generateLoginNode = (userJid, config) => {
@@ -11,11 +11,34 @@ export class USyncContactProtocol {
11
11
  };
12
12
  }
13
13
  getUserElement(user) {
14
- //TODO: Implement type / username fields (not yet supported)
14
+ if (user.phone) {
15
+ return {
16
+ tag: 'contact',
17
+ attrs: {},
18
+ content: user.phone
19
+ };
20
+ }
21
+ if (user.username) {
22
+ return {
23
+ tag: 'contact',
24
+ attrs: {
25
+ username: user.username,
26
+ ...(user.usernameKey ? { pin: user.usernameKey } : {}),
27
+ ...(user.lid ? { lid: user.lid } : {})
28
+ }
29
+ };
30
+ }
31
+ if (user.type) {
32
+ return {
33
+ tag: 'contact',
34
+ attrs: {
35
+ type: user.type
36
+ }
37
+ };
38
+ }
15
39
  return {
16
40
  tag: 'contact',
17
- attrs: {},
18
- content: user.phone
41
+ attrs: {}
19
42
  };
20
43
  }
21
44
  parser(node) {
@@ -0,0 +1,25 @@
1
+ import { assertNodeErrorFree } from '../../WABinary/index.js';
2
+ import { USyncUser } from '../USyncUser.js';
3
+ export class USyncUsernameProtocol {
4
+ constructor() {
5
+ this.name = 'username';
6
+ }
7
+ getQueryElement() {
8
+ return {
9
+ tag: 'username',
10
+ attrs: {}
11
+ };
12
+ }
13
+ getUserElement(user) {
14
+ void user;
15
+ return null;
16
+ }
17
+ parser(node) {
18
+ if (node.tag === 'username') {
19
+ assertNodeErrorFree(node);
20
+ return typeof node.content === 'string' ? node.content : null;
21
+ }
22
+ return null;
23
+ }
24
+ }
25
+ //# sourceMappingURL=USyncUsernameProtocol.js.map
@@ -2,4 +2,5 @@ export * from './USyncDeviceProtocol.js';
2
2
  export * from './USyncContactProtocol.js';
3
3
  export * from './USyncStatusProtocol.js';
4
4
  export * from './USyncDisappearingModeProtocol.js';
5
+ export * from './USyncUsernameProtocol.js';
5
6
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
1
  import { getBinaryNodeChild } from '../WABinary/index.js';
2
2
  import { USyncBotProfileProtocol } from './Protocols/UsyncBotProfileProtocol.js';
3
3
  import { USyncLIDProtocol } from './Protocols/UsyncLIDProtocol.js';
4
- import { USyncContactProtocol, USyncDeviceProtocol, USyncDisappearingModeProtocol, USyncStatusProtocol } from './Protocols/index.js';
4
+ import { USyncContactProtocol, USyncDeviceProtocol, USyncDisappearingModeProtocol, USyncStatusProtocol, USyncUsernameProtocol } from './Protocols/index.js';
5
5
  import { USyncUser } from './USyncUser.js';
6
6
  export class USyncQuery {
7
7
  constructor() {
@@ -23,7 +23,7 @@ export class USyncQuery {
23
23
  return this;
24
24
  }
25
25
  parseUSyncQueryResult(result) {
26
- if (!result || result.attrs.type !== 'result') {
26
+ if (result?.attrs.type !== 'result') {
27
27
  return;
28
28
  }
29
29
  const protocolMap = Object.fromEntries(this.protocols.map(protocol => {
@@ -90,5 +90,9 @@ export class USyncQuery {
90
90
  this.protocols.push(new USyncLIDProtocol());
91
91
  return this;
92
92
  }
93
+ withUsernameProtocol() {
94
+ this.protocols.push(new USyncUsernameProtocol());
95
+ return this;
96
+ }
93
97
  }
94
98
  //# sourceMappingURL=USyncQuery.js.map
@@ -11,6 +11,14 @@ export class USyncUser {
11
11
  this.phone = phone;
12
12
  return this;
13
13
  }
14
+ withUsername(username) {
15
+ this.username = username;
16
+ return this;
17
+ }
18
+ withUsernameKey(usernameKey) {
19
+ this.usernameKey = usernameKey;
20
+ return this;
21
+ }
14
22
  withType(type) {
15
23
  this.type = type;
16
24
  return this;
package/package.json CHANGED
@@ -8,7 +8,7 @@
8
8
  "require": "./lib/index.cjs"
9
9
  }
10
10
  },
11
- "version": "3.5.1",
11
+ "version": "5.0.2",
12
12
  "description": "A WebSockets library for interacting with WhatsApp Web",
13
13
  "keywords": [
14
14
  "whatsapp",
@@ -19,28 +19,26 @@
19
19
  "url": "git@github.com:WhiskeySockets/Baileys.git"
20
20
  },
21
21
  "license": "MIT",
22
- "author": "Ryuu Reinzz",
22
+ "author": "ryuu-reinzz",
23
+ "types": "lib/index.d.ts",
23
24
  "files": [
24
25
  "lib/**/*",
25
26
  "WAProto/**/*",
26
27
  "engine-requirements.js"
27
28
  ],
28
- "scripts": {
29
- "start": "node engine-requirements.js"
30
- },
31
29
  "dependencies": {
32
30
  "@cacheable/node-cache": "^1.4.0",
33
- "@ryuu-reinzz/haruka-lib": "^3.7.1",
31
+ "@ryuu-reinzz/haruka-lib": "4.0.3",
34
32
  "@hapi/boom": "^9.1.3",
35
33
  "async-mutex": "^0.5.0",
36
34
  "better-sqlite3": "^12.5.0",
37
35
  "libsignal": "npm:@ryuu-reinzz/libsignal@2.2.0",
38
36
  "lru-cache": "^11.1.0",
39
- "music-metadata": "^11.7.0",
37
+ "music-metadata": "^11.12.3",
40
38
  "p-queue": "^9.0.0",
41
39
  "pino": "^9.6",
42
40
  "protobufjs": "^8.0.0",
43
- "whatsapp-rust-bridge": "0.5.2",
41
+ "whatsapp-rust-bridge": "0.5.4",
44
42
  "ws": "^8.13.0"
45
43
  },
46
44
  "devDependencies": {
@@ -59,7 +57,7 @@
59
57
  "eslint-config-prettier": "^10.1.2",
60
58
  "eslint-plugin-prettier": "^5.4.0",
61
59
  "jest": "^30.0.5",
62
- "jimp": "^1.6.0",
60
+ "jimp": "^1.6.1",
63
61
  "jiti": "^2.4.2",
64
62
  "json": "^11.0.0",
65
63
  "link-preview-js": "^3.0.0",
@@ -67,8 +65,8 @@
67
65
  "open": "^8.4.2",
68
66
  "pino-pretty": "^13.1.1",
69
67
  "prettier": "^3.5.3",
70
- "protobufjs-cli": "^2.0.1",
71
- "release-it": "^15.10.3",
68
+ "protobufjs-cli": "^1.1.3",
69
+ "release-it": "^20.0.1",
72
70
  "ts-jest": "^29.4.0",
73
71
  "tsc-esm-fix": "^3.1.2",
74
72
  "tsx": "^4.20.3",
@@ -78,10 +76,39 @@
78
76
  },
79
77
  "peerDependencies": {
80
78
  "audio-decode": "^2.1.3",
81
- "jimp": "^1.6.0",
79
+ "jimp": "^1.6.1",
82
80
  "link-preview-js": "^3.0.0",
83
81
  "sharp": "*"
84
82
  },
83
+ "resolutions": {
84
+ "ajv@npm:^6.12.4": "^6.14.0",
85
+ "basic-ftp": "^5.2.4",
86
+ "brace-expansion@npm:^1.1.7": "^1.1.13",
87
+ "brace-expansion@npm:^2.0.1": "^2.0.3",
88
+ "flatted": "^3.4.2",
89
+ "glob@npm:^10.2.2": "^10.5.0",
90
+ "glob@npm:^10.3.10": "^10.5.0",
91
+ "glob@npm:^10.5.0": "^10.5.0",
92
+ "handlebars": "^4.7.9",
93
+ "ip-address": "^10.1.1",
94
+ "js-yaml@npm:^3.13.1": "^3.14.2",
95
+ "js-yaml@npm:^4.1.0": "^4.1.1",
96
+ "markdown-it": "^14.1.1",
97
+ "minimatch@npm:^3.0.4": "^3.1.5",
98
+ "minimatch@npm:^3.1.2": "^3.1.5",
99
+ "minimatch@npm:^5.0.1": "^5.1.8",
100
+ "minimatch@npm:^9.0.4": "^9.0.9",
101
+ "minimatch@npm:^9.0.5": "^9.0.9",
102
+ "picomatch@npm:^2.0.4": "^2.3.2",
103
+ "picomatch@npm:^2.3.1": "^2.3.2",
104
+ "picomatch@npm:^4.0.0": "^4.0.4",
105
+ "picomatch@npm:^4.0.2": "^4.0.4",
106
+ "socks": "^2.8.8",
107
+ "tar": "^7.5.11",
108
+ "tmp": "^0.2.5",
109
+ "underscore": "^1.13.8",
110
+ "yaml@npm:^2.6.1": "^2.8.4"
111
+ },
85
112
  "peerDependenciesMeta": {
86
113
  "audio-decode": {
87
114
  "optional": true