boho 2.1.2 → 2.2.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/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "boho",
3
- "version": "2.1.2",
3
+ "version": "2.2.0",
4
4
  "description": "Secure Lightweight Encryption & Authentication Library for Node.js, Browsers and Arduino.",
5
5
  "type": "module",
6
6
  "exports": {
7
+ "types": "./dist/boho.d.ts",
7
8
  "import": "./dist/boho.js",
8
- "require": "./dist/boho.cjs"
9
+ "require": null
9
10
  },
10
11
  "types": "dist/boho.d.ts",
11
12
  "browser": "./dist/boho.min.js",
@@ -19,11 +20,10 @@
19
20
  "보호",
20
21
  "암호"
21
22
  ],
22
- "homepage": "https://github.com/remocons/iosignal/tree/main/packages/boho#readme",
23
+ "homepage": "https://github.com/remocons/boho#readme",
23
24
  "repository": {
24
25
  "type": "git",
25
- "url": "https://github.com/remocons/iosignal.git",
26
- "directory": "packages/boho"
26
+ "url": "git+https://github.com/remocons/boho.git"
27
27
  },
28
28
  "author": {
29
29
  "name": "Taeo Lee",
@@ -31,16 +31,22 @@
31
31
  },
32
32
  "license": "MIT",
33
33
  "devDependencies": {
34
- "@rollup/plugin-commonjs": "^28.0.3",
35
- "@rollup/plugin-node-resolve": "^15.3.1",
34
+ "@rollup/plugin-commonjs": "^29.0.3",
35
+ "@rollup/plugin-node-resolve": "^16.0.3",
36
36
  "@rollup/plugin-terser": "^1.0.0",
37
- "rollup": "^4.36.0"
37
+ "rollup": "^4.62.4",
38
+ "typescript": "^5.9.3"
38
39
  },
39
40
  "dependencies": {
40
- "meta-buffer-pack": "^2.1.2"
41
+ "buffer": "^6.0.3",
42
+ "meta-buffer-pack": "^2.1.4"
41
43
  },
42
44
  "scripts": {
43
45
  "build": "rollup -c",
44
- "test": "node --test"
46
+ "test": "node --test test/*.js && npm run test:types",
47
+ "pretest": "npm run build",
48
+ "test:types": "tsc -p test/types/tsconfig.json",
49
+ "test:arduino": "npm run build && node --test test/arduino/interop.test.js",
50
+ "test:iosignal": "npm run build && node --import ./test/iosignal/register.js --test test/iosignal/full-flow.test.js"
45
51
  }
46
52
  }
package/rollup.config.js CHANGED
@@ -12,10 +12,6 @@ export default [
12
12
  name: 'Boho',
13
13
  sourcemap: true
14
14
  },
15
- {
16
- file: './dist/boho.cjs',
17
- format: 'cjs'
18
- },
19
15
  {
20
16
  file: './dist/boho.js',
21
17
  format: 'es',
package/src/boho.js CHANGED
@@ -13,6 +13,28 @@ export { BohoMsg, Meta, MetaSize, sha256 }
13
13
  import { Buffer } from 'buffer/index.js'
14
14
  export { Buffer }
15
15
 
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
23
+ }
24
+
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)
31
+ }
32
+
33
+ function validClock(clock) {
34
+ return clock.readUInt16LE(4) < 1000
35
+ }
36
+
37
+
16
38
  /**
17
39
  * Generates a random byte buffer.
18
40
  * @param {number} size - Number of bytes to generate
@@ -40,7 +62,9 @@ export class Boho {
40
62
  this.localNonce = Buffer.alloc(4)
41
63
  this.remoteNonce = Buffer.alloc(4)
42
64
  this.isAuthorized = false
43
- this.counter = 0;
65
+ this.counter = 0
66
+ this._hasKey = false
67
+ this._lastSendTime = 0
44
68
  }
45
69
 
46
70
  /**
@@ -55,7 +79,9 @@ export class Boho {
55
79
  this.localNonce.fill(0)
56
80
  this.remoteNonce.fill(0)
57
81
  this.isAuthorized = false
58
- this.counter = 0;
82
+ this.counter = 0
83
+ this._hasKey = false
84
+ this._lastSendTime = 0
59
85
  }
60
86
 
61
87
  /**
@@ -82,8 +108,9 @@ export class Boho {
82
108
  * @param {any} data
83
109
  */
84
110
  set_key(data) {
85
- let keySum = MBP.B8(sha256.hash(data))
86
- keySum.copy(this._otpSrc44, 0, 0, 32)
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)))
87
114
  }
88
115
 
89
116
  /**
@@ -112,7 +139,12 @@ export class Boho {
112
139
  * @param {Buffer} data
113
140
  */
114
141
  copy_key(data) {
115
- data.copy(this._otpSrc44, 0, 0, 32)
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
+
116
148
  }
117
149
 
118
150
  /**
@@ -132,37 +164,34 @@ export class Boho {
132
164
  * Sets random clock value (salt12) in otpSrc44.
133
165
  */
134
166
  set_clock_rand() {
135
- const now = Date.now()
136
- const secTime = parseInt(now / 1000)
137
- const milTime = now % 1000
138
- if (++this.counter > 65535) this.counter = 0;
139
- const salt12 = Buffer.concat([
140
- MBP.NB('32L', secTime),
141
- MBP.NB('16L', milTime),
142
- MBP.NB('16L', this.counter),
143
- RAND(4) // JS: use crypto.getRandomValues(), Arduino: use micros()
144
- ])
145
- salt12.copy(this._otpSrc44, 32)
167
+ this.set_clock_nonce(RAND(4))
146
168
  }
147
169
 
148
- /**
149
- * Sets otpSrc44 with given nonce and clock value.
150
- * @param {Buffer} nonce
151
- */
170
+ /** Sets a monotonic clock/counter and a 4-byte nonce. */
152
171
  set_clock_nonce(nonce) {
153
- const now = Date.now()
154
- const secTime = parseInt(now / 1000)
155
- const milTime = now % 1000
156
- if (++this.counter > 65535) this.counter = 0;
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
157
182
  const salt12 = Buffer.concat([
158
- MBP.NB('32L', secTime),
159
- MBP.NB('16L', milTime),
183
+ MBP.NB('32L', Math.floor(now / 1000)),
184
+ MBP.NB('16L', now % 1000),
160
185
  MBP.NB('16L', this.counter),
161
- nonce
186
+ Buffer.from(nonce)
162
187
  ])
163
188
  salt12.copy(this._otpSrc44, 32)
164
189
  }
165
190
 
191
+ _requireKey() {
192
+ if (!this._hasKey) throw new Error('Set a key before encryption or authentication')
193
+ }
194
+
166
195
  /**
167
196
  * Sets salt12 value in otpSrc44.
168
197
  * @param {Buffer} salt12
@@ -179,6 +208,7 @@ export class Boho {
179
208
  * Initializes OTP value.
180
209
  */
181
210
  resetOTP() {
211
+ this._requireKey()
182
212
  let otp32 = MBP.B8(sha256.hash(this._otpSrc44))
183
213
  otp32.copy(this._otp36, 0, 0, 32)
184
214
  }
@@ -194,20 +224,22 @@ export class Boho {
194
224
  }
195
225
 
196
226
  /**
197
- * Generates HMAC value.
227
+ * Generates the legacy SHA-256 prefix tag (not standard HMAC).
198
228
  * @param {Buffer} data
199
229
  */
200
230
  generateHMAC(data) {
231
+ this._requireKey()
201
232
  let hmacSrc = Buffer.concat([this._otpSrc44, data])
202
233
  this._hmac = MBP.B8(sha256.hash(hmacSrc))
203
234
  }
204
235
 
205
236
  /**
206
- * Returns 8-byte HMAC value.
237
+ * Returns the truncated 8-byte legacy tag (not standard HMAC).
207
238
  * @param {Buffer} data
208
239
  * @returns {Buffer}
209
240
  */
210
241
  getHMAC8(data) {
242
+ this._requireKey()
211
243
  let hmacSrc = Buffer.concat([this._otpSrc44, data])
212
244
  this._hmac = MBP.B8(sha256.hash(hmacSrc))
213
245
  return this._hmac.subarray(0, 8)
@@ -273,7 +305,9 @@ export class Boho {
273
305
  * @returns {Buffer|boolean}
274
306
  */
275
307
  auth_req(buffer) {
276
- let server_time_nonce = MBP.unpack(buffer, Meta.SERVER_TIME_NONCE)
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
277
311
  if (server_time_nonce) {
278
312
  let salt12 = Buffer.concat([
279
313
  MBP.NB('32L', server_time_nonce.unixTime),
@@ -312,23 +346,26 @@ export class Boho {
312
346
  */
313
347
  verify_auth_req(data) {
314
348
 
349
+ if (!this._hasKey) return false
315
350
  let infoPack
316
351
  if (data instanceof Uint8Array) {
317
- infoPack = MBP.unpack(data, Meta.AUTH_REQ)
318
- if (!infoPack) {
319
- return
320
- }
321
- } else {
322
- infoPack = data;
352
+ infoPack = readPacket(data, BohoMsg.AUTH_REQ, MetaSize.AUTH_REQ, Meta.AUTH_REQ)
353
+ } else if (data && typeof data === 'object') {
354
+ infoPack = data
323
355
  }
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
324
361
 
325
362
  this.set_salt12(this.auth_salt12, 'verify_auth_req 1/2')
326
363
 
327
364
  this.generateHMAC(infoPack.nonce)
328
365
  let hmac32 = this._hmac
329
366
 
330
- if (MBP.equal(infoPack.hmac32, hmac32)) {
331
- this.remoteNonce = infoPack.nonce
367
+ if (equalTag(infoPack.hmac32, hmac32)) {
368
+ this.remoteNonce = Buffer.from(infoPack.nonce)
332
369
 
333
370
  let salt12 = Buffer.concat([
334
371
  this.localNonce,
@@ -356,7 +393,8 @@ export class Boho {
356
393
  * @returns {boolean}
357
394
  */
358
395
  verify_auth_res(buffer) {
359
- let auth_res = MBP.unpack(buffer, Meta.AUTH_RES)
396
+ if (!this._hasKey) return false
397
+ let auth_res = readPacket(buffer, BohoMsg.AUTH_RES, MetaSize.AUTH_RES, Meta.AUTH_RES)
360
398
  if (auth_res) {
361
399
  let salt12 = Buffer.concat([
362
400
  this.remoteNonce,
@@ -366,7 +404,7 @@ export class Boho {
366
404
  this.set_salt12(salt12, 'verify_auth_res')
367
405
  this.generateHMAC(this.localNonce)
368
406
  let hmac32 = this._hmac
369
- if (MBP.equal(hmac32, auth_res.hmac32)) {
407
+ if (equalTag(hmac32, auth_res.hmac32)) {
370
408
  this.isAuthorized = true
371
409
  return true
372
410
  }
@@ -383,7 +421,7 @@ export class Boho {
383
421
  * @returns {Buffer|undefined}
384
422
  */
385
423
  encrypt_488(data) {
386
- if (!this.isAuthorized) return
424
+ if (!this.isAuthorized || !this._hasKey) return
387
425
 
388
426
  data = MBP.B8(data)
389
427
 
@@ -409,28 +447,26 @@ export class Boho {
409
447
  * @returns {Buffer|undefined}
410
448
  */
411
449
  decrypt_488(data) {
412
- data = MBP.B8(data)
413
-
414
- let pack = MBP.unpack(data, Meta.ENC_488)
415
-
416
- if (pack) {
417
-
418
- let salt12 = Buffer.concat([
419
- pack.otpSrc8,
420
- this.localNonce
421
- ])
422
-
423
- this.set_salt12(salt12 , 'decrypt_488')
424
- this.resetOTP()
425
-
426
- let xdata = pack.$OTHERS.subarray(0, pack.len)
427
- let decData = this.xotp(xdata)
428
-
429
- let hmac8 = this.getHMAC8(decData)
430
-
431
- if (MBP.equal(hmac8, pack.hmac8)) return decData
432
-
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
433
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
434
470
  }
435
471
 
436
472
  /**
@@ -439,6 +475,7 @@ export class Boho {
439
475
  * @returns {Buffer}
440
476
  */
441
477
  encryptPack(data) {
478
+ this._requireKey()
442
479
  data = MBP.B8(data)
443
480
 
444
481
  this.set_clock_rand()
@@ -463,35 +500,15 @@ export class Boho {
463
500
  * @returns {Buffer}
464
501
  */
465
502
  decryptPack(data) {
466
-
467
- if (data[0] !== BohoMsg.ENC_PACK) {
468
- return
469
- }
470
-
471
- let readPackLen = data.readUint32LE(1);
472
- if (readPackLen != data.byteLength - MetaSize.ENC_PACK) {
473
- return
474
- }
475
-
476
- try {
477
- let pack = MBP.unpack(data, Meta.ENC_PACK)
478
- if (!pack) return
479
-
480
- this.set_salt12(pack.salt12, 'decryptPack')
481
- this.resetOTP()
482
-
483
- let xdata = pack.$OTHERS
484
- let decData = this.xotp(xdata)
485
- let hmac8 = this.getHMAC8(decData)
486
-
487
- if (MBP.equal(pack.hmac, hmac8)) {
488
- pack.data = decData
489
- return pack
490
- }
491
-
492
- } catch (error) {
493
-
494
- }
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
495
512
  }
496
513
 
497
514
  /**
@@ -501,12 +518,7 @@ export class Boho {
501
518
  * @returns {Buffer}
502
519
  */
503
520
  encrypt_e2e(data, key) {
504
- let baseKey = Buffer.alloc(32)
505
- baseKey.set(this._otpSrc44.subarray(0, 32))
506
- this.set_key(key)
507
- let pack = this.encryptPack(data)
508
- this._otpSrc44.set(baseKey)
509
- return pack;
521
+ return this._withKey(key, () => this.encryptPack(data))
510
522
  }
511
523
 
512
524
  /**
@@ -516,12 +528,25 @@ export class Boho {
516
528
  * @returns {Buffer}
517
529
  */
518
530
  decrypt_e2e(data, key) {
519
- let baseKey = Buffer.alloc(32)
520
- baseKey.set(this._otpSrc44.subarray(0, 32))
521
- this.set_key(key)
522
- let decPack = this.decryptPack(data)
523
- this._otpSrc44.set(baseKey)
524
- return decPack
531
+ return this._withKey(key, () => this.decryptPack(data))
532
+ }
533
+
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
+ }
525
550
  }
526
551
 
527
552
  }
@@ -33,12 +33,12 @@ describe('AUTH process ESM', function () {
33
33
  s.set_key(key) // if correct.
34
34
  const auth_res_buffer = s.verify_auth_req(unpack)
35
35
 
36
- const auth_res_buffer_with_incorrect_hmac = Boho.Buffer.alloc(9)
37
- const isCorrectSeverHMAC = c.verify_auth_res(auth_res_buffer)
36
+ const auth_res_buffer_with_incorrect_hmac = Boho.Buffer.alloc(MetaSize.AUTH_RES)
38
37
 
39
38
  auth_res_buffer.copy(auth_res_buffer_with_incorrect_hmac)
40
39
  auth_res_buffer_with_incorrect_hmac[2] ^= 0x55 // change hmac
41
40
  const wrongSeverHMACResult = c.verify_auth_res(auth_res_buffer_with_incorrect_hmac)
41
+ const isCorrectSeverHMAC = c.verify_auth_res(auth_res_buffer)
42
42
 
43
43
 
44
44
  describe('1. server send SERVER_TIME_NONCE', function () {
@@ -47,7 +47,7 @@ describe('AUTH process ESM', function () {
47
47
  })
48
48
 
49
49
  it('should pack[0] is header type ', function () {
50
- assert.ok(auth_nonce_buffer[0], BohoMsg.SERVER_TIME_NONCE)
50
+ assert.equal(auth_nonce_buffer[0], BohoMsg.SERVER_TIME_NONCE)
51
51
  })
52
52
  })
53
53
 
@@ -57,7 +57,7 @@ describe('AUTH process ESM', function () {
57
57
  })
58
58
 
59
59
  it('should pack[0] is header type ', function () {
60
- assert.ok(auth_req_buffer[0], BohoMsg.AUTH_REQ)
60
+ assert.equal(auth_req_buffer[0], BohoMsg.AUTH_REQ)
61
61
  })
62
62
  })
63
63
 
@@ -0,0 +1,51 @@
1
+ #include <iostream>
2
+ #include <sstream>
3
+ #include <vector>
4
+ #include <string>
5
+ #include "Boho.h"
6
+ uint32_t clockMs = 1234, clockUs = 1234567;
7
+ uint32_t millis() { return clockMs; }
8
+ uint32_t micros() { return clockUs; }
9
+ TestSerial Serial;
10
+ std::vector<uint8_t> fromHex(const std::string& text) {
11
+ std::vector<uint8_t> out;
12
+ for (size_t i = 0; i < text.size(); i += 2) out.push_back(std::stoul(text.substr(i, 2), nullptr, 16));
13
+ return out;
14
+ }
15
+ void printHex(const std::vector<uint8_t>& data, size_t size) {
16
+ const char* hex = "0123456789abcdef";
17
+ for (size_t i = 0; i < size; i++) std::cout << hex[data[i] >> 4] << hex[data[i] & 15];
18
+ std::cout << std::endl;
19
+ }
20
+ int main() {
21
+ const uint16_t endian = 1;
22
+ if (*reinterpret_cast<const uint8_t*>(&endian) != 1) return 2;
23
+ Boho boho;
24
+ boho.set_id8("test-id"); boho.set_key("interop-shared-key");
25
+ std::string line;
26
+ while (std::getline(std::cin, line)) {
27
+ std::istringstream input(line);
28
+ std::string command, arg; input >> command >> arg;
29
+ if (command == "CLOCK") {
30
+ clockMs = std::stoul(arg); input >> clockUs; std::cout << "ok" << std::endl; continue;
31
+ }
32
+ if (command == "TIME") {
33
+ unsigned ms = 0; input >> ms; boho.setTime(std::stoul(arg), ms); std::cout << "ok" << std::endl; continue;
34
+ }
35
+ auto data = fromHex(arg);
36
+ std::vector<uint8_t> out(data.size() + 128);
37
+ size_t length = 0;
38
+ if (command == "AUTH") length = boho.auth_req(out.data(), data.data(), data.size());
39
+ else if (command == "VERIFY") {
40
+ std::cout << (boho.verify_auth_res(data.data(), data.size()) ? "1" : "0") << std::endl; continue;
41
+ }
42
+ else if (command == "PACK") length = boho.encryptPack(out.data(), data.data(), data.size());
43
+ else if (command == "UNPACK") length = boho.decryptPack(out.data(), data.data(), data.size());
44
+ else if (command == "E2E") length = boho.encrypt_e2e(out.data(), data.data(), data.size(), "interop-e2e-key");
45
+ else if (command == "DE2E") length = boho.decrypt_e2e(out.data(), data.data(), data.size(), "interop-e2e-key");
46
+ else if (command == "SEND") length = boho.encrypt_488(out.data(), data.data(), data.size());
47
+ else if (command == "RECV") length = boho.decrypt_488(out.data(), data.data(), data.size());
48
+ else return 3;
49
+ printHex(out, length);
50
+ }
51
+ }
@@ -0,0 +1,89 @@
1
+ import { before, after, describe, it } from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import { spawn, spawnSync } from 'node:child_process'
4
+ import { mkdtempSync, rmSync, readFileSync } from 'node:fs'
5
+ import { tmpdir } from 'node:os'
6
+ import { join, resolve } from 'node:path'
7
+ import { fileURLToPath } from 'node:url'
8
+ import readline from 'node:readline'
9
+ import vm from 'node:vm'
10
+ import Source from '../../src/index.js'
11
+ import Distribution from '../../dist/boho.js'
12
+
13
+ const directory = fileURLToPath(new URL('.', import.meta.url))
14
+ const arduino = process.env.BOHO_ARDUINO_PATH || resolve(directory, '../../../boho-arduino')
15
+ let build, executable
16
+ before(() => {
17
+ build = mkdtempSync(join(tmpdir(), 'boho-arduino-'))
18
+ executable = join(build, 'interop')
19
+ const args = ['-std=c++11', '-Wno-deprecated-declarations', '-I', join(directory, 'shims'), '-I', join(arduino, 'src'),
20
+ join(directory, 'host.cpp'), join(arduino, 'src/Boho.cpp'), '-o', executable]
21
+ if (process.platform !== 'darwin') args.push('-lcrypto')
22
+ const result = spawnSync('c++', args, { encoding: 'utf8', timeout: 30000 })
23
+ assert.equal(result.status, 0, result.stderr || String(result.error))
24
+ })
25
+ after(() => { if (build) rmSync(build, { recursive: true, force: true }) })
26
+
27
+ async function withPeer(run) {
28
+ const child = spawn(executable, [], { stdio: ['pipe', 'pipe', 'pipe'] })
29
+ const lines = readline.createInterface({ input: child.stdout })[Symbol.asyncIterator]()
30
+ const ask = async (command, value = '') => {
31
+ const reply = lines.next()
32
+ child.stdin.write(`${command} ${typeof value === 'string' ? value : Buffer.from(value).toString('hex')}\n`)
33
+ const line = await reply
34
+ assert.equal(line.done, false, 'C++ peer closed unexpectedly')
35
+ return line.value
36
+ }
37
+ try { await run(ask) } finally { child.stdin.end(); child.kill(); await lines.return() }
38
+ }
39
+
40
+ const browser = { crypto: globalThis.crypto, TextEncoder, TextDecoder, Uint8Array, ArrayBuffer }
41
+ vm.runInNewContext(readFileSync(new URL('../../dist/boho.min.js', import.meta.url), 'utf8'), browser)
42
+ for (const [name, B] of [['source', Source], ['ESM', Distribution], ['UMD', browser.Boho]]) {
43
+ describe(`${name} ↔ unchanged Arduino Boho.cpp`, { timeout: 10000 }, () => {
44
+ it('exchanges normal and E2E packets in both directions', async () => withPeer(async ask => {
45
+ const b = new B(); b.set_key('interop-shared-key')
46
+ for (const size of [1, 31, 32, 33, 257]) {
47
+ const plain = B.Buffer.from(Array.from({length: size}, (_, i) => i & 255))
48
+ const encoded = B.Buffer.from(await ask('PACK', plain), 'hex')
49
+ assert.equal(b.decryptPack(encoded).data.toString('hex'), plain.toString('hex'))
50
+ assert.equal(await ask('UNPACK', b.encryptPack(plain)), plain.toString('hex'))
51
+ const e2e = B.Buffer.from(await ask('E2E', plain), 'hex')
52
+ assert.equal(b.decrypt_e2e(e2e, 'interop-e2e-key').data.toString('hex'), plain.toString('hex'))
53
+ assert.equal(await ask('DE2E', b.encrypt_e2e(plain, 'interop-e2e-key')), plain.toString('hex'))
54
+ }
55
+ }))
56
+ it('authenticates the Arduino client and exchanges 488 packets', async () => withPeer(async ask => {
57
+ const server = new B(); server.set_key('interop-shared-key')
58
+ const request = B.Buffer.from(await ask('AUTH', server.server_time_nonce()), 'hex')
59
+ const response = server.verify_auth_req(request)
60
+ assert.ok(response)
61
+ assert.equal(await ask('VERIFY', response), '1')
62
+ for (const size of [1, 31, 32, 33, 257]) {
63
+ const plain = B.Buffer.alloc(size, 0x5a)
64
+ const packet = B.Buffer.from(await ask('SEND', plain), 'hex')
65
+ assert.equal(server.decrypt_488(packet).toString('hex'), plain.toString('hex'))
66
+ assert.equal(server.decrypt_488(packet).toString('hex'), plain.toString('hex'))
67
+ assert.equal(await ask('RECV', server.encrypt_488(plain)), plain.toString('hex'))
68
+ }
69
+ }))
70
+ it('accepts Arduino counter wrap and clock resynchronization', async () => withPeer(async ask => {
71
+ const server = new B(); server.set_key('interop-shared-key')
72
+ const challenge = server.server_time_nonce()
73
+ // The challenge counter seeds the Arduino sender; force wrap on send 2.
74
+ challenge.writeUInt16LE(65534, 7)
75
+ server.auth_salt12 = B.Buffer.from(challenge.subarray(1))
76
+ const request = B.Buffer.from(await ask('AUTH', challenge), 'hex')
77
+ assert.equal(await ask('VERIFY', server.verify_auth_req(request)), '1')
78
+ const plain = B.Buffer.from('counter wrap')
79
+ for (const expected of [65535, 0, 1]) {
80
+ const packet = B.Buffer.from(await ask('SEND', plain), 'hex')
81
+ assert.equal(packet.readUInt16LE(11), expected)
82
+ assert.equal(server.decrypt_488(packet).toString(), plain.toString())
83
+ }
84
+ await ask('TIME', '100 0')
85
+ const oldClockPacket = B.Buffer.from(await ask('SEND', plain), 'hex')
86
+ assert.equal(server.decrypt_488(oldClockPacket).toString(), plain.toString())
87
+ }))
88
+ })
89
+ }
@@ -0,0 +1,8 @@
1
+ #pragma once
2
+ #include <cstdint>
3
+ #include <cstdlib>
4
+ #include <cstdio>
5
+ uint32_t millis();
6
+ uint32_t micros();
7
+ struct TestSerial { void write(const char*) {} };
8
+ extern TestSerial Serial;
@@ -0,0 +1 @@
1
+ #pragma once