@hiroosy/baileys-lite 0.0.1

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 (63) hide show
  1. package/README.md +25 -0
  2. package/WAProto/index.d.ts +15932 -0
  3. package/WAProto/index.js +115856 -0
  4. package/engine-requirements.js +11 -0
  5. package/package.json +27 -0
  6. package/src/binary/wa-binary-constants.js +1300 -0
  7. package/src/binary/wa-binary.js +649 -0
  8. package/src/constants.js +143 -0
  9. package/src/defaults.js +102 -0
  10. package/src/foundation/audio-duration.js +530 -0
  11. package/src/foundation/audio-samples.js +268 -0
  12. package/src/foundation/boom.js +46 -0
  13. package/src/foundation/cache.js +142 -0
  14. package/src/foundation/concurrency.js +87 -0
  15. package/src/foundation/curve25519.js +221 -0
  16. package/src/foundation/link-preview.js +320 -0
  17. package/src/foundation/logger.js +69 -0
  18. package/src/foundation/long.js +140 -0
  19. package/src/foundation/protobuf-minimal.js +619 -0
  20. package/src/foundation/wa-crypto.js +76 -0
  21. package/src/foundation/zip.js +124 -0
  22. package/src/index.js +48 -0
  23. package/src/signal/libsignal.js +1051 -0
  24. package/src/signal/signal-group.js +487 -0
  25. package/src/signal/signal-repository.js +646 -0
  26. package/src/socket/business-communities.js +830 -0
  27. package/src/socket/chats.js +674 -0
  28. package/src/socket/groups-newsletter.js +342 -0
  29. package/src/socket/messages-recv.js +1835 -0
  30. package/src/socket/messages-send.js +1202 -0
  31. package/src/socket/socket-core.js +833 -0
  32. package/src/socket/usync.js +291 -0
  33. package/src/socket-client/websocket-client.js +124 -0
  34. package/src/utils/auth-state-core.js +764 -0
  35. package/src/utils/auth-state-storage.js +316 -0
  36. package/src/utils/chat-sync.js +1045 -0
  37. package/src/utils/media.js +841 -0
  38. package/src/utils/message-compose.js +1609 -0
  39. package/src/utils/message-processing.js +958 -0
  40. package/src/utils/wa-protocol-core.js +1283 -0
  41. package/src/vendor/jpeg-js/LICENSE +25 -0
  42. package/src/vendor/jpeg-js/decoder.js +1152 -0
  43. package/src/vendor/jpeg-js/encoder.js +824 -0
  44. package/src/vendor/pngjs/LICENSE +20 -0
  45. package/src/vendor/pngjs/bitmapper.js +273 -0
  46. package/src/vendor/pngjs/bitpacker.js +167 -0
  47. package/src/vendor/pngjs/constants.js +38 -0
  48. package/src/vendor/pngjs/crc.js +47 -0
  49. package/src/vendor/pngjs/filter-pack.js +179 -0
  50. package/src/vendor/pngjs/filter-parse-sync.js +27 -0
  51. package/src/vendor/pngjs/filter-parse.js +185 -0
  52. package/src/vendor/pngjs/format-normaliser.js +101 -0
  53. package/src/vendor/pngjs/interlace.js +101 -0
  54. package/src/vendor/pngjs/packer-sync.js +65 -0
  55. package/src/vendor/pngjs/packer.js +138 -0
  56. package/src/vendor/pngjs/paeth-predictor.js +22 -0
  57. package/src/vendor/pngjs/parser-sync.js +121 -0
  58. package/src/vendor/pngjs/parser.js +299 -0
  59. package/src/vendor/pngjs/png-sync.js +19 -0
  60. package/src/vendor/pngjs/sync-inflate.js +174 -0
  61. package/src/vendor/pngjs/sync-reader.js +54 -0
  62. package/src/wam/wam-constants.js +22853 -0
  63. package/src/wam/wam.js +151 -0
@@ -0,0 +1,1051 @@
1
+ /**
2
+ * Native Signal protocol implementation (X3DH + Double Ratchet, 1:1 sessions).
3
+ *
4
+ * Replaces the `libsignal` npm package (WhiskeySockets/libsignal-node 6.0.0),
5
+ * together with its dependencies `curve25519-js` and `protobufjs`.
6
+ * It is a faithful port: same wire format, same session serialization, same
7
+ * error classes and same public API, so existing auth-state / session data
8
+ * stays compatible. Verified against the original package in
9
+ * test/native-deps.mjs (cross-encrypt / decrypt in both directions).
10
+ */
11
+ import * as nodeCrypto from 'node:crypto'
12
+ import { publicFromPrivate, randomX25519, sharedKey, sign as xeddsaSign, verify as xeddsaVerify } from '../foundation/curve25519.js'
13
+
14
+ /* ------------------------------------------------------------------ */
15
+ /* errors */
16
+ /* ------------------------------------------------------------------ */
17
+
18
+ export class SignalError extends Error {}
19
+
20
+ export class UntrustedIdentityKeyError extends SignalError {
21
+ constructor(addr, identityKey) {
22
+ super()
23
+ this.name = 'UntrustedIdentityKeyError'
24
+ this.addr = addr
25
+ this.identityKey = identityKey
26
+ }
27
+ }
28
+
29
+ export class SessionError extends SignalError {
30
+ constructor(message) {
31
+ super(message)
32
+ this.name = 'SessionError'
33
+ }
34
+ }
35
+
36
+ export class MessageCounterError extends SessionError {
37
+ constructor(message) {
38
+ super(message)
39
+ this.name = 'MessageCounterError'
40
+ }
41
+ }
42
+
43
+ export class PreKeyError extends SessionError {
44
+ constructor(message) {
45
+ super(message)
46
+ this.name = 'PreKeyError'
47
+ }
48
+ }
49
+
50
+ /* ------------------------------------------------------------------ */
51
+ /* crypto */
52
+ /* ------------------------------------------------------------------ */
53
+
54
+ const assertBuffer = value => {
55
+ if (!(value instanceof Buffer)) throw TypeError(`Expected Buffer instead of: ${value.constructor.name}`)
56
+ return value
57
+ }
58
+
59
+ export const crypto = {
60
+ encrypt(key, data, iv) {
61
+ assertBuffer(key)
62
+ assertBuffer(data)
63
+ assertBuffer(iv)
64
+ const cipher = nodeCrypto.createCipheriv('aes-256-cbc', key, iv)
65
+ return Buffer.concat([cipher.update(data), cipher.final()])
66
+ },
67
+ decrypt(key, data, iv) {
68
+ assertBuffer(key)
69
+ assertBuffer(data)
70
+ assertBuffer(iv)
71
+ const decipher = nodeCrypto.createDecipheriv('aes-256-cbc', key, iv)
72
+ return Buffer.concat([decipher.update(data), decipher.final()])
73
+ },
74
+ calculateMAC(key, data) {
75
+ assertBuffer(key)
76
+ assertBuffer(data)
77
+ return Buffer.from(nodeCrypto.createHmac('sha256', key).update(data).digest())
78
+ },
79
+ hash(data) {
80
+ assertBuffer(data)
81
+ return nodeCrypto.createHash('sha512').update(data).digest()
82
+ },
83
+ // Salts always end up being 32 bytes
84
+ deriveSecrets(input, salt, info, chunks) {
85
+ // RFC 5869 that only returns the first 3 32-byte chunks
86
+ assertBuffer(input)
87
+ assertBuffer(salt)
88
+ assertBuffer(info)
89
+ if (salt.byteLength != 32) throw new Error('Got salt of incorrect length')
90
+ chunks = chunks || 3
91
+ if (!(chunks >= 1 && chunks <= 3)) throw new Error('chunks must be between 1 and 3')
92
+ const PRK = crypto.calculateMAC(salt, input)
93
+ const infoArray = new Uint8Array(info.byteLength + 1 + 32)
94
+ infoArray.set(info, 32)
95
+ infoArray[infoArray.length - 1] = 1
96
+ const signed = [crypto.calculateMAC(PRK, Buffer.from(infoArray.slice(32)))]
97
+ if (chunks > 1) {
98
+ infoArray.set(signed[signed.length - 1])
99
+ infoArray[infoArray.length - 1] = 2
100
+ signed.push(crypto.calculateMAC(PRK, Buffer.from(infoArray)))
101
+ }
102
+ if (chunks > 2) {
103
+ infoArray.set(signed[signed.length - 1])
104
+ infoArray[infoArray.length - 1] = 3
105
+ signed.push(crypto.calculateMAC(PRK, Buffer.from(infoArray)))
106
+ }
107
+ return signed
108
+ },
109
+ verifyMAC(data, key, mac, length) {
110
+ const calculatedMac = crypto.calculateMAC(key, data).slice(0, length)
111
+ if (mac.length !== length || calculatedMac.length !== length) throw new Error('Bad MAC length')
112
+ if (!mac.equals(calculatedMac)) throw new Error('Bad MAC')
113
+ }
114
+ }
115
+
116
+ /* ------------------------------------------------------------------ */
117
+ /* curve (33-byte "DJB type 5" public keys, 32-byte private keys) */
118
+ /* ------------------------------------------------------------------ */
119
+
120
+ const KEY_BUNDLE_TYPE = Buffer.from([5])
121
+ const prefixKeyInPublicKey = pubKey => Buffer.concat([KEY_BUNDLE_TYPE, pubKey])
122
+
123
+ const validatePrivKey = privKey => {
124
+ if (privKey === undefined) throw new Error('Undefined private key')
125
+ if (!(privKey instanceof Buffer)) throw new Error(`Invalid private key type: ${privKey.constructor.name}`)
126
+ if (privKey.byteLength != 32) throw new Error(`Incorrect private key length: ${privKey.byteLength}`)
127
+ }
128
+
129
+ const scrubPubKeyFormat = pubKey => {
130
+ if (!(pubKey instanceof Buffer)) throw new Error(`Invalid public key type: ${pubKey.constructor.name}`)
131
+ if (pubKey === undefined || ((pubKey.byteLength != 33 || pubKey[0] != 5) && pubKey.byteLength != 32)) {
132
+ throw new Error('Invalid public key')
133
+ }
134
+ if (pubKey.byteLength == 33) return pubKey.slice(1)
135
+ console.error('WARNING: Expected pubkey of length 33, please report the ST and client that generated the pubkey')
136
+ return pubKey
137
+ }
138
+
139
+ const unclampEd25519PrivateKey = clampedSk => {
140
+ const unclampedSk = new Uint8Array(clampedSk)
141
+ unclampedSk[0] |= 6 // Ensure last 3 bits match expected `110` pattern
142
+ unclampedSk[31] |= 128 // Restore the highest bit
143
+ unclampedSk[31] &= ~64 // Clear the second-highest bit
144
+ return unclampedSk
145
+ }
146
+
147
+ export const curve = {
148
+ getPublicFromPrivateKey(privKey) {
149
+ return prefixKeyInPublicKey(publicFromPrivate(unclampEd25519PrivateKey(privKey)))
150
+ },
151
+ generateKeyPair() {
152
+ const { pub, priv } = randomX25519()
153
+ return { pubKey: prefixKeyInPublicKey(pub), privKey: priv }
154
+ },
155
+ calculateAgreement(pubKey, privKey) {
156
+ pubKey = scrubPubKeyFormat(pubKey)
157
+ validatePrivKey(privKey)
158
+ if (!pubKey || pubKey.byteLength != 32) throw new Error('Invalid public key')
159
+ return sharedKey(privKey, pubKey)
160
+ },
161
+ calculateSignature(privKey, message) {
162
+ validatePrivKey(privKey)
163
+ if (!message) throw new Error('Invalid message')
164
+ return Buffer.from(xeddsaSign(privKey, message))
165
+ },
166
+ verifySignature(pubKey, msg, sig, isInit) {
167
+ pubKey = scrubPubKeyFormat(pubKey)
168
+ if (!pubKey || pubKey.byteLength != 32) throw new Error('Invalid public key')
169
+ if (!msg) throw new Error('Invalid message')
170
+ if (!sig || sig.byteLength != 64) throw new Error('Invalid signature')
171
+ return isInit ? true : xeddsaVerify(pubKey, msg, sig)
172
+ }
173
+ }
174
+
175
+ /* ------------------------------------------------------------------ */
176
+ /* keyhelper */
177
+ /* ------------------------------------------------------------------ */
178
+
179
+ const isNonNegativeInteger = n => typeof n === 'number' && n % 1 === 0 && n >= 0
180
+
181
+ export const keyhelper = {
182
+ generateIdentityKeyPair: curve.generateKeyPair,
183
+ generateRegistrationId() {
184
+ const registrationId = Uint16Array.from(nodeCrypto.randomBytes(2))[0]
185
+ return registrationId & 0x3fff
186
+ },
187
+ generateSignedPreKey(identityKeyPair, signedKeyId) {
188
+ if (
189
+ !(identityKeyPair.privKey instanceof Buffer) ||
190
+ identityKeyPair.privKey.byteLength != 32 ||
191
+ !(identityKeyPair.pubKey instanceof Buffer) ||
192
+ identityKeyPair.pubKey.byteLength != 33
193
+ ) {
194
+ throw new TypeError('Invalid argument for identityKeyPair')
195
+ }
196
+ if (!isNonNegativeInteger(signedKeyId)) throw new TypeError('Invalid argument for signedKeyId: ' + signedKeyId)
197
+ const keyPair = curve.generateKeyPair()
198
+ const sig = curve.calculateSignature(identityKeyPair.privKey, keyPair.pubKey)
199
+ return { keyId: signedKeyId, keyPair, signature: sig }
200
+ },
201
+ generatePreKey(keyId) {
202
+ if (!isNonNegativeInteger(keyId)) throw new TypeError('Invalid argument for keyId: ' + keyId)
203
+ return { keyId, keyPair: curve.generateKeyPair() }
204
+ }
205
+ }
206
+
207
+ /* ------------------------------------------------------------------ */
208
+ /* minimal protobuf (proto2 varint + length-delimited only) */
209
+ /* ------------------------------------------------------------------ */
210
+
211
+ const writeVarint = (out, n) => {
212
+ n = n >>> 0
213
+ while (n > 127) {
214
+ out.push((n & 127) | 128)
215
+ n >>>= 7
216
+ }
217
+ out.push(n)
218
+ }
219
+
220
+ class PbReader {
221
+ constructor(buf) {
222
+ this.buf = buf
223
+ this.pos = 0
224
+ this.len = buf.length
225
+ }
226
+ varint() {
227
+ // uint32 semantics (protobufjs reads up to 5 bytes, keeps low 32 bits)
228
+ let value = 0
229
+ for (let i = 0; i < 5; i++) {
230
+ if (this.pos >= this.len) throw RangeError(`index out of range: ${this.pos} + 1 > ${this.len}`)
231
+ const b = this.buf[this.pos++]
232
+ value = (value | ((b & 127) << (7 * i))) >>> 0
233
+ if (b < 128) return value
234
+ }
235
+ // consume any remaining continuation bytes (up to 10 total)
236
+ for (let i = 5; i < 10; i++) {
237
+ if (this.pos >= this.len) throw RangeError(`index out of range: ${this.pos} + 1 > ${this.len}`)
238
+ if (this.buf[this.pos++] < 128) return value
239
+ }
240
+ throw Error('invalid varint encoding')
241
+ }
242
+ bytes() {
243
+ const length = this.varint()
244
+ const start = this.pos
245
+ const end = start + length
246
+ if (end > this.len) throw RangeError(`index out of range: ${this.pos} + ${length} > ${this.len}`)
247
+ this.pos = end
248
+ return Buffer.from(this.buf.subarray(start, end))
249
+ }
250
+ skipType(wireType) {
251
+ switch (wireType) {
252
+ case 0:
253
+ this.varint()
254
+ break
255
+ case 1:
256
+ this.pos += 8
257
+ break
258
+ case 2: {
259
+ // NOTE: not `this.pos += this.varint()` — that reads `pos` BEFORE varint() advances it
260
+ const skip = this.varint()
261
+ this.pos += skip
262
+ break
263
+ }
264
+ case 5:
265
+ this.pos += 4
266
+ break
267
+ default:
268
+ throw Error('invalid wire type ' + wireType + ' at offset ' + this.pos)
269
+ }
270
+ if (this.pos > this.len) throw RangeError('index out of range')
271
+ }
272
+ }
273
+
274
+ /** Build a tiny message class: fields = [[name, fieldNo, 'bytes'|'uint32', encodeOrder]] */
275
+ const defineMessage = (fields, defaults) => {
276
+ const Msg = function (props) {
277
+ if (props) for (const k of Object.keys(props)) if (props[k] != null) this[k] = props[k]
278
+ }
279
+ for (const f of fields) Msg.prototype[f.name] = defaults[f.name]
280
+ Msg.create = props => new Msg(props)
281
+ Msg.encode = message => {
282
+ const out = []
283
+ for (const f of fields) {
284
+ // protobufjs only writes fields that are OWN properties and non-null
285
+ if (message[f.name] != null && Object.prototype.hasOwnProperty.call(message, f.name)) {
286
+ if (f.type === 'uint32') {
287
+ writeVarint(out, (f.no << 3) | 0)
288
+ writeVarint(out, message[f.name])
289
+ } else {
290
+ writeVarint(out, (f.no << 3) | 2)
291
+ const b = message[f.name]
292
+ writeVarint(out, b.length)
293
+ for (let i = 0; i < b.length; i++) out.push(b[i])
294
+ }
295
+ }
296
+ }
297
+ const buf = Buffer.from(out)
298
+ return { finish: () => new Uint8Array(buf.buffer, buf.byteOffset, buf.length) }
299
+ }
300
+ Msg.decode = data => {
301
+ const reader = new PbReader(data)
302
+ const message = new Msg()
303
+ const byNo = new Map(fields.map(f => [f.no, f]))
304
+ while (reader.pos < reader.len) {
305
+ const tag = reader.varint()
306
+ const f = byNo.get(tag >>> 3)
307
+ if (f) message[f.name] = f.type === 'uint32' ? reader.varint() : reader.bytes()
308
+ else reader.skipType(tag & 7)
309
+ }
310
+ return message
311
+ }
312
+ return Msg
313
+ }
314
+
315
+ // textsecure.WhisperMessage
316
+ export const WhisperMessage = defineMessage(
317
+ [
318
+ { name: 'ephemeralKey', no: 1, type: 'bytes' },
319
+ { name: 'counter', no: 2, type: 'uint32' },
320
+ { name: 'previousCounter', no: 3, type: 'uint32' },
321
+ { name: 'ciphertext', no: 4, type: 'bytes' }
322
+ ],
323
+ { ephemeralKey: Buffer.alloc(0), counter: 0, previousCounter: 0, ciphertext: Buffer.alloc(0) }
324
+ )
325
+
326
+ // textsecure.PreKeyWhisperMessage
327
+ export const PreKeyWhisperMessage = defineMessage(
328
+ [
329
+ { name: 'preKeyId', no: 1, type: 'uint32' },
330
+ { name: 'baseKey', no: 2, type: 'bytes' },
331
+ { name: 'identityKey', no: 3, type: 'bytes' },
332
+ { name: 'message', no: 4, type: 'bytes' },
333
+ { name: 'registrationId', no: 5, type: 'uint32' },
334
+ { name: 'signedPreKeyId', no: 6, type: 'uint32' }
335
+ ],
336
+ {
337
+ preKeyId: 0,
338
+ baseKey: Buffer.alloc(0),
339
+ identityKey: Buffer.alloc(0),
340
+ message: Buffer.alloc(0),
341
+ registrationId: 0,
342
+ signedPreKeyId: 0
343
+ }
344
+ )
345
+
346
+ /* ------------------------------------------------------------------ */
347
+ /* ProtocolAddress */
348
+ /* ------------------------------------------------------------------ */
349
+
350
+ export class ProtocolAddress {
351
+ static from(encodedAddress) {
352
+ if (typeof encodedAddress !== 'string' || !encodedAddress.match(/.*\.\d+/)) throw new Error('Invalid address encoding')
353
+ const parts = encodedAddress.split('.')
354
+ return new this(parts[0], parseInt(parts[1]))
355
+ }
356
+ constructor(id, deviceId) {
357
+ if (typeof id !== 'string') throw new TypeError('id required for addr')
358
+ if (id.indexOf('.') !== -1) throw new TypeError('encoded addr detected')
359
+ this.id = id
360
+ if (typeof deviceId !== 'number') throw new TypeError('number required for deviceId')
361
+ this.deviceId = deviceId
362
+ }
363
+ toString() {
364
+ return `${this.id}.${this.deviceId}`
365
+ }
366
+ is(other) {
367
+ if (!(other instanceof ProtocolAddress)) return false
368
+ return other.id === this.id && other.deviceId === this.deviceId
369
+ }
370
+ }
371
+
372
+ /* ------------------------------------------------------------------ */
373
+ /* job queue (serializes session I/O per address) */
374
+ /* ------------------------------------------------------------------ */
375
+
376
+ const _queueAsyncBuckets = new Map()
377
+ const _gcLimit = 10000
378
+
379
+ async function _asyncQueueExecutor(queue, cleanup) {
380
+ let offt = 0
381
+ while (true) {
382
+ const limit = Math.min(queue.length, _gcLimit) // Break up thundering herds for GC duty.
383
+ for (let i = offt; i < limit; i++) {
384
+ const job = queue[i]
385
+ try {
386
+ job.resolve(await job.awaitable())
387
+ } catch (e) {
388
+ job.reject(e)
389
+ }
390
+ }
391
+ if (limit < queue.length) {
392
+ /* Perform lazy GC of queue for faster iteration. */
393
+ if (limit >= _gcLimit) {
394
+ queue.splice(0, limit)
395
+ offt = 0
396
+ } else {
397
+ offt = limit
398
+ }
399
+ } else {
400
+ break
401
+ }
402
+ }
403
+ cleanup()
404
+ }
405
+
406
+ const queueJob = (bucket, awaitable) => {
407
+ let inactive
408
+ if (!_queueAsyncBuckets.has(bucket)) {
409
+ _queueAsyncBuckets.set(bucket, [])
410
+ inactive = true
411
+ }
412
+ const queue = _queueAsyncBuckets.get(bucket)
413
+ const job = new Promise((resolve, reject) => queue.push({ awaitable, resolve, reject }))
414
+ if (inactive) _asyncQueueExecutor(queue, () => _queueAsyncBuckets.delete(bucket))
415
+ return job
416
+ }
417
+
418
+ /* ------------------------------------------------------------------ */
419
+ /* SessionRecord / SessionEntry */
420
+ /* ------------------------------------------------------------------ */
421
+
422
+ const BaseKeyType = { OURS: 1, THEIRS: 2 }
423
+ const ChainType = { SENDING: 1, RECEIVING: 2 }
424
+ const CLOSED_SESSIONS_MAX = 40
425
+ const SESSION_RECORD_VERSION = 'v1'
426
+
427
+ const assertBufferType = value => {
428
+ if (!Buffer.isBuffer(value)) throw new TypeError('Buffer required')
429
+ }
430
+
431
+ class SessionEntry {
432
+ constructor() {
433
+ this._chains = {}
434
+ }
435
+ toString() {
436
+ const baseKey = this.indexInfo && this.indexInfo.baseKey && this.indexInfo.baseKey.toString('base64')
437
+ return `<SessionEntry [baseKey=${baseKey}]>`
438
+ }
439
+ inspect() {
440
+ return this.toString()
441
+ }
442
+ addChain(key, value) {
443
+ assertBufferType(key)
444
+ const id = key.toString('base64')
445
+ if (Object.prototype.hasOwnProperty.call(this._chains, id)) throw new Error('Overwrite attempt')
446
+ this._chains[id] = value
447
+ }
448
+ getChain(key) {
449
+ assertBufferType(key)
450
+ return this._chains[key.toString('base64')]
451
+ }
452
+ deleteChain(key) {
453
+ assertBufferType(key)
454
+ const id = key.toString('base64')
455
+ if (!Object.prototype.hasOwnProperty.call(this._chains, id)) throw new ReferenceError('Not Found')
456
+ delete this._chains[id]
457
+ }
458
+ *chains() {
459
+ for (const [k, v] of Object.entries(this._chains)) yield [Buffer.from(k, 'base64'), v]
460
+ }
461
+ serialize() {
462
+ const data = {
463
+ registrationId: this.registrationId,
464
+ currentRatchet: {
465
+ ephemeralKeyPair: {
466
+ pubKey: this.currentRatchet.ephemeralKeyPair.pubKey.toString('base64'),
467
+ privKey: this.currentRatchet.ephemeralKeyPair.privKey.toString('base64')
468
+ },
469
+ lastRemoteEphemeralKey: this.currentRatchet.lastRemoteEphemeralKey.toString('base64'),
470
+ previousCounter: this.currentRatchet.previousCounter,
471
+ rootKey: this.currentRatchet.rootKey.toString('base64')
472
+ },
473
+ indexInfo: {
474
+ baseKey: this.indexInfo.baseKey.toString('base64'),
475
+ baseKeyType: this.indexInfo.baseKeyType,
476
+ closed: this.indexInfo.closed,
477
+ used: this.indexInfo.used,
478
+ created: this.indexInfo.created,
479
+ remoteIdentityKey: this.indexInfo.remoteIdentityKey.toString('base64')
480
+ },
481
+ _chains: this._serialize_chains(this._chains)
482
+ }
483
+ if (this.pendingPreKey) {
484
+ data.pendingPreKey = Object.assign({}, this.pendingPreKey)
485
+ data.pendingPreKey.baseKey = this.pendingPreKey.baseKey.toString('base64')
486
+ }
487
+ return data
488
+ }
489
+ static deserialize(data) {
490
+ const obj = new this()
491
+ obj.registrationId = data.registrationId
492
+ obj.currentRatchet = {
493
+ ephemeralKeyPair: {
494
+ pubKey: Buffer.from(data.currentRatchet.ephemeralKeyPair.pubKey, 'base64'),
495
+ privKey: Buffer.from(data.currentRatchet.ephemeralKeyPair.privKey, 'base64')
496
+ },
497
+ lastRemoteEphemeralKey: Buffer.from(data.currentRatchet.lastRemoteEphemeralKey, 'base64'),
498
+ previousCounter: data.currentRatchet.previousCounter,
499
+ rootKey: Buffer.from(data.currentRatchet.rootKey, 'base64')
500
+ }
501
+ obj.indexInfo = {
502
+ baseKey: Buffer.from(data.indexInfo.baseKey, 'base64'),
503
+ baseKeyType: data.indexInfo.baseKeyType,
504
+ closed: data.indexInfo.closed,
505
+ used: data.indexInfo.used,
506
+ created: data.indexInfo.created,
507
+ remoteIdentityKey: Buffer.from(data.indexInfo.remoteIdentityKey, 'base64')
508
+ }
509
+ obj._chains = this._deserialize_chains(data._chains)
510
+ if (data.pendingPreKey) {
511
+ obj.pendingPreKey = Object.assign({}, data.pendingPreKey)
512
+ obj.pendingPreKey.baseKey = Buffer.from(data.pendingPreKey.baseKey, 'base64')
513
+ }
514
+ return obj
515
+ }
516
+ _serialize_chains(chains) {
517
+ const r = {}
518
+ for (const key of Object.keys(chains)) {
519
+ const c = chains[key]
520
+ const messageKeys = {}
521
+ for (const [idx, mk] of Object.entries(c.messageKeys)) messageKeys[idx] = mk.toString('base64')
522
+ r[key] = {
523
+ chainKey: { counter: c.chainKey.counter, key: c.chainKey.key && c.chainKey.key.toString('base64') },
524
+ chainType: c.chainType,
525
+ messageKeys
526
+ }
527
+ }
528
+ return r
529
+ }
530
+ static _deserialize_chains(chains_data) {
531
+ const r = {}
532
+ for (const key of Object.keys(chains_data)) {
533
+ const c = chains_data[key]
534
+ const messageKeys = {}
535
+ for (const [idx, mk] of Object.entries(c.messageKeys)) messageKeys[idx] = Buffer.from(mk, 'base64')
536
+ r[key] = {
537
+ chainKey: { counter: c.chainKey.counter, key: c.chainKey.key && Buffer.from(c.chainKey.key, 'base64') },
538
+ chainType: c.chainType,
539
+ messageKeys
540
+ }
541
+ }
542
+ return r
543
+ }
544
+ }
545
+
546
+ const migrations = [
547
+ {
548
+ version: 'v1',
549
+ migrate: function migrateV1(data) {
550
+ const sessions = data._sessions
551
+ if (data.registrationId) {
552
+ for (const key in sessions) {
553
+ if (!sessions[key].registrationId) sessions[key].registrationId = data.registrationId
554
+ }
555
+ } else {
556
+ for (const key in sessions) {
557
+ if (sessions[key].indexInfo.closed === -1) {
558
+ console.error('V1 session storage migration error: registrationId', data.registrationId, 'for open session version', data.version)
559
+ }
560
+ }
561
+ }
562
+ }
563
+ }
564
+ ]
565
+
566
+ export class SessionRecord {
567
+ static createEntry() {
568
+ return new SessionEntry()
569
+ }
570
+ static migrate(data) {
571
+ let run = data.version === undefined
572
+ for (let i = 0; i < migrations.length; ++i) {
573
+ if (run) {
574
+ console.info('Migrating session to:', migrations[i].version)
575
+ migrations[i].migrate(data)
576
+ } else if (migrations[i].version === data.version) {
577
+ run = true
578
+ }
579
+ }
580
+ if (!run) throw new Error('Error migrating SessionRecord')
581
+ }
582
+ static deserialize(data) {
583
+ if (data.version !== SESSION_RECORD_VERSION) this.migrate(data)
584
+ const obj = new this()
585
+ if (data._sessions) {
586
+ for (const [key, entry] of Object.entries(data._sessions)) obj.sessions[key] = SessionEntry.deserialize(entry)
587
+ }
588
+ return obj
589
+ }
590
+ constructor() {
591
+ this.sessions = {}
592
+ this.version = SESSION_RECORD_VERSION
593
+ }
594
+ serialize() {
595
+ const _sessions = {}
596
+ for (const [key, entry] of Object.entries(this.sessions)) _sessions[key] = entry.serialize()
597
+ return { _sessions, version: this.version }
598
+ }
599
+ haveOpenSession() {
600
+ const openSession = this.getOpenSession()
601
+ return !!openSession && typeof openSession.registrationId === 'number'
602
+ }
603
+ getSession(key) {
604
+ assertBufferType(key)
605
+ const session = this.sessions[key.toString('base64')]
606
+ if (session && session.indexInfo.baseKeyType === BaseKeyType.OURS) {
607
+ throw new Error('Tried to lookup a session using our basekey')
608
+ }
609
+ return session
610
+ }
611
+ getOpenSession() {
612
+ for (const session of Object.values(this.sessions)) {
613
+ if (!this.isClosed(session)) return session
614
+ }
615
+ }
616
+ setSession(session) {
617
+ this.sessions[session.indexInfo.baseKey.toString('base64')] = session
618
+ }
619
+ getSessions() {
620
+ // Return sessions ordered with most recently used first.
621
+ return Array.from(Object.values(this.sessions)).sort((a, b) => {
622
+ const aUsed = a.indexInfo.used || 0
623
+ const bUsed = b.indexInfo.used || 0
624
+ return aUsed === bUsed ? 0 : aUsed < bUsed ? 1 : -1
625
+ })
626
+ }
627
+ closeSession(session) {
628
+ if (this.isClosed(session)) {
629
+ console.warn('Session already closed', session)
630
+ return
631
+ }
632
+ console.info('Closing session:', session)
633
+ session.indexInfo.closed = Date.now()
634
+ }
635
+ openSession(session) {
636
+ if (!this.isClosed(session)) console.warn('Session already open')
637
+ console.info('Opening session:', session)
638
+ session.indexInfo.closed = -1
639
+ }
640
+ isClosed(session) {
641
+ return session.indexInfo.closed !== -1
642
+ }
643
+ removeOldSessions() {
644
+ while (Object.keys(this.sessions).length > CLOSED_SESSIONS_MAX) {
645
+ let oldestKey
646
+ let oldestSession
647
+ for (const [key, session] of Object.entries(this.sessions)) {
648
+ if (session.indexInfo.closed !== -1 && (!oldestSession || session.indexInfo.closed < oldestSession.indexInfo.closed)) {
649
+ oldestKey = key
650
+ oldestSession = session
651
+ }
652
+ }
653
+ if (oldestKey) {
654
+ console.info('Removing old closed session:', oldestSession)
655
+ delete this.sessions[oldestKey]
656
+ } else {
657
+ throw new Error('Corrupt sessions object')
658
+ }
659
+ }
660
+ }
661
+ deleteAllSessions() {
662
+ for (const key of Object.keys(this.sessions)) delete this.sessions[key]
663
+ }
664
+ }
665
+
666
+ /* ------------------------------------------------------------------ */
667
+ /* SessionBuilder (X3DH) */
668
+ /* ------------------------------------------------------------------ */
669
+
670
+ export class SessionBuilder {
671
+ constructor(storage, protocolAddress) {
672
+ this.addr = protocolAddress
673
+ this.storage = storage
674
+ }
675
+
676
+ async initOutgoing(device) {
677
+ const fqAddr = this.addr.toString()
678
+ return await queueJob(fqAddr, async () => {
679
+ if (!(await this.storage.isTrustedIdentity(this.addr.id, device.identityKey))) {
680
+ throw new UntrustedIdentityKeyError(this.addr.id, device.identityKey)
681
+ }
682
+ curve.verifySignature(device.identityKey, device.signedPreKey.publicKey, device.signedPreKey.signature, true)
683
+ const baseKey = curve.generateKeyPair()
684
+ const devicePreKey = device.preKey && device.preKey.publicKey
685
+ const session = await this.initSession(
686
+ true,
687
+ baseKey,
688
+ undefined,
689
+ device.identityKey,
690
+ devicePreKey,
691
+ device.signedPreKey.publicKey,
692
+ device.registrationId
693
+ )
694
+ session.pendingPreKey = { signedKeyId: device.signedPreKey.keyId, baseKey: baseKey.pubKey }
695
+ if (device.preKey) session.pendingPreKey.preKeyId = device.preKey.keyId
696
+ let record = await this.storage.loadSession(fqAddr)
697
+ if (!record) {
698
+ record = new SessionRecord()
699
+ } else {
700
+ const openSession = record.getOpenSession()
701
+ if (openSession) record.closeSession(openSession)
702
+ }
703
+ record.setSession(session)
704
+ await this.storage.storeSession(fqAddr, record)
705
+ })
706
+ }
707
+
708
+ async initIncoming(record, message) {
709
+ const fqAddr = this.addr.toString()
710
+ if (!(await this.storage.isTrustedIdentity(fqAddr, message.identityKey))) {
711
+ throw new UntrustedIdentityKeyError(this.addr.id, message.identityKey)
712
+ }
713
+ if (record.getSession(message.baseKey)) {
714
+ // This just means we haven't replied.
715
+ return
716
+ }
717
+ const preKeyPair = await this.storage.loadPreKey(message.preKeyId)
718
+ if (message.preKeyId && !preKeyPair) throw new PreKeyError('Invalid PreKey ID')
719
+ const signedPreKeyPair = await this.storage.loadSignedPreKey(message.signedPreKeyId)
720
+ if (!signedPreKeyPair) throw new PreKeyError('Missing SignedPreKey')
721
+ const existingOpenSession = record.getOpenSession()
722
+ if (existingOpenSession) {
723
+ console.warn('Closing open session in favor of incoming prekey bundle')
724
+ record.closeSession(existingOpenSession)
725
+ }
726
+ record.setSession(
727
+ await this.initSession(false, preKeyPair, signedPreKeyPair, message.identityKey, message.baseKey, undefined, message.registrationId)
728
+ )
729
+ return message.preKeyId
730
+ }
731
+
732
+ async initSession(isInitiator, ourEphemeralKey, ourSignedKey, theirIdentityPubKey, theirEphemeralPubKey, theirSignedPubKey, registrationId) {
733
+ if (isInitiator) {
734
+ if (ourSignedKey) throw new Error('Invalid call to initSession')
735
+ ourSignedKey = ourEphemeralKey
736
+ } else {
737
+ if (theirSignedPubKey) throw new Error('Invalid call to initSession')
738
+ theirSignedPubKey = theirEphemeralPubKey
739
+ }
740
+ let sharedSecret
741
+ if (!ourEphemeralKey || !theirEphemeralPubKey) sharedSecret = new Uint8Array(32 * 4)
742
+ else sharedSecret = new Uint8Array(32 * 5)
743
+ for (let i = 0; i < 32; i++) sharedSecret[i] = 0xff
744
+ const ourIdentityKey = await this.storage.getOurIdentity()
745
+ const a1 = curve.calculateAgreement(theirSignedPubKey, ourIdentityKey.privKey)
746
+ const a2 = curve.calculateAgreement(theirIdentityPubKey, ourSignedKey.privKey)
747
+ const a3 = curve.calculateAgreement(theirSignedPubKey, ourSignedKey.privKey)
748
+ if (isInitiator) {
749
+ sharedSecret.set(new Uint8Array(a1), 32)
750
+ sharedSecret.set(new Uint8Array(a2), 32 * 2)
751
+ } else {
752
+ sharedSecret.set(new Uint8Array(a1), 32 * 2)
753
+ sharedSecret.set(new Uint8Array(a2), 32)
754
+ }
755
+ sharedSecret.set(new Uint8Array(a3), 32 * 3)
756
+ if (ourEphemeralKey && theirEphemeralPubKey) {
757
+ const a4 = curve.calculateAgreement(theirEphemeralPubKey, ourEphemeralKey.privKey)
758
+ sharedSecret.set(new Uint8Array(a4), 32 * 4)
759
+ }
760
+ const masterKey = crypto.deriveSecrets(Buffer.from(sharedSecret), Buffer.alloc(32), Buffer.from('WhisperText'))
761
+ const session = SessionRecord.createEntry()
762
+ session.registrationId = registrationId
763
+ session.currentRatchet = {
764
+ rootKey: masterKey[0],
765
+ ephemeralKeyPair: isInitiator ? curve.generateKeyPair() : ourSignedKey,
766
+ lastRemoteEphemeralKey: theirSignedPubKey,
767
+ previousCounter: 0
768
+ }
769
+ session.indexInfo = {
770
+ created: Date.now(),
771
+ used: Date.now(),
772
+ remoteIdentityKey: theirIdentityPubKey,
773
+ baseKey: isInitiator ? ourEphemeralKey.pubKey : theirEphemeralPubKey,
774
+ baseKeyType: isInitiator ? BaseKeyType.OURS : BaseKeyType.THEIRS,
775
+ closed: -1
776
+ }
777
+ if (isInitiator) {
778
+ // If we're initiating we go ahead and set our first sending ephemeral key now,
779
+ // otherwise we figure it out when we first maybeStepRatchet with the remote's ephemeral key
780
+ this.calculateSendingRatchet(session, theirSignedPubKey)
781
+ }
782
+ return session
783
+ }
784
+
785
+ calculateSendingRatchet(session, remoteKey) {
786
+ const ratchet = session.currentRatchet
787
+ const sharedSecret = curve.calculateAgreement(remoteKey, ratchet.ephemeralKeyPair.privKey)
788
+ const masterKey = crypto.deriveSecrets(sharedSecret, ratchet.rootKey, Buffer.from('WhisperRatchet'))
789
+ session.addChain(ratchet.ephemeralKeyPair.pubKey, {
790
+ messageKeys: {},
791
+ chainKey: { counter: -1, key: masterKey[1] },
792
+ chainType: ChainType.SENDING
793
+ })
794
+ ratchet.rootKey = masterKey[0]
795
+ }
796
+ }
797
+
798
+ /* ------------------------------------------------------------------ */
799
+ /* SessionCipher (Double Ratchet) */
800
+ /* ------------------------------------------------------------------ */
801
+
802
+ const VERSION = 3
803
+
804
+ export class SessionCipher {
805
+ constructor(storage, protocolAddress) {
806
+ if (!(protocolAddress instanceof ProtocolAddress)) throw new TypeError('protocolAddress must be a ProtocolAddress')
807
+ this.addr = protocolAddress
808
+ this.storage = storage
809
+ }
810
+
811
+ _encodeTupleByte(number1, number2) {
812
+ if (number1 > 15 || number2 > 15) throw TypeError('Numbers must be 4 bits or less')
813
+ return (number1 << 4) | number2
814
+ }
815
+
816
+ _decodeTupleByte(byte) {
817
+ return [byte >> 4, byte & 0xf]
818
+ }
819
+
820
+ toString() {
821
+ return `<SessionCipher(${this.addr.toString()})>`
822
+ }
823
+
824
+ async getRecord() {
825
+ const record = await this.storage.loadSession(this.addr.toString())
826
+ if (record && !(record instanceof SessionRecord)) throw new TypeError('SessionRecord type expected from loadSession')
827
+ return record
828
+ }
829
+
830
+ async storeRecord(record) {
831
+ record.removeOldSessions()
832
+ await this.storage.storeSession(this.addr.toString(), record)
833
+ }
834
+
835
+ async queueJob(awaitable) {
836
+ return await queueJob(this.addr.toString(), awaitable)
837
+ }
838
+
839
+ async encrypt(data) {
840
+ assertBuffer(data)
841
+ const ourIdentityKey = await this.storage.getOurIdentity()
842
+ return await this.queueJob(async () => {
843
+ const record = await this.getRecord()
844
+ if (!record) throw new SessionError('No sessions')
845
+ const session = record.getOpenSession()
846
+ if (!session) throw new SessionError('No open session')
847
+ const remoteIdentityKey = session.indexInfo.remoteIdentityKey
848
+ if (!(await this.storage.isTrustedIdentity(this.addr.id, remoteIdentityKey))) {
849
+ throw new UntrustedIdentityKeyError(this.addr.id, remoteIdentityKey)
850
+ }
851
+ const chain = session.getChain(session.currentRatchet.ephemeralKeyPair.pubKey)
852
+ if (chain.chainType === ChainType.RECEIVING) throw new Error('Tried to encrypt on a receiving chain')
853
+ this.fillMessageKeys(chain, chain.chainKey.counter + 1)
854
+ const keys = crypto.deriveSecrets(chain.messageKeys[chain.chainKey.counter], Buffer.alloc(32), Buffer.from('WhisperMessageKeys'))
855
+ delete chain.messageKeys[chain.chainKey.counter]
856
+ const msg = WhisperMessage.create()
857
+ msg.ephemeralKey = session.currentRatchet.ephemeralKeyPair.pubKey
858
+ msg.counter = chain.chainKey.counter
859
+ msg.previousCounter = session.currentRatchet.previousCounter
860
+ msg.ciphertext = crypto.encrypt(keys[0], data, keys[2].slice(0, 16))
861
+ const msgBuf = WhisperMessage.encode(msg).finish()
862
+ const macInput = Buffer.alloc(msgBuf.byteLength + 33 * 2 + 1)
863
+ macInput.set(ourIdentityKey.pubKey)
864
+ macInput.set(session.indexInfo.remoteIdentityKey, 33)
865
+ macInput[33 * 2] = this._encodeTupleByte(VERSION, VERSION)
866
+ macInput.set(msgBuf, 33 * 2 + 1)
867
+ const mac = crypto.calculateMAC(keys[1], macInput)
868
+ const result = Buffer.alloc(msgBuf.byteLength + 9)
869
+ result[0] = this._encodeTupleByte(VERSION, VERSION)
870
+ result.set(msgBuf, 1)
871
+ result.set(mac.slice(0, 8), msgBuf.byteLength + 1)
872
+ await this.storeRecord(record)
873
+ let type, body
874
+ if (session.pendingPreKey) {
875
+ type = 3 // prekey bundle
876
+ const preKeyMsg = PreKeyWhisperMessage.create({
877
+ identityKey: ourIdentityKey.pubKey,
878
+ registrationId: await this.storage.getOurRegistrationId(),
879
+ baseKey: session.pendingPreKey.baseKey,
880
+ signedPreKeyId: session.pendingPreKey.signedKeyId,
881
+ message: result
882
+ })
883
+ if (session.pendingPreKey.preKeyId) preKeyMsg.preKeyId = session.pendingPreKey.preKeyId
884
+ body = Buffer.concat([
885
+ Buffer.from([this._encodeTupleByte(VERSION, VERSION)]),
886
+ Buffer.from(PreKeyWhisperMessage.encode(preKeyMsg).finish())
887
+ ])
888
+ } else {
889
+ type = 1 // normal
890
+ body = result
891
+ }
892
+ return { type, body, registrationId: session.registrationId }
893
+ })
894
+ }
895
+
896
+ async decryptWithSessions(data, sessions) {
897
+ // Iterate through the sessions, attempting to decrypt using each one.
898
+ // Stop and return the result if we get a valid result.
899
+ if (!sessions.length) throw new SessionError('No sessions available')
900
+ const errs = []
901
+ for (const session of sessions) {
902
+ let plaintext
903
+ try {
904
+ plaintext = await this.doDecryptWhisperMessage(data, session)
905
+ session.indexInfo.used = Date.now()
906
+ return { session, plaintext }
907
+ } catch (e) {
908
+ errs.push(e)
909
+ }
910
+ }
911
+ console.error('Failed to decrypt message with any known session...')
912
+ for (const e of errs) console.error('Session error:' + e, e.stack)
913
+ throw new SessionError('No matching sessions found for message')
914
+ }
915
+
916
+ async decryptWhisperMessage(data) {
917
+ assertBuffer(data)
918
+ return await this.queueJob(async () => {
919
+ const record = await this.getRecord()
920
+ if (!record) throw new SessionError('No session record')
921
+ const result = await this.decryptWithSessions(data, record.getSessions())
922
+ const remoteIdentityKey = result.session.indexInfo.remoteIdentityKey
923
+ if (!(await this.storage.isTrustedIdentity(this.addr.id, remoteIdentityKey))) {
924
+ throw new UntrustedIdentityKeyError(this.addr.id, remoteIdentityKey)
925
+ }
926
+ if (record.isClosed(result.session)) {
927
+ // It's possible for this to happen when processing a backlog of messages.
928
+ console.warn('Decrypted message with closed session.')
929
+ }
930
+ await this.storeRecord(record)
931
+ return result.plaintext
932
+ })
933
+ }
934
+
935
+ async decryptPreKeyWhisperMessage(data) {
936
+ assertBuffer(data)
937
+ const versions = this._decodeTupleByte(data[0])
938
+ if (versions[1] > 3 || versions[0] < 3) throw new Error('Incompatible version number on PreKeyWhisperMessage')
939
+ return await this.queueJob(async () => {
940
+ let record = await this.getRecord()
941
+ const preKeyProto = PreKeyWhisperMessage.decode(data.slice(1))
942
+ if (!record) {
943
+ if (preKeyProto.registrationId == null) throw new Error('No registrationId')
944
+ record = new SessionRecord()
945
+ }
946
+ const builder = new SessionBuilder(this.storage, this.addr)
947
+ const preKeyId = await builder.initIncoming(record, preKeyProto)
948
+ const session = record.getSession(preKeyProto.baseKey)
949
+ const plaintext = await this.doDecryptWhisperMessage(preKeyProto.message, session)
950
+ await this.storeRecord(record)
951
+ if (preKeyId) await this.storage.removePreKey(preKeyId)
952
+ return plaintext
953
+ })
954
+ }
955
+
956
+ async doDecryptWhisperMessage(messageBuffer, session) {
957
+ assertBuffer(messageBuffer)
958
+ if (!session) throw new TypeError('session required')
959
+ const versions = this._decodeTupleByte(messageBuffer[0])
960
+ if (versions[1] > 3 || versions[0] < 3) throw new Error('Incompatible version number on WhisperMessage')
961
+ const messageProto = messageBuffer.slice(1, -8)
962
+ const message = WhisperMessage.decode(messageProto)
963
+ this.maybeStepRatchet(session, message.ephemeralKey, message.previousCounter)
964
+ const chain = session.getChain(message.ephemeralKey)
965
+ if (chain.chainType === ChainType.SENDING) throw new Error('Tried to decrypt on a sending chain')
966
+ this.fillMessageKeys(chain, message.counter)
967
+ if (!Object.prototype.hasOwnProperty.call(chain.messageKeys, message.counter)) {
968
+ // Most likely the message was already decrypted and we are trying to process twice.
969
+ throw new MessageCounterError('Key used already or never filled')
970
+ }
971
+ const messageKey = chain.messageKeys[message.counter]
972
+ delete chain.messageKeys[message.counter]
973
+ const keys = crypto.deriveSecrets(messageKey, Buffer.alloc(32), Buffer.from('WhisperMessageKeys'))
974
+ const ourIdentityKey = await this.storage.getOurIdentity()
975
+ const macInput = Buffer.alloc(messageProto.byteLength + 33 * 2 + 1)
976
+ macInput.set(session.indexInfo.remoteIdentityKey)
977
+ macInput.set(ourIdentityKey.pubKey, 33)
978
+ macInput[33 * 2] = this._encodeTupleByte(VERSION, VERSION)
979
+ macInput.set(messageProto, 33 * 2 + 1)
980
+ // This is where we most likely fail if the session is not a match.
981
+ crypto.verifyMAC(macInput, keys[1], messageBuffer.slice(-8), 8)
982
+ const plaintext = crypto.decrypt(keys[0], message.ciphertext, keys[2].slice(0, 16))
983
+ delete session.pendingPreKey
984
+ return plaintext
985
+ }
986
+
987
+ fillMessageKeys(chain, counter) {
988
+ if (chain.chainKey.counter >= counter) return
989
+ if (counter - chain.chainKey.counter > 2000) throw new SessionError('Over 2000 messages into the future!')
990
+ if (chain.chainKey.key === undefined) throw new SessionError('Chain closed')
991
+ const key = chain.chainKey.key
992
+ chain.messageKeys[chain.chainKey.counter + 1] = crypto.calculateMAC(key, Buffer.from([1]))
993
+ chain.chainKey.key = crypto.calculateMAC(key, Buffer.from([2]))
994
+ chain.chainKey.counter += 1
995
+ return this.fillMessageKeys(chain, counter)
996
+ }
997
+
998
+ maybeStepRatchet(session, remoteKey, previousCounter) {
999
+ if (session.getChain(remoteKey)) return
1000
+ const ratchet = session.currentRatchet
1001
+ const previousRatchet = session.getChain(ratchet.lastRemoteEphemeralKey)
1002
+ if (previousRatchet) {
1003
+ this.fillMessageKeys(previousRatchet, previousCounter)
1004
+ delete previousRatchet.chainKey.key // Close
1005
+ }
1006
+ this.calculateRatchet(session, remoteKey, false)
1007
+ // Now swap the ephemeral key and calculate the new sending chain
1008
+ const prevCounter = session.getChain(ratchet.ephemeralKeyPair.pubKey)
1009
+ if (prevCounter) {
1010
+ ratchet.previousCounter = prevCounter.chainKey.counter
1011
+ session.deleteChain(ratchet.ephemeralKeyPair.pubKey)
1012
+ }
1013
+ ratchet.ephemeralKeyPair = curve.generateKeyPair()
1014
+ this.calculateRatchet(session, remoteKey, true)
1015
+ ratchet.lastRemoteEphemeralKey = remoteKey
1016
+ }
1017
+
1018
+ calculateRatchet(session, remoteKey, sending) {
1019
+ const ratchet = session.currentRatchet
1020
+ const sharedSecret = curve.calculateAgreement(remoteKey, ratchet.ephemeralKeyPair.privKey)
1021
+ const masterKey = crypto.deriveSecrets(sharedSecret, ratchet.rootKey, Buffer.from('WhisperRatchet'), /*chunks*/ 2)
1022
+ const chainKey = sending ? ratchet.ephemeralKeyPair.pubKey : remoteKey
1023
+ session.addChain(chainKey, {
1024
+ messageKeys: {},
1025
+ chainKey: { counter: -1, key: masterKey[1] },
1026
+ chainType: sending ? ChainType.SENDING : ChainType.RECEIVING
1027
+ })
1028
+ ratchet.rootKey = masterKey[0]
1029
+ }
1030
+
1031
+ async hasOpenSession() {
1032
+ return await this.queueJob(async () => {
1033
+ const record = await this.getRecord()
1034
+ if (!record) return false
1035
+ return record.haveOpenSession()
1036
+ })
1037
+ }
1038
+
1039
+ async closeOpenSession() {
1040
+ return await this.queueJob(async () => {
1041
+ const record = await this.getRecord()
1042
+ if (record) {
1043
+ const openSession = record.getOpenSession()
1044
+ if (openSession) {
1045
+ record.closeSession(openSession)
1046
+ await this.storeRecord(record)
1047
+ }
1048
+ }
1049
+ })
1050
+ }
1051
+ }