@itznomo/baileys 0.0.0-stage → 0.0.3

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,455 @@
1
+ import * as nodeCrypto from 'node:crypto'
2
+ import { crypto as signalCrypto, curve as signalCurve } from './libsignal.js'
3
+
4
+ const { calculateMAC, decrypt, deriveSecrets, encrypt } = signalCrypto
5
+ const { calculateSignature, generateKeyPair, verifySignature } = signalCurve
6
+ import { proto } from '../../WAProto/index.js'
7
+ import { BufferJSON } from '../utils/wa-protocol-core.js'
8
+
9
+ export class CiphertextMessage {
10
+ constructor() {
11
+ this.UNSUPPORTED_VERSION = 1
12
+ this.CURRENT_VERSION = 3
13
+ this.WHISPER_TYPE = 2
14
+ this.PREKEY_TYPE = 3
15
+ this.SENDERKEY_TYPE = 4
16
+ this.SENDERKEY_DISTRIBUTION_TYPE = 5
17
+ this.ENCRYPTED_MESSAGE_OVERHEAD = 53
18
+ }
19
+ }
20
+
21
+ export const keyhelper = {
22
+ generateSenderKey() {
23
+ return nodeCrypto.randomBytes(32)
24
+ },
25
+ generateSenderKeyId() {
26
+ return nodeCrypto.randomInt(2147483647)
27
+ },
28
+ generateSenderSigningKey(key) {
29
+ if (!key) key = generateKeyPair()
30
+ return {
31
+ public: Buffer.from(key.pubKey),
32
+ private: Buffer.from(key.privKey)
33
+ }
34
+ }
35
+ }
36
+
37
+ function isNull(str) {
38
+ return str === null || str === ''
39
+ }
40
+ function intValue(num) {
41
+ const MAX_VALUE = 0x7fffffff
42
+ const MIN_VALUE = -0x80000000
43
+ if (num > MAX_VALUE || num < MIN_VALUE) return num & 0xffffffff
44
+ return num
45
+ }
46
+ function hashCode(strKey) {
47
+ let hash = 0
48
+ if (!isNull(strKey)) {
49
+ for (let i = 0; i < strKey.length; i++) {
50
+ hash = hash * 31 + strKey.charCodeAt(i)
51
+ hash = intValue(hash)
52
+ }
53
+ }
54
+ return hash
55
+ }
56
+
57
+ export class SenderKeyName {
58
+ constructor(groupId, sender) {
59
+ this.groupId = groupId
60
+ this.sender = sender
61
+ }
62
+ getGroupId() {
63
+ return this.groupId
64
+ }
65
+ getSender() {
66
+ return this.sender
67
+ }
68
+ serialize() {
69
+ return `${this.groupId}::${this.sender.id}::${this.sender.deviceId}`
70
+ }
71
+ toString() {
72
+ return this.serialize()
73
+ }
74
+ equals(other) {
75
+ if (other === null) return false
76
+ return this.groupId === other.groupId && this.sender.toString() === other.sender.toString()
77
+ }
78
+ hashCode() {
79
+ return hashCode(this.groupId) ^ hashCode(this.sender.toString())
80
+ }
81
+ }
82
+
83
+ export class SenderMessageKey {
84
+ constructor(iteration, seed) {
85
+ const derivative = deriveSecrets(seed, Buffer.alloc(32), Buffer.from('WhisperGroup'))
86
+ const keys = new Uint8Array(32)
87
+ keys.set(new Uint8Array(derivative[0].slice(16)))
88
+ keys.set(new Uint8Array(derivative[1].slice(0, 16)), 16)
89
+ this.iv = Buffer.from(derivative[0].slice(0, 16))
90
+ this.cipherKey = Buffer.from(keys.buffer)
91
+ this.iteration = iteration
92
+ this.seed = seed
93
+ }
94
+ getIteration() {
95
+ return this.iteration
96
+ }
97
+ getIv() {
98
+ return this.iv
99
+ }
100
+ getCipherKey() {
101
+ return this.cipherKey
102
+ }
103
+ getSeed() {
104
+ return this.seed
105
+ }
106
+ }
107
+
108
+ export class SenderChainKey {
109
+ constructor(iteration, chainKey) {
110
+ this.MESSAGE_KEY_SEED = Buffer.from([0x01])
111
+ this.CHAIN_KEY_SEED = Buffer.from([0x02])
112
+ this.iteration = iteration
113
+ this.chainKey = Buffer.from(chainKey)
114
+ }
115
+ getIteration() {
116
+ return this.iteration
117
+ }
118
+ getSenderMessageKey() {
119
+ return new SenderMessageKey(this.iteration, this.getDerivative(this.MESSAGE_KEY_SEED, this.chainKey))
120
+ }
121
+ getNext() {
122
+ return new SenderChainKey(this.iteration + 1, this.getDerivative(this.CHAIN_KEY_SEED, this.chainKey))
123
+ }
124
+ getSeed() {
125
+ return this.chainKey
126
+ }
127
+ getDerivative(seed, key) {
128
+ return calculateMAC(key, seed)
129
+ }
130
+ }
131
+
132
+ export class SenderKeyState {
133
+ constructor(id, iteration, chainKey, signatureKeyPair, signatureKeyPublic, signatureKeyPrivate, senderKeyStateStructure) {
134
+ this.MAX_MESSAGE_KEYS = 2000
135
+ if (senderKeyStateStructure) {
136
+ this.senderKeyStateStructure = {
137
+ ...senderKeyStateStructure,
138
+ senderMessageKeys: Array.isArray(senderKeyStateStructure.senderMessageKeys) ? senderKeyStateStructure.senderMessageKeys : []
139
+ }
140
+ } else {
141
+ if (signatureKeyPair) {
142
+ signatureKeyPublic = signatureKeyPair.public
143
+ signatureKeyPrivate = signatureKeyPair.private
144
+ }
145
+ this.senderKeyStateStructure = {
146
+ senderKeyId: id || 0,
147
+ senderChainKey: {
148
+ iteration: iteration || 0,
149
+ seed: Buffer.from(chainKey || [])
150
+ },
151
+ senderSigningKey: {
152
+ public: Buffer.from(signatureKeyPublic || []),
153
+ private: Buffer.from(signatureKeyPrivate || [])
154
+ },
155
+ senderMessageKeys: []
156
+ }
157
+ }
158
+ }
159
+ getKeyId() {
160
+ return this.senderKeyStateStructure.senderKeyId
161
+ }
162
+ getSenderChainKey() {
163
+ return new SenderChainKey(this.senderKeyStateStructure.senderChainKey.iteration, this.senderKeyStateStructure.senderChainKey.seed)
164
+ }
165
+ setSenderChainKey(chainKey) {
166
+ this.senderKeyStateStructure.senderChainKey = {
167
+ iteration: chainKey.getIteration(),
168
+ seed: chainKey.getSeed()
169
+ }
170
+ }
171
+ getSigningKeyPublic() {
172
+ const publicKey = Buffer.from(this.senderKeyStateStructure.senderSigningKey.public)
173
+ if (publicKey.length === 32) {
174
+ const fixed = Buffer.alloc(33)
175
+ fixed[0] = 0x05
176
+ publicKey.copy(fixed, 1)
177
+ return fixed
178
+ }
179
+ return publicKey
180
+ }
181
+ getSigningKeyPrivate() {
182
+ const privateKey = this.senderKeyStateStructure.senderSigningKey.private
183
+ return Buffer.from(privateKey || [])
184
+ }
185
+ hasSenderMessageKey(iteration) {
186
+ return this.senderKeyStateStructure.senderMessageKeys.some(key => key.iteration === iteration)
187
+ }
188
+ addSenderMessageKey(senderMessageKey) {
189
+ this.senderKeyStateStructure.senderMessageKeys.push({
190
+ iteration: senderMessageKey.getIteration(),
191
+ seed: senderMessageKey.getSeed()
192
+ })
193
+ if (this.senderKeyStateStructure.senderMessageKeys.length > this.MAX_MESSAGE_KEYS) {
194
+ this.senderKeyStateStructure.senderMessageKeys.shift()
195
+ }
196
+ }
197
+ removeSenderMessageKey(iteration) {
198
+ const index = this.senderKeyStateStructure.senderMessageKeys.findIndex(key => key.iteration === iteration)
199
+ if (index !== -1) {
200
+ const messageKey = this.senderKeyStateStructure.senderMessageKeys[index]
201
+ this.senderKeyStateStructure.senderMessageKeys.splice(index, 1)
202
+ return new SenderMessageKey(messageKey.iteration, messageKey.seed)
203
+ }
204
+ return null
205
+ }
206
+ getStructure() {
207
+ return this.senderKeyStateStructure
208
+ }
209
+ }
210
+
211
+ export class SenderKeyRecord {
212
+ constructor(serialized) {
213
+ this.MAX_STATES = 5
214
+ this.senderKeyStates = []
215
+ if (serialized) {
216
+ for (const structure of serialized) {
217
+ this.senderKeyStates.push(new SenderKeyState(null, null, null, null, null, null, structure))
218
+ }
219
+ }
220
+ }
221
+ isEmpty() {
222
+ return this.senderKeyStates.length === 0
223
+ }
224
+ getSenderKeyState(keyId) {
225
+ if (keyId === undefined && this.senderKeyStates.length) {
226
+ return this.senderKeyStates[this.senderKeyStates.length - 1]
227
+ }
228
+ return this.senderKeyStates.find(state => state.getKeyId() === keyId)
229
+ }
230
+ addSenderKeyState(id, iteration, chainKey, signatureKey) {
231
+ this.senderKeyStates.push(new SenderKeyState(id, iteration, chainKey, null, signatureKey))
232
+ if (this.senderKeyStates.length > this.MAX_STATES) this.senderKeyStates.shift()
233
+ }
234
+ setSenderKeyState(id, iteration, chainKey, keyPair) {
235
+ this.senderKeyStates.length = 0
236
+ this.senderKeyStates.push(new SenderKeyState(id, iteration, chainKey, keyPair))
237
+ }
238
+ serialize() {
239
+ return this.senderKeyStates.map(state => state.getStructure())
240
+ }
241
+ static deserialize(data) {
242
+ if (typeof data === 'object' && !Buffer.isBuffer(data) && !Array.isArray(data) && data.senderKeyStates) {
243
+ return new SenderKeyRecord(data)
244
+ }
245
+ const str = typeof data === 'string' ? data : (Buffer.isBuffer(data) ? data.toString('utf-8') : Buffer.from(data).toString('utf-8'))
246
+ const parsed = JSON.parse(str, BufferJSON.reviver)
247
+ return new SenderKeyRecord(parsed)
248
+ }
249
+ }
250
+
251
+ export class SenderKeyDistributionMessage extends CiphertextMessage {
252
+ constructor(id, iteration, chainKey, signatureKey, serialized) {
253
+ super()
254
+ if (serialized) {
255
+ try {
256
+ const message = serialized.slice(1)
257
+ const distributionMessage = proto.SenderKeyDistributionMessage.decode(message).toJSON()
258
+ this.serialized = serialized
259
+ this.id = distributionMessage.id
260
+ this.iteration = distributionMessage.iteration
261
+ this.chainKey =
262
+ typeof distributionMessage.chainKey === 'string' ? Buffer.from(distributionMessage.chainKey, 'base64') : distributionMessage.chainKey
263
+ this.signatureKey =
264
+ typeof distributionMessage.signingKey === 'string' ? Buffer.from(distributionMessage.signingKey, 'base64') : distributionMessage.signingKey
265
+ } catch (e) {
266
+ throw new Error(String(e))
267
+ }
268
+ } else {
269
+ const version = this.intsToByteHighAndLow(this.CURRENT_VERSION, this.CURRENT_VERSION)
270
+ this.id = id
271
+ this.iteration = iteration
272
+ this.chainKey = chainKey
273
+ this.signatureKey = signatureKey
274
+ const message = proto.SenderKeyDistributionMessage.encode(
275
+ proto.SenderKeyDistributionMessage.create({ id, iteration, chainKey, signingKey: this.signatureKey })
276
+ ).finish()
277
+ this.serialized = Buffer.concat([Buffer.from([version]), message])
278
+ }
279
+ }
280
+ intsToByteHighAndLow(highValue, lowValue) {
281
+ return (((highValue << 4) | lowValue) & 0xff) % 256
282
+ }
283
+ serialize() {
284
+ return this.serialized
285
+ }
286
+ getType() {
287
+ return this.SENDERKEY_DISTRIBUTION_TYPE
288
+ }
289
+ getIteration() {
290
+ return this.iteration
291
+ }
292
+ getChainKey() {
293
+ return this.chainKey
294
+ }
295
+ getSignatureKey() {
296
+ return this.signatureKey
297
+ }
298
+ getId() {
299
+ return this.id
300
+ }
301
+ }
302
+
303
+ export class SenderKeyMessage extends CiphertextMessage {
304
+ constructor(keyId, iteration, ciphertext, signatureKey, serialized) {
305
+ super()
306
+ this.SIGNATURE_LENGTH = 64
307
+ if (serialized) {
308
+ const version = serialized[0]
309
+ const message = serialized.slice(1, serialized.length - this.SIGNATURE_LENGTH)
310
+ const signature = serialized.slice(-1 * this.SIGNATURE_LENGTH)
311
+ const senderKeyMessage = proto.SenderKeyMessage.decode(message).toJSON()
312
+ this.serialized = serialized
313
+ this.messageVersion = (version & 0xff) >> 4
314
+ this.keyId = senderKeyMessage.id
315
+ this.iteration = senderKeyMessage.iteration
316
+ this.ciphertext =
317
+ typeof senderKeyMessage.ciphertext === 'string' ? Buffer.from(senderKeyMessage.ciphertext, 'base64') : senderKeyMessage.ciphertext
318
+ this.signature = signature
319
+ } else {
320
+ const version = (((this.CURRENT_VERSION << 4) | this.CURRENT_VERSION) & 0xff) % 256
321
+ const ciphertextBuffer = Buffer.from(ciphertext)
322
+ const message = proto.SenderKeyMessage.encode(
323
+ proto.SenderKeyMessage.create({ id: keyId, iteration, ciphertext: ciphertextBuffer })
324
+ ).finish()
325
+ const signature = this.getSignature(signatureKey, Buffer.concat([Buffer.from([version]), message]))
326
+ this.serialized = Buffer.concat([Buffer.from([version]), message, Buffer.from(signature)])
327
+ this.messageVersion = this.CURRENT_VERSION
328
+ this.keyId = keyId
329
+ this.iteration = iteration
330
+ this.ciphertext = ciphertextBuffer
331
+ this.signature = signature
332
+ }
333
+ }
334
+ getKeyId() {
335
+ return this.keyId
336
+ }
337
+ getIteration() {
338
+ return this.iteration
339
+ }
340
+ getCipherText() {
341
+ return this.ciphertext
342
+ }
343
+ verifySignature(signatureKey) {
344
+ const part1 = this.serialized.slice(0, this.serialized.length - this.SIGNATURE_LENGTH)
345
+ const part2 = this.serialized.slice(-1 * this.SIGNATURE_LENGTH)
346
+ const res = verifySignature(signatureKey, part1, part2)
347
+ if (!res) throw new Error('Invalid signature!')
348
+ }
349
+ getSignature(signatureKey, serialized) {
350
+ return Buffer.from(calculateSignature(signatureKey, serialized))
351
+ }
352
+ serialize() {
353
+ return this.serialized
354
+ }
355
+ getType() {
356
+ return 4
357
+ }
358
+ }
359
+
360
+ export class GroupSessionBuilder {
361
+ constructor(senderKeyStore) {
362
+ this.senderKeyStore = senderKeyStore
363
+ }
364
+ async process(senderKeyName, senderKeyDistributionMessage) {
365
+ const senderKeyRecord = await this.senderKeyStore.loadSenderKey(senderKeyName)
366
+ senderKeyRecord.addSenderKeyState(
367
+ senderKeyDistributionMessage.getId(),
368
+ senderKeyDistributionMessage.getIteration(),
369
+ senderKeyDistributionMessage.getChainKey(),
370
+ senderKeyDistributionMessage.getSignatureKey()
371
+ )
372
+ await this.senderKeyStore.storeSenderKey(senderKeyName, senderKeyRecord)
373
+ }
374
+ async create(senderKeyName) {
375
+ const senderKeyRecord = await this.senderKeyStore.loadSenderKey(senderKeyName)
376
+ if (senderKeyRecord.isEmpty()) {
377
+ const keyId = keyhelper.generateSenderKeyId()
378
+ const senderKey = keyhelper.generateSenderKey()
379
+ const signingKey = keyhelper.generateSenderSigningKey()
380
+ senderKeyRecord.setSenderKeyState(keyId, 0, senderKey, signingKey)
381
+ await this.senderKeyStore.storeSenderKey(senderKeyName, senderKeyRecord)
382
+ }
383
+ const state = senderKeyRecord.getSenderKeyState()
384
+ if (!state) throw new Error('No session state available')
385
+ return new SenderKeyDistributionMessage(
386
+ state.getKeyId(),
387
+ state.getSenderChainKey().getIteration(),
388
+ state.getSenderChainKey().getSeed(),
389
+ state.getSigningKeyPublic()
390
+ )
391
+ }
392
+ }
393
+
394
+ export class GroupCipher {
395
+ constructor(senderKeyStore, senderKeyName) {
396
+ this.senderKeyStore = senderKeyStore
397
+ this.senderKeyName = senderKeyName
398
+ }
399
+ async encrypt(paddedPlaintext) {
400
+ const record = await this.senderKeyStore.loadSenderKey(this.senderKeyName)
401
+ if (!record) throw new Error('No SenderKeyRecord found for encryption')
402
+ const senderKeyState = record.getSenderKeyState()
403
+ if (!senderKeyState) throw new Error('No session to encrypt message')
404
+ const iteration = senderKeyState.getSenderChainKey().getIteration()
405
+ const senderKey = this.getSenderKey(senderKeyState, iteration === 0 ? 0 : iteration + 1)
406
+ const ciphertext = await this.getCipherText(senderKey.getIv(), senderKey.getCipherKey(), paddedPlaintext)
407
+ const senderKeyMessage = new SenderKeyMessage(senderKeyState.getKeyId(), senderKey.getIteration(), ciphertext, senderKeyState.getSigningKeyPrivate())
408
+ await this.senderKeyStore.storeSenderKey(this.senderKeyName, record)
409
+ return senderKeyMessage.serialize()
410
+ }
411
+ async decrypt(senderKeyMessageBytes) {
412
+ const record = await this.senderKeyStore.loadSenderKey(this.senderKeyName)
413
+ if (!record) throw new Error('No SenderKeyRecord found for decryption')
414
+ const senderKeyMessage = new SenderKeyMessage(null, null, null, null, senderKeyMessageBytes)
415
+ const senderKeyState = record.getSenderKeyState(senderKeyMessage.getKeyId())
416
+ if (!senderKeyState) throw new Error('No session found to decrypt message')
417
+ senderKeyMessage.verifySignature(senderKeyState.getSigningKeyPublic())
418
+ const senderKey = this.getSenderKey(senderKeyState, senderKeyMessage.getIteration())
419
+ const plaintext = await this.getPlainText(senderKey.getIv(), senderKey.getCipherKey(), senderKeyMessage.getCipherText())
420
+ await this.senderKeyStore.storeSenderKey(this.senderKeyName, record)
421
+ return plaintext
422
+ }
423
+ getSenderKey(senderKeyState, iteration) {
424
+ let senderChainKey = senderKeyState.getSenderChainKey()
425
+ if (senderChainKey.getIteration() > iteration) {
426
+ if (senderKeyState.hasSenderMessageKey(iteration)) {
427
+ const messageKey = senderKeyState.removeSenderMessageKey(iteration)
428
+ if (!messageKey) throw new Error('No sender message key found for iteration')
429
+ return messageKey
430
+ }
431
+ throw new Error(`Received message with old counter: ${senderChainKey.getIteration()}, ${iteration}`)
432
+ }
433
+ if (iteration - senderChainKey.getIteration() > 2000) throw new Error('Over 2000 messages into the future!')
434
+ while (senderChainKey.getIteration() < iteration) {
435
+ senderKeyState.addSenderMessageKey(senderChainKey.getSenderMessageKey())
436
+ senderChainKey = senderChainKey.getNext()
437
+ }
438
+ senderKeyState.setSenderChainKey(senderChainKey.getNext())
439
+ return senderChainKey.getSenderMessageKey()
440
+ }
441
+ async getPlainText(iv, key, ciphertext) {
442
+ try {
443
+ return decrypt(key, ciphertext, iv)
444
+ } catch {
445
+ throw new Error('InvalidMessageException')
446
+ }
447
+ }
448
+ async getCipherText(iv, key, plaintext) {
449
+ try {
450
+ return encrypt(key, plaintext, iv)
451
+ } catch {
452
+ throw new Error('InvalidMessageException')
453
+ }
454
+ }
455
+ }