@johnhenry/browsermesh-core 0.0.1 → 0.1.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/handshake.mjs CHANGED
@@ -10,8 +10,10 @@ import { silentCatch } from './silent-catch.mjs'
10
10
  * signaler interface that WebRTCTransport expects (sendOffer, sendAnswer,
11
11
  * sendIceCandidate, onOffer, onAnswer, onIceCandidate).
12
12
  *
13
- * DirectInputHandshake handles manual key exchange for direct pairing
14
- * without a signaling server -- via clipboard paste or QR code.
13
+ * DirectInputHandshake handles manual exchange of a peer's identity and
14
+ * connection parameters -- via clipboard paste or QR code -- without a
15
+ * server. Note that this covers the KEY exchange only: the token carries
16
+ * no SDP, so establishing the connection still needs a signaling channel.
15
17
  *
16
18
  * HandshakeCoordinator orchestrates the full connection flow:
17
19
  * discovery -> transport selection -> handshake -> session.
@@ -27,13 +29,38 @@ import { silentCatch } from './silent-catch.mjs'
27
29
  // Helpers
28
30
  // ---------------------------------------------------------------------------
29
31
 
32
+ /**
33
+ * Largest number of bytes handed to `String.fromCharCode` at a time.
34
+ *
35
+ * The spread form -- `String.fromCharCode(...bytes)` -- turns every byte into
36
+ * a separate argument, and V8 caps an argument list at roughly 124k entries,
37
+ * so it throws `RangeError: Maximum call stack size exceeded` on inputs above
38
+ * that. The exact ceiling moves with the stack depth of the caller, which is
39
+ * worse than a fixed limit: the same input can encode from one call site and
40
+ * throw from another. Chunking removes the ceiling entirely.
41
+ */
42
+ const FROM_CHAR_CODE_CHUNK = 0x8000
43
+
30
44
  /**
31
45
  * Convert a Uint8Array to a base64url string (no padding).
46
+ *
47
+ * Handles inputs of any length. See FROM_CHAR_CODE_CHUNK for why this is a
48
+ * chunked loop rather than the shorter spread form.
49
+ *
32
50
  * @param {Uint8Array} bytes
33
51
  * @returns {string}
34
52
  */
35
53
  function toBase64Url(bytes) {
36
- const bin = String.fromCharCode(...bytes)
54
+ // subarray() is zero-copy but TypedArray-only; callers outside this module
55
+ // may hand us a plain array of byte values, which the old spread accepted.
56
+ const view = ArrayBuffer.isView(bytes) ? bytes : Uint8Array.from(bytes)
57
+ let bin = ''
58
+ for (let i = 0; i < view.length; i += FROM_CHAR_CODE_CHUNK) {
59
+ bin += String.fromCharCode.apply(
60
+ null,
61
+ view.subarray(i, i + FROM_CHAR_CODE_CHUNK),
62
+ )
63
+ }
37
64
  const b64 = btoa(bin)
38
65
  return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
39
66
  }
@@ -63,9 +90,52 @@ function randomHex(byteLen = 16) {
63
90
  return [...bytes].map(b => b.toString(16).padStart(2, '0')).join('')
64
91
  }
65
92
 
93
+ /**
94
+ * Thrown by `DirectInputHandshake.decodeToken()` for any malformed token.
95
+ *
96
+ * One error type for the whole decode path, so a caller wiring up a QR
97
+ * scanner catches this instead of guessing which of `DOMException`,
98
+ * `SyntaxError` or `TypeError` the platform will produce. The originating
99
+ * platform error, when there is one, is kept as `cause`.
100
+ */
101
+ export class TokenDecodeError extends Error {
102
+ /**
103
+ * @param {string} message
104
+ * @param {object} [opts]
105
+ * @param {unknown} [opts.cause]
106
+ */
107
+ constructor(message, opts) {
108
+ super(message, opts)
109
+ this.name = 'TokenDecodeError'
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Longest encoded token `decodeToken()` will look at, in characters.
115
+ *
116
+ * A ConnectionToken is a few hundred bytes; the densest QR code holds 2,953
117
+ * bytes, so anything a camera can actually read is two orders of magnitude
118
+ * below this. The cap exists only to bound what a hostile string can make the
119
+ * process allocate -- it is deliberately generous rather than tight.
120
+ *
121
+ * Note the asymmetry: `encodeToken()` is uncapped, because a caller encoding
122
+ * their own token is not the untrusted side. A token built from a very large
123
+ * `iceServers` list can therefore encode to more than this and fail to decode.
124
+ * Pass `{ maxLength }` if that is genuinely your case.
125
+ */
126
+ export const MAX_ENCODED_TOKEN_LENGTH = 128 * 1024
127
+
66
128
  /** Token TTL in milliseconds (5 minutes). */
67
129
  const TOKEN_TTL_MS = 5 * 60 * 1000
68
130
 
131
+ /**
132
+ * Default cap on the number of consumed nonces a DirectInputHandshake will
133
+ * remember. Entries normally age out with the token TTL well before this
134
+ * matters; the cap exists so that a peer flooding distinct tokens cannot
135
+ * grow the set without bound.
136
+ */
137
+ const DEFAULT_MAX_CONSUMED_NONCES = 10_000
138
+
69
139
  /** Default connection timeout in milliseconds. */
70
140
  const DEFAULT_TIMEOUT_MS = 30_000
71
141
 
@@ -313,12 +383,29 @@ export class SignalingClient {
313
383
  // ---------------------------------------------------------------------------
314
384
 
315
385
  /**
316
- * Manual key exchange for direct pairing without a signaling server.
386
+ * Out-of-band exchange of a peer's identity and connection parameters.
387
+ *
388
+ * Generates a connection token containing the local pod's identity and
389
+ * connection parameters, shareable via clipboard paste or QR code. The
390
+ * receiving peer decodes and validates the token, then uses it to reach
391
+ * the issuer.
317
392
  *
318
- * Generates a connection token containing the local pod's identity
319
- * and connection parameters. The token can be shared via clipboard
320
- * paste or QR code. The receiving peer decodes and validates the
321
- * token to establish a connection.
393
+ * **What this does and does not do.** The *key exchange* needs no server:
394
+ * the token travels over whatever out-of-band channel you like. The
395
+ * *connection* still does. A ConnectionToken carries podId, publicKey,
396
+ * nonce, timestamp and optionally signalingUrl/iceServers -- it carries no
397
+ * SDP offer. `HandshakeCoordinator.connectViaToken()` therefore requires
398
+ * either an existing signalingClient or a `token.signalingUrl`, and throws
399
+ * 'No signaling channel available' without one.
400
+ *
401
+ * Earlier revisions of this docstring said "direct pairing without a
402
+ * signaling server", which read as a promise of serverless pairing. It was
403
+ * never that. Putting an SDP offer with pre-gathered ICE candidates into
404
+ * the token would make it that -- see issue #5 -- and is the one design
405
+ * that needs no rendezvous, no STUN and no certificate for two peers on a
406
+ * LAN. It is not implemented here.
407
+ *
408
+ * Tokens are single use: see `validateToken()`.
322
409
  */
323
410
  export class DirectInputHandshake {
324
411
  /** @type {string} */
@@ -336,6 +423,16 @@ export class DirectInputHandshake {
336
423
  /** @type {Function} */
337
424
  #onLog
338
425
 
426
+ /**
427
+ * Nonces of tokens this instance has already accepted, mapped to the
428
+ * timestamp at which they may be forgotten. Enforces single use.
429
+ * @type {Map<string, number>}
430
+ */
431
+ #consumedNonces = new Map()
432
+
433
+ /** @type {number} */
434
+ #maxConsumedNonces
435
+
339
436
  /**
340
437
  * @param {object} opts
341
438
  * @param {string} opts.localPodId - Local pod identifier
@@ -343,8 +440,11 @@ export class DirectInputHandshake {
343
440
  * @param {string} [opts.signalingUrl] - Optional signaling server URL to include in token
344
441
  * @param {object[]} [opts.iceServers] - Optional ICE server configs to include in token
345
442
  * @param {Function} [opts.onLog] - Logging callback (level, msg)
443
+ * @param {number} [opts.maxConsumedNonces=10000] - Cap on the replay set. Entries
444
+ * normally age out with the token TTL; this cap bounds memory if a peer floods
445
+ * distinct tokens faster than they expire.
346
446
  */
347
- constructor({ localPodId, getPublicKeyBytes, signalingUrl, iceServers, onLog } = {}) {
447
+ constructor({ localPodId, getPublicKeyBytes, signalingUrl, iceServers, onLog, maxConsumedNonces = DEFAULT_MAX_CONSUMED_NONCES } = {}) {
348
448
  if (!localPodId || typeof localPodId !== 'string') {
349
449
  throw new Error('localPodId is required and must be a non-empty string')
350
450
  }
@@ -356,6 +456,56 @@ export class DirectInputHandshake {
356
456
  this.#signalingUrl = signalingUrl || null
357
457
  this.#iceServers = iceServers || null
358
458
  this.#onLog = onLog || (() => {})
459
+ this.#maxConsumedNonces = Number.isInteger(maxConsumedNonces) && maxConsumedNonces > 0
460
+ ? maxConsumedNonces
461
+ : DEFAULT_MAX_CONSUMED_NONCES
462
+ }
463
+
464
+ /**
465
+ * Number of tokens currently held in the replay set. Entries age out
466
+ * once they are past the token TTL. Exposed for observability and tests.
467
+ * @returns {number}
468
+ */
469
+ get consumedTokenCount() {
470
+ this.#pruneConsumedNonces()
471
+ return this.#consumedNonces.size
472
+ }
473
+
474
+ /**
475
+ * Forget every consumed nonce, so previously used tokens validate again.
476
+ *
477
+ * Only for tests and for deliberately resetting a pairing session. Calling
478
+ * this in production re-opens the replay window for any token still inside
479
+ * its TTL.
480
+ */
481
+ forgetConsumedTokens() {
482
+ this.#consumedNonces.clear()
483
+ }
484
+
485
+ /**
486
+ * Drop replay-set entries that are past their expiry, and enforce the cap.
487
+ * @param {number} [now]
488
+ */
489
+ #pruneConsumedNonces(now = Date.now()) {
490
+ for (const [key, expiresAt] of this.#consumedNonces) {
491
+ if (expiresAt <= now) this.#consumedNonces.delete(key)
492
+ }
493
+ // Map iterates in insertion order, so the front is the oldest.
494
+ while (this.#consumedNonces.size > this.#maxConsumedNonces) {
495
+ const oldest = this.#consumedNonces.keys().next()
496
+ if (oldest.done) break
497
+ this.#consumedNonces.delete(oldest.value)
498
+ }
499
+ }
500
+
501
+ /**
502
+ * Replay-set key for a token. A nonce is only meaningful relative to the
503
+ * pod that issued it, so both are part of the key.
504
+ * @param {ConnectionToken} token
505
+ * @returns {string}
506
+ */
507
+ #nonceKey(token) {
508
+ return `${token.podId}\u0000${token.nonce}`
359
509
  }
360
510
 
361
511
  /**
@@ -399,24 +549,87 @@ export class DirectInputHandshake {
399
549
  /**
400
550
  * Decode a base64url-encoded token string back into a ConnectionToken.
401
551
  *
552
+ * This is the first thing in the library that touches a scanned QR code or
553
+ * a pasted clipboard string -- the least trustworthy input it handles -- so
554
+ * it reports failure in one way instead of leaking whatever the platform
555
+ * happened to throw. Previously a malformed string surfaced a raw
556
+ * `DOMException` from `atob` or a `SyntaxError` from `JSON.parse`, neither
557
+ * of which the signature mentioned and neither of which says anything
558
+ * useful to the person holding the phone.
559
+ *
560
+ * Every failure is now a {@link TokenDecodeError} whose `cause` is the
561
+ * original platform error, and input longer than `maxLength` is refused
562
+ * before any allocation, so a hostile QR cannot ask for arbitrary memory.
563
+ *
402
564
  * @param {string} encoded - base64url-encoded JSON string
565
+ * @param {object} [opts]
566
+ * @param {number} [opts.maxLength=MAX_ENCODED_TOKEN_LENGTH] - Reject input
567
+ * longer than this many characters without decoding it.
403
568
  * @returns {ConnectionToken}
569
+ * @throws {TokenDecodeError} On non-string, oversized, non-base64url,
570
+ * non-JSON, or non-object input.
404
571
  */
405
- static decodeToken(encoded) {
406
- const bytes = fromBase64Url(encoded)
407
- const json = new TextDecoder().decode(bytes)
408
- return JSON.parse(json)
572
+ static decodeToken(encoded, { maxLength = MAX_ENCODED_TOKEN_LENGTH } = {}) {
573
+ if (typeof encoded !== 'string') {
574
+ throw new TokenDecodeError(`Token must be a string, got ${typeof encoded}`)
575
+ }
576
+ if (encoded.length === 0) {
577
+ throw new TokenDecodeError('Token is empty')
578
+ }
579
+ if (encoded.length > maxLength) {
580
+ throw new TokenDecodeError(
581
+ `Token is too long: ${encoded.length} characters, limit is ${maxLength}`,
582
+ )
583
+ }
584
+
585
+ let bytes
586
+ try {
587
+ bytes = fromBase64Url(encoded)
588
+ } catch (cause) {
589
+ throw new TokenDecodeError('Token is not valid base64url', { cause })
590
+ }
591
+
592
+ let parsed
593
+ try {
594
+ parsed = JSON.parse(new TextDecoder().decode(bytes))
595
+ } catch (cause) {
596
+ throw new TokenDecodeError('Token is not valid JSON', { cause })
597
+ }
598
+
599
+ // JSON.parse happily returns 123, null or "str". The declared return type
600
+ // is an object, and validateToken() would only reject those later with a
601
+ // vaguer message, so reject here.
602
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
603
+ throw new TokenDecodeError(
604
+ `Token JSON is not an object (got ${Array.isArray(parsed) ? 'array' : parsed === null ? 'null' : typeof parsed})`,
605
+ )
606
+ }
607
+ return parsed
409
608
  }
410
609
 
411
610
  /**
412
611
  * Validate a received connection token.
413
612
  *
414
- * Checks: has podId, has publicKey, has nonce, not self, not expired (5min TTL).
613
+ * Checks: has podId, has publicKey, has nonce, not self, not expired
614
+ * (5min TTL), not more than 30s in the future, and **not previously used**.
615
+ *
616
+ * Tokens are single use. On success the token's nonce is recorded, and any
617
+ * later token carrying the same podId+nonce is rejected with
618
+ * `'Token already used'`. This is what makes a token shared over an
619
+ * observable channel — a QR code on a screen, a clipboard, a screenshot —
620
+ * safe to show: capturing it buys one pairing at most, not five minutes of
621
+ * unlimited pairings.
622
+ *
623
+ * Pass `{ consume: false }` to check a token without spending it (e.g. to
624
+ * show the user what they scanned before they confirm). The token is then
625
+ * still redeemable, so a consuming call must follow before it is acted on.
415
626
  *
416
627
  * @param {ConnectionToken} token
628
+ * @param {object} [opts]
629
+ * @param {boolean} [opts.consume=true] - Record the nonce on success
417
630
  * @returns {{ valid: boolean, error?: string }}
418
631
  */
419
- validateToken(token) {
632
+ validateToken(token, { consume = true } = {}) {
420
633
  if (!token || typeof token !== 'object') {
421
634
  return { valid: false, error: 'Token is not an object' }
422
635
  }
@@ -435,7 +648,8 @@ export class DirectInputHandshake {
435
648
  if (typeof token.timestamp !== 'number') {
436
649
  return { valid: false, error: 'Token missing timestamp' }
437
650
  }
438
- const age = Date.now() - token.timestamp
651
+ const now = Date.now()
652
+ const age = now - token.timestamp
439
653
  if (age > TOKEN_TTL_MS) {
440
654
  return { valid: false, error: 'Token expired' }
441
655
  }
@@ -443,6 +657,19 @@ export class DirectInputHandshake {
443
657
  if (age < -30_000) {
444
658
  return { valid: false, error: 'Token timestamp is in the future' }
445
659
  }
660
+
661
+ // Single use. Age out entries first so the set stays bounded by the TTL.
662
+ this.#pruneConsumedNonces(now)
663
+ const key = this.#nonceKey(token)
664
+ if (this.#consumedNonces.has(key)) {
665
+ this.#onLog(1, `Rejected replayed connection token from pod ${token.podId}`)
666
+ return { valid: false, error: 'Token already used' }
667
+ }
668
+ if (consume) {
669
+ // Remember it for as long as it could still be presented.
670
+ this.#consumedNonces.set(key, token.timestamp + TOKEN_TTL_MS)
671
+ }
672
+
446
673
  return { valid: true }
447
674
  }
448
675
 
@@ -629,9 +856,18 @@ export class HandshakeCoordinator {
629
856
  * Parses the token, optionally creates a signaling client from the
630
857
  * token's signalingUrl, and negotiates a transport.
631
858
  *
859
+ * Note on lifetimes: `TransportFactory.negotiate()` returns a transport that
860
+ * has been *created but not yet connected* — no offer, answer or ICE
861
+ * candidate has crossed the wire when it resolves. A signaler this method
862
+ * created is therefore kept open past negotiate() and torn down on the
863
+ * transport's `close` event instead. When the transport exposes no
864
+ * `onClose()`, ownership passes to the caller via the returned `signaler`.
865
+ *
632
866
  * @param {ConnectionToken} token - Decoded connection token
633
867
  * @param {object} [transportFactory] - Override transport factory
634
- * @returns {Promise<{ transport: object, sessionInfo: object }>}
868
+ * @returns {Promise<{ transport: object, sessionInfo: object, signaler: SignalingClient|null }>}
869
+ * `signaler` is the client this call created and still owns, or null when
870
+ * the coordinator's own signaling client was used.
635
871
  */
636
872
  async connectViaToken(token, transportFactory) {
637
873
  const factory = transportFactory || this.#transportFactory
@@ -682,12 +918,23 @@ export class HandshakeCoordinator {
682
918
  }
683
919
 
684
920
  this.#onLog(2, `Connected via token to ${remotePodId}`)
685
- // Clean up signaler we created — transport is now established
921
+
922
+ // Do NOT disconnect here. negotiate() returns a created-but-unconnected
923
+ // transport; the signaling channel is about to carry the offer, the
924
+ // answer and every ICE candidate. Tear it down when the transport does.
686
925
  if (createdSignaler && signaler) {
687
- signaler.disconnect()
926
+ if (typeof transport.onClose === 'function') {
927
+ transport.onClose(() => signaler.disconnect())
928
+ } else {
929
+ this.#onLog(
930
+ 1,
931
+ 'Transport exposes no onClose(); returning the signaling client for the caller to disconnect',
932
+ )
933
+ }
688
934
  }
935
+
689
936
  this.#fire('connected', { remotePodId, transport, sessionInfo })
690
- return { transport, sessionInfo }
937
+ return { transport, sessionInfo, signaler: createdSignaler ? signaler : null }
691
938
  } catch (err) {
692
939
  // Clean up signaler we created on failure
693
940
  if (createdSignaler && signaler) {
@@ -173,10 +173,14 @@ export class IdentityExportTool extends BrowserTool {
173
173
  }
174
174
 
175
175
  const jwk = await mgr.identityManager.export(podId, passphrase);
176
- const encrypted = jwk.encrypted ? ' (encrypted)' : '';
176
+ // Label both outcomes. An unlabelled blob that happens to be a raw
177
+ // private key is the one thing this output must never be.
178
+ const label = jwk.encrypted
179
+ ? ' (encrypted)'
180
+ : ' (UNENCRYPTED — this is the raw private key)';
177
181
  return {
178
182
  success: true,
179
- output: `Identity exported${encrypted}:\n${JSON.stringify(jwk, null, 2)}`,
183
+ output: `Identity exported${label}:\n${JSON.stringify(jwk, null, 2)}`,
180
184
  };
181
185
  } catch (err) {
182
186
  return { success: false, output: '', error: `Export failed: ${err.message}` };
@@ -189,28 +193,38 @@ export class IdentityExportTool extends BrowserTool {
189
193
  export class IdentityImportTool extends BrowserTool {
190
194
  get name() { return 'identity_import'; }
191
195
  get description() {
192
- return 'Import an identity from a JWK private key.';
196
+ return 'Import an identity from a JWK private key, or from an encrypted export.';
193
197
  }
194
198
  get parameters() {
195
199
  return {
196
200
  type: 'object',
197
201
  properties: {
198
- keyData: { type: 'object', description: 'JWK private key object' },
202
+ keyData: {
203
+ type: 'object',
204
+ description: 'JWK private key object, or an encrypted export envelope',
205
+ },
199
206
  label: { type: 'string', description: 'Human-readable label' },
207
+ // identity_export takes a passphrase; without the matching parameter
208
+ // here, everything that tool encrypts is unimportable through the
209
+ // tool interface.
210
+ passphrase: {
211
+ type: 'string',
212
+ description: 'Passphrase, required when keyData is an encrypted export',
213
+ },
200
214
  },
201
215
  required: ['keyData'],
202
216
  };
203
217
  }
204
218
  get permission() { return 'approve'; }
205
219
 
206
- async execute({ keyData, label }) {
220
+ async execute({ keyData, label, passphrase }) {
207
221
  try {
208
222
  const mgr = identityToolsContext.getAutoIdMgr();
209
223
  if (!mgr) {
210
224
  return { success: false, output: '', error: 'Identity manager not initialized.' };
211
225
  }
212
226
 
213
- const summary = await mgr.identityManager.import(keyData, label || 'imported');
227
+ const summary = await mgr.identityManager.import(keyData, label || 'imported', { passphrase });
214
228
  await mgr.identityManager.save();
215
229
  return {
216
230
  success: true,
@@ -114,8 +114,12 @@ export class IdentityWallet {
114
114
  /**
115
115
  * Export an identity as JWK, optionally encrypted with a passphrase.
116
116
  *
117
+ * With a passphrase this resolves to an encrypted envelope or it rejects —
118
+ * it never falls back to the raw private key. Without one it resolves to
119
+ * the raw private-key JWK by design.
120
+ *
117
121
  * @param {string} podId
118
- * @param {string} [passphrase]
122
+ * @param {string} [passphrase] - Must be a non-empty string when given
119
123
  * @returns {Promise<object>}
120
124
  */
121
125
  async exportIdentity(podId, passphrase) {