@johnhenry/browsermesh-apps 0.1.1 → 0.3.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.
Files changed (50) hide show
  1. package/README.md +443 -1
  2. package/package.json +18 -3
  3. package/src/agent-runtime.mjs +342 -0
  4. package/src/chunk-replication.mjs +751 -0
  5. package/src/cloud-storage-backend.mjs +932 -0
  6. package/src/cloud-storage.mjs +799 -0
  7. package/src/compat.mjs +98 -0
  8. package/src/gpu-kernel.mjs +242 -0
  9. package/src/gpu.mjs +101 -7
  10. package/src/grant-log.mjs +840 -0
  11. package/src/index.mjs +32 -2
  12. package/src/kernel-mesh.mjs +56 -0
  13. package/src/key-distribution.mjs +525 -0
  14. package/src/manifest-sync.mjs +363 -0
  15. package/src/mesh-agent-swarm.mjs +376 -0
  16. package/src/mesh-bootstrap.mjs +1481 -0
  17. package/src/mesh-compute.mjs +397 -0
  18. package/src/mesh-dht.mjs +182 -0
  19. package/src/mesh-fetch.mjs +246 -0
  20. package/src/mesh-hardening.mjs +226 -0
  21. package/src/mesh-health.mjs +282 -0
  22. package/src/mesh-keepalive.mjs +353 -0
  23. package/src/mesh-kv.mjs +673 -0
  24. package/src/mesh-orchestrator-tools.mjs +251 -0
  25. package/src/mesh-orchestrator.mjs +343 -0
  26. package/src/mesh-relay-backend.mjs +289 -0
  27. package/src/mesh-relay-host.mjs +362 -0
  28. package/src/mesh-rpc.mjs +300 -0
  29. package/src/mesh-service.mjs +403 -0
  30. package/src/mesh-swarm.mjs +677 -0
  31. package/src/mesh-sync.mjs +253 -0
  32. package/src/mesh-timestamp.mjs +265 -0
  33. package/src/mesh-torrent.mjs +683 -0
  34. package/src/mesh-verification.mjs +367 -0
  35. package/src/mesh-websocket.mjs +722 -0
  36. package/src/observability-bridge.mjs +453 -0
  37. package/src/orchestrator.mjs +18 -5
  38. package/src/peer-agent-swarm.mjs +12 -1
  39. package/src/peer-chat.mjs +230 -61
  40. package/src/peer-compute.mjs +66 -3
  41. package/src/peer-escrow.mjs +350 -1
  42. package/src/peer-files.mjs +362 -168
  43. package/src/peer-ipfs.mjs +205 -10
  44. package/src/peer-node.mjs +127 -19
  45. package/src/peer-registry.mjs +242 -18
  46. package/src/peer-routing.mjs +369 -5
  47. package/src/peer-terminal.mjs +400 -130
  48. package/src/signaling.mjs +231 -0
  49. package/src/webrtc-negotiator.mjs +209 -0
  50. package/src/peer-session.mjs +0 -937
@@ -1,4 +1,5 @@
1
1
  import { silentCatch } from './silent-catch.mjs'
2
+ import { matchScope } from '@johnhenry/browsermesh-primitives'
2
3
  /**
3
4
  * clawser-peer-registry.js -- Unified peer registry with permission management.
4
5
  *
@@ -13,6 +14,51 @@ import { silentCatch } from './silent-catch.mjs'
13
14
  * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-registry.test.mjs
14
15
  */
15
16
 
17
+ // ---------------------------------------------------------------------------
18
+ // Capability tokens (Phase 5 -- real granting/revocation, layered under the
19
+ // existing ACL template mechanism, not replacing it)
20
+ // ---------------------------------------------------------------------------
21
+
22
+ /**
23
+ * Duck-typed default token, used only when no `tokenFactory` is injected.
24
+ * Shaped to satisfy both this module's own default `CapabilityValidator`
25
+ * fallback below AND the real `@johnhenry/browsermesh-core` `CapabilityValidator`
26
+ * (whose `register()`/`revokeTree()`/`validate()` only ever touch `.id`,
27
+ * `.revoked`, `.parentId`, `.resource`, `.permissions`, `.constraints`,
28
+ * `.isExpired()`, `.hasPermission()`, `.revoke()` -- nothing constructor-specific)
29
+ * -- so real callers (see `mesh-bootstrap.mjs`) can inject the real
30
+ * `CapabilityToken` class as `tokenFactory` for the genuine, tested class,
31
+ * while this file itself stays decoupled from `-core` at the module level,
32
+ * matching the existing peerManager/trustGraph/acl DI pattern in this class.
33
+ */
34
+ let _localCapTokenSeq = 0
35
+ class _DefaultCapabilityToken {
36
+ constructor({ issuer, holder, resource, permissions, constraints = {}, parentId = null, createdAt, expiresAt = null }) {
37
+ this.id = `peercap_${Date.now()}_${++_localCapTokenSeq}`
38
+ this.issuer = issuer
39
+ this.holder = holder
40
+ this.resource = resource
41
+ this.permissions = [...permissions]
42
+ this.constraints = { ...constraints }
43
+ this.parentId = parentId
44
+ this.createdAt = createdAt || Date.now()
45
+ this.expiresAt = expiresAt
46
+ this.revoked = false
47
+ }
48
+
49
+ isExpired(now = Date.now()) {
50
+ return this.expiresAt !== null && this.expiresAt !== undefined && now >= this.expiresAt
51
+ }
52
+
53
+ hasPermission(perm) {
54
+ return this.permissions.includes(perm)
55
+ }
56
+
57
+ revoke() {
58
+ this.revoked = true
59
+ }
60
+ }
61
+
16
62
  // ---------------------------------------------------------------------------
17
63
  // PeerRegistry
18
64
  // ---------------------------------------------------------------------------
@@ -41,15 +87,48 @@ export class PeerRegistry {
41
87
  /** @type {Map<string, number>} */
42
88
  #observedTrust = new Map()
43
89
 
90
+ /**
91
+ * Real capability tokens issued through `grantCapabilities()`, tracked so
92
+ * `revokeCapabilities()` can find and revoke the matching token(s) later,
93
+ * and so `checkAccess()` can consult live revocation status. Keyed by
94
+ * peer pubKey -> (exact granted scope string -> token). Only scopes
95
+ * granted via `grantCapabilities()` get an entry here; peers configured
96
+ * purely via `updatePermissions()`/`addEntry()`/default templates have no
97
+ * tracked tokens and are therefore governed by the ACL alone, unaffected
98
+ * by this mechanism (see checkAccess()).
99
+ *
100
+ * @type {Map<string, Map<string, object>>}
101
+ */
102
+ #capabilityTokens = new Map()
103
+
104
+ /** Validates/revokes tokens -- real `CapabilityValidator` when injected, a
105
+ * duck-typed equivalent otherwise. @type {{ register: Function, revokeTree: Function }} */
106
+ #capabilityValidator
107
+
108
+ /** Constructs a token object for grantCapabilities() -- real `CapabilityToken`
109
+ * when injected, `_DefaultCapabilityToken` otherwise. @type {Function} */
110
+ #tokenFactory
111
+
44
112
  /**
45
113
  * @param {object} opts
46
114
  * @param {string} opts.localPodId - Owner identity used for ACL and trust edges
47
115
  * @param {import('@johnhenry/browsermesh-core').MeshPeerManager} [opts.peerManager]
48
116
  * @param {import('@johnhenry/browsermesh-core').TrustGraph} [opts.trustGraph]
49
117
  * @param {import('@johnhenry/browsermesh-core').MeshACL} [opts.acl]
118
+ * @param {import('@johnhenry/browsermesh-core').CapabilityValidator} [opts.capabilityValidator]
119
+ * Backs the real granting/revocation path for `grantCapabilities()`/
120
+ * `revokeCapabilities()` (Phase 5). Defaults to a lightweight in-package
121
+ * equivalent when omitted, so this class stays usable without `-core`
122
+ * installed -- inject the real class (see `mesh-bootstrap.mjs`) for the
123
+ * genuine, tested implementation.
124
+ * @param {Function} [opts.tokenFactory] - `(opts) => token`, used to construct
125
+ * the token registered with `capabilityValidator` on each grant. Defaults to
126
+ * a small duck-typed equivalent of `@johnhenry/browsermesh-core`'s
127
+ * `CapabilityToken`; pass `(opts) => new CapabilityToken(opts)` to use the
128
+ * real class.
50
129
  * @param {Function} [opts.onLog] - Logging callback (level, msg)
51
130
  */
52
- constructor({ localPodId, peerManager, trustGraph, acl, onLog }) {
131
+ constructor({ localPodId, peerManager, trustGraph, acl, capabilityValidator, tokenFactory, onLog }) {
53
132
  if (!localPodId || typeof localPodId !== 'string') {
54
133
  throw new Error('localPodId is required and must be a non-empty string')
55
134
  }
@@ -63,6 +142,8 @@ export class PeerRegistry {
63
142
  this.#peerManager = peerManager ?? this.#createDefaultPeerManager()
64
143
  this.#trustGraph = trustGraph ?? this.#createDefaultTrustGraph()
65
144
  this.#acl = acl ?? this.#createDefaultACL()
145
+ this.#capabilityValidator = capabilityValidator ?? this.#createDefaultCapabilityValidator()
146
+ this.#tokenFactory = tokenFactory ?? ((tokenOpts) => new _DefaultCapabilityToken(tokenOpts))
66
147
  }
67
148
 
68
149
  // ── Peer CRUD ───────────────────────────────────────────────────────
@@ -104,6 +185,17 @@ export class PeerRegistry {
104
185
  // Remove ACL roster entry
105
186
  this.#acl.revokeAll(pubKey)
106
187
 
188
+ // Revoke any live capability tokens issued to this peer and stop
189
+ // tracking them -- a removed peer must not retain live tokens that a
190
+ // later re-add under the same pubKey could otherwise inherit.
191
+ const peerTokens = this.#capabilityTokens.get(pubKey)
192
+ if (peerTokens) {
193
+ for (const token of peerTokens.values()) {
194
+ if (!token.revoked) this.#capabilityValidator.revokeTree(token.id)
195
+ }
196
+ this.#capabilityTokens.delete(pubKey)
197
+ }
198
+
107
199
  if (existed) {
108
200
  this.#onLog(2, `PeerRegistry: removed ${pubKey}`)
109
201
  }
@@ -148,14 +240,22 @@ export class PeerRegistry {
148
240
  }
149
241
 
150
242
  /**
151
- * Grant additional capability scopes to a peer via a dynamic ACL template.
152
- * Creates a per-peer template named `_peer_{pubKey}` that merges with
153
- * any existing scopes.
243
+ * Grant additional capability scopes to a peer via a dynamic ACL template,
244
+ * AND issue a real capability token per scope through the injected (or
245
+ * default) `CapabilityValidator` (Phase 5). The ACL template remains the
246
+ * mechanism `checkAccess()` primarily checks -- fully backward compatible
247
+ * with any caller that only cares about the pre-Phase-5 ACL behavior --
248
+ * while the token gives `revokeCapabilities()` a live revocation target
249
+ * that `checkAccess()` additionally consults, independent of whether/when
250
+ * the ACL template itself gets re-read.
154
251
  *
155
252
  * @param {string} pubKey
156
253
  * @param {string[]} scopes - Scopes to add (e.g. ['files:read', 'chat:write'])
254
+ * @param {object} [opts]
255
+ * @param {number|null} [opts.expiresAt] - Optional expiry (ms epoch) applied
256
+ * to newly-issued tokens for this call. Omit for no expiry.
157
257
  */
158
- grantCapabilities(pubKey, scopes) {
258
+ grantCapabilities(pubKey, scopes, opts = {}) {
159
259
  const templateName = `_peer_${pubKey}`
160
260
  const existing = this.#acl.getTemplate(templateName)
161
261
  const merged = existing
@@ -171,12 +271,44 @@ export class PeerRegistry {
171
271
  this.#acl.addEntry(pubKey, templateName)
172
272
  }
173
273
 
274
+ // Issue a real capability token per scope so revocation has a live
275
+ // target beyond the ACL template. Skip scopes that already have a live
276
+ // (non-revoked, non-expired) token -- re-granting an already-granted
277
+ // scope is a no-op at the token layer, matching the ACL's own
278
+ // dedup/additive behavior above. A scope whose prior token was revoked
279
+ // gets a fresh token (tokens are one-way revocable, never un-revoked).
280
+ let peerTokens = this.#capabilityTokens.get(pubKey)
281
+ if (!peerTokens) {
282
+ peerTokens = new Map()
283
+ this.#capabilityTokens.set(pubKey, peerTokens)
284
+ }
285
+ for (const scope of scopes) {
286
+ const current = peerTokens.get(scope)
287
+ const currentLive = current && !current.revoked &&
288
+ !(typeof current.isExpired === 'function' && current.isExpired())
289
+ if (currentLive) continue
290
+
291
+ const token = this.#tokenFactory({
292
+ issuer: this.#localPodId,
293
+ holder: pubKey,
294
+ resource: scope,
295
+ permissions: ['use'],
296
+ expiresAt: opts.expiresAt ?? null,
297
+ })
298
+ this.#capabilityValidator.register(token)
299
+ peerTokens.set(scope, token)
300
+ }
301
+
174
302
  this.#onLog(3, `PeerRegistry: granted ${scopes.join(', ')} to ${pubKey}`)
175
303
  }
176
304
 
177
305
  /**
178
- * Revoke specific capability scopes from a peer.
179
- * If no scopes remain, removes the per-peer template and roster entry.
306
+ * Revoke specific capability scopes from a peer: removes them from the ACL
307
+ * template (if no scopes remain, removes the per-peer template and roster
308
+ * entry -- unchanged from pre-Phase-5 behavior) AND revokes the matching
309
+ * capability token(s) issued by `grantCapabilities()` through the
310
+ * `CapabilityValidator`, so `checkAccess()`'s live check denies immediately
311
+ * regardless of ACL template state.
180
312
  *
181
313
  * @param {string} pubKey
182
314
  * @param {string[]} scopes - Scopes to remove
@@ -184,18 +316,32 @@ export class PeerRegistry {
184
316
  revokeCapabilities(pubKey, scopes) {
185
317
  const templateName = `_peer_${pubKey}`
186
318
  const existing = this.#acl.getTemplate(templateName)
187
- if (!existing) return
188
319
 
189
- const remaining = existing.scopes.filter(s => !scopes.includes(s))
320
+ if (existing) {
321
+ const remaining = existing.scopes.filter(s => !scopes.includes(s))
322
+
323
+ if (remaining.length === 0) {
324
+ this.#acl.removeEntry(pubKey)
325
+ this.#acl.removeTemplate(templateName)
326
+ } else {
327
+ this.#acl.addTemplate(templateName, remaining, `Auto-generated for ${pubKey}`)
328
+ // Re-sync the roster entry
329
+ this.#acl.removeEntry(pubKey)
330
+ this.#acl.addEntry(pubKey, templateName)
331
+ }
332
+ }
190
333
 
191
- if (remaining.length === 0) {
192
- this.#acl.removeEntry(pubKey)
193
- this.#acl.removeTemplate(templateName)
194
- } else {
195
- this.#acl.addTemplate(templateName, remaining, `Auto-generated for ${pubKey}`)
196
- // Re-sync the roster entry
197
- this.#acl.removeEntry(pubKey)
198
- this.#acl.addEntry(pubKey, templateName)
334
+ // Revoke the matching token(s), if any were issued via grantCapabilities().
335
+ // Scoped precisely: only the exact scopes named here are touched, so a
336
+ // different, still-granted scope for the same peer is unaffected.
337
+ const peerTokens = this.#capabilityTokens.get(pubKey)
338
+ if (peerTokens) {
339
+ for (const scope of scopes) {
340
+ const token = peerTokens.get(scope)
341
+ if (token && !token.revoked) {
342
+ this.#capabilityValidator.revokeTree(token.id)
343
+ }
344
+ }
199
345
  }
200
346
 
201
347
  this.#onLog(3, `PeerRegistry: revoked ${scopes.join(', ')} from ${pubKey}`)
@@ -221,13 +367,39 @@ export class PeerRegistry {
221
367
  /**
222
368
  * Check if a peer is allowed to perform an action on a resource.
223
369
  *
370
+ * First checks the ACL template (unchanged, pre-Phase-5 behavior -- owner
371
+ * bypass, roster/template scope matching). If the ACL allows it, ALSO
372
+ * consults live revocation status for any capability token issued via
373
+ * `grantCapabilities()` whose scope covers this resource/action (Phase 5):
374
+ * a token that was granted then revoked denies access on this check, even
375
+ * if the ACL template itself hasn't been re-read or doesn't (e.g. a
376
+ * broader wildcard scope that revokeCapabilities()'s exact-match ACL
377
+ * removal didn't touch). Peers/scopes never routed through
378
+ * `grantCapabilities()` (e.g. `updatePermissions()`/`addEntry()` callers,
379
+ * default templates) have no tracked token and are therefore governed by
380
+ * the ACL alone, exactly as before.
381
+ *
224
382
  * @param {string} pubKey
225
383
  * @param {string} resource
226
384
  * @param {string} action
227
385
  * @returns {{ allowed: boolean, reason?: string }}
228
386
  */
229
387
  checkAccess(pubKey, resource, action) {
230
- return this.#acl.check(pubKey, resource, action)
388
+ const aclResult = this.#acl.check(pubKey, resource, action)
389
+ if (!aclResult.allowed) return aclResult
390
+
391
+ const scope = `${resource}:${action}`
392
+ const peerTokens = this.#capabilityTokens.get(pubKey)
393
+ if (peerTokens) {
394
+ for (const [grantedScope, token] of peerTokens) {
395
+ if (!matchScope(grantedScope, scope)) continue
396
+ if (token.revoked || (typeof token.isExpired === 'function' && token.isExpired())) {
397
+ return { allowed: false, reason: 'capability_revoked' }
398
+ }
399
+ }
400
+ }
401
+
402
+ return aclResult
231
403
  }
232
404
 
233
405
  // ── Trust management ────────────────────────────────────────────────
@@ -592,4 +764,56 @@ export class PeerRegistry {
592
764
  },
593
765
  }
594
766
  }
767
+
768
+ /**
769
+ * Create a minimal duck-typed CapabilityValidator when none is injected.
770
+ * Mirrors the subset of `@johnhenry/browsermesh-core`'s real
771
+ * `CapabilityValidator` that `grantCapabilities()`/`revokeCapabilities()`/
772
+ * `checkAccess()` actually use: `register()`, `revokeTree()` (revokes a
773
+ * token and, transitively, any tracked token whose `parentId` chains up to
774
+ * it -- unused by this class today since tokens here are always
775
+ * root/flat, but kept for parity with the real class and any future
776
+ * attenuation use), and `validate()` for completeness/introspection.
777
+ * @returns {object}
778
+ */
779
+ #createDefaultCapabilityValidator() {
780
+ const tokens = new Map()
781
+ const revokedIds = new Set()
782
+
783
+ const validator = {
784
+ register(token) {
785
+ tokens.set(token.id, token)
786
+ if (token.revoked) revokedIds.add(token.id)
787
+ },
788
+ revokeTree(tokenId) {
789
+ revokedIds.add(tokenId)
790
+ const token = tokens.get(tokenId)
791
+ if (token) token.revoke()
792
+ for (const [id, t] of tokens) {
793
+ if (t.parentId === tokenId && !revokedIds.has(id)) {
794
+ validator.revokeTree(id)
795
+ }
796
+ }
797
+ },
798
+ validate(tokenId, resource, permission) {
799
+ const token = tokens.get(tokenId)
800
+ if (!token) return { allowed: false, reason: 'Token not found' }
801
+ if (revokedIds.has(tokenId)) return { allowed: false, reason: 'Token revoked' }
802
+ if (token.isExpired()) return { allowed: false, reason: 'Token expired' }
803
+ if (!token.hasPermission(permission)) {
804
+ return { allowed: false, reason: `Permission "${permission}" not granted` }
805
+ }
806
+ const pattern = token.resource
807
+ const matches = pattern === resource || pattern === '*' ||
808
+ (pattern.endsWith('*') && resource.startsWith(pattern.slice(0, -1)))
809
+ if (!matches) {
810
+ return { allowed: false, reason: `Resource "${resource}" not covered by "${pattern}"` }
811
+ }
812
+ return { allowed: true }
813
+ },
814
+ get size() { return tokens.size },
815
+ listTokens() { return [...tokens.values()] },
816
+ }
817
+ return validator
818
+ }
595
819
  }