boho 2.2.0 → 2.2.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "boho",
3
- "version": "2.2.0",
3
+ "version": "2.2.2",
4
4
  "description": "Secure Lightweight Encryption & Authentication Library for Node.js, Browsers and Arduino.",
5
5
  "type": "module",
6
6
  "exports": {
package/src/boho.js CHANGED
@@ -44,6 +44,22 @@ export function RAND(size) {
44
44
  return globalThis.crypto.getRandomValues(Buffer.alloc(size))
45
45
  }
46
46
 
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
61
+ }
62
+
47
63
  /**
48
64
  * Boho security protocol class
49
65
  */
@@ -52,32 +68,38 @@ export class Boho {
52
68
  * @constructor
53
69
  */
54
70
  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)
71
+ this._block = null // see STATE_FIELDS
72
+ this._state = null // field views into _block, read and replaced through the accessors below
64
73
  this.isAuthorized = false
65
74
  this.counter = 0
66
75
  this._hasKey = false
67
76
  this._lastSendTime = 0
68
77
  }
69
78
 
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 }
95
+
70
96
  /**
71
97
  * Initializes authentication state.
72
98
  */
73
99
  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)
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)
81
103
  this.isAuthorized = false
82
104
  this.counter = 0
83
105
  this._hasKey = false
@@ -283,18 +305,25 @@ export class Boho {
283
305
  const unixTime = Math.floor(now / 1000)
284
306
  const milliseconds = now % 1000;
285
307
 
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
- ])
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])
314
+ } 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)
321
+ }
322
+ const salt12 = this._state ? this._state.auth_salt12 : this._block.subarray(OFFSET.auth_salt12, OFFSET.auth_salt12 + 12)
294
323
 
295
324
  let infoPack = Buffer.concat([
296
325
  MBP.NB('8', BohoMsg.SERVER_TIME_NONCE),
297
- this.auth_salt12
326
+ salt12
298
327
  ])
299
328
  return infoPack
300
329
  }
@@ -0,0 +1,99 @@
1
+ // The key and authentication buffers are made on first use, as views into one block.
2
+ import { describe, it } from 'node:test'
3
+ import assert from 'node:assert/strict'
4
+ import Boho from '../src/index.js'
5
+
6
+ const FIELDS = ['_id8', '_otpSrc44', '_otp36', '_hmac', 'auth_salt12', 'localNonce', 'remoteNonce']
7
+ const SIZES = [8, 44, 36, 32, 12, 4, 4]
8
+
9
+ function authorizedPair() {
10
+ const client = new Boho(), server = new Boho()
11
+ client.set_id8('lazy-id'); client.set_key('lazy-key')
12
+ const request = client.auth_req(server.server_time_nonce())
13
+ server.set_key('lazy-key')
14
+ assert.equal(client.verify_auth_res(server.verify_auth_req(request)), true)
15
+ return { client, server }
16
+ }
17
+
18
+ describe('Boho key and authentication state', () => {
19
+ it('holds no buffers until first used', () => {
20
+ const boho = new Boho()
21
+ assert.equal(boho._block, null); assert.equal(boho._state, null)
22
+ boho.clearAuth()
23
+ assert.equal(boho._block, null, 'clearAuth on an unused instance allocates nothing')
24
+ assert.equal(boho.isAuthorized, false)
25
+ })
26
+
27
+ it('gives zeroed, separate views of the documented sizes', () => {
28
+ const boho = new Boho()
29
+ FIELDS.forEach((name, i) => {
30
+ assert.equal(boho[name].length, SIZES[i], name)
31
+ assert.ok(boho[name].every(byte => byte === 0), `${name} starts zeroed`)
32
+ })
33
+ FIELDS.forEach(name => boho[name].fill(0xff))
34
+ FIELDS.forEach(name => assert.ok(boho[name].every(byte => byte === 0xff), `${name} not overwritten by a neighbour`))
35
+ boho.clearAuth()
36
+ FIELDS.forEach(name => assert.ok(boho[name].every(byte => byte === 0), `${name} cleared`))
37
+ })
38
+
39
+ it('keeps a replaced buffer and clears it', () => {
40
+ const boho = new Boho()
41
+ const nonce = Boho.Buffer.from([1, 2, 3, 4])
42
+ boho.localNonce = nonce
43
+ assert.equal(boho.localNonce, nonce)
44
+ boho.clearAuth()
45
+ assert.deepEqual([...nonce], [0, 0, 0, 0])
46
+ })
47
+
48
+ it('a login challenge alone writes the block without field views', () => {
49
+ const server = new Boho(), before = Math.floor(Date.now() / 1000)
50
+ const pack = server.server_time_nonce()
51
+ assert.equal(server._state, null, 'no field views')
52
+ assert.equal(server._block.length, 140)
53
+ assert.equal(pack.length, 13)
54
+ const salt = pack.subarray(1)
55
+ assert.ok(Math.abs(salt.readUInt32LE(0) - before) <= 1, 'unix time')
56
+ assert.ok(salt.readUInt16LE(4) < 1000, 'milliseconds')
57
+ // Reading the fields later sees the same challenge.
58
+ assert.deepEqual([...server.auth_salt12], [...salt])
59
+ assert.deepEqual([...server.localNonce], [...salt.subarray(8, 12)])
60
+ // Two challenges differ in their random bytes.
61
+ const other = new Boho().server_time_nonce()
62
+ assert.notDeepEqual([...other.subarray(7)], [...salt.subarray(6)])
63
+ })
64
+
65
+ it('a new challenge after a login replaces the fields', () => {
66
+ const { server } = authorizedPair()
67
+ const pack = server.server_time_nonce()
68
+ assert.deepEqual([...server.auth_salt12], [...pack.subarray(1)])
69
+ assert.deepEqual([...server.localNonce], [...pack.subarray(9, 13)])
70
+ const client = new Boho()
71
+ client.set_id8('lazy-id'); client.set_key('lazy-key')
72
+ assert.equal(client.verify_auth_res(server.verify_auth_req(client.auth_req(pack))), true)
73
+ })
74
+
75
+ it('instances do not share state', () => {
76
+ const a = new Boho(), b = new Boho()
77
+ a._id8.fill(7)
78
+ assert.ok(b._id8.every(byte => byte === 0))
79
+ })
80
+
81
+ it('authenticates and encrypts both ways, also after clearAuth and a new login', () => {
82
+ for (let round = 0; round < 2; round++) {
83
+ const { client, server } = authorizedPair()
84
+ const fromClient = server.decrypt_488(client.encrypt_488(Boho.Buffer.from('hello server')))
85
+ assert.equal(Boho.Buffer.from(fromClient).toString(), 'hello server')
86
+ const fromServer = client.decrypt_488(server.encrypt_488(Boho.Buffer.from('hello client')))
87
+ assert.equal(Boho.Buffer.from(fromServer).toString(), 'hello client')
88
+ client.clearAuth(); server.clearAuth()
89
+ assert.equal(client.isAuthorized, false)
90
+ }
91
+ })
92
+
93
+ it('E2E on an instance that never authenticated', () => {
94
+ const sender = new Boho(), receiver = new Boho()
95
+ const pack = sender.encrypt_e2e(Boho.Buffer.from('payload'), 'e2e-key')
96
+ assert.equal(Boho.Buffer.from(receiver.decrypt_e2e(pack, 'e2e-key').data).toString(), 'payload')
97
+ assert.equal(receiver.decrypt_e2e(pack, 'wrong-key'), undefined)
98
+ })
99
+ })
@@ -12,8 +12,10 @@ import PatchedBoho from '../../dist/boho.js'
12
12
  const dir = fileURLToPath(new URL('.', import.meta.url))
13
13
  const iosignal = process.env.IOSIGNAL_PATH || resolve(dir, '../../../iosignal')
14
14
  const arduino = process.env.IOSIGNAL_ARDUINO_PATH || resolve(dir, '../../../iosignal-arduino')
15
+ const bohoArduino = process.env.BOHO_ARDUINO_PATH || resolve(dir, '../../../boho-arduino')
15
16
  const load = path => import(pathToFileURL(join(iosignal, path)))
16
17
  const {Manager} = await load('src/server/Manager.js')
18
+ const {serverOption} = await load('src/server/serverOption.js')
17
19
  const {BohoAuth} = await load('src/auth/BohoAuth.js')
18
20
  const {IOCongSocket} = await load('src/client/IOCongSocket.js')
19
21
  const {CongRx} = await load('src/client/CongPacket.js')
@@ -25,8 +27,8 @@ it('Arduino IOSignal (80-byte RX) ↔ real iosignal server ↔ JS client: auth,
25
27
  let child, lines, io, manager
26
28
  try {
27
29
  const args=['-std=c++11','-ffunction-sections','-fdata-sections','-Wno-deprecated-declarations',
28
- '-I',join(dir,'shims'),'-I',join(dir,'../arduino/shims'),'-I',join(arduino,'src'),
29
- join(dir,'host.cpp'),...['Boho.cpp','CongPacket.cpp','IOSignal.cpp'].map(f=>join(arduino,'src',f)),
30
+ '-I',join(dir,'shims'),'-I',join(dir,'../arduino/shims'),'-I',join(arduino,'src'),'-I',join(bohoArduino,'src'),
31
+ join(dir,'host.cpp'),join(bohoArduino,'src/Boho.cpp'),...['CongPacket.cpp','IOSignal.cpp'].map(f=>join(arduino,'src',f)),
30
32
  '-o',executable]
31
33
  args.push(process.platform==='darwin'?'-Wl,-dead_strip':'-Wl,--gc-sections')
32
34
  if(process.platform!=='darwin')args.push('-lcrypto')
@@ -43,7 +45,7 @@ it('Arduino IOSignal (80-byte RX) ↔ real iosignal server ↔ JS client: auth,
43
45
  write(data){this.pending.push(Buffer.from(data))}
44
46
  end(){this.readyState='closed'} destroy(){this.end()}
45
47
  }
46
- const server=new EventEmitter();server.serviceNames=new Set()
48
+ const server=new EventEmitter();server.serviceNames=new Set();server.security=Object.freeze({...serverOption.security})
47
49
  const auth=new BohoAuth({getAuth:async id=>id==='arduino'?{key:'arduino-key',cid:'arduino',level:1}:
48
50
  id==='jsclient'?{key:'js-key',cid:'js',level:1}:null})
49
51
  manager=new Manager(server,auth)