whalibmob 5.40.46 → 5.40.47

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 (51) hide show
  1. package/index.d.ts +4 -6
  2. package/index.js +16 -14
  3. package/lib/Client.js +32 -7
  4. package/lib/signal/SenderKey.js +1 -1
  5. package/lib/signal/SignalProtocol.js +204 -65
  6. package/lib/signal/SignalStore.js +9 -5
  7. package/lib/signal/core/LICENSE +27 -0
  8. package/lib/signal/core/THIRD_PARTY_LICENSES.md +4225 -0
  9. package/lib/signal/core/index.cjs +2805 -0
  10. package/lib/signal/core/wasm/nosimd.wasm +0 -0
  11. package/lib/signal/core/wasm/simd.wasm +0 -0
  12. package/lib/signal/libsignal/LICENSE +21 -0
  13. package/lib/signal/libsignal/address.js +27 -0
  14. package/lib/signal/libsignal/bytes.js +16 -0
  15. package/lib/signal/libsignal/crypto.js +60 -93
  16. package/lib/signal/libsignal/curve.js +47 -138
  17. package/lib/signal/libsignal/errors.js +68 -27
  18. package/lib/signal/libsignal/group.js +85 -0
  19. package/lib/signal/libsignal/index.js +35 -10
  20. package/lib/signal/libsignal/keys.js +27 -0
  21. package/lib/signal/libsignal/legacy-session-codec.js +135 -0
  22. package/lib/signal/libsignal/legacy-session.js +31 -0
  23. package/lib/signal/libsignal/lock.js +46 -0
  24. package/lib/signal/libsignal/prekey-header.js +59 -0
  25. package/lib/signal/libsignal/session-format.js +43 -0
  26. package/lib/signal/libsignal/session.js +198 -0
  27. package/lib/signal/libsignal/store.js +2 -0
  28. package/package.json +7 -2
  29. package/lib/signal/WaSignalGroup/ciphertext-message.js +0 -15
  30. package/lib/signal/WaSignalGroup/group-session-builder.js +0 -46
  31. package/lib/signal/WaSignalGroup/group_cipher.js +0 -93
  32. package/lib/signal/WaSignalGroup/index.js +0 -27
  33. package/lib/signal/WaSignalGroup/keyhelper.js +0 -24
  34. package/lib/signal/WaSignalGroup/sender-chain-key.js +0 -35
  35. package/lib/signal/WaSignalGroup/sender-key-distribution-message.js +0 -137
  36. package/lib/signal/WaSignalGroup/sender-key-message.js +0 -140
  37. package/lib/signal/WaSignalGroup/sender-key-name.js +0 -59
  38. package/lib/signal/WaSignalGroup/sender-key-record.js +0 -63
  39. package/lib/signal/WaSignalGroup/sender-key-state.js +0 -101
  40. package/lib/signal/WaSignalGroup/sender-message-key.js +0 -34
  41. package/lib/signal/libsignal/WhisperTextProtocol.js +0 -933
  42. package/lib/signal/libsignal/base_key_type.js +0 -7
  43. package/lib/signal/libsignal/chain_type.js +0 -6
  44. package/lib/signal/libsignal/keyhelper.js +0 -45
  45. package/lib/signal/libsignal/numeric_fingerprint.js +0 -83
  46. package/lib/signal/libsignal/protobufs.js +0 -10
  47. package/lib/signal/libsignal/protocol_address.js +0 -40
  48. package/lib/signal/libsignal/queue_job.js +0 -71
  49. package/lib/signal/libsignal/session_builder.js +0 -171
  50. package/lib/signal/libsignal/session_cipher.js +0 -334
  51. package/lib/signal/libsignal/session_record.js +0 -316
package/index.d.ts CHANGED
@@ -2408,19 +2408,17 @@ export declare const Messages: {
2408
2408
 
2409
2409
  /**
2410
2410
  * `whalibmob/lib/signal/` — SignalProtocol.js, SignalStore.js and SenderKey.js
2411
- * gathered into one namespace, with the two vendored libraries under their own.
2411
+ * gathered into one namespace, with the vendored libsignal under its own.
2412
2412
  */
2413
2413
  export declare const Signal: LibModule & {
2414
2414
  SignalProtocol: any;
2415
2415
  SignalStore: any;
2416
2416
  SenderKeyStore: any;
2417
2417
  SenderKeyCrypto: any;
2418
- /** Group ciphers and sender-key records. */
2419
- WaSignalGroup: LibModule;
2420
2418
  /**
2421
- * The vendored libsignal. Its own barrel leaves six modules out; they are
2422
- * here — `BaseKeyType`, `ChainType`, `protobufs`, `queueJob`,
2423
- * `FingerprintGenerator`, `textsecure`.
2419
+ * The vendored libsignal (MIT, WebAssembly core): `encrypt`, `decrypt`,
2420
+ * `processPreKeyBundle`, `groupEncrypt`, `groupDecrypt`,
2421
+ * `createSenderKeyDistribution`, `processSenderKeyDistribution`, ...
2424
2422
  */
2425
2423
  libsignal: LibModule;
2426
2424
  };
package/index.js CHANGED
@@ -196,26 +196,28 @@ const Argo = require('./lib/argo/ArgoDecoder');
196
196
  const WAUSync = require('./lib/WAUSync');
197
197
 
198
198
  // Signal — lib/signal/. SignalProtocol.js, SignalStore.js and SenderKey.js have
199
- // no name in common, so the three are one namespace. The two vendored libraries
200
- // keep theirs, being libraries.
199
+ // no name in common, so the three are one namespace. The vendored libsignal
200
+ // (lib/signal/libsignal, MIT, WebAssembly core) keeps its own names.
201
201
  const Signal = Object.assign({},
202
202
  require('./lib/signal/SignalProtocol'),
203
203
  require('./lib/signal/SignalStore'),
204
204
  require('./lib/signal/SenderKey'),
205
205
  {
206
- WaSignalGroup: require('./lib/signal/WaSignalGroup'),
207
- // libsignal's own barrel leaves six of its modules out. They are added to a
208
- // copy of it here rather than written into it, so
209
- // require('whalibmob/lib/signal/libsignal') stays exactly what it was.
206
+ // The barrel, plus the modules it builds on, under `internals`. Added to a
207
+ // copy so require('whalibmob/lib/signal/libsignal') stays what it is.
210
208
  libsignal: Object.assign({}, require('./lib/signal/libsignal'), {
211
- BaseKeyType: require('./lib/signal/libsignal/base_key_type'),
212
- ChainType: require('./lib/signal/libsignal/chain_type'),
213
- protobufs: require('./lib/signal/libsignal/protobufs'),
214
- queueJob: require('./lib/signal/libsignal/queue_job'),
215
- FingerprintGenerator:
216
- require('./lib/signal/libsignal/numeric_fingerprint').FingerprintGenerator,
217
- textsecure:
218
- require('./lib/signal/libsignal/WhisperTextProtocol').textsecure
209
+ internals: {
210
+ bytes: require('./lib/signal/libsignal/bytes'),
211
+ crypto: require('./lib/signal/libsignal/crypto'),
212
+ curve: require('./lib/signal/libsignal/curve'),
213
+ errors: require('./lib/signal/libsignal/errors'),
214
+ legacySessionCodec: require('./lib/signal/libsignal/legacy-session-codec'),
215
+ legacySession: require('./lib/signal/libsignal/legacy-session'),
216
+ lock: require('./lib/signal/libsignal/lock'),
217
+ prekeyHeader: require('./lib/signal/libsignal/prekey-header'),
218
+ sessionFormat: require('./lib/signal/libsignal/session-format'),
219
+ store: require('./lib/signal/libsignal/store')
220
+ }
219
221
  })
220
222
  });
221
223
 
package/lib/Client.js CHANGED
@@ -83,6 +83,12 @@ const {
83
83
  // Status posts are messages addressed here.
84
84
  const STATUS_BROADCAST_JID = 'status@broadcast';
85
85
 
86
+ // A top-level <status> stanza: a contact's status update, handled like a
87
+ // message from status@broadcast but acked with its own class.
88
+ function _isStatusStanza(node) {
89
+ return !!node && node.description === 'status';
90
+ }
91
+
86
92
  // The two prefixes a call-link token is wrapped in, as WhatsApp Web uses them.
87
93
  const CALL_AUDIO_PREFIX = 'https://call.whatsapp.com/voice/';
88
94
  const CALL_VIDEO_PREFIX = 'https://call.whatsapp.com/video/';
@@ -4005,6 +4011,7 @@ class WhalibmobClient extends EventEmitter {
4005
4011
  const { makeOfflineNodeProcessor } = require('./OfflineNodeProcessor');
4006
4012
  this.__offlineQueue = makeOfflineNodeProcessor(new Map([
4007
4013
  ['message', (n) => this._handleMessage(n)],
4014
+ ['status', (n) => this._handleMessage(n)],
4008
4015
  ['receipt', (n) => this._handleReceipt(n)],
4009
4016
  ['notification', (n) => this._handleNotification(n)],
4010
4017
  ['call', (n) => this._handleCall(n)]
@@ -4040,7 +4047,7 @@ class WhalibmobClient extends EventEmitter {
4040
4047
  // `offline`, and handling a burst of them the way live stanzas are
4041
4048
  // handled starts every one of them at once — see OfflineNodeProcessor.
4042
4049
  if (node.attrs && node.attrs.offline &&
4043
- (tag === 'message' || tag === 'receipt' ||
4050
+ (tag === 'message' || tag === 'status' || tag === 'receipt' ||
4044
4051
  tag === 'notification' || tag === 'call')) {
4045
4052
  this._offlineQueue.enqueue(tag, node);
4046
4053
  return;
@@ -4048,6 +4055,12 @@ class WhalibmobClient extends EventEmitter {
4048
4055
 
4049
4056
  if (tag === 'iq') this._handleIq(node);
4050
4057
  else if (tag === 'message') this._handleMessage(node);
4058
+ // A contact's status update. It used to come as a <message> addressed
4059
+ // from status@broadcast; the server now also pushes it as a top-level
4060
+ // <status> stanza of the same shape. Left unacked, it holds back the
4061
+ // offline backlog and every live message queued behind it, and the
4062
+ // server ends the stream with <stream:error><ack class="status"/>.
4063
+ else if (tag === 'status') this._handleMessage(node);
4051
4064
  else if (tag === 'receipt') this._handleReceipt(node);
4052
4065
  else if (tag === 'ack') this._handleAck(node);
4053
4066
  else if (tag === 'notification') this._handleNotification(node);
@@ -4284,7 +4297,7 @@ class WhalibmobClient extends EventEmitter {
4284
4297
  // told it is in flight before that, never after.
4285
4298
  if (skmsgNode && isGroup) {
4286
4299
  this._captureInflight(id, from, ts);
4287
- this._sendMessageAck(id, fromRaw, partRaw);
4300
+ this._ackIncoming(node, id, fromRaw, partRaw);
4288
4301
  this._sendDeliveryReceipt(id, fromRaw, partRaw);
4289
4302
  this._queueIncoming(this._messageMutex, 'MSG', async () => {
4290
4303
  // SKDM must be processed (awaited) before we attempt skmsg decryption,
@@ -4299,7 +4312,7 @@ class WhalibmobClient extends EventEmitter {
4299
4312
 
4300
4313
  if (dmEncNode && this._signal) {
4301
4314
  this._captureInflight(id, from, ts);
4302
- this._sendMessageAck(id, fromRaw, partRaw);
4315
+ this._ackIncoming(node, id, fromRaw, partRaw);
4303
4316
  this._sendDeliveryReceipt(id, fromRaw, partRaw);
4304
4317
  this._queueIncoming(this._messageMutex, 'MSG', () =>
4305
4318
  this._decryptDMMessage({ node, from, participant, fromRaw, partRaw, senderPn, id, ts, dmEncNode }));
@@ -4316,13 +4329,23 @@ class WhalibmobClient extends EventEmitter {
4316
4329
  // Nothing here this client can open into a message, so nothing to keep:
4317
4330
  // the store counts it as one it could not read rather than miss it.
4318
4331
  this._captureDecryptFailure(id, from);
4319
- this._sendMessageAck(id, fromRaw, partRaw);
4332
+ this._ackIncoming(node, id, fromRaw, partRaw);
4320
4333
  this._sendDeliveryReceipt(id, fromRaw, partRaw);
4321
4334
  this.emit('message', {
4322
4335
  id, from, participant, ts, text, node,
4323
4336
  fromMe: false, chat: from
4324
4337
  });
4325
- this._sendReadReceipt(id, fromRaw, partRaw);
4338
+ if (!_isStatusStanza(node)) this._sendReadReceipt(id, fromRaw, partRaw);
4339
+ }
4340
+
4341
+ // The transport ack for a stanza _handleMessage took in.
4342
+ //
4343
+ // A <message> is acked with class="message" and no type. A <status> is acked
4344
+ // the way every other pushed stanza is: class="status", echoing its type and
4345
+ // participant. Acking it as a message leaves the <status> itself unacked.
4346
+ _ackIncoming(node, id, fromRaw, partRaw) {
4347
+ if (_isStatusStanza(node)) this._sendStanzaAck(node);
4348
+ else this._sendMessageAck(id, fromRaw, partRaw);
4326
4349
  }
4327
4350
 
4328
4351
  // The other name this contact answers to, with the device kept.
@@ -4587,7 +4610,7 @@ class WhalibmobClient extends EventEmitter {
4587
4610
  _whaDbg('[DBG] SKDM_ONLY_ERR ' + e.message);
4588
4611
  }
4589
4612
  }
4590
- this._sendReadReceipt(id, fromRaw, partRaw);
4613
+ if (!_isStatusStanza(node)) this._sendReadReceipt(id, fromRaw, partRaw);
4591
4614
  return;
4592
4615
  }
4593
4616
 
@@ -4628,7 +4651,9 @@ class WhalibmobClient extends EventEmitter {
4628
4651
  // Nothing is read by receiving our own message back. A read receipt for
4629
4652
  // it would be addressed to ourselves and marks the chat read on every
4630
4653
  // other device — which is not what happened.
4631
- if (!dest) this._sendReadReceipt(id, fromRaw, partRaw);
4654
+ // A status is not read by arriving: "seen" is reported to its author,
4655
+ // so it is left to the caller (markRead) rather than sent on delivery.
4656
+ if (!dest && !_isStatusStanza(node)) this._sendReadReceipt(id, fromRaw, partRaw);
4632
4657
 
4633
4658
  // ── pkmsg = peer opened a new Signal session (identity/device change) ──
4634
4659
  // Re-issue our tcToken to them so the fresh session carries a valid
@@ -354,7 +354,7 @@ class SenderKeyStore {
354
354
  this._save();
355
355
  }
356
356
 
357
- // Raw access for WaSignalGroup SenderKeyRecord storage (JSON-serialized Buffer format)
357
+ // Raw access for sender-key record storage (JSON-serialized Buffer format)
358
358
  loadRecord(key) {
359
359
  const v = this._data['wsg:' + key];
360
360
  if (!v) return null;
@@ -1,12 +1,17 @@
1
1
  'use strict';
2
2
 
3
- const crypto = require('crypto');
4
3
  const libsignal = require('./libsignal');
4
+ const { Boom } = require('../errors');
5
5
  const { SignalStore } = require('./SignalStore');
6
6
  const { SenderKeyStore } = require('./SenderKey');
7
- const { GroupCipher, GroupSessionBuilder, SenderKeyRecord, SenderKeyName, SenderKeyDistributionMessage } = require('./WaSignalGroup/index');
8
7
 
9
- const { SessionCipher, SessionBuilder, ProtocolAddress, keyhelper } = libsignal;
8
+ // The Signal Protocol itself — X3DH, the double ratchet, sender keys — runs in
9
+ // the WebAssembly core under ./core, driven through ./libsignal. Everything in
10
+ // this file is the binding between that and whalibmob's own stores.
11
+ //
12
+ // Sessions and sender keys are read and written in the same JSON shape as
13
+ // before ('legacy' format, the default), so the files already on disk are used
14
+ // as they are and nothing has to be migrated.
10
15
 
11
16
  // The pre-key pool, sized the way the reference client sizes it.
12
17
  //
@@ -50,31 +55,129 @@ async function _withMutex(key, fn) {
50
55
  }
51
56
  }
52
57
 
53
- // ─── WaSignalGroup storage adapter ──────────────────────────────────────────
54
- // Bridges SenderKeyStore (file-backed) to the async loadSenderKey/storeSenderKey
55
- // interface expected by GroupCipher and GroupSessionBuilder.
58
+ // ─── Store bindings ─────────────────────────────────────────────────────────
59
+ //
60
+ // The protocol reads what an operation needs, runs it, and hands back every
61
+ // change in one commit({ sessions, identities, preKeys, senderKeys }). These
62
+ // two objects translate that to the SignalStore / SenderKeyStore methods, so
63
+ // the stores — and any wrapper around them, such as makeCacheableSignalKeyStore
64
+ // — keep the method names they always had.
65
+ //
66
+ // Keys cross the boundary in both directions as { public, private } here and
67
+ // { pubKey, privKey } in the stores. Sessions cross as the stored JSON row.
56
68
 
57
- class WaSignalGroupStorage {
58
- constructor(senderKeyStore) {
59
- this._store = senderKeyStore;
60
- }
69
+ const toBuf = (u8) => Buffer.from(u8.buffer, u8.byteOffset, u8.byteLength);
61
70
 
62
- async loadSenderKey(senderKeyName) {
63
- const key = typeof senderKeyName === 'string' ? senderKeyName : senderKeyName.toString();
64
- const raw = this._store.loadRecord(key);
65
- if (raw) {
66
- try {
67
- return SenderKeyRecord.deserialize(raw);
68
- } catch (_) {}
71
+ function sessionStoreFor(proto) {
72
+ const store = proto.store;
73
+ return {
74
+ async getLocalIdentity() {
75
+ const kp = await store.getOurIdentity();
76
+ return {
77
+ identityKeyPair: { public: kp.pubKey, private: kp.privKey },
78
+ registrationId: await store.getOurRegistrationId()
79
+ };
80
+ },
81
+ async loadSession(address) {
82
+ const row = await store.loadSession(address);
83
+ return row == null ? null : row;
84
+ },
85
+ async loadIdentity(address) {
86
+ if (typeof store.loadIdentityKey !== 'function') return null;
87
+ const key = await store.loadIdentityKey(address);
88
+ return key || null;
89
+ },
90
+ async loadPreKey(id) {
91
+ const kp = await store.loadPreKey(id);
92
+ return kp ? { public: kp.pubKey, private: kp.privKey } : null;
93
+ },
94
+ async loadSignedPreKey(id) {
95
+ const kp = await store.loadSignedPreKey(id);
96
+ if (!kp) return null;
97
+ // The store keeps the pair; the signature is the one this account
98
+ // published, held on the protocol object. Only the pair takes part in
99
+ // decrypting a prekey message.
100
+ const spk = proto.signedPreKey;
101
+ const signature = spk && Number(spk.keyId) === Number(id) && spk.signature
102
+ ? spk.signature : Buffer.alloc(64);
103
+ return { keyPair: { public: kp.pubKey, private: kp.privKey }, signature };
104
+ },
105
+ // No isTrustedIdentity: a peer's identity is trusted on first use and a
106
+ // changed one replaces it, starting a new session — which is what this
107
+ // library has always done.
108
+ async commit(writes) {
109
+ for (const [address, row] of Object.entries(writes.sessions || {})) {
110
+ if (row === null) await store.deleteSession(address);
111
+ else await store.storeSession(address, row);
112
+ }
113
+ if (typeof store.saveIdentity === 'function') {
114
+ for (const [address, key] of Object.entries(writes.identities || {})) {
115
+ await store.saveIdentity(address, toBuf(key));
116
+ }
117
+ }
118
+ for (const id of Object.keys(writes.preKeys || {})) {
119
+ await store.removePreKey(Number(id));
120
+ }
69
121
  }
70
- return new SenderKeyRecord();
71
- }
122
+ };
123
+ }
124
+
125
+ function senderKeyStoreFor(senderKeyStore) {
126
+ return {
127
+ async loadSenderKey(id) {
128
+ const raw = senderKeyStore.loadRecord(id);
129
+ return raw && raw.length ? raw : null;
130
+ },
131
+ async commit(writes) {
132
+ for (const [id, bytes] of Object.entries(writes.senderKeys || {})) {
133
+ senderKeyStore.saveRecord(id, toBuf(bytes));
134
+ }
135
+ }
136
+ };
137
+ }
72
138
 
73
- async storeSenderKey(senderKeyName, record) {
74
- const key = typeof senderKeyName === 'string' ? senderKeyName : senderKeyName.toString();
75
- const serialized = Buffer.from(JSON.stringify(record.serialize()), 'utf-8');
76
- this._store.saveRecord(key, serialized);
139
+ // The errors callers tell apart by their text — the address search in the
140
+ // client asks "is this simply not where the session lives?" — keep the wording
141
+ // they have always had, with the stable code alongside.
142
+ //
143
+ // msg every failure to open a normal message under this address — no
144
+ // record, no session that matches, a bad MAC, a spent counter — was
145
+ // one error, "No matching sessions found for message", and the search
146
+ // moved on to the next address for any of them.
147
+ // pkmsg a missing one-time pre-key was "Invalid PreKey ID", which the search
148
+ // also moves on from; anything else stops it.
149
+ // group no sender key under this name was "No session found to decrypt
150
+ // message"; anything else stops it.
151
+ const NO_MATCHING_SESSIONS = 'No matching sessions found for message';
152
+ const WORDING = {
153
+ msg: {
154
+ NO_SESSION: NO_MATCHING_SESSIONS,
155
+ INVALID_MESSAGE: NO_MATCHING_SESSIONS,
156
+ DUPLICATE_MESSAGE: NO_MATCHING_SESSIONS,
157
+ INVALID_SESSION: NO_MATCHING_SESSIONS
158
+ },
159
+ pkmsg: {
160
+ MISSING_PRE_KEY: 'Invalid PreKey ID',
161
+ DUPLICATE_MESSAGE: 'Key used already or never filled'
162
+ },
163
+ group: {
164
+ NO_SESSION: 'No session found to decrypt message'
165
+ },
166
+ send: {
167
+ NO_SESSION: 'No open session'
77
168
  }
169
+ };
170
+
171
+ function legacyError(err, kind) {
172
+ if (!libsignal.isSignalError(err)) return err;
173
+ const head = (WORDING[kind] || {})[err.code];
174
+ if (!head) return err;
175
+ // 404 when the session or key that had to exist is missing, 400 otherwise.
176
+ const status = err.code === 'NO_SESSION' || err.code === 'MISSING_PRE_KEY' ? 404 : 400;
177
+ const out = new Boom(head + ': ' + err.message, { statusCode: status, data: { code: err.code } });
178
+ out.code = err.code;
179
+ out.cause = err;
180
+ return out;
78
181
  }
79
182
 
80
183
  const BLOCK_SIZE = 16;
@@ -103,9 +206,13 @@ class SignalProtocol {
103
206
  constructor(store) {
104
207
  this.store = store;
105
208
  this.senderKeyStore = new SenderKeyStore();
106
- this._wsgStorage = new WaSignalGroupStorage(this.senderKeyStore);
107
209
  }
108
210
 
211
+ // Built per call rather than kept, so a store or sender-key store that is
212
+ // swapped on the instance is the one the next operation sees.
213
+ get _sessionStore() { return sessionStoreFor(this); }
214
+ get _senderKeyStore() { return senderKeyStoreFor(this.senderKeyStore); }
215
+
109
216
  static fromStore(waStore, signalFilePath, skFilePath) {
110
217
  const store = new SignalStore();
111
218
  store.init(
@@ -119,7 +226,6 @@ class SignalProtocol {
119
226
 
120
227
  const proto = new SignalProtocol(store);
121
228
  if (skFilePath) proto.senderKeyStore.attachFile(skFilePath);
122
- proto._wsgStorage = new WaSignalGroupStorage(proto.senderKeyStore);
123
229
 
124
230
  proto._ensureSignedPreKey(waStore);
125
231
  proto._ensurePreKeys();
@@ -157,9 +263,11 @@ class SignalProtocol {
157
263
  const startId = this.store.nextPreKeyId();
158
264
  const newKeys = [];
159
265
  for (let i = 0; i < count; i++) {
160
- const kp = keyhelper.generatePreKey(startId + i);
161
- this.store.storePreKey(kp.keyId, kp.keyPair);
162
- newKeys.push({ keyId: kp.keyId, pubKey: kp.keyPair.pubKey });
266
+ const kp = libsignal.generatePreKey(startId + i);
267
+ // 33-byte 0x05-prefixed public half and 32-byte private half, as before.
268
+ const keyPair = { pubKey: toBuf(kp.keyPair.public), privKey: toBuf(kp.keyPair.private) };
269
+ this.store.storePreKey(kp.keyId, keyPair);
270
+ newKeys.push({ keyId: kp.keyId, pubKey: keyPair.pubKey });
163
271
  }
164
272
  return newKeys;
165
273
  }
@@ -271,9 +379,8 @@ class SignalProtocol {
271
379
  }
272
380
 
273
381
  async buildSessionFromBundle(jid, bundle) {
274
- const addr = jidToAddress(jid);
275
- const builder = new SessionBuilder(this.store, addr);
276
- await builder.initOutgoing({
382
+ const addr = jidToAddress(jid);
383
+ await libsignal.processPreKeyBundle(this._sessionStore, addr, {
277
384
  registrationId: bundle.registrationId,
278
385
  identityKey: bundle.identityKey,
279
386
  signedPreKey: {
@@ -285,7 +392,7 @@ class SignalProtocol {
285
392
  keyId: bundle.preKey.keyId,
286
393
  publicKey: bundle.preKey.publicKey
287
394
  } : undefined
288
- });
395
+ }).catch(err => { throw legacyError(err, 'bundle'); });
289
396
  }
290
397
 
291
398
  async buildSessionsFromBundles(bundleMap) {
@@ -307,26 +414,32 @@ class SignalProtocol {
307
414
  // Mutex per JID — prevents Signal session race conditions
308
415
  return _withMutex(jid, async () => {
309
416
  const addr = jidToAddress(jid);
310
- const cipher = new SessionCipher(this.store, addr);
311
417
  const padded = pad(Buffer.from(plaintext));
312
- const result = await cipher.encrypt(padded);
418
+ let result;
419
+ try {
420
+ result = await libsignal.encrypt(this._sessionStore, addr, padded);
421
+ } catch (err) {
422
+ throw legacyError(err, 'send');
423
+ }
313
424
  return {
314
- type: result.type === 3 ? 'pkmsg' : 'msg',
315
- ciphertext: Buffer.from(result.body, 'binary')
425
+ type: result.type === 'pkmsg' ? 'pkmsg' : 'msg',
426
+ ciphertext: toBuf(result.ciphertext)
316
427
  };
317
428
  });
318
429
  }
319
430
 
320
431
  async decrypt(jid, type, ciphertext) {
321
- const addr = jidToAddress(jid);
322
- const cipher = new SessionCipher(this.store, addr);
432
+ const addr = jidToAddress(jid);
433
+ const kind = type === 'pkmsg' ? 'pkmsg' : 'msg';
323
434
  let plaintext;
324
- if (type === 'pkmsg') {
325
- plaintext = await cipher.decryptPreKeyWhisperMessage(ciphertext);
326
- } else {
327
- plaintext = await cipher.decryptWhisperMessage(ciphertext);
435
+ try {
436
+ plaintext = await libsignal.decrypt(this._sessionStore, addr, {
437
+ type: kind, ciphertext: Buffer.from(ciphertext)
438
+ });
439
+ } catch (err) {
440
+ throw legacyError(err, kind);
328
441
  }
329
- return unpad(Buffer.from(plaintext));
442
+ return unpad(toBuf(plaintext));
330
443
  }
331
444
 
332
445
  // ─── Bulk encrypt for multiple devices (MD fanout) ─────────────────────────
@@ -364,8 +477,8 @@ class SignalProtocol {
364
477
 
365
478
  // ─── SenderKey group encrypt / decrypt ────────────────────────────────────
366
479
  //
367
- // Uses WaSignalGroup GroupCipher/GroupSessionBuilder.
368
- // SenderKeyName format: groupId::senderId::0 (device 0 for group identity).
480
+ // A sender key is stored under groupId::user::device — the same key string
481
+ // as always, so the records already on disk are found where they are.
369
482
 
370
483
  _senderKeyName(groupId, senderId) {
371
484
  // A SenderKey belongs to a device, not to an account. Every device that
@@ -381,41 +494,61 @@ class SignalProtocol {
381
494
  const colon = userPart.indexOf(':');
382
495
  const user = colon >= 0 ? userPart.slice(0, colon) : userPart;
383
496
  const deviceId = colon >= 0 ? (parseInt(userPart.slice(colon + 1), 10) || 0) : 0;
384
- return new SenderKeyName(groupId, { id: user, deviceId });
497
+ return libsignal.createAddress(user, deviceId);
385
498
  }
386
499
 
387
500
  async senderKeyEncrypt(groupId, senderId, plaintext) {
388
- const senderName = this._senderKeyName(groupId, senderId);
389
- const cipher = new GroupCipher(this._wsgStorage, senderName);
501
+ const sender = this._senderKeyName(groupId, senderId);
390
502
  const padded = pad(Buffer.from(plaintext));
391
- return cipher.encrypt(padded);
503
+ try {
504
+ const { ciphertext } = await libsignal.groupEncrypt(this._senderKeyStore, groupId, sender, padded);
505
+ return toBuf(ciphertext);
506
+ } catch (err) {
507
+ throw legacyError(err, 'group');
508
+ }
392
509
  }
393
510
 
394
511
  async senderKeyDecrypt(groupId, senderId, ciphertext) {
395
- const senderName = this._senderKeyName(groupId, senderId);
396
- const cipher = new GroupCipher(this._wsgStorage, senderName);
397
- const raw = await cipher.decrypt(Buffer.from(ciphertext));
398
- return unpad(Buffer.from(raw));
512
+ const sender = this._senderKeyName(groupId, senderId);
513
+ let raw;
514
+ try {
515
+ raw = await libsignal.groupDecrypt(this._senderKeyStore, groupId, sender, Buffer.from(ciphertext));
516
+ } catch (err) {
517
+ throw legacyError(err, 'group');
518
+ }
519
+ return unpad(toBuf(raw));
399
520
  }
400
521
 
401
522
  async buildSKDM(groupId, senderId) {
402
- const senderName = this._senderKeyName(groupId, senderId);
403
- const builder = new GroupSessionBuilder(this._wsgStorage);
404
- const skdm = await builder.create(senderName);
405
- return skdm.serialize();
523
+ const sender = this._senderKeyName(groupId, senderId);
524
+ try {
525
+ return toBuf(await libsignal.createSenderKeyDistribution(this._senderKeyStore, groupId, sender));
526
+ } catch (err) {
527
+ throw legacyError(err, 'group');
528
+ }
406
529
  }
407
530
 
408
531
  async processSKDM(groupId, senderId, skdmBytes) {
409
- const senderName = this._senderKeyName(groupId, senderId);
410
- const builder = new GroupSessionBuilder(this._wsgStorage);
411
- const skdmMsg = new SenderKeyDistributionMessage(null, null, null, null, Buffer.from(skdmBytes));
412
- await builder.process(senderName, skdmMsg);
532
+ const sender = this._senderKeyName(groupId, senderId);
533
+ try {
534
+ await libsignal.processSenderKeyDistribution(this._senderKeyStore, groupId, sender, Buffer.from(skdmBytes));
535
+ } catch (err) {
536
+ throw legacyError(err, 'group');
537
+ }
413
538
  }
414
539
 
415
540
  async hasSenderKey(groupId, senderId) {
416
- const senderName = this._senderKeyName(groupId, senderId);
417
- const record = await this._wsgStorage.loadSenderKey(senderName);
418
- return !record.isEmpty();
541
+ const id = libsignal.senderKeyId(groupId, this._senderKeyName(groupId, senderId));
542
+ const raw = this.senderKeyStore.loadRecord(id);
543
+ if (!raw || !raw.length) return false;
544
+ // A record with no state in it holds no key. The stored record is the JSON
545
+ // list of sender-key states.
546
+ try {
547
+ const parsed = JSON.parse(raw.toString('utf8'));
548
+ return Array.isArray(parsed) ? parsed.length > 0 : true;
549
+ } catch (_) {
550
+ return true;
551
+ }
419
552
  }
420
553
  }
421
554
 
@@ -445,7 +578,13 @@ function jidToAddress(jid) {
445
578
  } else {
446
579
  user = String(jid);
447
580
  }
448
- return new ProtocolAddress(user, deviceId);
581
+ // A plain { name, deviceId }. toString() keeps the "user.device" form the
582
+ // session files are keyed by, so code that printed an address still does.
583
+ const addr = libsignal.createAddress(user, deviceId);
584
+ Object.defineProperty(addr, 'toString', {
585
+ value: () => libsignal.addressToString(addr), enumerable: false
586
+ });
587
+ return addr;
449
588
  }
450
589
 
451
590
  module.exports = {
@@ -2,7 +2,7 @@
2
2
 
3
3
  const fs = require('fs');
4
4
  const path = require('path');
5
- const { SessionRecord } = require('./libsignal');
5
+ const { hasOpenSession } = require('./libsignal/session-format.js');
6
6
 
7
7
  // ─── Debounced async writer ────────────────────────────────────────────────────
8
8
  //
@@ -582,15 +582,19 @@ class SignalStore {
582
582
 
583
583
  // ─── Sessions ─────────────────────────────────────────────────────────────
584
584
 
585
+ // A session crosses this boundary as the stored row itself — the JSON object
586
+ // that is written to the .signal.json file, in the same shape it has always
587
+ // had there. The protocol reads and returns that shape directly.
585
588
  async loadSession(encodedAddress) {
586
589
  const data = this._sessions[encodedAddress];
587
590
  if (!data) return undefined;
588
- const obj = typeof data === 'string' ? JSON.parse(data) : data;
589
- return SessionRecord.deserialize(obj);
591
+ return typeof data === 'string' ? JSON.parse(data) : data;
590
592
  }
591
593
 
592
594
  async storeSession(encodedAddress, record) {
593
- this._sessions[encodedAddress] = record.serialize();
595
+ // A row from an older caller may still be an object with serialize().
596
+ this._sessions[encodedAddress] =
597
+ record && typeof record.serialize === 'function' ? record.serialize() : record;
594
598
  this._save();
595
599
  }
596
600
 
@@ -627,7 +631,7 @@ class SignalStore {
627
631
  let open = false;
628
632
  try {
629
633
  const obj = typeof data === 'string' ? JSON.parse(data) : data;
630
- open = SessionRecord.deserialize(obj).haveOpenSession();
634
+ open = hasOpenSession(obj);
631
635
  } catch (_) {
632
636
  open = false;
633
637
  }
@@ -0,0 +1,27 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rajeh Taher/WhiskeySockets
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ ---
24
+
25
+ index.cjs and wasm/*.wasm are the unmodified build of @whiskeysockets/baileys-core
26
+ 0.6.0 (MIT). The WebAssembly is compiled from the Rust crates listed, with their
27
+ licenses, in THIRD_PARTY_LICENSES.md.