boho 2.2.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/boho.js CHANGED
@@ -1,553 +1,350 @@
1
- // Copyright (c) 2024 Taeo Lee (sixgen@gmail.com)
1
+ // Copyright (c) 2024-2026 Taeo Lee (sixgen@gmail.com)
2
2
  // MIT License
3
3
  //
4
4
  // https://github.com/remocons/boho
5
5
  //
6
+ // Boho 3: shared-key authentication and encrypted messages on Ascon (NIST SP 800-232).
6
7
  //
8
+ // login SERVER_TIME_NONCE (13 B) → AUTH_REQ (33 B) → AUTH_RES (17 B)
9
+ // session ENC / ENC_E2E: 21-byte header, Ascon-AEAD128 with an 8-byte tag
10
+ // pack/E2E ENC_PACK: 29-byte header (16-byte nonce with an 8-byte sender value)
7
11
  //
8
- import { sha256 } from './sha256-mbp.js'
12
+ // Keys: Ascon-CXOF128(Z = "boho/v2/key") of the key string, 16 bytes (deriveKey). A server
13
+ // stores this derived key, never the key string. Each login makes a new session key.
14
+ // Boho 2.x (SHA-256 based, classic/) is not supported: its message codes are not reused.
9
15
  import MBP from 'meta-buffer-pack'
10
- export { MBP }
11
- import { BohoMsg, Meta, MetaSize } from './constants.js'
12
- export { BohoMsg, Meta, MetaSize, sha256 }
13
16
  import { Buffer } from 'buffer/index.js'
14
- export { Buffer }
17
+ import { encrypt, decrypt, cxof128 } from './ascon.js'
18
+ import { BohoMsg, MetaSize } from './constants.js'
15
19
 
16
- // Avoid data-dependent early exits when comparing fixed-length tags.
17
- // JavaScript engines do not guarantee constant-time execution.
18
- function equalTag(a, b) {
19
- if (!(a instanceof Uint8Array) || !(b instanceof Uint8Array) || a.length !== b.length) return false
20
- let difference = 0
21
- for (let i = 0; i < a.length; i++) difference |= a[i] ^ b[i]
22
- return difference === 0
20
+ export { MBP, Buffer, BohoMsg, MetaSize }
21
+
22
+ const KEY_CUSTOM = 'boho/v2/key'
23
+ const SESSION_CUSTOM = 'boho/v2/session'
24
+ const TAG = 8
25
+ const KEY_SIZE = 16
26
+ const DIR = { client: 1, server: 2 } // the direction byte of what that side sends
27
+ const encoder = new TextEncoder()
28
+
29
+ /**
30
+ * Random bytes from the platform's cryptographic generator.
31
+ * @param {number} size
32
+ * @returns {Buffer}
33
+ */
34
+ export function RAND (size) {
35
+ const out = Buffer.alloc(size)
36
+ globalThis.crypto.getRandomValues(out)
37
+ return out
23
38
  }
24
39
 
25
- function readPacket(data, type, size, meta, variable = false) {
26
- if (!(data instanceof Uint8Array)) return
27
- const buffer = Buffer.from(data)
28
- if (buffer.length < size || buffer[0] !== type) return
29
- if (variable ? buffer.readUInt32LE(1) !== buffer.length - size : buffer.length !== size) return
30
- return MBP.unpack(buffer, meta)
40
+ function bytes (data) {
41
+ if (typeof data === 'string') return encoder.encode(data)
42
+ return MBP.B8(data)
31
43
  }
32
44
 
33
- function validClock(clock) {
34
- return clock.readUInt16LE(4) < 1000
45
+ function equal (a, b) {
46
+ if (!(a instanceof Uint8Array) || !(b instanceof Uint8Array) || a.length !== b.length) return false
47
+ let difference = 0
48
+ for (let i = 0; i < a.length; i++) difference |= a[i] ^ b[i]
49
+ return difference === 0
35
50
  }
36
51
 
52
+ function wipe (b) { if (b) b.fill(0) }
37
53
 
38
54
  /**
39
- * Generates a random byte buffer.
40
- * @param {number} size - Number of bytes to generate
55
+ * Key string (the part after "id." in id.key, or an E2E key) → the 16-byte key.
56
+ * Servers store it (for example base64) as the key of an ID.
57
+ * @param {string|Uint8Array} key
41
58
  * @returns {Buffer}
42
59
  */
43
- export function RAND(size) {
44
- return globalThis.crypto.getRandomValues(Buffer.alloc(size))
60
+ export function deriveKey (key) {
61
+ const k = bytes(key)
62
+ if (!k.length) throw new RangeError('key must not be empty')
63
+ return Buffer.from(cxof128(k, KEY_SIZE, KEY_CUSTOM))
45
64
  }
46
65
 
47
- /**
48
- * Boho security protocol class
49
- */
50
- export class Boho {
51
- /**
52
- * @constructor
53
- */
54
- constructor() {
55
-
56
- this._id8 = Buffer.alloc(8)
57
- this._otpSrc44 = Buffer.alloc(44)
58
- this._otp36 = Buffer.alloc(36)
59
- this._hmac = Buffer.alloc(32)
60
-
61
- this.auth_salt12 = Buffer.alloc(12)
62
- this.localNonce = Buffer.alloc(4)
63
- this.remoteNonce = Buffer.alloc(4)
64
- this.isAuthorized = false
65
- this.counter = 0
66
- this._hasKey = false
67
- this._lastSendTime = 0
68
- }
69
-
70
- /**
71
- * Initializes authentication state.
72
- */
73
- clearAuth() {
74
- this._id8.fill(0)
75
- this._otpSrc44.fill(0)
76
- this._otp36.fill(0)
77
- this._hmac.fill(0)
78
- this.auth_salt12.fill(0)
79
- this.localNonce.fill(0)
80
- this.remoteNonce.fill(0)
81
- this.isAuthorized = false
82
- this.counter = 0
83
- this._hasKey = false
84
- this._lastSendTime = 0
85
- }
86
-
87
- /**
88
- * Sets id8 by hashing the input data.
89
- * @param {any} data
90
- */
91
- set_hash_id8(data) {
92
- let idSum = MBP.B8(sha256.hash(data))
93
- idSum.copy(this._id8, 0, 0, 8)
94
- }
95
-
96
- /**
97
- * Sets the id8 value.
98
- * @param {any} data
99
- */
100
- set_id8(data) {
101
- let encStr = MBP.B8(data)
102
- this._id8.fill(0)
103
- encStr.copy(this._id8, 0, 0, 8)
66
+ function readHeader (packet) {
67
+ const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength)
68
+ return {
69
+ length: view.getUint32(1, true),
70
+ sec: view.getUint32(5, true),
71
+ ms: view.getUint16(9, true),
72
+ counter: view.getUint16(11, true)
104
73
  }
74
+ }
105
75
 
106
- /**
107
- * Sets the key value by hashing and storing in otpSrc44.
108
- * @param {any} data
109
- */
110
- set_key(data) {
111
- const bytes = MBP.B8(data)
112
- if (!bytes || bytes.length === 0) throw new TypeError('Key must not be empty')
113
- this.copy_key(MBP.B8(sha256.hash(bytes)))
114
- }
76
+ function sessionNonce (header, dir) {
77
+ const nonce = new Uint8Array(16)
78
+ nonce.set(header.subarray(5, 13))
79
+ nonce[8] = dir
80
+ return nonce
81
+ }
115
82
 
116
- /**
117
- * Splits 'id.key' string and sets id8 and key.
118
- * @param {string} id_key
119
- */
120
- set_id_key(id_key) {
121
- let delimiterPosition = id_key.indexOf('.')
122
- if (delimiterPosition == -1) return
123
- let id = id_key.substring(0, delimiterPosition)
124
- let key = id_key.substring(delimiterPosition + 1)
125
- this.set_id8(id)
126
- this.set_key(key)
127
- }
83
+ function validChallenge (c) {
84
+ return c instanceof Uint8Array && c.length === MetaSize.SERVER_TIME_NONCE &&
85
+ c[0] === BohoMsg.SERVER_TIME_NONCE && (c[5] | (c[6] << 8)) < 1000
86
+ }
128
87
 
129
- /**
130
- * Copies id8 value from external buffer.
131
- * @param {Buffer} data
132
- */
133
- copy_id8(data) {
134
- data.copy(this._id8, 0, 0, 8)
88
+ export class Boho {
89
+ constructor () {
90
+ /** True after a verified login (AUTH_RES on a client, AUTH_REQ on a server). */
91
+ this.isAuthorized = false
92
+ this._id8 = new Uint8Array(8)
93
+ this._key = null
94
+ this._sessionKey = null
95
+ this._serverProof = null
96
+ this._challenge = null
97
+ this._role = null // 'client' or 'server': which direction byte this side sends
98
+ this._lastMs = -1
99
+ this._lastCounter = 0
100
+ this._sender = null
135
101
  }
136
102
 
137
- /**
138
- * Copies key value from external buffer.
139
- * @param {Buffer} data
140
- */
141
- copy_key(data) {
142
- if (!(data instanceof Uint8Array) || data.length !== 32) {
143
- throw new TypeError('copy_key requires exactly 32 bytes')
144
- }
145
- this._otpSrc44.set(data, 0)
146
- this._hasKey = true
147
-
103
+ clearAuth () {
104
+ wipe(this._id8); wipe(this._key); wipe(this._sessionKey); wipe(this._serverProof)
105
+ this._key = this._sessionKey = this._serverProof = this._role = null
106
+ this.isAuthorized = false
148
107
  }
149
108
 
150
- /**
151
- * Applies sha256 hash n times.
152
- * @param {any} srcData
153
- * @param {number} n
154
- * @returns {Uint8Array}
155
- */
156
- sha256_n(srcData, n) {
157
- let hashSum = sha256.hash(srcData)
158
- for (let i = 0; i < n; i++) hashSum = sha256.hash(hashSum)
159
- return hashSum
109
+ /** The login ID: at most 8 bytes are used. */
110
+ set_id8 (id) {
111
+ this._id8 = new Uint8Array(8)
112
+ this._id8.set(bytes(id).subarray(0, 8))
160
113
  }
161
114
 
162
-
163
- /**
164
- * Sets random clock value (salt12) in otpSrc44.
165
- */
166
- set_clock_rand() {
167
- this.set_clock_nonce(RAND(4))
115
+ copy_id8 (id8) {
116
+ this._id8 = Uint8Array.from(id8.subarray(0, 8))
168
117
  }
169
118
 
170
- /** Sets a monotonic clock/counter and a 4-byte nonce. */
171
- set_clock_nonce(nonce) {
172
- if (!(nonce instanceof Uint8Array) || nonce.length !== 4) {
173
- throw new TypeError('Nonce must be 4 bytes')
174
- }
175
- let now = Math.max(Date.now(), this._lastSendTime)
176
- this.counter = (this.counter + 1) & 0xffff
177
- if (this.counter === 0 && now === this._lastSendTime) now++
178
- if (!Number.isSafeInteger(now) || now < 0 || Math.floor(now / 1000) > 0xffffffff) {
179
- throw new RangeError('Clock is outside the protocol range')
180
- }
181
- this._lastSendTime = now
182
- const salt12 = Buffer.concat([
183
- MBP.NB('32L', Math.floor(now / 1000)),
184
- MBP.NB('16L', now % 1000),
185
- MBP.NB('16L', this.counter),
186
- Buffer.from(nonce)
187
- ])
188
- salt12.copy(this._otpSrc44, 32)
189
- }
190
-
191
- _requireKey() {
192
- if (!this._hasKey) throw new Error('Set a key before encryption or authentication')
119
+ /** Key string → key. A new key ends the session. */
120
+ set_key (key) {
121
+ this.isAuthorized = false
122
+ wipe(this._sessionKey); this._sessionKey = null
123
+ this._key = key ? deriveKey(key) : null
193
124
  }
194
125
 
195
- /**
196
- * Sets salt12 value in otpSrc44.
197
- * @param {Buffer} salt12
198
- */
199
- set_salt12(salt12 , caller) {
200
- // console.log('boho.set_salt12', salt12 , caller )
201
- if( salt12.byteLength != 12){
202
- throw TypeError('set_salt12: Invalid salt12 byteLength.')
203
- }
204
- salt12.copy(this._otpSrc44, 32)
126
+ /** A stored 16-byte key (deriveKey), on a server. */
127
+ copy_key (key16) {
128
+ if (!(key16 instanceof Uint8Array) || key16.length !== KEY_SIZE) throw new RangeError('key must be 16 bytes')
129
+ this.isAuthorized = false
130
+ wipe(this._sessionKey); this._sessionKey = null
131
+ this._key = Uint8Array.from(key16)
205
132
  }
206
133
 
207
- /**
208
- * Initializes OTP value.
209
- */
210
- resetOTP() {
211
- this._requireKey()
212
- let otp32 = MBP.B8(sha256.hash(this._otpSrc44))
213
- otp32.copy(this._otp36, 0, 0, 32)
134
+ /** 'id.key' */
135
+ set_id_key (idKey) {
136
+ const dot = typeof idKey === 'string' ? idKey.indexOf('.') : -1
137
+ if (dot < 1 || dot === idKey.length - 1) { this.clearAuth(); return }
138
+ this.set_id8(idKey.slice(0, dot))
139
+ this.set_key(idKey.slice(dot + 1))
214
140
  }
215
141
 
216
- /**
217
- * Returns OTP value for the given index.
218
- * @param {number} otpIndex
219
- * @returns {Uint8Array}
220
- */
221
- getIndexOTP(otpIndex) {
222
- this._otp36.writeUInt32LE(otpIndex, 32)
223
- return sha256.hash(this._otp36)
142
+ _session (challenge, id8, clientNonce) {
143
+ const input = new Uint8Array(KEY_SIZE + 13 + 8 + 8)
144
+ input.set(this._key, 0)
145
+ input.set(challenge, 16)
146
+ input.set(id8, 29)
147
+ input.set(clientNonce, 37)
148
+ const out = cxof128(input, 48, SESSION_CUSTOM)
149
+ wipe(input)
150
+ return out
224
151
  }
225
152
 
226
- /**
227
- * Generates the legacy SHA-256 prefix tag (not standard HMAC).
228
- * @param {Buffer} data
229
- */
230
- generateHMAC(data) {
231
- this._requireKey()
232
- let hmacSrc = Buffer.concat([this._otpSrc44, data])
233
- this._hmac = MBP.B8(sha256.hash(hmacSrc))
234
- }
153
+ // ---- server ----
235
154
 
236
155
  /**
237
- * Returns the truncated 8-byte legacy tag (not standard HMAC).
238
- * @param {Buffer} data
156
+ * The server's challenge: type | unixTime4 | ms2 | random2 | random4 (13 bytes).
157
+ * Kept for verify_auth_req.
239
158
  * @returns {Buffer}
240
159
  */
241
- getHMAC8(data) {
242
- this._requireKey()
243
- let hmacSrc = Buffer.concat([this._otpSrc44, data])
244
- this._hmac = MBP.B8(sha256.hash(hmacSrc))
245
- return this._hmac.subarray(0, 8)
160
+ server_time_nonce () {
161
+ const now = Date.now()
162
+ const packet = Buffer.alloc(MetaSize.SERVER_TIME_NONCE)
163
+ packet[0] = BohoMsg.SERVER_TIME_NONCE
164
+ packet.writeUInt32LE(Math.floor(now / 1000), 1)
165
+ packet.writeUInt16LE(now % 1000, 5)
166
+ globalThis.crypto.getRandomValues(packet.subarray(7, 13))
167
+ this._challenge = Buffer.from(packet)
168
+ return packet
246
169
  }
247
170
 
248
171
  /**
249
- * OTP-based XOR encryption/decryption
250
- * @param {Buffer} data
251
- * @param {number} [otpStartIndex=0]
252
- * @param {boolean} [shareDataBuffer=false]
253
- * @returns {Buffer}
172
+ * Checks a client's AUTH_REQ against the challenge this side sent (server_time_nonce, or the
173
+ * one given), with the ID's stored key (copy_key). On success the session is ready and
174
+ * AUTH_RES is returned.
175
+ * @returns {Buffer|false}
254
176
  */
255
- xotp(data, otpStartIndex = 0, shareDataBuffer = false) {
256
-
257
- data = MBP.B8(data, shareDataBuffer)
258
-
259
- let len = data.byteLength
260
- let otpIndex = otpStartIndex
261
- let dataOffset = 0
262
- let xorCalcLen = 0
263
-
264
- while (len > 0) {
265
- xorCalcLen = len < 32 ? len : 32
266
- let iotp = this.getIndexOTP(++otpIndex);
267
- for (let i = 0; i < xorCalcLen; i++) {
268
- data[dataOffset++] ^= iotp[i]
269
- }
270
- len -= 32
271
- }
272
- return data
177
+ verify_auth_req (packet, challenge = this._challenge) {
178
+ if (!this._key || !validChallenge(challenge) || !(packet instanceof Uint8Array) ||
179
+ packet.length !== MetaSize.AUTH_REQ || packet[0] !== BohoMsg.AUTH_REQ) return false
180
+ const id8 = packet.subarray(1, 9)
181
+ const out = this._session(challenge, id8, packet.subarray(9, 17))
182
+ if (!equal(packet.subarray(17, 33), out.subarray(16, 32))) { wipe(out); return false }
183
+ this._id8 = Uint8Array.from(id8)
184
+ this._sessionKey = out.slice(0, 16)
185
+ this._role = 'server'
186
+ this.isAuthorized = true
187
+ const res = Buffer.alloc(MetaSize.AUTH_RES)
188
+ res[0] = BohoMsg.AUTH_RES
189
+ res.set(out.subarray(32, 48), 1)
190
+ wipe(out)
191
+ return res
273
192
  }
274
193
 
275
- // B. AUTH process
194
+ // ---- client ----
276
195
 
277
196
  /**
278
- * Generates server time and nonce signal
279
- * @returns {Buffer}
197
+ * AUTH_REQ for the server's SERVER_TIME_NONCE.
198
+ * @returns {Buffer|false}
280
199
  */
281
- server_time_nonce() {
282
- const now = Date.now()
283
- const unixTime = Math.floor(now / 1000)
284
- const milliseconds = now % 1000;
285
-
286
- this.localNonce = RAND(4)
287
- //keep
288
- this.auth_salt12 = Buffer.concat([
289
- MBP.NB('32L', unixTime),
290
- MBP.NB('16L', milliseconds),
291
- RAND(2), // used for client's counter IV.
292
- this.localNonce
293
- ])
294
-
295
- let infoPack = Buffer.concat([
296
- MBP.NB('8', BohoMsg.SERVER_TIME_NONCE),
297
- this.auth_salt12
298
- ])
299
- return infoPack
200
+ auth_req (serverTimeNonce, clientNonce = RAND(8)) {
201
+ if (!this._key || !validChallenge(serverTimeNonce)) return false
202
+ const out = this._session(serverTimeNonce, this._id8, clientNonce)
203
+ this._sessionKey = out.slice(0, 16)
204
+ this._serverProof = out.slice(32, 48)
205
+ this._role = 'client'
206
+ this.isAuthorized = false
207
+ const packet = Buffer.alloc(MetaSize.AUTH_REQ)
208
+ packet[0] = BohoMsg.AUTH_REQ
209
+ packet.set(this._id8, 1)
210
+ packet.set(clientNonce, 9)
211
+ packet.set(out.subarray(16, 32), 17)
212
+ wipe(out)
213
+ return packet
300
214
  }
301
215
 
302
- /**
303
- * Generates AUTH_REQ message
304
- * @param {Buffer} buffer server's time nonce
305
- * @returns {Buffer|boolean}
306
- */
307
- auth_req(buffer) {
308
- if (!this._hasKey) return false
309
- let server_time_nonce = readPacket(buffer, BohoMsg.SERVER_TIME_NONCE, MetaSize.SERVER_TIME_NONCE, Meta.SERVER_TIME_NONCE)
310
- if (server_time_nonce && server_time_nonce.milTime >= 1000) return false
311
- if (server_time_nonce) {
312
- let salt12 = Buffer.concat([
313
- MBP.NB('32L', server_time_nonce.unixTime),
314
- MBP.NB('16L', server_time_nonce.milTime),
315
- MBP.NB('16L', server_time_nonce.counter),
316
- server_time_nonce.nonce
317
- ])
318
-
319
- this.set_salt12(salt12, 'auth_req')
320
-
321
- this.localNonce = RAND(4)
322
- this.generateHMAC(this.localNonce)
323
-
324
- this.remoteNonce = server_time_nonce.nonce
325
-
326
- let auth_hmac_buffer = MBP.pack(
327
- MBP.MB('#header', '8', BohoMsg.AUTH_REQ),
328
- MBP.MB('#id8', this._id8),
329
- MBP.MB('#nonce', this.localNonce),
330
- MBP.MB('#hmac32', this._hmac),
331
- )
332
-
333
- return auth_hmac_buffer
334
- }
335
- return false
216
+ /** Checks the server's AUTH_RES. */
217
+ verify_auth_res (packet) {
218
+ if (!this._serverProof || !(packet instanceof Uint8Array) || packet.length !== MetaSize.AUTH_RES ||
219
+ packet[0] !== BohoMsg.AUTH_RES || !equal(packet.subarray(1), this._serverProof)) return
220
+ wipe(this._serverProof); this._serverProof = null
221
+ this.isAuthorized = true
222
+ return true
336
223
  }
337
224
 
338
- /*
339
- step 4. for server
340
- */
341
-
342
- /**
343
- * Verify client's AUTH_REQ.
344
- * @param {Buffer|object} data
345
- * @returns {boolean}
346
- */
347
- verify_auth_req(data) {
348
-
349
- if (!this._hasKey) return false
350
- let infoPack
351
- if (data instanceof Uint8Array) {
352
- infoPack = readPacket(data, BohoMsg.AUTH_REQ, MetaSize.AUTH_REQ, Meta.AUTH_REQ)
353
- } else if (data && typeof data === 'object') {
354
- infoPack = data
225
+ // ---- messages ----
226
+
227
+ // The next outgoing (time, counter): strictly increasing, from the wall clock.
228
+ _nextClock () {
229
+ let ms = Date.now()
230
+ let counter
231
+ if (ms > this._lastMs) {
232
+ counter = (this._lastCounter + 1) & 0xffff
233
+ } else {
234
+ ms = this._lastMs
235
+ counter = this._lastCounter + 1
236
+ if (counter > 0xffff) { ms++; counter = 0 }
355
237
  }
356
- if (!infoPack || infoPack.header !== BohoMsg.AUTH_REQ ||
357
- !(infoPack.id8 instanceof Uint8Array) || infoPack.id8.length !== 8 ||
358
- !(infoPack.nonce instanceof Uint8Array) || infoPack.nonce.length !== 4 ||
359
- !(infoPack.hmac32 instanceof Uint8Array) || infoPack.hmac32.length !== 32 ||
360
- (infoPack.$OTHERS && infoPack.$OTHERS.length !== 0)) return false
361
-
362
- this.set_salt12(this.auth_salt12, 'verify_auth_req 1/2')
363
-
364
- this.generateHMAC(infoPack.nonce)
365
- let hmac32 = this._hmac
366
-
367
- if (equalTag(infoPack.hmac32, hmac32)) {
368
- this.remoteNonce = Buffer.from(infoPack.nonce)
369
-
370
- let salt12 = Buffer.concat([
371
- this.localNonce,
372
- this.remoteNonce,
373
- this.localNonce
374
- ])
375
-
376
- this.set_salt12(salt12, 'verify_auth_req 2/2')
377
- this.generateHMAC(infoPack.nonce)
378
- let replyHMAC = this._hmac
379
-
380
- let auth_res = MBP.rawPack(
381
- MBP.MB('header', '8', BohoMsg.AUTH_RES),
382
- MBP.MB('hmac32', replyHMAC)
383
- )
384
- this.isAuthorized = true
385
- return auth_res
386
- }
387
- return false
238
+ this._lastMs = ms
239
+ this._lastCounter = counter
240
+ return { sec: Math.floor(ms / 1000), ms: ms % 1000, counter }
388
241
  }
389
242
 
390
- /**
391
- * Verifies server's AUTH_RES HMAC.
392
- * @param {Buffer} buffer
393
- * @returns {boolean}
394
- */
395
- verify_auth_res(buffer) {
396
- if (!this._hasKey) return false
397
- let auth_res = readPacket(buffer, BohoMsg.AUTH_RES, MetaSize.AUTH_RES, Meta.AUTH_RES)
398
- if (auth_res) {
399
- let salt12 = Buffer.concat([
400
- this.remoteNonce,
401
- this.localNonce,
402
- this.remoteNonce,
403
- ])
404
- this.set_salt12(salt12, 'verify_auth_res')
405
- this.generateHMAC(this.localNonce)
406
- let hmac32 = this._hmac
407
- if (equalTag(hmac32, auth_res.hmac32)) {
408
- this.isAuthorized = true
409
- return true
410
- }
411
- }
412
- return
243
+ _header (type, length) {
244
+ const clock = this._nextClock()
245
+ const h = new Uint8Array(13)
246
+ const view = new DataView(h.buffer)
247
+ h[0] = type
248
+ view.setUint32(1, length, true)
249
+ view.setUint32(5, clock.sec, true)
250
+ view.setUint16(9, clock.ms, true)
251
+ view.setUint16(11, clock.counter, true)
252
+ return h
413
253
  }
414
254
 
415
- // C. Secure Communication
416
-
417
- // Must AUTH first.
418
255
  /**
419
- * Generates encrypted 488 packet after authentication
420
- * @param {Buffer} data
256
+ * ENC (the whole message) or ENC_E2E (a routing header; the caller appends the E2E body).
257
+ * Only after a verified login.
421
258
  * @returns {Buffer|undefined}
422
259
  */
423
- encrypt_488(data) {
424
- if (!this.isAuthorized || !this._hasKey) return
425
-
426
- data = MBP.B8(data)
427
-
428
- this.set_clock_nonce(this.remoteNonce)
429
- this.resetOTP()
430
-
431
- let hmac8 = this.getHMAC8(data)
432
- let encData = this.xotp(data)
433
-
434
- let pack = MBP.pack(
435
- MBP.MB('#type', '8', BohoMsg.ENC_488),
436
- MBP.MB('#len', '32L', data.byteLength),
437
- MBP.MB('#otpSrc8', this._otpSrc44.subarray(32, 40)),
438
- MBP.MB('#hmac8', hmac8),
439
- MBP.MB('#xdata', encData)
440
- )
441
- return pack
260
+ encrypt_session (data, type = BohoMsg.ENC) {
261
+ if (!this.isAuthorized || !this._sessionKey) return
262
+ if (type !== BohoMsg.ENC && type !== BohoMsg.ENC_E2E) return
263
+ const plain = bytes(data)
264
+ const header = this._header(type, plain.length)
265
+ const sealed = encrypt(this._sessionKey, sessionNonce(header, DIR[this._role]), plain, header, TAG)
266
+ const packet = Buffer.alloc(MetaSize.ENC + plain.length)
267
+ packet.set(header, 0)
268
+ packet.set(sealed.subarray(plain.length), 13)
269
+ packet.set(sealed.subarray(0, plain.length), 21)
270
+ return packet
442
271
  }
443
272
 
444
273
  /**
445
- * Decrypts 488 packet after authentication
446
- * @param {Buffer} data
447
- * @returns {Buffer|undefined}
274
+ * Opens ENC (exact length) or the routing header of ENC_E2E (the body after it is not read).
275
+ * @returns {Buffer|undefined} the plaintext
448
276
  */
449
- decrypt_488(data) {
450
- if (!this.isAuthorized || !this._hasKey) return
451
- // iosignal ENC_E2E wraps only an encrypted routing header. The remaining
452
- // bytes are an opaque end-to-end packet and must not enter this decryptor.
453
- let header = data
454
- if (data instanceof Uint8Array && data[0] === BohoMsg.ENC_E2E) {
455
- if (data.length < MetaSize.ENC_488) return
456
- const packet = Buffer.from(data)
457
- const headerLength = packet.readUInt32LE(1)
458
- if (headerLength > packet.length - MetaSize.ENC_488) return
459
- header = Buffer.from(packet.subarray(0, MetaSize.ENC_488 + headerLength))
460
- header[0] = BohoMsg.ENC_488
461
- }
462
- const pack = readPacket(header, BohoMsg.ENC_488, MetaSize.ENC_488, Meta.ENC_488, true)
463
- if (!pack || !validClock(pack.otpSrc8)) return
464
- this.set_salt12(Buffer.concat([pack.otpSrc8, this.localNonce]), 'decrypt_488')
465
- this.resetOTP()
466
- const decData = this.xotp(pack.$OTHERS ?? Buffer.alloc(0))
467
- if (!equalTag(this.getHMAC8(decData), pack.hmac8)) return
468
- // Session freshness/replay policy belongs to the caller (iosignal).
469
- return decData
277
+ decrypt_session (packet) {
278
+ if (!this.isAuthorized || !this._sessionKey || !(packet instanceof Uint8Array) || packet.length < MetaSize.ENC) return
279
+ const type = packet[0]
280
+ if (type !== BohoMsg.ENC && type !== BohoMsg.ENC_E2E) return
281
+ const h = readHeader(packet)
282
+ const room = packet.length - MetaSize.ENC
283
+ if (h.length > room || (type === BohoMsg.ENC && h.length !== room) || h.ms >= 1000) return
284
+ const header = packet.subarray(0, 13)
285
+ const sealed = new Uint8Array(h.length + TAG)
286
+ sealed.set(packet.subarray(21, 21 + h.length))
287
+ sealed.set(packet.subarray(13, 21), h.length)
288
+ const other = this._role === 'client' ? DIR.server : DIR.client
289
+ const plain = decrypt(this._sessionKey, sessionNonce(header, other), sealed, header, TAG)
290
+ return plain ? Buffer.from(plain.buffer, plain.byteOffset, plain.byteLength) : undefined
470
291
  }
471
292
 
472
- /**
473
- * Generates encrypted packet for up to 2^32-1 bytes
474
- * @param {Buffer} data
475
- * @returns {Buffer}
476
- */
477
- encryptPack(data) {
478
- this._requireKey()
479
- data = MBP.B8(data)
480
-
481
- this.set_clock_rand()
482
- this.resetOTP()
483
-
484
- let hmac8 = this.getHMAC8(data)
485
- let encData = this.xotp(data)
486
-
487
- let pack = MBP.pack(
488
- MBP.MB('#type', '8', BohoMsg.ENC_PACK),
489
- MBP.MB('#len', '32L', data.byteLength),
490
- MBP.MB('#salt12', this._otpSrc44.subarray(32)),
491
- MBP.MB('#hmac8', hmac8),
492
- MBP.MB('#xdata', encData)
493
- )
494
- return pack
293
+ _seal (key, data) {
294
+ const plain = bytes(data)
295
+ this._sender ??= RAND(8)
296
+ const clock = this._nextClock()
297
+ const head = new Uint8Array(21)
298
+ const view = new DataView(head.buffer)
299
+ head[0] = BohoMsg.ENC_PACK
300
+ view.setUint32(1, plain.length, true)
301
+ view.setUint32(5, clock.sec, true)
302
+ view.setUint16(9, clock.ms, true)
303
+ view.setUint16(11, clock.counter, true)
304
+ head.set(this._sender, 13)
305
+ const sealed = encrypt(key, head.subarray(5, 21), plain, head.subarray(0, 5), TAG)
306
+ const packet = Buffer.alloc(MetaSize.ENC_PACK + plain.length)
307
+ packet.set(head, 0)
308
+ packet.set(sealed.subarray(plain.length), 21)
309
+ packet.set(sealed.subarray(0, plain.length), 29)
310
+ return packet
495
311
  }
496
312
 
497
- /**
498
- * Decrypts encrypted packet
499
- * @param {Buffer} data
500
- * @returns {Buffer}
501
- */
502
- decryptPack(data) {
503
- if (!this._hasKey) return
504
- const pack = readPacket(data, BohoMsg.ENC_PACK, MetaSize.ENC_PACK, Meta.ENC_PACK, true)
505
- if (!pack) return
506
- this.set_salt12(pack.salt12, 'decryptPack')
507
- this.resetOTP()
508
- const decData = this.xotp(pack.$OTHERS ?? Buffer.alloc(0))
509
- if (!equalTag(pack.hmac, this.getHMAC8(decData))) return
510
- pack.data = decData
511
- return pack
313
+ _open (key, packet) {
314
+ if (!(packet instanceof Uint8Array) || packet.length < MetaSize.ENC_PACK || packet[0] !== BohoMsg.ENC_PACK) return
315
+ const h = readHeader(packet)
316
+ if (h.length !== packet.length - MetaSize.ENC_PACK || h.ms >= 1000) return
317
+ const sealed = new Uint8Array(h.length + TAG)
318
+ sealed.set(packet.subarray(29))
319
+ sealed.set(packet.subarray(21, 29), h.length)
320
+ const plain = decrypt(key, packet.subarray(5, 21), sealed, packet.subarray(0, 5), TAG)
321
+ if (!plain) return
322
+ return {
323
+ type: BohoMsg.ENC_PACK, len: h.length, sec: h.sec, ms: h.ms, counter: h.counter,
324
+ sender: Buffer.from(packet.subarray(13, 21)),
325
+ data: Buffer.from(plain.buffer, plain.byteOffset, plain.byteLength)
326
+ }
512
327
  }
513
328
 
514
- /**
515
- * End-to-end encryption
516
- * @param {Buffer} data
517
- * @param {Buffer} key
518
- * @returns {Buffer}
519
- */
520
- encrypt_e2e(data, key) {
521
- return this._withKey(key, () => this.encryptPack(data))
522
- }
329
+ /** ENC_PACK with this side's key. */
330
+ encryptPack (data) { if (this._key) return this._seal(this._key, data) }
523
331
 
524
- /**
525
- * End-to-end decryption
526
- * @param {Buffer} data
527
- * @param {Buffer} key
528
- * @returns {Buffer}
529
- */
530
- decrypt_e2e(data, key) {
531
- return this._withKey(key, () => this.decryptPack(data))
532
- }
332
+ /** Opens ENC_PACK with this side's key: { data, sec, ms, counter, sender, ... } or undefined. */
333
+ decryptPack (packet) { if (this._key) return this._open(this._key, packet) }
533
334
 
534
- _withKey(key, operation) {
535
- const bytes = MBP.B8(key)
536
- if (!bytes || bytes.length === 0) throw new TypeError('Key must not be empty')
537
- const state = [Buffer.from(this._otpSrc44), Buffer.from(this._otp36), Buffer.from(this._hmac)]
538
- const hadKey = this._hasKey
539
- try {
540
- this._otpSrc44.set(sha256.hash(bytes), 0)
541
- this._hasKey = true
542
- return operation()
543
- } finally {
544
- this._otpSrc44.set(state[0])
545
- this._otp36.set(state[1])
546
- this._hmac.set(state[2])
547
- this._hasKey = hadKey
548
- for (const buffer of state) buffer.fill(0)
549
- }
335
+ /** ENC_PACK with an E2E key string. */
336
+ encrypt_e2e (data, key) {
337
+ if (!key) return
338
+ const k = deriveKey(key)
339
+ try { return this._seal(k, data) } finally { wipe(k) }
550
340
  }
551
341
 
342
+ /** Opens ENC_PACK with an E2E key string: { data, ... } or undefined. */
343
+ decrypt_e2e (packet, key) {
344
+ if (!key) return
345
+ const k = deriveKey(key)
346
+ try { return this._open(k, packet) } finally { wipe(k) }
347
+ }
552
348
  }
553
349
 
350
+ Boho.deriveKey = deriveKey