@neelegirly/baileys 2.2.29 → 2.2.31

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/LICENSE CHANGED
@@ -1,6 +1,11 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2025 Neele
3
+ Copyright (c) 2025 Rajeh Taher/WhiskeySockets (Baileys, upstream)
4
+ Copyright (c) 2025 Neele Girl (@neelegirly/baileys, fork)
5
+
6
+ This project is a fork of Baileys (https://github.com/WhiskeySockets/Baileys)
7
+ and contains substantial portions of that software. The upstream copyright
8
+ notice above is retained as required by the MIT license.
4
9
 
5
10
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
11
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -6,23 +6,41 @@
6
6
  ### *QR Branding · Self-Healing WA-Web-Version · Wrapper-Aware Update Notify · LID · Smart Queue*
7
7
 
8
8
  [![npm](https://img.shields.io/npm/v/%40neelegirly%2Fbaileys?style=for-the-badge&color=ff69b4&logo=npm)](https://www.npmjs.com/package/@neelegirly/baileys)
9
- [![wa-api](https://img.shields.io/badge/wa--api-1.8.10-c77dff?style=for-the-badge)](https://www.npmjs.com/package/@neelegirly/wa-api)
10
- [![libsignal](https://img.shields.io/badge/libsignal-1.0.32-f4a261?style=for-the-badge)](https://www.npmjs.com/package/@neelegirly/libsignal)
11
- [![WA-Web](https://img.shields.io/badge/WhatsApp--Web-2.3000.1035194821-25D366?style=for-the-badge&logo=whatsapp)](https://web.whatsapp.com)
9
+ [![wa-api](https://img.shields.io/badge/wa--api-1.8.13-c77dff?style=for-the-badge)](https://www.npmjs.com/package/@neelegirly/wa-api)
10
+ [![libsignal](https://img.shields.io/badge/libsignal-1.0.33-f4a261?style=for-the-badge)](https://www.npmjs.com/package/@neelegirly/libsignal)
11
+ [![WA-Web](https://img.shields.io/badge/WhatsApp--Web-2.3000.1043857760-25D366?style=for-the-badge&logo=whatsapp)](https://web.whatsapp.com)
12
12
  [![Node](https://img.shields.io/badge/Node-16+-4caf50?style=for-the-badge&logo=node.js)](https://nodejs.org)
13
13
 
14
14
  <p align="center">
15
15
  <img src="https://files.catbox.moe/5bqumy.jpeg" width="780" alt="@neelegirly/baileys Hero" />
16
16
  </p>
17
17
 
18
- <p align="center"><sub>2026 Glow-Up Edition · self-healing QR/Pairing · Companion-Stack auf <strong>2.2.26 / 1.8.10 / 1.0.32</strong></sub></p>
18
+ <p align="center"><sub>2026 Glow-Up Edition · self-healing QR/Pairing · Companion-Stack auf <strong>2.2.31 / 1.8.14 / 1.0.33</strong></sub></p>
19
19
 
20
- [**Installation**](#-installation) · [**Quickstart**](#-quickstart) · [**Was ist dieser Fork?**](#-was-ist-dieser-fork) · [**Versionsschema**](#-versionsschema) · [**Message-ID**](#-message-id-anpassung-neele) · [**Release Notes**](#-release-notes-2226)
20
+ [**Installation**](#-installation) · [**Quickstart**](#-quickstart) · [**Was ist dieser Fork?**](#-was-ist-dieser-fork) · [**Versionsschema**](#-versionsschema) · [**Message-ID**](#-message-id-anpassung-neele) · [**Release Notes**](#-release-notes-2230)
21
21
 
22
22
  </div>
23
23
 
24
24
  ---
25
25
 
26
+ > ### ⚠️ Das hier ist **NICHT** `WhiskeySockets/Baileys`
27
+ >
28
+ > `@neelegirly/baileys` ist ein **eigenständiger Fork**, gepflegt von **Neele Girl**.
29
+ > Eigene Versionszählung (`2.2.x`, **nicht** `6.7.x` / `7.x`), eigene Anpassungen:
30
+ > **Multi-Buttons** (`interactiveMessage` / `carouselMessage` / `nativeFlow`),
31
+ > **QR-/Pairing-Stabilität**, self-healing WA-Web-Version, eigene Message-ID-Signatur,
32
+ > `Store`-Layer und Mongo-/Single-File-Auth-States.
33
+ >
34
+ > Bug-Reports gehören zu **[neelegirly/baileys/issues](https://github.com/neelegirly/baileys/issues)** —
35
+ > **nicht** ins Upstream-Repo. Umgekehrt gilt: Upstream-Issues/PRs treffen auf diesen Fork
36
+ > oft nicht zu, weil er strukturell abweicht.
37
+ >
38
+ > Basiert auf **[Baileys](https://github.com/WhiskeySockets/Baileys)** von Rajeh Taher/WhiskeySockets,
39
+ > MIT-lizenziert — deren Copyright-Vermerk bleibt in der [LICENSE](LICENSE) erhalten. Danke für die Grundlage. 🌸
40
+ > Nicht offiziell mit WhatsApp, Meta oder dem Baileys-Upstream verbunden.
41
+
42
+ ---
43
+
26
44
  ## 🌷 Was ist dieser Fork?
27
45
 
28
46
  `@neelegirly/baileys` ist ein gepflegter **Fork von [Baileys](https://github.com/WhiskeySockets/Baileys)** (multi-device WhatsApp-Web-API für Node.js). Er bleibt nah am Upstream, ergänzt aber ein paar fokussierte Neelegirly-Eigenheiten:
@@ -61,8 +79,8 @@ Wichtig zu verstehen — hier laufen **zwei voneinander unabhängige** Versionsn
61
79
 
62
80
  | Nummer | Beispiel | Bedeutung |
63
81
  | --- | --- | --- |
64
- | **Fork-Version** | `2.2.26` | Die npm-Version *dieses Pakets*. Eigenes semver-Schema von Neelegirly – **nicht** identisch mit der Upstream-Baileys-Versionsnummer. |
65
- | **WhatsApp-Web-Baseline** | `2.3000.1035194821` | Die Client-Version, die im Handshake an WhatsApp gemeldet wird. Wird zur Laufzeit aktuell gehalten (self-healing). |
82
+ | **Fork-Version** | `2.2.31` | Die npm-Version *dieses Pakets*. Eigenes semver-Schema von Neelegirly – **nicht** identisch mit der Upstream-Baileys-Versionsnummer. |
83
+ | **WhatsApp-Web-Baseline** | `2.3000.1043857760` | Die Client-Version, die im Handshake an WhatsApp gemeldet wird. Wird zur Laufzeit aktuell gehalten (self-healing). |
66
84
 
67
85
  Die Fork-Version `2.2.x` ist also reines Paket-Versioning. Welche WhatsApp-Web-Version tatsächlich verbunden wird, zeigt der Boot-Banner und `fetchLatestBaileysVersion()`.
68
86
 
@@ -84,14 +102,14 @@ generateMessageID() // → z. B. "3AC18D8ANEELE3B14420"
84
102
  ## 🚀 Installation
85
103
 
86
104
  ```bash
87
- npm install @neelegirly/baileys@2.2.26 @neelegirly/libsignal@1.0.32 --save-exact
105
+ npm install @neelegirly/baileys@2.2.31 @neelegirly/libsignal@1.0.33 --save-exact
88
106
  ```
89
107
 
90
108
  ```bash
91
- yarn add @neelegirly/baileys@2.2.26 @neelegirly/libsignal@1.0.32 --exact
109
+ yarn add @neelegirly/baileys@2.2.31 @neelegirly/libsignal@1.0.33 --exact
92
110
  ```
93
111
 
94
- > Für den kompletten Stack passt dazu `@neelegirly/wa-api@1.8.10`.
112
+ > Für den kompletten Stack passt dazu `@neelegirly/wa-api@1.8.13`.
95
113
 
96
114
  ### Update eines bestehenden Setups
97
115
 
@@ -146,9 +164,9 @@ start().catch(console.error)
146
164
 
147
165
  | Paket | Version | Rolle |
148
166
  |------|---------|-------|
149
- | `@neelegirly/baileys` | `2.2.26` | Socket, Events, Messaging |
150
- | `@neelegirly/libsignal` | `1.0.32` | Signal-Protokoll-Komponente |
151
- | `@neelegirly/wa-api` | `1.8.10` | Lifecycle-, Session- und Update-Wrapper |
167
+ | `@neelegirly/baileys` | `2.2.31` | Socket, Events, Messaging |
168
+ | `@neelegirly/libsignal` | `1.0.33` | Signal-Protokoll-Komponente |
169
+ | `@neelegirly/wa-api` | `1.8.13` | Lifecycle-, Session- und Update-Wrapper |
152
170
 
153
171
  ---
154
172
 
@@ -167,13 +185,29 @@ Beim QR-Scan werden Markenzeilen ober- und unterhalb des QR-Codes ausgegeben. Ve
167
185
 
168
186
  ---
169
187
 
170
- ## 📝 Release Notes `2.2.26`
171
-
172
- - 🛠️ **QR-/Pairing-Login repariert.** Die veraltete, hartcodierte WhatsApp-Web-Version führte zu `statusCode 405` ("Multi-device mismatch") und verhinderte jeden QR-Scan. Baseline auf `2.3000.1035194821` aktualisiert.
173
- - 🌐 **Self-Healing WA-Web-Version.** `fetchLatestBaileysVersion()` bezieht die Versionsangabe jetzt aus einer **gepflegten, immer aktuellen Quelle** statt aus einer toten URL (die zuvor mit `404` ins Leere lief und still eine veraltete Version pinnte). Künftige WhatsApp-Versions-Bumps heilen sich damit selbst.
174
- - 🧷 **Message-ID-Logik unverändert.** Die `NEELE`-Signatur in `generateMessageID` / `generateMessageIDV2` bleibt exakt erhalten.
175
- - 🪧 **Modernisierter Boot-Banner.** Zusätzliche, ehrliche Zeile mit der aktiven WhatsApp-Web-Baseline.
176
- - 🔗 Companion-Stack auf `2.2.26 / 1.8.10 / 1.0.32` aktualisiert.
188
+ ## 📝 Release Notes `2.2.31`
189
+
190
+ - 🔐 **„Warte auf diese Nachricht“: Gerät beim Entschlüsseln erhalten.** Sessions von Zweitgeräten (WhatsApp Web/Desktop) landeten im Datensatz des Handys, der Bot verschlüsselte ans Handy danach mit dem falschen Schlüssel.
191
+ - 🔁 **Retry repariert.** Neuzustellung an die echte Geräteadresse (vorher eine erfundene `<lid>@s.whatsapp.net`), beide Adressen (LID + Nummer) frisch, Schlüssel direkt aus der Retry-Anfrage (portiert aus WhiskeySockets 7.0.0-rc14, MIT), Logzeile `[ONIMAI retry]`.
192
+ - 🗝️ **Signal-Sessions:** kein Ersatz durch fremde Geräte, max. 40 Sessions je Datensatz, keine ~200 Lesezugriffe je Nachricht mehr.
193
+ - 🧩 **Multi-Buttons / Native Flow / Carousel** und **Umfrage-Stimmen** ohne patch-package.
194
+ - 🧷 NEELE-Message-IDs, QR/Pairing, Store, Auth-Helfer unverändert. Details: `CHANGELOG.md`.
195
+ - 🔗 Companion-Stack: `2.2.31 / 1.8.14 / 1.0.33`.
196
+
197
+ ## 📝 Release Notes `2.2.30`
198
+
199
+ - 🔧 **`fetchLatestWaWebVersion()` repariert.** Die Guard-Zeile las `match?.match[1]` statt `match?.[1]` und warf dadurch **bei jedem Aufruf** einen `TypeError`, der im `catch` verschwand. Die Funktion fiel deshalb *immer* still auf die eingebaute Baseline zurück und meldete `isLatest: false` — sie hat nie funktioniert. Jetzt liefert sie die echte Live-Version von `web.whatsapp.com/sw.js`.
200
+ - 📌 **WA-Web-Baseline aktualisiert** auf `2.3000.1043857760` (vorher `2.3000.1035194821`). Das ist nur der Offline-Notnagel: `fetchLatestBaileysVersion()` holt die Version weiterhin zur Laufzeit. Greift also, wenn beim Start kein Netz zur Versionsquelle besteht.
201
+ - ⚖️ **LICENSE korrigiert.** Der MIT-Copyright-Vermerk des Upstreams (Rajeh Taher/WhiskeySockets) war entfernt worden — MIT verlangt ihn aber bei substanziellen Teilen. Er steht jetzt wieder drin, neben dem Fork-Copyright.
202
+ - 🏷️ **Klarere Abgrenzung.** README-Kopf, `description` und `contributors` machen unmissverständlich, dass dies ein eigenständiger Fork von Neele Girl ist und **nicht** `WhiskeySockets/Baileys`.
203
+ - 🧷 **Message-ID- und QR-/Pairing-Logik unverändert.** Kein Byte an `generateMessageID` / `generateMessageIDV2` (`NEELE`-Signatur) oder am QR-/Pairing-Flow.
204
+ - 🔗 Companion-Stack: `2.2.30 / 1.8.13 / 1.0.33`.
205
+
206
+ > **Kein Upstream-Merge.** Dieser Fork weicht strukturell von `WhiskeySockets/Baileys` ab
207
+ > (eigener `Store`-Layer, `Socket/registration`, `WASignalGroup`, eigene Message-IDs; Upstream 7.x
208
+ > setzt inzwischen auf `whatsapp-rust-bridge` und hat `Store` entfernt). Ein mechanischer Merge
209
+ > würde den Fork zerlegen. Der einzige Punkt, der Logins wirklich bricht — die WhatsApp-Web-Version —
210
+ > wird zur Laufzeit self-healing nachgezogen.
177
211
 
178
212
  ---
179
213
 
@@ -1 +1 @@
1
- {"version":[2,3000,1035194821]}
1
+ {"version":[2,3000,1043857760]}
@@ -145,15 +145,16 @@ function makeLibSignalRepository(auth, logger, pnFromLIDUSync) {
145
145
  if (!user) {
146
146
  return []
147
147
  }
148
+ // ONIMAI(retry-lid): nur DASSELBE Geraet unter seiner anderen Adresse (PN <-> LID).
149
+ // Frueher kam bei Geraet != 0 auch die Session von Geraet 0 als Ersatz in Frage.
150
+ // Das ist ein anderes Geraet mit anderen Schluesseln: damit verschluesselt, kann
151
+ // das Zielgeraet nichts lesen, und die kopierte Session spaltet die Kette auf.
148
152
  const resolved = []
149
153
  const mappedPn = await lidMapping.getPNForLID(`${user}@lid`)
150
154
  if (mappedPn) {
151
155
  const pnUser = jidUserPart(mappedPn)
152
156
  if (pnUser) {
153
157
  resolved.push(`${pnUser}.${device || '0'}`)
154
- if ((device || '0') !== '0') {
155
- resolved.push(`${pnUser}.0`)
156
- }
157
158
  }
158
159
  }
159
160
  const mappedLid = await lidMapping.getLIDForPN(`${user}@s.whatsapp.net`)
@@ -161,9 +162,6 @@ function makeLibSignalRepository(auth, logger, pnFromLIDUSync) {
161
162
  const lidUser = jidUserPart(mappedLid)
162
163
  if (lidUser) {
163
164
  resolved.push(`${lidUser}.${device || '0'}`)
164
- if ((device || '0') !== '0') {
165
- resolved.push(`${lidUser}.0`)
166
- }
167
165
  }
168
166
  }
169
167
  return unique(resolved.filter((candidate) => candidate !== id))
@@ -173,9 +171,20 @@ function makeLibSignalRepository(auth, logger, pnFromLIDUSync) {
173
171
  if (!normalized || !normalized.includes('@')) {
174
172
  return []
175
173
  }
176
- if (type !== 'msg' || hasExplicitDevice(jid)) {
177
- return [jidToSignalProtocolAddress(String(jid || '').trim()).toString()]
174
+ const exactId = jidToSignalProtocolAddress(String(jid || '').trim()).toString()
175
+ // pkmsg baut eine Session auf: genau unter der Adresse des Absendergeraets
176
+ if (type !== 'msg') {
177
+ return [exactId]
178
178
  }
179
+ // ONIMAI(retry-lid): eine JID ohne Geraeteteil IST Geraet 0. Frueher wurden hier
180
+ // die Sessions der Geraete 0..99 beider Adressen probiert — rund 200 Lesezugriffe
181
+ // je Nachricht (der Zwischenspeicher wird bei jedem Speichern geleert), und
182
+ // Sessions fremder Geraete koennen eine Nachricht ohnehin nie entschluesseln.
183
+ // Jetzt: dasselbe Geraet unter PN und LID; bei Geraet != 0 zusaetzlich der
184
+ // Datensatz von Geraet 0 — dort landeten bis 10/2026 die Sessions ALLER Geraete
185
+ // (decode-wa-message strich das Geraet weg). Ohne diesen Rueckgriff braeuchte
186
+ // jedes Zweitgeraet nach dem Update erst einen Retry.
187
+ const device = WABinary_1.jidDecode(String(jid || '').trim())?.device || 0
179
188
  const relatedJids = [normalized]
180
189
  if (/@lid$/i.test(normalized)) {
181
190
  const mappedPn = await lidMapping.getPNForLID(normalized)
@@ -191,26 +200,23 @@ function makeLibSignalRepository(auth, logger, pnFromLIDUSync) {
191
200
  }
192
201
  const sessionUsers = unique(relatedJids.map((value) => jidUserPart(value)).filter(Boolean))
193
202
  if (!sessionUsers.length) {
194
- return [jidToSignalProtocolAddress(normalized).toString()]
203
+ return [exactId]
195
204
  }
196
- const cacheKey = sessionUsers.slice().sort().join('|')
205
+ const cacheKey = `${sessionUsers.slice().sort().join('|')}#${device}`
197
206
  const cached = sessionAddressCache.get(cacheKey)
198
207
  if (cached?.length) {
199
208
  return [...cached]
200
209
  }
201
- const candidateIds = []
202
- for (const user of sessionUsers) {
203
- for (let device = 0; device <= 99; device += 1) {
204
- candidateIds.push(`${user}.${device}`)
205
- }
206
- }
207
- const existing = candidateIds.length
208
- ? await auth.keys.get('session', candidateIds)
209
- : {}
210
+ const candidateIds = unique([
211
+ exactId,
212
+ ...sessionUsers.map((user) => `${user}.${device}`),
213
+ ...(device !== 0 ? sessionUsers.map((user) => `${user}.0`) : [])
214
+ ])
215
+ const existing = await auth.keys.get('session', candidateIds)
210
216
  const orderedIds = candidateIds.filter((candidateId) => !!existing?.[candidateId])
211
217
  const finalIds = orderedIds.length
212
218
  ? orderedIds
213
- : [jidToSignalProtocolAddress(normalized).toString()]
219
+ : [exactId]
214
220
  sessionAddressCache.set(cacheKey, finalIds)
215
221
  return [...finalIds]
216
222
  }
@@ -376,6 +382,17 @@ function signalStorage({ creds, keys }, helpers = {}) {
376
382
  }
377
383
  },
378
384
  storeSession: async (id, session) => {
385
+ // ONIMAI(retry-lid): libsignal kappt alte Sessions nur beim Ver-/Entschluesseln,
386
+ // nicht beim Aufbau (initOutgoing). Jeder erzwungene Neuaufbau haengte deshalb
387
+ // eine Session an: 1207 Stueck / 1 MB fuer ein einziges Geraet. Hier wie in
388
+ // libsignal auf 40 geschlossene begrenzen; die offene Session bleibt immer.
389
+ try {
390
+ if (typeof session?.removeOldSessions === 'function') {
391
+ session.removeOldSessions()
392
+ }
393
+ } catch (_error) {
394
+ // "Corrupt sessions object" o. ae.: lieber unveraendert speichern als nichts
395
+ }
379
396
  await keys.set({ 'session': { [id]: session.serialize() } })
380
397
  if (typeof invalidateSessionAddressCache === 'function') {
381
398
  invalidateSessionAddressCache()
@@ -27,6 +27,82 @@ const ENFORCEMENT_TYPE_VALUES = new Set(
27
27
  const isValidEnforcementType = (value) =>
28
28
  typeof value === "string" && ENFORCEMENT_TYPE_VALUES.has(value);
29
29
 
30
+ // ONIMAI(retry-lid): Der Baileys-Logger steht in wa-api auf "silent". Ob eine
31
+ // Retry-Anfrage ("Warte auf diese Nachricht") beantwortet wurde, war deshalb nie
32
+ // sichtbar. Eine Zeile je Ereignis, hoechstens 30 pro Minute.
33
+ // Abschaltbar mit ONIMAI_LOG_RETRY_RESEND=0.
34
+ const onimaiRetryLogState = { windowStart: 0, lines: 0, dropped: 0 };
35
+ const onimaiRetryLog = (stage, info = {}) => {
36
+ if (process.env.ONIMAI_LOG_RETRY_RESEND === "0") return;
37
+ try {
38
+ const now = Date.now();
39
+ if (now - onimaiRetryLogState.windowStart > 60000) {
40
+ if (onimaiRetryLogState.dropped) {
41
+ console.warn(`[ONIMAI retry] ${onimaiRetryLogState.dropped} weitere Zeilen unterdrueckt`);
42
+ }
43
+ onimaiRetryLogState.windowStart = now;
44
+ onimaiRetryLogState.lines = 0;
45
+ onimaiRetryLogState.dropped = 0;
46
+ }
47
+ if (onimaiRetryLogState.lines >= 30) {
48
+ onimaiRetryLogState.dropped += 1;
49
+ return;
50
+ }
51
+ onimaiRetryLogState.lines += 1;
52
+ const parts = [`[ONIMAI retry] ${stage}`];
53
+ for (const [k, v] of Object.entries(info)) {
54
+ if (v !== undefined && v !== null && v !== "") parts.push(`${k}=${v}`);
55
+ }
56
+ console.warn(parts.join(" "));
57
+ } catch (_) {
58
+ /* Logging darf den Empfang nie stoeren */
59
+ }
60
+ };
61
+
62
+ // ONIMAI(retry-bundle): portiert aus WhiskeySockets/Baileys 7.0.0-rc14,
63
+ // Utils/signal.js `extractE2ESessionFromRetryReceipt` (MIT, (c) WhiskeySockets).
64
+ // Das anfragende Geraet schickt in der Retry-Anfrage seine EIGENEN aktuellen
65
+ // Schluessel mit (<keys>). Daraus gebaut passt die Session garantiert zu genau
66
+ // diesem Geraet — kein Umweg ueber den Server (spart auch eine Abfrage).
67
+ const onimaiIsValidUInt = (n) => typeof n === "number" && Number.isInteger(n);
68
+ const onimaiBundleFromRetryReceipt = (receipt) => {
69
+ try {
70
+ const keysNode = WABinary_1.getBinaryNodeChild(receipt, "keys");
71
+ if (!keysNode) return null;
72
+ const typeBuf = WABinary_1.getBinaryNodeChildBuffer(keysNode, "type");
73
+ if (!typeBuf || typeBuf.length !== 1 || typeBuf[0] !== Defaults_1.KEY_BUNDLE_TYPE[0]) return null;
74
+ const identity = WABinary_1.getBinaryNodeChildBuffer(keysNode, "identity");
75
+ const skey = WABinary_1.getBinaryNodeChild(keysNode, "skey");
76
+ if (!identity || identity.length !== 32 || !skey) return null;
77
+ const registrationId = WABinary_1.getBinaryNodeChildUInt(receipt, "registration", 4);
78
+ if (!onimaiIsValidUInt(registrationId)) return null;
79
+ const signedPubKey = WABinary_1.getBinaryNodeChildBuffer(skey, "value");
80
+ const signedSig = WABinary_1.getBinaryNodeChildBuffer(skey, "signature");
81
+ const signedKeyId = WABinary_1.getBinaryNodeChildUInt(skey, "id", 3);
82
+ if (!signedPubKey || signedPubKey.length !== 32 || !signedSig || !onimaiIsValidUInt(signedKeyId)) return null;
83
+ let preKey;
84
+ const preKeyNode = WABinary_1.getBinaryNodeChild(keysNode, "key");
85
+ if (preKeyNode) {
86
+ const preKeyPub = WABinary_1.getBinaryNodeChildBuffer(preKeyNode, "value");
87
+ const preKeyId = WABinary_1.getBinaryNodeChildUInt(preKeyNode, "id", 3);
88
+ if (!preKeyPub || preKeyPub.length !== 32 || !onimaiIsValidUInt(preKeyId)) return null;
89
+ preKey = { keyId: preKeyId, publicKey: Utils_1.generateSignalPubKey(preKeyPub) };
90
+ }
91
+ return {
92
+ registrationId,
93
+ identityKey: Utils_1.generateSignalPubKey(identity),
94
+ signedPreKey: {
95
+ keyId: signedKeyId,
96
+ publicKey: Utils_1.generateSignalPubKey(signedPubKey),
97
+ signature: signedSig,
98
+ },
99
+ preKey,
100
+ };
101
+ } catch (_error) {
102
+ return null;
103
+ }
104
+ };
105
+
30
106
  const makeMessagesRecvSocket = (config) => {
31
107
  const {
32
108
  logger,
@@ -1147,7 +1223,7 @@ const makeMessagesRecvSocket = (config) => {
1147
1223
  msgRetryCache.set(key, newValue);
1148
1224
  };
1149
1225
 
1150
- const sendMessagesAgain = async (key, ids, retryNode) => {
1226
+ const sendMessagesAgain = async (key, ids, retryNode, receiptNode) => {
1151
1227
  // ╭─ OniSelf fork fix (bug ≤2.2.26, shipped in 2.2.27) ───────────────────╮
1152
1228
  // │ BUG: this fork populates messageRetryManager's recent-message cache │
1153
1229
  // │ on every outgoing send (enableRecentMessageCache defaults to true, │
@@ -1175,8 +1251,51 @@ const makeMessagesRecvSocket = (config) => {
1175
1251
  // if it's the primary jid sending the request
1176
1252
  // just re-send the message to everyone
1177
1253
  // prevents the first message decryption failure
1254
+ // (wie WhiskeySockets: Hauptgeraet -> an alle, Zweitgeraet -> gezielt. Ein gezielter
1255
+ // Gruppen-Resend an "<nummer>@lid" ohne Geraeteteil kam im Live-Test nicht an.)
1178
1256
  const sendToAll = !WABinary_1.jidDecode(participant)?.device;
1179
- await assertSessions([participant], true);
1257
+ // ONIMAI(retry-lid): dasselbe Geraet hat zwei Adressen (LID + Telefonnummer). Der
1258
+ // Retry kommt meist ueber die LID, der normale Sendeweg (auch "an alle") nimmt in
1259
+ // diesem Fork aber die Nummer. Wurde nur die LID-Session erneuert, lief die Nachricht
1260
+ // wieder ueber die alte, fuer das Geraet unlesbare Nummern-Session. Beide frisch.
1261
+ const retrySessionJids = [participant];
1262
+ try {
1263
+ const decodedParticipant = WABinary_1.jidDecode(participant);
1264
+ const mapping = signalRepository?.lidMapping;
1265
+ if (decodedParticipant?.user && mapping) {
1266
+ let counterpart = null;
1267
+ if (WABinary_1.isLidUser(participant)) {
1268
+ counterpart = await mapping.getPNForLID?.(`${decodedParticipant.user}@lid`);
1269
+ } else if (WABinary_1.isJidUser(participant)) {
1270
+ counterpart = await mapping.getLIDForPN?.(`${decodedParticipant.user}@s.whatsapp.net`);
1271
+ }
1272
+ const decodedCounterpart = counterpart ? WABinary_1.jidDecode(counterpart) : null;
1273
+ if (decodedCounterpart?.user && decodedCounterpart.user !== decodedParticipant.user) {
1274
+ retrySessionJids.push(
1275
+ WABinary_1.jidEncode(decodedCounterpart.user, decodedCounterpart.server, decodedParticipant.device)
1276
+ );
1277
+ }
1278
+ }
1279
+ } catch (_error) {
1280
+ /* ohne Zuordnung bleibt es bei der Adresse aus dem Retry */
1281
+ }
1282
+ // ONIMAI(retry-bundle): Schluessel aus der Retry-Anfrage selbst (s. o.) fuer die
1283
+ // Adresse aus dem Retry; die zweite Adresse holt wie bisher frisch vom Server
1284
+ // (ein Einmal-Prekey darf nicht fuer zwei Sessions benutzt werden).
1285
+ let injectedFromBundle = false;
1286
+ const bundle = receiptNode ? onimaiBundleFromRetryReceipt(receiptNode) : null;
1287
+ if (bundle) {
1288
+ try {
1289
+ await signalRepository.injectE2ESession({ jid: participant, session: bundle });
1290
+ injectedFromBundle = true;
1291
+ } catch (error) {
1292
+ logger.warn({ error: error?.message, participant }, "failed to inject session from retry receipt");
1293
+ }
1294
+ }
1295
+ const sessionJidsToFetch = injectedFromBundle ? retrySessionJids.slice(1) : retrySessionJids;
1296
+ if (sessionJidsToFetch.length) {
1297
+ await assertSessions(sessionJidsToFetch, true);
1298
+ }
1180
1299
 
1181
1300
  if (WABinary_1.isJidGroup(remoteJid)) {
1182
1301
  await authState.keys.set({ "sender-key-memory": { [remoteJid]: null } });
@@ -1193,7 +1312,12 @@ const makeMessagesRecvSocket = (config) => {
1193
1312
  const msgRelayOpts = { messageId: ids[i] };
1194
1313
 
1195
1314
  if (sendToAll) {
1196
- msgRelayOpts.useUserDevicesCache = false;
1315
+ // Geraeteliste im Einzelchat frisch (wie Upstream). In Gruppen haette das die
1316
+ // Listen ALLER Mitglieder neu abgefragt — je Retry (rate-overlimit); die Liste
1317
+ // des Anfragenden haelt der devices-Hinweis (2.2.29) ohnehin aktuell.
1318
+ if (!WABinary_1.isJidGroup(remoteJid)) {
1319
+ msgRelayOpts.useUserDevicesCache = false;
1320
+ }
1197
1321
  } else {
1198
1322
  msgRelayOpts.participant = {
1199
1323
  jid: participant,
@@ -1202,11 +1326,20 @@ const makeMessagesRecvSocket = (config) => {
1202
1326
  }
1203
1327
 
1204
1328
  await relayMessage(key.remoteJid, msg, msgRelayOpts);
1329
+ onimaiRetryLog("resent", {
1330
+ jid: key.remoteJid,
1331
+ id: ids[i],
1332
+ participant,
1333
+ count: retryNode?.attrs?.count,
1334
+ to: sendToAll ? "all" : "device",
1335
+ keys: injectedFromBundle ? "receipt" : "server",
1336
+ });
1205
1337
  } else {
1206
1338
  logger.debug(
1207
1339
  { jid: key.remoteJid, id: ids[i] },
1208
1340
  "recv retry request, but message not available"
1209
1341
  );
1342
+ onimaiRetryLog("missing", { jid: key.remoteJid, id: ids[i], participant, count: retryNode?.attrs?.count });
1210
1343
  }
1211
1344
  }
1212
1345
  };
@@ -1297,12 +1430,18 @@ const makeMessagesRecvSocket = (config) => {
1297
1430
  if (key.fromMe) {
1298
1431
  try {
1299
1432
  logger.debug({ attrs, key }, "recv retry request");
1300
- await sendMessagesAgain(key, ids, retryNode);
1433
+ await sendMessagesAgain(key, ids, retryNode, node);
1301
1434
  } catch (error) {
1302
1435
  logger.error(
1303
1436
  { key, ids, trace: error.stack },
1304
1437
  "error in sending message again"
1305
1438
  );
1439
+ onimaiRetryLog("failed", {
1440
+ jid: key.remoteJid,
1441
+ id: ids[0],
1442
+ participant: key.participant,
1443
+ error: String(error?.message || error).slice(0, 120),
1444
+ });
1306
1445
  }
1307
1446
  } else {
1308
1447
  logger.info(
@@ -1315,6 +1454,7 @@ const makeMessagesRecvSocket = (config) => {
1315
1454
  { attrs, key },
1316
1455
  "will not send message again, as sent too many times"
1317
1456
  );
1457
+ onimaiRetryLog("limit", { jid: key.remoteJid, id: ids[0], participant: key.participant });
1318
1458
  }
1319
1459
  }
1320
1460
  }),
@@ -2015,4 +2155,6 @@ const makeMessagesRecvSocket = (config) => {
2015
2155
 
2016
2156
  module.exports = {
2017
2157
  makeMessagesRecvSocket,
2158
+ // fuer Tests (tests/wa_retry_lid_geraet.test.mjs in Onimai)
2159
+ onimaiBundleFromRetryReceipt,
2018
2160
  };
@@ -608,9 +608,13 @@ const makeMessagesSocket = (config) => {
608
608
  additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' }
609
609
  }
610
610
 
611
- const { user, device } = WABinary_1.jidDecode(participant.jid)
611
+ const { user, device, server } = WABinary_1.jidDecode(participant.jid)
612
612
 
613
- devices.push({ user, device })
613
+ // ONIMAI(retry-lid): Server + JID des anfragenden Geraets behalten.
614
+ // Vorher wurde im Gruppenzweig daraus "<lid-nummer>:<geraet>@s.whatsapp.net"
615
+ // gebaut — eine Telefonnummer, die es nicht gibt. Die Neuzustellung kam
616
+ // nie an, der Empfaenger blieb auf "Warte auf diese Nachricht".
617
+ devices.push({ user, device, server, jid: participant.jid })
614
618
  }
615
619
 
616
620
  await authState.keys.transaction(async () => {
@@ -640,7 +644,16 @@ const makeMessagesSocket = (config) => {
640
644
  }
641
645
 
642
646
  else if (!isStatus) {
643
- groupData = await groupMetadata(jid)
647
+ try {
648
+ groupData = await groupMetadata(jid)
649
+ } catch (error) {
650
+ // ONIMAI(retry-lid): Eine gezielte Neuzustellung an EIN Geraet braucht
651
+ // die Teilnehmerliste nicht. Drosselt WhatsApp die Gruppenabfrage
652
+ // (rate-overlimit), darf der Retry daran nicht scheitern.
653
+ if (!participant) throw error
654
+ logger.debug({ jid, error: error?.message }, 'group metadata unavailable for targeted resend')
655
+ groupData = undefined
656
+ }
644
657
  groupData = sanitizeGroupMetadataParticipants(groupData)
645
658
  }
646
659
 
@@ -692,7 +705,10 @@ const makeMessagesSocket = (config) => {
692
705
  throw new boom_1.Boom('Per-jid patching is not supported in groups')
693
706
  }
694
707
  const bytes = Utils_1.encodeWAMessage(patched)
695
- const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid'
708
+ // ONIMAI(retry-lid): ohne Gruppendaten verraet die Adresse des anfragenden Geraets den Modus
709
+ const groupAddressingMode = additionalAttributes?.['addressing_mode']
710
+ || groupData?.addressingMode
711
+ || (participant && !WABinary_1.isLidUser(participant.jid) ? 'pn' : 'lid')
696
712
  const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId
697
713
 
698
714
  const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
@@ -164,12 +164,28 @@ const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
164
164
  category: stanza.attrs.category,
165
165
  author,
166
166
  async decrypt() {
167
+ // ONIMAI(retry-lid): Geraet des Absenders. Die Signal-Adresse ist (Nummer, GERAET).
168
+ // Frueher strich jidNormalizedUser das Geraet weg: ein pkmsg von WhatsApp Web
169
+ // (z. B. Geraet 5) baute seine Session im Datensatz von Geraet 0 (Handy) auf und
170
+ // wurde dort die offene Session. Der Bot verschluesselte ans Handy danach mit dem
171
+ // Schluessel des anderen Geraets -> "Warte auf diese Nachricht" auf dem Handy.
172
+ // participant_pn traegt das Geraet nicht immer, darum aus der Original-Adresse.
173
+ const senderDevice = (() => {
174
+ const decoded = WABinary_1.jidDecode(String(stanza.attrs.participant || stanza.attrs.from || '').trim())
175
+ return typeof decoded?.device === 'number' ? decoded.device : undefined
176
+ })()
167
177
  const normalizeDecryptJid = (jid = '') => {
168
178
  const value = String(jid || '').trim()
169
179
  if (!value || !value.includes('@')) {
170
180
  return ''
171
181
  }
172
- return WABinary_1.jidNormalizedUser(value)
182
+ const decoded = WABinary_1.jidDecode(value)
183
+ if (!decoded?.user) {
184
+ return ''
185
+ }
186
+ const server = decoded.server === 'c.us' ? 's.whatsapp.net' : decoded.server
187
+ const device = typeof decoded.device === 'number' ? decoded.device : senderDevice
188
+ return WABinary_1.jidEncode(decoded.user, server, device)
173
189
  }
174
190
  let decryptables = 0
175
191
  if (Array.isArray(stanza.content)) {
@@ -424,8 +424,8 @@ const fetchLatestWaWebVersion = async (options) => {
424
424
  responseType: 'json'
425
425
  })
426
426
  const regex = /\\?"client_revision\\?":\s*(\d+)/
427
- const match = data.match(regex)
428
- if (!match?.match[1]) {
427
+ const match = String(data).match(regex)
428
+ if (!match?.[1]) {
429
429
  return {
430
430
  version: baileys_version_json_1.version,
431
431
  isLatest: false,
@@ -748,6 +748,10 @@ const generateWAMessageContent = async (message, options) => {
748
748
  m.requestPhoneNumberMessage = {}
749
749
  }
750
750
 
751
+ else if ('interactiveMessage' in message || 'viewOnceMessage' in message || 'viewOnceMessageV2' in message || 'viewOnceMessageV2Extension' in message) {
752
+ m = message;
753
+ }
754
+
751
755
  else {
752
756
  const mess = await prepareWAMessageMedia(message, options)
753
757
  const [type] = Object.keys(mess)
@@ -406,7 +406,7 @@ const jid2 = message.key.participant;
406
406
  const creationMsgKey = content.pollUpdateMessage.pollCreationMessageKey
407
407
  // we need to fetch the poll creation message to get the poll enc key
408
408
  const pollMsg2 = await getMessage(creationMsgKey);
409
- const pollMsg = pollMsg.botInvokeMessage?.message || pollMsg2;
409
+ const pollMsg = pollMsg2?.botInvokeMessage?.message || pollMsg2;
410
410
  if (pollMsg) {
411
411
  const meIdNormalised = WABinary_1.jidNormalizedUser(meId)
412
412
  const pollCreatorJid = generics_1.getKeyAuthor(creationMsgKey, meIdNormalised)
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@neelegirly/baileys",
3
- "version": "2.2.29",
4
- "description": "Neelegirly fork of Baileys: multi-device WhatsApp Web API for Node.js",
3
+ "version": "2.2.31",
4
+ "description": "Eigenstaendiger Baileys-Fork von Neele Girl (NICHT WhiskeySockets/Baileys) — multi-device WhatsApp Web API fuer Node.js, mit Multi-Button-Support, QR-/Pairing-Stabilitaet und self-healing WA-Web-Version.",
5
5
  "keywords": [
6
6
  "whatsapp",
7
7
  "js-whatsapp",
@@ -20,7 +20,10 @@
20
20
  "url": "git+https://github.com/neelegirly/baileys.git"
21
21
  },
22
22
  "license": "MIT",
23
- "author": "neelegirly",
23
+ "author": "Neele Girl (neelegirly)",
24
+ "contributors": [
25
+ "Rajeh Taher/WhiskeySockets — Baileys upstream (https://github.com/WhiskeySockets/Baileys)"
26
+ ],
24
27
  "main": "lib/index.js",
25
28
  "module": "lib/index.js",
26
29
  "types": "lib/index.d.ts",
@@ -51,6 +54,8 @@
51
54
  "cache-manager": "4.0.1",
52
55
  "futoin-hkdf": "^1.5.1",
53
56
  "libphonenumber-js": "^1.10.20",
57
+ "lodash": "^4.17.21",
58
+ "lru-cache": "^11.1.0",
54
59
  "music-metadata": "^7.12.3",
55
60
  "node-cache": "^5.1.2",
56
61
  "pino": "^7.0.0",