@johnhenry/browsermesh-core 0.7.1 → 0.9.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,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-core",
3
- "version": "0.7.1",
3
+ "version": "0.9.0",
4
4
  "description": "Identity, crypto, peer management, and trust primitives for BrowserMesh",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -19,6 +19,9 @@
19
19
  "url": "https://github.com/johnhenry/browsermesh",
20
20
  "directory": "packages/browsermesh-core"
21
21
  },
22
+ "dependencies": {
23
+ "@johnhenry/keyvault": "^0.1.0"
24
+ },
22
25
  "peerDependencies": {
23
26
  "@johnhenry/browsermesh-primitives": ">=0.3.0 <1.0.0",
24
27
  "@johnhenry/browsermesh-apps": ">=0.4.0 <1.0.0"
package/src/handshake.mjs CHANGED
@@ -778,14 +778,27 @@ export class HandshakeCoordinator {
778
778
  */
779
779
  #glareWaiters = new Map()
780
780
 
781
+ /** @type {object[]|null} Default ICE servers for every WebRTC transport */
782
+ #iceServers
783
+
784
+ /** @type {'all'|'relay'|undefined} Default iceTransportPolicy */
785
+ #iceTransportPolicy
786
+
781
787
  /**
782
788
  * @param {object} opts
783
789
  * @param {string} opts.localPodId - Local pod identifier
784
790
  * @param {SignalingClient} [opts.signalingClient] - Signaling client instance
785
791
  * @param {object} [opts.transportFactory] - TransportFactory instance
786
792
  * @param {Function} [opts.onLog] - Logging callback (level, msg)
793
+ * @param {object[]} [opts.iceServers] - Default STUN/TURN servers for every
794
+ * WebRTC transport this coordinator creates (offer side, answer side and
795
+ * connectViaToken). A per-call `iceServers` overrides it.
796
+ * @param {'all'|'relay'} [opts.iceTransportPolicy] - Default
797
+ * `iceTransportPolicy` for those transports ('relay' = TURN-only, which
798
+ * needs a `turn:`/`turns:` entry in `iceServers`). A per-call value
799
+ * overrides it.
787
800
  */
788
- constructor({ localPodId, signalingClient, transportFactory, onLog } = {}) {
801
+ constructor({ localPodId, signalingClient, transportFactory, onLog, iceServers, iceTransportPolicy } = {}) {
789
802
  if (!localPodId || typeof localPodId !== 'string') {
790
803
  throw new Error('localPodId is required and must be a non-empty string')
791
804
  }
@@ -793,6 +806,8 @@ export class HandshakeCoordinator {
793
806
  this.#signalingClient = signalingClient || null
794
807
  this.#transportFactory = transportFactory || null
795
808
  this.#onLog = onLog || (() => {})
809
+ this.#iceServers = iceServers || null
810
+ this.#iceTransportPolicy = iceTransportPolicy
796
811
 
797
812
  // Wire incoming offer events from signaling client
798
813
  if (this.#signalingClient) {
@@ -802,6 +817,27 @@ export class HandshakeCoordinator {
802
817
  }
803
818
  }
804
819
 
820
+ /**
821
+ * Resolve the WebRTC transport options carrying ICE configuration.
822
+ * Precedence: per-call value > `fallbackIceServers` (e.g. a token's) >
823
+ * coordinator default. Keys are only present when a value exists, so a
824
+ * coordinator with no ICE config leaves the transport's own defaults
825
+ * (STUN list, 'all' policy) untouched. `config.iceServers` is kept for
826
+ * factories/proxies that read the legacy shape.
827
+ *
828
+ * @param {{ iceServers?: object[], iceTransportPolicy?: string }} [perCall]
829
+ * @param {object[]} [fallbackIceServers]
830
+ * @returns {object}
831
+ */
832
+ #iceOpts(perCall = {}, fallbackIceServers) {
833
+ const iceServers = perCall.iceServers ?? fallbackIceServers ?? this.#iceServers
834
+ const iceTransportPolicy = perCall.iceTransportPolicy ?? this.#iceTransportPolicy
835
+ const out = { config: { iceServers: iceServers || [] } }
836
+ if (iceServers) out.iceServers = iceServers
837
+ if (iceTransportPolicy) out.iceTransportPolicy = iceTransportPolicy
838
+ return out
839
+ }
840
+
805
841
  /**
806
842
  * Initiate a connection to a remote peer via the signaling server.
807
843
  *
@@ -811,7 +847,8 @@ export class HandshakeCoordinator {
811
847
  * @param {string} remotePodId - Target peer identifier
812
848
  * @param {object} [opts]
813
849
  * @param {object} [opts.endpoints] - Map of transport type -> constructor opts
814
- * @param {object[]} [opts.iceServers] - ICE server configs
850
+ * @param {object[]} [opts.iceServers] - ICE server configs (overrides the constructor default)
851
+ * @param {'all'|'relay'} [opts.iceTransportPolicy] - Overrides the constructor default
815
852
  * @param {number} [opts.timeout] - Connection timeout in ms
816
853
  * @returns {Promise<{ transport: object, sessionInfo: object }>}
817
854
  */
@@ -849,9 +886,7 @@ export class HandshakeCoordinator {
849
886
 
850
887
  this.#onLog(2, `Initiating connection to ${remotePodId}`)
851
888
 
852
- const endpointOpts = opts.endpoints || {
853
- webrtc: { config: { iceServers: opts.iceServers || [] } },
854
- }
889
+ const endpointOpts = opts.endpoints || { webrtc: this.#iceOpts(opts) }
855
890
 
856
891
  const promise = (async () => {
857
892
  let timeoutHandle
@@ -904,9 +939,12 @@ export class HandshakeCoordinator {
904
939
  *
905
940
  * @param {string} remotePodId - Initiating peer identifier
906
941
  * @param {object} offer - SDP offer
942
+ * @param {object} [opts]
943
+ * @param {object[]} [opts.iceServers] - Overrides the constructor default
944
+ * @param {'all'|'relay'} [opts.iceTransportPolicy] - Overrides the constructor default
907
945
  * @returns {Promise<{ transport: object, sessionInfo: object }>}
908
946
  */
909
- async acceptConnection(remotePodId, offer) {
947
+ async acceptConnection(remotePodId, offer, opts = {}) {
910
948
  if (!this.#transportFactory) {
911
949
  throw new Error('TransportFactory is required for acceptConnection')
912
950
  }
@@ -940,6 +978,7 @@ export class HandshakeCoordinator {
940
978
  localPodId: this.#localPodId,
941
979
  remotePodId,
942
980
  signaler: this.#signalingClient,
981
+ ...this.#iceOpts(opts),
943
982
  })
944
983
 
945
984
  if (typeof transport.handleOffer === 'function') {
@@ -979,11 +1018,14 @@ export class HandshakeCoordinator {
979
1018
  *
980
1019
  * @param {ConnectionToken} token - Decoded connection token
981
1020
  * @param {object} [transportFactory] - Override transport factory
1021
+ * @param {object} [opts]
1022
+ * @param {object[]} [opts.iceServers] - Overrides token.iceServers and the constructor default
1023
+ * @param {'all'|'relay'} [opts.iceTransportPolicy] - Overrides the constructor default
982
1024
  * @returns {Promise<{ transport: object, sessionInfo: object, signaler: SignalingClient|null }>}
983
1025
  * `signaler` is the client this call created and still owns, or null when
984
1026
  * the coordinator's own signaling client was used.
985
1027
  */
986
- async connectViaToken(token, transportFactory) {
1028
+ async connectViaToken(token, transportFactory, opts = {}) {
987
1029
  const factory = transportFactory || this.#transportFactory
988
1030
  if (!factory) {
989
1031
  throw new Error('TransportFactory is required for connectViaToken')
@@ -1010,9 +1052,8 @@ export class HandshakeCoordinator {
1010
1052
  throw new Error('No signaling channel available (provide signalingClient or token.signalingUrl)')
1011
1053
  }
1012
1054
 
1013
- const iceServers = token.iceServers || []
1014
1055
  const endpointOpts = {
1015
- webrtc: { config: { iceServers } },
1056
+ webrtc: this.#iceOpts(opts, token.iceServers),
1016
1057
  }
1017
1058
 
1018
1059
  try {
package/src/identity.mjs CHANGED
@@ -13,6 +13,7 @@
13
13
  */
14
14
 
15
15
  import { silentCatch } from './silent-catch.mjs'
16
+ import { seal, open as openRecord, needsUpgrade, VaultError } from '@johnhenry/keyvault';
16
17
  import {
17
18
  PodIdentity,
18
19
  derivePodId,
@@ -24,13 +25,18 @@ import {
24
25
  export { PodIdentity, derivePodId, encodeBase64url, decodeBase64url };
25
26
 
26
27
  // ---------------------------------------------------------------------------
27
- // PBKDF2 / AES-GCM constants (shared with VaultIdentityStorage)
28
+ // Passphrase encryption (via @johnhenry/keyvault)
28
29
  // ---------------------------------------------------------------------------
29
30
 
30
- const VAULT_PBKDF2_ITERATIONS = 310_000;
31
- const VAULT_SALT_BYTES = 16;
32
- const VAULT_IV_BYTES = 12;
33
- const VAULT_KDF = 'PBKDF2-SHA256';
31
+ /** Record type of an encrypted private key stored by VaultIdentityStorage. */
32
+ const VAULT_TYPE = 'browsermesh-vault';
33
+ /** Record type of an encrypted identity export (`export(podId, passphrase)`). */
34
+ const EXPORT_TYPE = 'browsermesh-identity-export';
35
+ /**
36
+ * The only KDF name the pre-keyvault envelope (`kdf` was a string) could carry.
37
+ * Kept to refuse any other string with the message callers have always seen.
38
+ */
39
+ const LEGACY_VAULT_KDF = 'PBKDF2-SHA256';
34
40
 
35
41
  /**
36
42
  * Reject a passphrase that would not actually protect anything.
@@ -57,94 +63,56 @@ function requirePassphrase(passphrase, source) {
57
63
  }
58
64
 
59
65
  /**
60
- * PBKDF2(SHA-256) → AES-256-GCM over a UTF-8 string.
61
- *
62
- * The KDF name and iteration count travel with the ciphertext so a future
63
- * change of parameters does not orphan envelopes written under the old ones.
66
+ * Encrypt a UTF-8 string under a passphrase with keyvault (PBKDF2-SHA256 at
67
+ * keyvault's current default, AES-256-GCM, KDF parameters and `header`
68
+ * authenticated and stored in the record).
64
69
  *
65
70
  * @param {string} plaintext
66
71
  * @param {string} passphrase
67
- * @returns {Promise<{ kdf: string, iterations: number, salt: string, iv: string, ciphertext: string }>}
72
+ * @param {string} type - Record type
73
+ * @param {object} [header] - Extra readable, authenticated fields
74
+ * @returns {Promise<object>} A keyvault record (plain JSON object)
68
75
  */
69
- async function encryptWithPassphrase(plaintext, passphrase) {
70
- const enc = new TextEncoder();
71
- const salt = crypto.getRandomValues(new Uint8Array(VAULT_SALT_BYTES));
72
- const iv = crypto.getRandomValues(new Uint8Array(VAULT_IV_BYTES));
73
-
74
- const baseKey = await crypto.subtle.importKey(
75
- 'raw',
76
- enc.encode(passphrase),
77
- 'PBKDF2',
78
- false,
79
- ['deriveKey']
80
- );
81
-
82
- const aesKey = await crypto.subtle.deriveKey(
83
- { name: 'PBKDF2', salt, iterations: VAULT_PBKDF2_ITERATIONS, hash: 'SHA-256' },
84
- baseKey,
85
- { name: 'AES-GCM', length: 256 },
86
- false,
87
- ['encrypt']
88
- );
89
-
90
- const ciphertext = new Uint8Array(
91
- await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, aesKey, enc.encode(plaintext))
92
- );
93
-
94
- return {
95
- kdf: VAULT_KDF,
96
- iterations: VAULT_PBKDF2_ITERATIONS,
97
- salt: encodeBase64url(salt),
98
- iv: encodeBase64url(iv),
99
- ciphertext: encodeBase64url(ciphertext),
100
- };
76
+ async function encryptWithPassphrase(plaintext, passphrase, type, header) {
77
+ return JSON.parse(await seal(plaintext, passphrase, { type, header }));
101
78
  }
102
79
 
103
80
  /**
104
- * Inverse of {@link encryptWithPassphrase}.
81
+ * Inverse of {@link encryptWithPassphrase}. Also opens envelopes written by
82
+ * browsermesh-core <= 0.8.0 (`{ kdf?, iterations?, salt, iv, ciphertext }`,
83
+ * 310k iterations when `iterations` is absent, passphrase used as typed).
105
84
  *
106
- * `iterations` is read from the envelope so blobs written before the count
107
- * was recorded (and before it was raised to match the documented 310k) still
108
- * open.
85
+ * Errors keep the shapes this API has always had: a wrong passphrase (or a
86
+ * modified record) rejects with a DOMException named `OperationError`, an
87
+ * unknown string `kdf` with `Unsupported key derivation function: <kdf>`.
88
+ * Anything else keyvault reports is rethrown as its `VaultError`.
109
89
  *
110
- * @param {{ kdf?: string, iterations?: number, salt: string, iv: string, ciphertext: string }} envelope
90
+ * @param {object} envelope
111
91
  * @param {string} passphrase
112
- * @returns {Promise<string>}
92
+ * @param {string[]} types - Accepted record types
93
+ * @returns {Promise<{ plaintext: string, upgrade: boolean }>}
113
94
  */
114
- async function decryptWithPassphrase(envelope, passphrase) {
115
- const { kdf, iterations, salt, iv, ciphertext } = envelope;
116
- if (kdf !== undefined && kdf !== VAULT_KDF) {
117
- throw new Error(`Unsupported key derivation function: ${kdf}`);
118
- }
119
-
120
- const baseKey = await crypto.subtle.importKey(
121
- 'raw',
122
- new TextEncoder().encode(passphrase),
123
- 'PBKDF2',
124
- false,
125
- ['deriveKey']
126
- );
127
-
128
- const aesKey = await crypto.subtle.deriveKey(
129
- {
130
- name: 'PBKDF2',
131
- salt: decodeBase64url(salt),
132
- iterations: iterations ?? VAULT_PBKDF2_ITERATIONS,
133
- hash: 'SHA-256',
134
- },
135
- baseKey,
136
- { name: 'AES-GCM', length: 256 },
137
- false,
138
- ['decrypt']
139
- );
140
-
141
- const plaintext = await crypto.subtle.decrypt(
142
- { name: 'AES-GCM', iv: decodeBase64url(iv) },
143
- aesKey,
144
- decodeBase64url(ciphertext)
145
- );
146
-
147
- return new TextDecoder().decode(plaintext);
95
+ async function decryptWithPassphrase(envelope, passphrase, types) {
96
+ if (typeof envelope?.kdf === 'string' && envelope.kdf !== LEGACY_VAULT_KDF) {
97
+ throw new Error(`Unsupported key derivation function: ${envelope.kdf}`);
98
+ }
99
+ try {
100
+ const r = await openRecord(envelope, passphrase);
101
+ if (!types.includes(r.type)) {
102
+ throw new VaultError('wrong_type', `unexpected record type ${JSON.stringify(String(r.type).slice(0, 60))}`);
103
+ }
104
+ return {
105
+ plaintext: new TextDecoder().decode(r.payload),
106
+ upgrade: needsUpgrade(envelope),
107
+ };
108
+ } catch (err) {
109
+ if (err instanceof VaultError && err.code === 'bad_passphrase') {
110
+ const e = new DOMException('The operation failed for an operation-specific reason', 'OperationError');
111
+ e.cause = err;
112
+ throw e;
113
+ }
114
+ throw err;
115
+ }
148
116
  }
149
117
 
150
118
  // ---------------------------------------------------------------------------
@@ -375,7 +343,7 @@ export class MeshIdentityManager {
375
343
  );
376
344
  let plaintext;
377
345
  try {
378
- plaintext = await decryptWithPassphrase(keyData, passphrase);
346
+ ({ plaintext } = await decryptWithPassphrase(keyData, passphrase, [VAULT_TYPE, EXPORT_TYPE]));
379
347
  } catch (err) {
380
348
  throw unreadable(err);
381
349
  }
@@ -456,8 +424,11 @@ export class MeshIdentityManager {
456
424
  * is the documented plaintext-export path, and the caller is responsible
457
425
  * for what happens to it next.
458
426
  *
459
- * Called with a passphrase, it returns an encrypted envelope
460
- * (`{ encrypted: true, kdf, iterations, salt, iv, ciphertext }`) or it
427
+ * Called with a passphrase, it returns an encrypted envelope, a
428
+ * `@johnhenry/keyvault` record
429
+ * (`{ v, t, encrypted: true, kdf: { name, iterations, salt }, iv, ct }`;
430
+ * browsermesh-core <= 0.8.0 wrote `{ encrypted: true, kdf, iterations,
431
+ * salt, iv, ciphertext }`, which `import()` still reads) or it
461
432
  * throws. It never quietly hands back the plaintext key instead: a caller
462
433
  * who asked for encryption and got an unlabelled JWK would have no way to
463
434
  * tell, and would go on to write, paste or QR-encode a private key it
@@ -488,7 +459,7 @@ export class MeshIdentityManager {
488
459
 
489
460
  let envelope;
490
461
  try {
491
- envelope = await encryptWithPassphrase(JSON.stringify(jwk), passphrase);
462
+ envelope = await encryptWithPassphrase(JSON.stringify(jwk), passphrase, EXPORT_TYPE, { encrypted: true });
492
463
  } catch (err) {
493
464
  // Deliberately not falling back to the plaintext JWK. Encryption was
494
465
  // asked for; if it cannot be done, the caller has to know.
@@ -499,7 +470,7 @@ export class MeshIdentityManager {
499
470
  );
500
471
  }
501
472
 
502
- return { encrypted: true, ...envelope };
473
+ return envelope;
503
474
  }
504
475
 
505
476
  // -- Lookup & Enumeration -----------------------------------------------
@@ -943,7 +914,9 @@ export class IndexedDBIdentityStorage {
943
914
  /**
944
915
  * Wraps another identity storage with passphrase-based encryption.
945
916
  * Only the privateKey field is encrypted; publicKey + metadata stored cleartext.
946
- * Uses PBKDF2(310k, SHA-256) → AES-256-GCM.
917
+ * Uses @johnhenry/keyvault (PBKDF2-SHA256 → AES-256-GCM). Records written by
918
+ * browsermesh-core <= 0.8.0 (310k iterations) still open and are re-encrypted
919
+ * with keyvault's current defaults on the first successful load.
947
920
  *
948
921
  * `getPassphrase` must resolve to a non-empty string. An empty string or a
949
922
  * missing value is refused rather than used: PBKDF2 accepts an empty key and
@@ -987,7 +960,8 @@ export class VaultIdentityStorage {
987
960
  const passphrase = requirePassphrase(await this.#getPassphrase(), 'getPassphrase');
988
961
  record.encryptedPrivateKey = await encryptWithPassphrase(
989
962
  JSON.stringify(record.privateKeyJwk),
990
- passphrase
963
+ passphrase,
964
+ VAULT_TYPE
991
965
  );
992
966
  record.privateKeyJwk = null;
993
967
  }
@@ -1009,10 +983,26 @@ export class VaultIdentityStorage {
1009
983
 
1010
984
  if (record.encryptedPrivateKey) {
1011
985
  const passphrase = requirePassphrase(await this.#getPassphrase(), 'getPassphrase');
1012
- record.privateKeyJwk = JSON.parse(
1013
- await decryptWithPassphrase(record.encryptedPrivateKey, passphrase)
1014
- );
986
+ const stored = record.encryptedPrivateKey;
987
+ const { plaintext, upgrade } = await decryptWithPassphrase(stored, passphrase, [VAULT_TYPE]);
988
+ record.privateKeyJwk = JSON.parse(plaintext);
1015
989
  delete record.encryptedPrivateKey;
990
+
991
+ // Re-encrypt records written under older parameters (310k iterations,
992
+ // no kdf recorded, the pre-keyvault envelope) with the current defaults.
993
+ // Best effort: the unlock has succeeded either way, and the old record
994
+ // stays valid if the write-back fails.
995
+ if (upgrade) {
996
+ try {
997
+ await this.#inner.save(podId, {
998
+ ...record,
999
+ privateKeyJwk: null,
1000
+ encryptedPrivateKey: await encryptWithPassphrase(plaintext, passphrase, VAULT_TYPE),
1001
+ });
1002
+ } catch (err) {
1003
+ silentCatch('clawser-mesh-identity', 'vault-upgrade', err);
1004
+ }
1005
+ }
1016
1006
  }
1017
1007
 
1018
1008
  return record;