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