boho 2.2.2 → 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,582 +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
- // The key and authentication buffers: [field, size]. They live in one zeroed block made on first
48
- // use (_block), and the fields are views into it made only when one is read or replaced (_state).
49
- // A server connection that is only given its login challenge (server_time_nonce, written into the
50
- // block directly) and never logs in holds the block alone: about 0.2 KB instead of 1.7 KB with a
51
- // buffer per field. A replaced field (this.localNonce = …) keeps the new buffer, as before.
52
- const STATE_FIELDS = [['_id8', 8], ['_otpSrc44', 44], ['_otp36', 36], ['_hmac', 32],
53
- ['auth_salt12', 12], ['localNonce', 4], ['remoteNonce', 4]]
54
- const OFFSET = {}
55
- const STATE_BYTES = STATE_FIELDS.reduce((offset, [name, size]) => { OFFSET[name] = offset; return offset + size }, 0)
56
-
57
- function createViews(block) {
58
- const state = {}
59
- for (const [name, size] of STATE_FIELDS) state[name] = block.subarray(OFFSET[name], OFFSET[name] + size)
60
- return state
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)
73
+ }
61
74
  }
62
75
 
63
- /**
64
- * Boho security protocol class
65
- */
66
- export class Boho {
67
- /**
68
- * @constructor
69
- */
70
- constructor() {
71
- this._block = null // see STATE_FIELDS
72
- this._state = null // field views into _block, read and replaced through the accessors below
73
- this.isAuthorized = false
74
- this.counter = 0
75
- this._hasKey = false
76
- this._lastSendTime = 0
77
- }
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
+ }
78
82
 
79
- _views() { return this._state ??= createViews(this._block ??= Buffer.alloc(STATE_BYTES)) }
80
-
81
- get _id8() { return this._views()._id8 }
82
- set _id8(value) { this._views()._id8 = value }
83
- get _otpSrc44() { return this._views()._otpSrc44 }
84
- set _otpSrc44(value) { this._views()._otpSrc44 = value }
85
- get _otp36() { return this._views()._otp36 }
86
- set _otp36(value) { this._views()._otp36 = value }
87
- get _hmac() { return this._views()._hmac }
88
- set _hmac(value) { this._views()._hmac = value }
89
- get auth_salt12() { return this._views().auth_salt12 }
90
- set auth_salt12(value) { this._views().auth_salt12 = value }
91
- get localNonce() { return this._views().localNonce }
92
- set localNonce(value) { this._views().localNonce = value }
93
- get remoteNonce() { return this._views().remoteNonce }
94
- set remoteNonce(value) { this._views().remoteNonce = value }
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
+ }
95
87
 
96
- /**
97
- * Initializes authentication state.
98
- */
99
- clearAuth() {
100
- // Nothing to clear before the first use. Replaced fields are not in the block: zero them too.
101
- this._block?.fill(0)
102
- if (this._state) for (const [name] of STATE_FIELDS) this._state[name].fill(0)
88
+ export class Boho {
89
+ constructor () {
90
+ /** True after a verified login (AUTH_RES on a client, AUTH_REQ on a server). */
103
91
  this.isAuthorized = false
104
- this.counter = 0
105
- this._hasKey = false
106
- this._lastSendTime = 0
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
107
101
  }
108
102
 
109
- /**
110
- * Sets id8 by hashing the input data.
111
- * @param {any} data
112
- */
113
- set_hash_id8(data) {
114
- let idSum = MBP.B8(sha256.hash(data))
115
- idSum.copy(this._id8, 0, 0, 8)
116
- }
117
-
118
- /**
119
- * Sets the id8 value.
120
- * @param {any} data
121
- */
122
- set_id8(data) {
123
- let encStr = MBP.B8(data)
124
- this._id8.fill(0)
125
- encStr.copy(this._id8, 0, 0, 8)
126
- }
127
-
128
- /**
129
- * Sets the key value by hashing and storing in otpSrc44.
130
- * @param {any} data
131
- */
132
- set_key(data) {
133
- const bytes = MBP.B8(data)
134
- if (!bytes || bytes.length === 0) throw new TypeError('Key must not be empty')
135
- this.copy_key(MBP.B8(sha256.hash(bytes)))
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
136
107
  }
137
108
 
138
- /**
139
- * Splits 'id.key' string and sets id8 and key.
140
- * @param {string} id_key
141
- */
142
- set_id_key(id_key) {
143
- let delimiterPosition = id_key.indexOf('.')
144
- if (delimiterPosition == -1) return
145
- let id = id_key.substring(0, delimiterPosition)
146
- let key = id_key.substring(delimiterPosition + 1)
147
- this.set_id8(id)
148
- this.set_key(key)
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))
149
113
  }
150
114
 
151
- /**
152
- * Copies id8 value from external buffer.
153
- * @param {Buffer} data
154
- */
155
- copy_id8(data) {
156
- data.copy(this._id8, 0, 0, 8)
115
+ copy_id8 (id8) {
116
+ this._id8 = Uint8Array.from(id8.subarray(0, 8))
157
117
  }
158
118
 
159
- /**
160
- * Copies key value from external buffer.
161
- * @param {Buffer} data
162
- */
163
- copy_key(data) {
164
- if (!(data instanceof Uint8Array) || data.length !== 32) {
165
- throw new TypeError('copy_key requires exactly 32 bytes')
166
- }
167
- this._otpSrc44.set(data, 0)
168
- this._hasKey = true
169
-
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
170
124
  }
171
125
 
172
- /**
173
- * Applies sha256 hash n times.
174
- * @param {any} srcData
175
- * @param {number} n
176
- * @returns {Uint8Array}
177
- */
178
- sha256_n(srcData, n) {
179
- let hashSum = sha256.hash(srcData)
180
- for (let i = 0; i < n; i++) hashSum = sha256.hash(hashSum)
181
- return hashSum
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)
182
132
  }
183
133
 
184
-
185
- /**
186
- * Sets random clock value (salt12) in otpSrc44.
187
- */
188
- set_clock_rand() {
189
- this.set_clock_nonce(RAND(4))
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))
190
140
  }
191
141
 
192
- /** Sets a monotonic clock/counter and a 4-byte nonce. */
193
- set_clock_nonce(nonce) {
194
- if (!(nonce instanceof Uint8Array) || nonce.length !== 4) {
195
- throw new TypeError('Nonce must be 4 bytes')
196
- }
197
- let now = Math.max(Date.now(), this._lastSendTime)
198
- this.counter = (this.counter + 1) & 0xffff
199
- if (this.counter === 0 && now === this._lastSendTime) now++
200
- if (!Number.isSafeInteger(now) || now < 0 || Math.floor(now / 1000) > 0xffffffff) {
201
- throw new RangeError('Clock is outside the protocol range')
202
- }
203
- this._lastSendTime = now
204
- const salt12 = Buffer.concat([
205
- MBP.NB('32L', Math.floor(now / 1000)),
206
- MBP.NB('16L', now % 1000),
207
- MBP.NB('16L', this.counter),
208
- Buffer.from(nonce)
209
- ])
210
- salt12.copy(this._otpSrc44, 32)
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
211
151
  }
212
152
 
213
- _requireKey() {
214
- if (!this._hasKey) throw new Error('Set a key before encryption or authentication')
215
- }
153
+ // ---- server ----
216
154
 
217
155
  /**
218
- * Sets salt12 value in otpSrc44.
219
- * @param {Buffer} salt12
220
- */
221
- set_salt12(salt12 , caller) {
222
- // console.log('boho.set_salt12', salt12 , caller )
223
- if( salt12.byteLength != 12){
224
- throw TypeError('set_salt12: Invalid salt12 byteLength.')
225
- }
226
- salt12.copy(this._otpSrc44, 32)
227
- }
228
-
229
- /**
230
- * Initializes OTP value.
156
+ * The server's challenge: type | unixTime4 | ms2 | random2 | random4 (13 bytes).
157
+ * Kept for verify_auth_req.
158
+ * @returns {Buffer}
231
159
  */
232
- resetOTP() {
233
- this._requireKey()
234
- let otp32 = MBP.B8(sha256.hash(this._otpSrc44))
235
- otp32.copy(this._otp36, 0, 0, 32)
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
236
169
  }
237
170
 
238
171
  /**
239
- * Returns OTP value for the given index.
240
- * @param {number} otpIndex
241
- * @returns {Uint8Array}
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}
242
176
  */
243
- getIndexOTP(otpIndex) {
244
- this._otp36.writeUInt32LE(otpIndex, 32)
245
- return sha256.hash(this._otp36)
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
246
192
  }
247
193
 
248
- /**
249
- * Generates the legacy SHA-256 prefix tag (not standard HMAC).
250
- * @param {Buffer} data
251
- */
252
- generateHMAC(data) {
253
- this._requireKey()
254
- let hmacSrc = Buffer.concat([this._otpSrc44, data])
255
- this._hmac = MBP.B8(sha256.hash(hmacSrc))
256
- }
194
+ // ---- client ----
257
195
 
258
196
  /**
259
- * Returns the truncated 8-byte legacy tag (not standard HMAC).
260
- * @param {Buffer} data
261
- * @returns {Buffer}
197
+ * AUTH_REQ for the server's SERVER_TIME_NONCE.
198
+ * @returns {Buffer|false}
262
199
  */
263
- getHMAC8(data) {
264
- this._requireKey()
265
- let hmacSrc = Buffer.concat([this._otpSrc44, data])
266
- this._hmac = MBP.B8(sha256.hash(hmacSrc))
267
- return this._hmac.subarray(0, 8)
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
268
214
  }
269
215
 
270
- /**
271
- * OTP-based XOR encryption/decryption
272
- * @param {Buffer} data
273
- * @param {number} [otpStartIndex=0]
274
- * @param {boolean} [shareDataBuffer=false]
275
- * @returns {Buffer}
276
- */
277
- xotp(data, otpStartIndex = 0, shareDataBuffer = false) {
278
-
279
- data = MBP.B8(data, shareDataBuffer)
280
-
281
- let len = data.byteLength
282
- let otpIndex = otpStartIndex
283
- let dataOffset = 0
284
- let xorCalcLen = 0
285
-
286
- while (len > 0) {
287
- xorCalcLen = len < 32 ? len : 32
288
- let iotp = this.getIndexOTP(++otpIndex);
289
- for (let i = 0; i < xorCalcLen; i++) {
290
- data[dataOffset++] ^= iotp[i]
291
- }
292
- len -= 32
293
- }
294
- return data
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
295
223
  }
296
224
 
297
- // B. AUTH process
225
+ // ---- messages ----
298
226
 
299
- /**
300
- * Generates server time and nonce signal
301
- * @returns {Buffer}
302
- */
303
- server_time_nonce() {
304
- const now = Date.now()
305
- const unixTime = Math.floor(now / 1000)
306
- const milliseconds = now % 1000;
307
-
308
- // salt12: unix time (32L), milliseconds (16L), 2 random bytes (the client's counter IV), nonce (4).
309
- // localNonce holds its own copy of the nonce.
310
- if (this._state) {
311
- // Field views exist (an earlier login on this instance): replace them as fields.
312
- this.localNonce = RAND(4)
313
- this.auth_salt12 = Buffer.concat([MBP.NB('32L', unixTime), MBP.NB('16L', milliseconds), RAND(2), this.localNonce])
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
314
233
  } else {
315
- // Write straight into the block, without making the field views (see STATE_FIELDS).
316
- const block = this._block ??= Buffer.alloc(STATE_BYTES), salt = OFFSET.auth_salt12
317
- block.writeUInt32LE(unixTime, salt)
318
- block.writeUInt16LE(milliseconds, salt + 4)
319
- globalThis.crypto.getRandomValues(block.subarray(salt + 6, salt + 12))
320
- block.copy(block, OFFSET.localNonce, salt + 8, salt + 12)
234
+ ms = this._lastMs
235
+ counter = this._lastCounter + 1
236
+ if (counter > 0xffff) { ms++; counter = 0 }
321
237
  }
322
- const salt12 = this._state ? this._state.auth_salt12 : this._block.subarray(OFFSET.auth_salt12, OFFSET.auth_salt12 + 12)
323
-
324
- let infoPack = Buffer.concat([
325
- MBP.NB('8', BohoMsg.SERVER_TIME_NONCE),
326
- salt12
327
- ])
328
- return infoPack
238
+ this._lastMs = ms
239
+ this._lastCounter = counter
240
+ return { sec: Math.floor(ms / 1000), ms: ms % 1000, counter }
329
241
  }
330
242
 
331
- /**
332
- * Generates AUTH_REQ message
333
- * @param {Buffer} buffer server's time nonce
334
- * @returns {Buffer|boolean}
335
- */
336
- auth_req(buffer) {
337
- if (!this._hasKey) return false
338
- let server_time_nonce = readPacket(buffer, BohoMsg.SERVER_TIME_NONCE, MetaSize.SERVER_TIME_NONCE, Meta.SERVER_TIME_NONCE)
339
- if (server_time_nonce && server_time_nonce.milTime >= 1000) return false
340
- if (server_time_nonce) {
341
- let salt12 = Buffer.concat([
342
- MBP.NB('32L', server_time_nonce.unixTime),
343
- MBP.NB('16L', server_time_nonce.milTime),
344
- MBP.NB('16L', server_time_nonce.counter),
345
- server_time_nonce.nonce
346
- ])
347
-
348
- this.set_salt12(salt12, 'auth_req')
349
-
350
- this.localNonce = RAND(4)
351
- this.generateHMAC(this.localNonce)
352
-
353
- this.remoteNonce = server_time_nonce.nonce
354
-
355
- let auth_hmac_buffer = MBP.pack(
356
- MBP.MB('#header', '8', BohoMsg.AUTH_REQ),
357
- MBP.MB('#id8', this._id8),
358
- MBP.MB('#nonce', this.localNonce),
359
- MBP.MB('#hmac32', this._hmac),
360
- )
361
-
362
- return auth_hmac_buffer
363
- }
364
- return false
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
365
253
  }
366
254
 
367
- /*
368
- step 4. for server
369
- */
370
-
371
255
  /**
372
- * Verify client's AUTH_REQ.
373
- * @param {Buffer|object} data
374
- * @returns {boolean}
256
+ * ENC (the whole message) or ENC_E2E (a routing header; the caller appends the E2E body).
257
+ * Only after a verified login.
258
+ * @returns {Buffer|undefined}
375
259
  */
376
- verify_auth_req(data) {
377
-
378
- if (!this._hasKey) return false
379
- let infoPack
380
- if (data instanceof Uint8Array) {
381
- infoPack = readPacket(data, BohoMsg.AUTH_REQ, MetaSize.AUTH_REQ, Meta.AUTH_REQ)
382
- } else if (data && typeof data === 'object') {
383
- infoPack = data
384
- }
385
- if (!infoPack || infoPack.header !== BohoMsg.AUTH_REQ ||
386
- !(infoPack.id8 instanceof Uint8Array) || infoPack.id8.length !== 8 ||
387
- !(infoPack.nonce instanceof Uint8Array) || infoPack.nonce.length !== 4 ||
388
- !(infoPack.hmac32 instanceof Uint8Array) || infoPack.hmac32.length !== 32 ||
389
- (infoPack.$OTHERS && infoPack.$OTHERS.length !== 0)) return false
390
-
391
- this.set_salt12(this.auth_salt12, 'verify_auth_req 1/2')
392
-
393
- this.generateHMAC(infoPack.nonce)
394
- let hmac32 = this._hmac
395
-
396
- if (equalTag(infoPack.hmac32, hmac32)) {
397
- this.remoteNonce = Buffer.from(infoPack.nonce)
398
-
399
- let salt12 = Buffer.concat([
400
- this.localNonce,
401
- this.remoteNonce,
402
- this.localNonce
403
- ])
404
-
405
- this.set_salt12(salt12, 'verify_auth_req 2/2')
406
- this.generateHMAC(infoPack.nonce)
407
- let replyHMAC = this._hmac
408
-
409
- let auth_res = MBP.rawPack(
410
- MBP.MB('header', '8', BohoMsg.AUTH_RES),
411
- MBP.MB('hmac32', replyHMAC)
412
- )
413
- this.isAuthorized = true
414
- return auth_res
415
- }
416
- return false
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
417
271
  }
418
272
 
419
273
  /**
420
- * Verifies server's AUTH_RES HMAC.
421
- * @param {Buffer} buffer
422
- * @returns {boolean}
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
423
276
  */
424
- verify_auth_res(buffer) {
425
- if (!this._hasKey) return false
426
- let auth_res = readPacket(buffer, BohoMsg.AUTH_RES, MetaSize.AUTH_RES, Meta.AUTH_RES)
427
- if (auth_res) {
428
- let salt12 = Buffer.concat([
429
- this.remoteNonce,
430
- this.localNonce,
431
- this.remoteNonce,
432
- ])
433
- this.set_salt12(salt12, 'verify_auth_res')
434
- this.generateHMAC(this.localNonce)
435
- let hmac32 = this._hmac
436
- if (equalTag(hmac32, auth_res.hmac32)) {
437
- this.isAuthorized = true
438
- return true
439
- }
440
- }
441
- return
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
442
291
  }
443
292
 
444
- // C. Secure Communication
445
-
446
- // Must AUTH first.
447
- /**
448
- * Generates encrypted 488 packet after authentication
449
- * @param {Buffer} data
450
- * @returns {Buffer|undefined}
451
- */
452
- encrypt_488(data) {
453
- if (!this.isAuthorized || !this._hasKey) return
454
-
455
- data = MBP.B8(data)
456
-
457
- this.set_clock_nonce(this.remoteNonce)
458
- this.resetOTP()
459
-
460
- let hmac8 = this.getHMAC8(data)
461
- let encData = this.xotp(data)
462
-
463
- let pack = MBP.pack(
464
- MBP.MB('#type', '8', BohoMsg.ENC_488),
465
- MBP.MB('#len', '32L', data.byteLength),
466
- MBP.MB('#otpSrc8', this._otpSrc44.subarray(32, 40)),
467
- MBP.MB('#hmac8', hmac8),
468
- MBP.MB('#xdata', encData)
469
- )
470
- 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
471
311
  }
472
312
 
473
- /**
474
- * Decrypts 488 packet after authentication
475
- * @param {Buffer} data
476
- * @returns {Buffer|undefined}
477
- */
478
- decrypt_488(data) {
479
- if (!this.isAuthorized || !this._hasKey) return
480
- // iosignal ENC_E2E wraps only an encrypted routing header. The remaining
481
- // bytes are an opaque end-to-end packet and must not enter this decryptor.
482
- let header = data
483
- if (data instanceof Uint8Array && data[0] === BohoMsg.ENC_E2E) {
484
- if (data.length < MetaSize.ENC_488) return
485
- const packet = Buffer.from(data)
486
- const headerLength = packet.readUInt32LE(1)
487
- if (headerLength > packet.length - MetaSize.ENC_488) return
488
- header = Buffer.from(packet.subarray(0, MetaSize.ENC_488 + headerLength))
489
- header[0] = BohoMsg.ENC_488
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)
490
326
  }
491
- const pack = readPacket(header, BohoMsg.ENC_488, MetaSize.ENC_488, Meta.ENC_488, true)
492
- if (!pack || !validClock(pack.otpSrc8)) return
493
- this.set_salt12(Buffer.concat([pack.otpSrc8, this.localNonce]), 'decrypt_488')
494
- this.resetOTP()
495
- const decData = this.xotp(pack.$OTHERS ?? Buffer.alloc(0))
496
- if (!equalTag(this.getHMAC8(decData), pack.hmac8)) return
497
- // Session freshness/replay policy belongs to the caller (iosignal).
498
- return decData
499
- }
500
-
501
- /**
502
- * Generates encrypted packet for up to 2^32-1 bytes
503
- * @param {Buffer} data
504
- * @returns {Buffer}
505
- */
506
- encryptPack(data) {
507
- this._requireKey()
508
- data = MBP.B8(data)
509
-
510
- this.set_clock_rand()
511
- this.resetOTP()
512
-
513
- let hmac8 = this.getHMAC8(data)
514
- let encData = this.xotp(data)
515
-
516
- let pack = MBP.pack(
517
- MBP.MB('#type', '8', BohoMsg.ENC_PACK),
518
- MBP.MB('#len', '32L', data.byteLength),
519
- MBP.MB('#salt12', this._otpSrc44.subarray(32)),
520
- MBP.MB('#hmac8', hmac8),
521
- MBP.MB('#xdata', encData)
522
- )
523
- return pack
524
327
  }
525
328
 
526
- /**
527
- * Decrypts encrypted packet
528
- * @param {Buffer} data
529
- * @returns {Buffer}
530
- */
531
- decryptPack(data) {
532
- if (!this._hasKey) return
533
- const pack = readPacket(data, BohoMsg.ENC_PACK, MetaSize.ENC_PACK, Meta.ENC_PACK, true)
534
- if (!pack) return
535
- this.set_salt12(pack.salt12, 'decryptPack')
536
- this.resetOTP()
537
- const decData = this.xotp(pack.$OTHERS ?? Buffer.alloc(0))
538
- if (!equalTag(pack.hmac, this.getHMAC8(decData))) return
539
- pack.data = decData
540
- return pack
541
- }
329
+ /** ENC_PACK with this side's key. */
330
+ encryptPack (data) { if (this._key) return this._seal(this._key, data) }
542
331
 
543
- /**
544
- * End-to-end encryption
545
- * @param {Buffer} data
546
- * @param {Buffer} key
547
- * @returns {Buffer}
548
- */
549
- encrypt_e2e(data, key) {
550
- return this._withKey(key, () => this.encryptPack(data))
551
- }
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) }
552
334
 
553
- /**
554
- * End-to-end decryption
555
- * @param {Buffer} data
556
- * @param {Buffer} key
557
- * @returns {Buffer}
558
- */
559
- decrypt_e2e(data, key) {
560
- return this._withKey(key, () => this.decryptPack(data))
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) }
561
340
  }
562
341
 
563
- _withKey(key, operation) {
564
- const bytes = MBP.B8(key)
565
- if (!bytes || bytes.length === 0) throw new TypeError('Key must not be empty')
566
- const state = [Buffer.from(this._otpSrc44), Buffer.from(this._otp36), Buffer.from(this._hmac)]
567
- const hadKey = this._hasKey
568
- try {
569
- this._otpSrc44.set(sha256.hash(bytes), 0)
570
- this._hasKey = true
571
- return operation()
572
- } finally {
573
- this._otpSrc44.set(state[0])
574
- this._otp36.set(state[1])
575
- this._hmac.set(state[2])
576
- this._hasKey = hadKey
577
- for (const buffer of state) buffer.fill(0)
578
- }
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) }
579
347
  }
580
-
581
348
  }
582
349
 
350
+ Boho.deriveKey = deriveKey