@johnhenry/browsermesh-core 0.0.0 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-core",
3
- "version": "0.0.0",
3
+ "version": "0.1.0",
4
4
  "description": "Identity, crypto, peer management, and trust primitives for BrowserMesh",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -33,6 +33,71 @@ export const CAP_DELEGATE = 0xDE;
33
33
  /** Wire type for WASM sandbox control message. */
34
34
  export const WASM_SANDBOX_CTRL = 0xDF;
35
35
 
36
+ // ---------------------------------------------------------------------------
37
+ // Attenuation invariants
38
+ // ---------------------------------------------------------------------------
39
+
40
+ /** Characters that end one segment of a resource identifier. */
41
+ const RESOURCE_SEPARATORS = new Set(['/', ':']);
42
+
43
+ /**
44
+ * Whether `childResource` falls entirely inside `parentResource`.
45
+ *
46
+ * Three ways a child can be covered:
47
+ * - it is the same resource;
48
+ * - the parent ends in `*` and the child extends what comes before it;
49
+ * - it extends the parent by whole segments — `fs:/data` covers
50
+ * `fs:/data/reports`, because the extension begins at a separator.
51
+ *
52
+ * That last clause is where a bare `startsWith` goes wrong. `fs:/data`
53
+ * "starts with"-covers `fs:/database`, and `svc://a` covers
54
+ * `svc://anything-at-all`: both are unrelated resources that merely share
55
+ * a character prefix. Requiring the extension to start at a separator (or
56
+ * the parent to end at one) keeps the sub-path case and drops those.
57
+ *
58
+ * A literal parent with no wildcard also used to fall through to
59
+ * `parentResource.slice(0, -1)`, chopping a real character off the scope
60
+ * and accepting anything sharing the truncated prefix. Both branches of
61
+ * that `if/else` were byte-identical; only the wildcard one was ever meant
62
+ * to exist.
63
+ *
64
+ * Shared by {@link CapabilityToken#attenuate} and
65
+ * {@link CapabilityChain#verify} so the two cannot drift apart: a chain
66
+ * arriving over the wire has to satisfy the same rule attenuate() enforces
67
+ * locally.
68
+ *
69
+ * @param {string} parentResource
70
+ * @param {string} childResource
71
+ * @returns {boolean}
72
+ */
73
+ export function resourceCovers(parentResource, childResource) {
74
+ if (childResource === parentResource) return true;
75
+
76
+ if (parentResource.endsWith('*')) {
77
+ return childResource.startsWith(parentResource.slice(0, -1));
78
+ }
79
+
80
+ if (!childResource.startsWith(parentResource)) return false;
81
+ if (RESOURCE_SEPARATORS.has(parentResource.at(-1))) return true;
82
+ return RESOURCE_SEPARATORS.has(childResource[parentResource.length]);
83
+ }
84
+
85
+ /**
86
+ * Whether `childExpiry` is no later than `parentExpiry`.
87
+ *
88
+ * `null` means "no expiry". A parent without one permits any child expiry;
89
+ * a parent with one requires the child to have an expiry that is not later.
90
+ *
91
+ * @param {number|null} parentExpiry
92
+ * @param {number|null} childExpiry
93
+ * @returns {boolean}
94
+ */
95
+ export function expiryNarrows(parentExpiry, childExpiry) {
96
+ if (parentExpiry === null || parentExpiry === undefined) return true;
97
+ if (childExpiry === null || childExpiry === undefined) return false;
98
+ return childExpiry <= parentExpiry;
99
+ }
100
+
36
101
  // ---------------------------------------------------------------------------
37
102
  // CapabilityToken
38
103
  // ---------------------------------------------------------------------------
@@ -152,19 +217,8 @@ export class CapabilityToken {
152
217
 
153
218
  // Resource must be same or narrower (prefix match)
154
219
  const childResource = resource || this.resource;
155
- if (childResource !== this.resource && !childResource.startsWith(this.resource)) {
156
- if (!this.resource.endsWith('*')) {
157
- // Check if parent has wildcard
158
- const parentBase = this.resource.slice(0, -1);
159
- if (!childResource.startsWith(parentBase)) {
160
- throw new Error('Cannot widen resource scope beyond parent');
161
- }
162
- } else {
163
- const parentBase = this.resource.slice(0, -1);
164
- if (!childResource.startsWith(parentBase)) {
165
- throw new Error('Cannot widen resource scope beyond parent');
166
- }
167
- }
220
+ if (!resourceCovers(this.resource, childResource)) {
221
+ throw new Error('Cannot widen resource scope beyond parent');
168
222
  }
169
223
 
170
224
  // Expiry must be ≤ parent expiry
@@ -179,8 +233,20 @@ export class CapabilityToken {
179
233
  throw new Error('Cannot extend max depth beyond parent');
180
234
  }
181
235
 
182
- // Merge constraints (child can only add, not remove)
236
+ // Merge constraints (child can only add, not remove).
237
+ //
238
+ // The spread lets a child overwrite a value it inherited, which is fine
239
+ // for constraints nothing enforces but not for maxCalls: that is the one
240
+ // CapabilityValidator.validate() actually checks, so raising it in a
241
+ // child is an amplification dressed up as a merge.
183
242
  const mergedConstraints = { ...this.constraints, ...constraints };
243
+ if (
244
+ this.constraints.maxCalls !== undefined &&
245
+ (mergedConstraints.maxCalls === undefined ||
246
+ mergedConstraints.maxCalls > this.constraints.maxCalls)
247
+ ) {
248
+ throw new Error('Cannot raise maxCalls beyond parent');
249
+ }
184
250
 
185
251
  return new CapabilityToken({
186
252
  issuer: this.holder,
@@ -277,8 +343,16 @@ export class CapabilityChain {
277
343
  * Verify chain integrity:
278
344
  * 1. Each token's parentId matches the previous token's id
279
345
  * 2. Permissions only narrow (never widen)
280
- * 3. Depth increments correctly
281
- * 4. No expired or revoked tokens (if checkValidity)
346
+ * 3. The resource scope only narrows (never widens)
347
+ * 4. The expiry only narrows (never extends)
348
+ * 5. Depth increments correctly
349
+ * 6. No expired or revoked tokens (if checkValidity)
350
+ *
351
+ * 3 and 4 are the reason this method cannot just trust `attenuate()`:
352
+ * a chain reaching this code came from {@link CapabilityChain.fromJSON}
353
+ * or from `append()`, neither of which builds its tokens by attenuation.
354
+ * Without these checks a chain could widen `fs:///docs/public/` to `*`
355
+ * and a one-second expiry to ten years and still verify.
282
356
  *
283
357
  * @param {boolean} [checkValidity=true]
284
358
  * @returns {{ valid: boolean, error?: string, brokenAt?: number }}
@@ -317,6 +391,24 @@ export class CapabilityChain {
317
391
  return { valid: false, error: `Permission amplification at index ${i}: "${perm}"`, brokenAt: i };
318
392
  }
319
393
  }
394
+
395
+ // Resource scope must be covered by the parent's
396
+ if (!resourceCovers(prev.resource, token.resource)) {
397
+ return {
398
+ valid: false,
399
+ error: `Resource amplification at index ${i}: "${token.resource}" is not within "${prev.resource}"`,
400
+ brokenAt: i,
401
+ };
402
+ }
403
+
404
+ // Expiry must not reach past the parent's
405
+ if (!expiryNarrows(prev.expiresAt, token.expiresAt)) {
406
+ return {
407
+ valid: false,
408
+ error: `Expiry amplification at index ${i}: ${token.expiresAt} is later than parent ${prev.expiresAt}`,
409
+ brokenAt: i,
410
+ };
411
+ }
320
412
  }
321
413
  }
322
414
 
@@ -561,6 +653,11 @@ export class WasmSandboxPolicy {
561
653
  // WasmSandbox
562
654
  // ---------------------------------------------------------------------------
563
655
 
656
+ /** Monotonic clock where available; Date.now() is a fine fallback here. */
657
+ function _now() {
658
+ return globalThis.performance?.now?.() ?? Date.now();
659
+ }
660
+
564
661
  /** @type {readonly string[]} */
565
662
  const SANDBOX_STATES = Object.freeze([
566
663
  'idle',
@@ -573,7 +670,15 @@ const SANDBOX_STATES = Object.freeze([
573
670
  ]);
574
671
 
575
672
  /**
576
- * Manages a single WASM module instance within policy constraints.
673
+ * Tracks one WASM module's resource usage against a policy budget.
674
+ *
675
+ * NOT an isolation boundary. This class does no instantiation and cannot
676
+ * preempt running code -- a JS caller cannot interrupt a WASM call by CPU time
677
+ * without running it in a worker and terminating that. What it does is
678
+ * account: it holds the policy, records memory and CPU against it, refuses
679
+ * allocations and executions that would exceed it, and drives the state
680
+ * machine. Actually running the module is the caller's job, supplied as the
681
+ * `invoke` argument to load(); everything here measures that.
577
682
  */
578
683
  export class WasmSandbox {
579
684
  /** @type {string} */
@@ -590,6 +695,8 @@ export class WasmSandbox {
590
695
  #stateListeners = [];
591
696
  /** @type {string|null} */
592
697
  #moduleHash = null;
698
+ /** @type {Function|null} caller-supplied executor for the loaded module */
699
+ #invoke = null;
593
700
  /** @type {number} */
594
701
  #createdAt;
595
702
  /** @type {string[]} */
@@ -624,24 +731,42 @@ export class WasmSandbox {
624
731
  get logs() { return [...this.#logs]; }
625
732
 
626
733
  /**
627
- * Load a WASM module (simulated — stores hash).
734
+ * Load a WASM module.
735
+ *
736
+ * The hash is recorded for identification. Pass `invoke` to make execute()
737
+ * actually run something: without it the sandbox has no module to call and
738
+ * execute() reports `executed: false` rather than inventing an outcome.
739
+ *
628
740
  * @param {string} moduleHash
741
+ * @param {Function} [invoke] - async (functionName, args) => result, or
742
+ * `{ result, cpuMs }` when the caller can measure CPU properly (a worker
743
+ * can; wall-clock here cannot distinguish CPU from waiting).
629
744
  */
630
- async load(moduleHash) {
745
+ async load(moduleHash, invoke) {
631
746
  if (this.#state !== 'idle') {
632
747
  throw new Error(`Cannot load in state "${this.#state}"`);
633
748
  }
749
+ if (invoke !== undefined && typeof invoke !== 'function') {
750
+ throw new Error('invoke must be a function');
751
+ }
634
752
  this._setState('loading');
635
753
  this.#moduleHash = moduleHash;
636
- this._log(`Module loaded: ${moduleHash}`);
754
+ this.#invoke = invoke || null;
755
+ this._log(`Module loaded: ${moduleHash}${invoke ? '' : ' (no invoke: execute() will run nothing)'}`);
637
756
  this._setState('ready');
638
757
  }
639
758
 
640
759
  /**
641
- * Execute within the sandbox.
760
+ * Execute within the sandbox, charging what it costs against the policy.
761
+ *
762
+ * `cpuMs` is measured, never invented. It is whatever the executor reports,
763
+ * or elapsed wall-clock around the call -- which is an upper bound on CPU,
764
+ * not CPU itself. With no executor loaded, nothing runs, nothing is charged,
765
+ * and `executed` is false.
766
+ *
642
767
  * @param {string} functionName
643
768
  * @param {*[]} [args]
644
- * @returns {Promise<{ result: *, cpuMs: number }>}
769
+ * @returns {Promise<{ result: *, cpuMs: number, executed: boolean }>}
645
770
  */
646
771
  async execute(functionName, args = []) {
647
772
  if (this.#state !== 'ready' && this.#state !== 'running') {
@@ -649,8 +774,30 @@ export class WasmSandbox {
649
774
  }
650
775
  this._setState('running');
651
776
 
652
- // Simulate execution with usage tracking
653
- const cpuMs = Math.random() * 10;
777
+ let result = null;
778
+ let executed = false;
779
+ let cpuMs = 0;
780
+
781
+ if (this.#invoke) {
782
+ const startedAt = _now();
783
+ let out;
784
+ try {
785
+ out = await this.#invoke(functionName, args);
786
+ } catch (err) {
787
+ this._setState('error');
788
+ this._log(`Execution failed: ${functionName} — ${err.message}`);
789
+ throw err;
790
+ }
791
+ executed = true;
792
+ if (out && typeof out === 'object' && typeof out.cpuMs === 'number') {
793
+ result = out.result ?? null;
794
+ cpuMs = out.cpuMs;
795
+ } else {
796
+ result = out ?? null;
797
+ cpuMs = _now() - startedAt;
798
+ }
799
+ }
800
+
654
801
  this.#usage.cpuMs += cpuMs;
655
802
 
656
803
  // Check policy limits
@@ -660,9 +807,13 @@ export class WasmSandbox {
660
807
  throw new Error(`Policy violation: ${violations.join(', ')}`);
661
808
  }
662
809
 
663
- this._log(`Executed: ${functionName}(${args.length} args) in ${cpuMs.toFixed(1)}ms`);
810
+ this._log(
811
+ executed
812
+ ? `Executed: ${functionName}(${args.length} args) in ${cpuMs.toFixed(1)}ms`
813
+ : `Executed nothing for ${functionName}: no invoke was supplied to load()`,
814
+ );
664
815
  this._setState('ready');
665
- return { result: null, cpuMs };
816
+ return { result, cpuMs, executed };
666
817
  }
667
818
 
668
819
  /** Pause execution. */
@@ -31,10 +31,63 @@ export const GROUP_KEY_ACK = 0x83
31
31
  * per-member envelope encryption. Older browsers only support P-256/P-384
32
32
  * ECDH — group key distribution falls back to metadata-only (current
33
33
  * behavior) when this is false.
34
- * @returns {boolean}
34
+ *
35
+ * Determining this requires attempting the operation: WebCrypto exposes no
36
+ * algorithm registry, so the presence of `crypto.subtle` says nothing about
37
+ * which curves it implements. The probe runs once and the answer is cached.
38
+ *
39
+ * The synchronous form returns the cached answer, and `null` when the probe
40
+ * has not resolved yet — treat `null` as "unknown, assume unsupported" or
41
+ * await `probeX25519Support()` first.
42
+ *
43
+ * @returns {boolean|null}
35
44
  */
36
45
  export function supportsX25519() {
37
- return typeof crypto !== 'undefined' && !!crypto.subtle
46
+ if (_x25519Supported === null) {
47
+ // Kick off the probe so a later synchronous call can answer.
48
+ probeX25519Support()
49
+ }
50
+ return _x25519Supported
51
+ }
52
+
53
+ /** @type {boolean|null} Cached probe result; null until the probe resolves. */
54
+ let _x25519Supported = null
55
+
56
+ /** @type {Promise<boolean>|null} In-flight probe, so it runs at most once. */
57
+ let _x25519Probe = null
58
+
59
+ /**
60
+ * Probe for real X25519 support by asking WebCrypto to generate a key.
61
+ * Resolves true or false; never throws. The result is cached.
62
+ *
63
+ * @returns {Promise<boolean>}
64
+ */
65
+ export function probeX25519Support() {
66
+ if (_x25519Probe) return _x25519Probe
67
+ _x25519Probe = (async () => {
68
+ if (typeof crypto === 'undefined' || !crypto.subtle ||
69
+ typeof crypto.subtle.generateKey !== 'function') {
70
+ return false
71
+ }
72
+ try {
73
+ await crypto.subtle.generateKey({ name: 'X25519' }, false, ['deriveBits'])
74
+ return true
75
+ } catch {
76
+ return false
77
+ }
78
+ })().then((ok) => {
79
+ _x25519Supported = ok
80
+ return ok
81
+ })
82
+ return _x25519Probe
83
+ }
84
+
85
+ /**
86
+ * Reset the cached X25519 probe. Tests only.
87
+ */
88
+ export function _resetX25519Probe() {
89
+ _x25519Supported = null
90
+ _x25519Probe = null
38
91
  }
39
92
 
40
93
  function bytesToB64(bytes) {
@@ -241,7 +294,7 @@ export class GroupKeyManager {
241
294
  * X25519 is unsupported in this environment.
242
295
  */
243
296
  async initEncryption() {
244
- if (!supportsX25519()) {
297
+ if (!(await probeX25519Support())) {
245
298
  this.#encryptionKeyPair = null
246
299
  return null
247
300
  }
@@ -525,7 +578,10 @@ export class GroupKeyManager {
525
578
  const state = this.getCurrentState()
526
579
  if (!state) return
527
580
 
528
- const canEnvelope = supportsX25519() && !!this.#encryptionKeyPair
581
+ // A local encryption keypair only exists when initEncryption() probed
582
+ // X25519 successfully, so its presence IS the support check -- no need to
583
+ // re-probe, and re-probing here would suspend before the broadcast.
584
+ const canEnvelope = !!this.#encryptionKeyPair
529
585
  let envelopes
530
586
  if (canEnvelope) {
531
587
  const targets = state.members.filter(m => m !== this.#localPodId && this.#memberPublicKeys.has(m))