@johnhenry/browsermesh-apps 0.2.0 → 0.4.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 +232 -1
  2. package/package.json +7 -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 +859 -0
  7. package/src/compat.mjs +98 -0
  8. package/src/grant-log.mjs +840 -0
  9. package/src/index.mjs +34 -2
  10. package/src/key-distribution.mjs +525 -0
  11. package/src/manifest-sync.mjs +363 -0
  12. package/src/mesh-agent-swarm.mjs +376 -0
  13. package/src/mesh-bootstrap.mjs +1131 -12
  14. package/src/mesh-compute.mjs +397 -0
  15. package/src/mesh-dht.mjs +182 -0
  16. package/src/mesh-fetch.mjs +246 -0
  17. package/src/mesh-hardening.mjs +226 -0
  18. package/src/mesh-health.mjs +282 -0
  19. package/src/mesh-keepalive.mjs +353 -0
  20. package/src/mesh-kv.mjs +673 -0
  21. package/src/mesh-orchestrator-tools.mjs +251 -0
  22. package/src/mesh-orchestrator.mjs +343 -0
  23. package/src/mesh-rpc.mjs +300 -0
  24. package/src/mesh-service.mjs +403 -0
  25. package/src/mesh-swarm.mjs +677 -0
  26. package/src/mesh-timestamp.mjs +265 -0
  27. package/src/mesh-torrent.mjs +683 -0
  28. package/src/mesh-verification.mjs +367 -0
  29. package/src/mesh-websocket.mjs +722 -0
  30. package/src/observability-bridge.mjs +453 -0
  31. package/src/orchestrator.mjs +18 -5
  32. package/src/peer-agent-swarm.mjs +12 -1
  33. package/src/peer-chat.mjs +230 -61
  34. package/src/peer-compute.mjs +66 -3
  35. package/src/peer-escrow.mjs +350 -1
  36. package/src/peer-files.mjs +362 -168
  37. package/src/peer-ipfs.mjs +205 -10
  38. package/src/peer-node.mjs +33 -2
  39. package/src/peer-routing.mjs +369 -5
  40. package/src/peer-terminal.mjs +400 -130
  41. package/src/serverless-executor-andbox.mjs +136 -0
  42. package/src/serverless-fetch.mjs +70 -0
  43. package/src/serverless-functions.mjs +67 -0
  44. package/src/serverless-peer-select.mjs +69 -0
  45. package/src/serverless-proxy.mjs +127 -0
  46. package/src/serverless-router.mjs +115 -0
  47. package/src/serverless-sites.mjs +116 -0
  48. package/src/serverless-static.mjs +202 -0
  49. package/src/serverless-wire.mjs +87 -0
  50. package/src/peer-session.mjs +0 -937
@@ -0,0 +1,367 @@
1
+ /**
2
+ * mesh-verification.mjs -- Phase 4 of the browsermesh-app-layer-migration
3
+ * plan (issue #119): wraps `peer-verification.mjs`'s `VerificationQuorum`/
4
+ * `Attestation` as a `MeshService` (`mesh-service.mjs`, Phase C's
5
+ * `attach()`/`ctx` convention).
6
+ *
7
+ * `VerificationQuorum` dispatches the SAME job to N peers, hashes each
8
+ * peer's reported result, groups by hash, and applies a voting strategy
9
+ * (unanimous/majority/threshold/byzantine) to decide a winning result with a
10
+ * confidence score and a set of `Attestation`s from the peers that agreed.
11
+ * "Enables trustless compute verification without TEEs" (see that file's own
12
+ * header) -- genuinely trust-bearing subject matter, approved to wire
13
+ * (issue #119: "real trust-bearing subject matter... proceed with normal
14
+ * care"), unlike `peer-compute.mjs`/`peer-terminal.mjs`, which stay blocked
15
+ * on issue #86's still-unresolved execution-gating design pass.
16
+ *
17
+ * ---------------------------------------------------------------------------
18
+ * WHAT `VerificationQuorum` ITSELF DOES AND DOES NOT DO -- read directly off
19
+ * its constructor and `submitVerified()`:
20
+ *
21
+ * - `scheduler.dispatch(peerId, job) -> Promise<result>` is a required
22
+ * constructor dependency. `VerificationQuorum` never sends a byte over
23
+ * any network itself -- exactly like `peer-compute.mjs`'s
24
+ * `FederatedCompute`, it is "a pure orchestrator that delegates real
25
+ * execution to an injected scheduler.dispatch() entirely outside the
26
+ * file" (this plan's own "Context" section, describing the #86
27
+ * correction for that sibling module). `#dispatchWithTimeout()` merely
28
+ * races whatever Promise `scheduler.dispatch()` returns against
29
+ * `policy.timeoutMs`.
30
+ * - `trust.getReputation(podId)` / `trust.listTrustedPeers(threshold?)` is
31
+ * the other required dependency, consulted only inside
32
+ * `#selectVerifiers()` to rank and pick which peers to ask.
33
+ *
34
+ * THE ONE GENUINELY NEW PIECE OF LOGIC THIS FILE CONTRIBUTES, THEREFORE, IS
35
+ * THE WIRE PROTOCOL BEHIND A REAL `scheduler` -- turning "ask peer X to run
36
+ * this job and tell me the result" into actual `ctx.sendTo()` /
37
+ * `ctx.onIncomingData()` traffic. This is the same shape of gap
38
+ * `mesh-timestamp.mjs` closes for `TimestampAuthority.stamp()`'s
39
+ * `peerTimestamps` collection, and `peer-routing.mjs`'s `ServerSharing`
40
+ * proxy-request/response closes for HTTP proxying: the wrapped class
41
+ * documents an injectable seam; this file is the first real implementation
42
+ * of that seam wired to a real `PeerNode`.
43
+ *
44
+ * ---------------------------------------------------------------------------
45
+ * LOCAL/ADMIN vs. PEER-INITIATED -- the actual real flow, traced end to end
46
+ * (not just the two named methods `setPolicy`/`submitVerified`):
47
+ *
48
+ * - `api.setPolicy(policy)` / `api.submitVerified(job, opts)` are LOCAL
49
+ * calls: this node's own operator/application code deciding to ask for
50
+ * (or configure how it asks for) verification. Nothing about calling
51
+ * these requires anything from a remote peer first.
52
+ * - `submitVerified()` -> `#selectVerifiers()` -> `trust.listTrustedPeers()`
53
+ * is ALSO local: it consults this node's OWN trust view (this file's
54
+ * default `trust` adapter reads `ctx.registry`, this node's own
55
+ * `PeerRegistry` -- never a remote query).
56
+ * - `submitVerified()` -> `scheduler.dispatch(peerId, job)` is where a
57
+ * PEER gets involved: this file's default `scheduler` sends a real
58
+ * `'verify-request'` envelope to `peerId` and awaits a `'verify-response'`
59
+ * reply.
60
+ * - Receiving a `'verify-request'` FROM a peer -- i.e., being asked to
61
+ * serve as a verifier -- is the genuinely PEER-INITIATED action, and the
62
+ * one that needs an authorization check: before this node ever executes
63
+ * anyone else's job, it gates the request through
64
+ * `ctx.registry.checkAccess(fromPubKey, accessResource, accessAction)`
65
+ * (default resource/action: `'verification'`/`'execute'`), exactly the
66
+ * `registry.checkAccess()` gate `chunk-replication.mjs`/`mesh-kv.mjs`/
67
+ * `mesh-relay-host.mjs` already established for "a peer wants this node
68
+ * to do something on its behalf." A denied or ungranted peer gets an
69
+ * explicit `{error: 'access denied'}` response (not a silent drop) --
70
+ * see "WHY AN EXPLICIT DENIAL RESPONSE" below.
71
+ *
72
+ * ---------------------------------------------------------------------------
73
+ * `executeFn` -- REQUIRED FOR THIS NODE TO SERVE AS A VERIFIER, NOT PROVIDED
74
+ * BY THIS FILE. Even after `checkAccess()` authorizes the requesting peer,
75
+ * "what does it mean to actually run `job`" is left ENTIRELY to a
76
+ * caller-supplied `opts.executeFn(job) -> Promise<result>`. This file never
77
+ * invents a way to execute arbitrary job payloads -- the same restraint
78
+ * `peer-compute.mjs`'s `FederatedCompute` already shows by delegating to an
79
+ * injected `scheduler.dispatch()`, just one layer further out: THIS file's
80
+ * OWN default `scheduler.dispatch()` implementation (the wire protocol) is
81
+ * real and wired, but the thing it ultimately calls on the answering side
82
+ * (`executeFn`) is not. A node whose operator never supplies `executeFn`
83
+ * can still SUBMIT verification jobs (the requesting role) but cleanly
84
+ * refuses to ANSWER them (the executing role) -- an authorized peer gets a
85
+ * fast, explicit `{error: 'verifier not configured to execute jobs'}`
86
+ * rather than a silent hang until the requester's own timeout. This mirrors
87
+ * issue #119's "approved to wire... proceed with normal care": the
88
+ * quorum/voting/attestation protocol itself is wired for real, while what
89
+ * code actually runs for a remote peer remains an explicit, per-deployment
90
+ * opt-in -- consistent with `peer-compute.mjs`/`peer-terminal.mjs` staying
91
+ * blocked on issue #86's still-open "what gates remote execution" design
92
+ * pass, rather than this file quietly deciding that question on the side.
93
+ *
94
+ * WHY AN EXPLICIT DENIAL RESPONSE (not a silent drop, unlike e.g.
95
+ * `chunk-replication.mjs`'s checkAccess-gated inbound mutation handlers):
96
+ * those are fire-and-forget broadcasts with no waiting caller. Here, the
97
+ * REQUESTING side's `scheduler.dispatch()` Promise is already open and
98
+ * waiting -- silently dropping would just make an unauthorized/unconfigured
99
+ * peer indistinguishable from a slow or dead one, forcing every such case to
100
+ * eat the full `dispatchTimeoutMs`. `VerificationQuorum.submitVerified()`
101
+ * already treats ANY rejected dispatch (timeout OR explicit error) the same
102
+ * way -- exclude that peer's result, emit `'timeout'` regardless of the
103
+ * real reason (see that method's own `catch`-adjacent `else` branch) -- so
104
+ * an explicit fast rejection changes nothing about quorum correctness, only
105
+ * how long a caller waits to find out.
106
+ *
107
+ * ---------------------------------------------------------------------------
108
+ * DEFAULT `trust` ADAPTER -- `PeerRegistry` (`peer-registry.mjs`) already
109
+ * implements `getReputation(pubKey)` natively with the exact signature
110
+ * `VerificationQuorum` wants. `listTrustedPeers(minLevel?)` does not exist
111
+ * on `PeerRegistry` as a single call, so this file's default composes it
112
+ * from two calls that DO exist: `peerNode.listPeers({status:'connected'})`
113
+ * (the reachable candidate set -- asking a peer with no live connection to
114
+ * verify a job cannot work) filtered through `ctx.registry.isTrusted(pubKey,
115
+ * null, minLevel)` (that peer's own established default `minLevel` of
116
+ * `0.25`, matching `PeerRegistry.isTrusted()`'s own documented default).
117
+ * Supply `opts.trust` directly to bypass this (e.g. to consider peers beyond
118
+ * those currently connected, or a different trust source entirely).
119
+ *
120
+ * ---------------------------------------------------------------------------
121
+ * Observability events (`ctx.emit()`, see `mesh-service.mjs`'s module doc
122
+ * comment for the full convention). `VerificationQuorum`'s own pre-existing
123
+ * `on`/`off` surface (`'verified'`/`'divergent'`/`'timeout'`) is bridged
124
+ * through verbatim, prefixed `verification:`:
125
+ *
126
+ * - `verification:verified` -- `{result, confidence, attestations}`,
127
+ * `VerificationQuorum`'s own `'verified'` payload, unchanged.
128
+ * - `verification:divergent` -- `{jobId, groups}`, `VerificationQuorum`'s
129
+ * own `'divergent'` payload, unchanged.
130
+ * - `verification:timeout` -- `{peerId, jobId, error}`, `VerificationQuorum`'s
131
+ * own `'timeout'` payload (fired for ANY failed/rejected dispatch, not
132
+ * only a real elapsed-time timeout -- see that class's own code).
133
+ *
134
+ * Plus this file's own, for the wire layer (mirroring `mesh-timestamp.mjs`'s
135
+ * `timestamp:witness-timeout` / `peer-routing.mjs`'s
136
+ * `mesh-routing:server-share-served`):
137
+ *
138
+ * - `verification:verify-served` `{from, requestId, ok}` -- this node, AS
139
+ * A VERIFIER, answered an authorized `'verify-request'` (`ok: true` if
140
+ * `executeFn` succeeded, `false` if it threw).
141
+ * - `verification:verify-request-denied` `{from, requestId, reason}` --
142
+ * an inbound `'verify-request'` was rejected before `executeFn` ever
143
+ * ran (`reason`: `'access_denied'` or `'no_executor'`).
144
+ *
145
+ * No browser-only imports at module level.
146
+ */
147
+
148
+ import { VerificationQuorum } from './peer-verification.mjs'
149
+
150
+ /** Shared envelope `type` for both verify request/response directions (tagged by `kind`), mirroring `mesh-timestamp.mjs`'s `'time-request'`/`'time-response'` shape. */
151
+ const DEFAULT_VERIFICATION_ENVELOPE_TYPE = 'mesh-verification'
152
+
153
+ /** How long the default `scheduler.dispatch()` waits for a matching `'verify-response'` before giving up. Independent of (and typically ⩾) `VerificationQuorum`'s own internal `policy.timeoutMs` -- whichever fires first wins; this one exists purely so a never-answering peer's pending entry is always eventually cleaned up. */
154
+ const DEFAULT_DISPATCH_TIMEOUT_MS = 30000
155
+
156
+ /** Default `resource`/`action` pair checked via `ctx.registry.checkAccess(fromPubKey, resource, action)` before honoring an inbound `'verify-request'`. */
157
+ const DEFAULT_ACCESS_RESOURCE = 'verification'
158
+ const DEFAULT_ACCESS_ACTION = 'execute'
159
+
160
+ /** Default trust threshold for the default `trust.listTrustedPeers()` adapter, matching `PeerRegistry.isTrusted()`'s own documented default. */
161
+ const DEFAULT_TRUST_THRESHOLD = 0.25
162
+
163
+ /**
164
+ * Build a `MeshService` descriptor (`mesh-service.mjs`, Phase C) wrapping
165
+ * `VerificationQuorum`. See this file's module doc comment for the full
166
+ * design writeup (what's local/admin-only vs. peer-initiated, why
167
+ * `executeFn` is required-but-not-provided, the default `trust` adapter).
168
+ *
169
+ * @param {object} [opts]
170
+ * @param {{dispatch: (peerId: string, job: object) => Promise<*>}} [opts.scheduler]
171
+ * Defaults to a real mesh-wired scheduler (`ctx.sendTo()` a `'verify-request'`,
172
+ * await a matching `'verify-response'`). Supply your own to bypass the
173
+ * network entirely (e.g. local-only testing) or use a different transport.
174
+ * @param {{getReputation: (podId: string) => number, listTrustedPeers: (threshold?: number) => string[]}} [opts.trust]
175
+ * Defaults to an adapter over `ctx.registry`/`peerNode.listPeers()` -- see
176
+ * module doc comment's "DEFAULT `trust` ADAPTER" section.
177
+ * @param {(job: object) => Promise<*>} [opts.executeFn] - Called to actually
178
+ * run an inbound, authorized verification job and produce this node's
179
+ * result. REQUIRED for this node to usefully serve as a verifier -- see
180
+ * module doc comment. Omitting it still allows this node to SUBMIT
181
+ * verification jobs (the requesting role).
182
+ * @param {number} [opts.dispatchTimeoutMs=30000] - How long the default
183
+ * `scheduler.dispatch()` waits for a `'verify-response'`.
184
+ * @param {string} [opts.envelopeType='mesh-verification']
185
+ * @param {string} [opts.accessResource='verification'] - `resource` passed to
186
+ * `ctx.registry.checkAccess()` for inbound `'verify-request'`s.
187
+ * @param {string} [opts.accessAction='execute'] - `action` passed to
188
+ * `ctx.registry.checkAccess()` for inbound `'verify-request'`s.
189
+ * @param {Function} [opts.onLog]
190
+ * @returns {import('./mesh-service.mjs').MeshService}
191
+ */
192
+ export function createVerificationService({
193
+ scheduler,
194
+ trust,
195
+ executeFn,
196
+ dispatchTimeoutMs = DEFAULT_DISPATCH_TIMEOUT_MS,
197
+ envelopeType = DEFAULT_VERIFICATION_ENVELOPE_TYPE,
198
+ accessResource = DEFAULT_ACCESS_RESOURCE,
199
+ accessAction = DEFAULT_ACCESS_ACTION,
200
+ onLog,
201
+ } = {}) {
202
+ const log = onLog || (() => {})
203
+
204
+ return {
205
+ name: 'verification',
206
+
207
+ attach(peerNode, ctx) {
208
+ // -- Default trust adapter (see module doc comment) -------------------
209
+ const effectiveTrust = trust || {
210
+ getReputation: (podId) => ctx.registry.getReputation(podId),
211
+ listTrustedPeers: (threshold = DEFAULT_TRUST_THRESHOLD) => {
212
+ const connected = typeof peerNode.listPeers === 'function'
213
+ ? peerNode.listPeers({ status: 'connected' })
214
+ : []
215
+ return connected
216
+ .map((p) => p.fingerprint)
217
+ .filter(Boolean)
218
+ .filter((pubKey) => ctx.registry.isTrusted(pubKey, null, threshold))
219
+ },
220
+ }
221
+
222
+ // -- Default scheduler: real request/response wire protocol -----------
223
+ let reqSeq = 0
224
+ const nextRequestId = () => `${peerNode.podId}:${Date.now()}:${++reqSeq}`
225
+
226
+ /** @type {Map<string, {resolve: Function, reject: Function, timer: ReturnType<typeof setTimeout>}>} */
227
+ const pendingDispatches = new Map()
228
+
229
+ const effectiveScheduler = scheduler || {
230
+ dispatch(peerId, job) {
231
+ const requestId = nextRequestId()
232
+ const promise = new Promise((resolve, reject) => {
233
+ const timer = setTimeout(() => {
234
+ pendingDispatches.delete(requestId)
235
+ reject(new Error(`mesh-verification: dispatch to ${peerId} timed out after ${dispatchTimeoutMs}ms`))
236
+ }, dispatchTimeoutMs)
237
+ pendingDispatches.set(requestId, { resolve, reject, timer })
238
+ })
239
+
240
+ ctx.sendTo(peerId, envelopeType, { kind: 'verify-request', requestId, job }).catch((err) => {
241
+ const pending = pendingDispatches.get(requestId)
242
+ if (pending) {
243
+ clearTimeout(pending.timer)
244
+ pendingDispatches.delete(requestId)
245
+ pending.reject(err)
246
+ }
247
+ })
248
+
249
+ return promise
250
+ },
251
+ }
252
+
253
+ const quorum = new VerificationQuorum({
254
+ scheduler: effectiveScheduler,
255
+ trust: effectiveTrust,
256
+ onLog: (level, msg) => log('mesh-verification:internal', { level, msg }),
257
+ })
258
+
259
+ // Bridge VerificationQuorum's own pre-existing on()/off() events
260
+ // through ctx.emit() -- see module doc comment's "Observability
261
+ // events" section.
262
+ const onVerified = (outcome) => ctx.emit('verification:verified', outcome)
263
+ const onDivergent = (data) => ctx.emit('verification:divergent', data)
264
+ const onTimeout = (data) => ctx.emit('verification:timeout', data)
265
+ quorum.on('verified', onVerified)
266
+ quorum.on('divergent', onDivergent)
267
+ quorum.on('timeout', onTimeout)
268
+
269
+ // -- Inbound wire handling ----------------------------------------------
270
+ async function handleVerifyRequest(fromPubKey, msg) {
271
+ const { requestId, job } = msg
272
+
273
+ const access = ctx.registry.checkAccess(fromPubKey, accessResource, accessAction)
274
+ if (!access.allowed) {
275
+ ctx.emit('verification:verify-request-denied', { from: fromPubKey, requestId, reason: 'access_denied' })
276
+ await ctx.sendTo(fromPubKey, envelopeType, { kind: 'verify-response', requestId, error: 'access denied' }).catch((err) => {
277
+ log('mesh-verification:response-send-failed', { to: fromPubKey, requestId, error: err?.message || String(err) })
278
+ })
279
+ return
280
+ }
281
+
282
+ if (typeof executeFn !== 'function') {
283
+ ctx.emit('verification:verify-request-denied', { from: fromPubKey, requestId, reason: 'no_executor' })
284
+ await ctx.sendTo(fromPubKey, envelopeType, { kind: 'verify-response', requestId, error: 'verifier not configured to execute jobs' }).catch((err) => {
285
+ log('mesh-verification:response-send-failed', { to: fromPubKey, requestId, error: err?.message || String(err) })
286
+ })
287
+ return
288
+ }
289
+
290
+ let response
291
+ try {
292
+ const result = await executeFn(job)
293
+ response = { kind: 'verify-response', requestId, result }
294
+ } catch (err) {
295
+ response = { kind: 'verify-response', requestId, error: err?.message || String(err) }
296
+ }
297
+
298
+ try {
299
+ await ctx.sendTo(fromPubKey, envelopeType, response)
300
+ ctx.emit('verification:verify-served', { from: fromPubKey, requestId, ok: !response.error })
301
+ } catch (err) {
302
+ log('mesh-verification:response-send-failed', { to: fromPubKey, requestId, error: err?.message || String(err) })
303
+ }
304
+ }
305
+
306
+ function handleVerifyResponse(msg) {
307
+ const pending = pendingDispatches.get(msg.requestId)
308
+ if (!pending) return // already resolved (timed out or answered) -- ignore
309
+ pendingDispatches.delete(msg.requestId)
310
+ clearTimeout(pending.timer)
311
+ if (msg.error) {
312
+ pending.reject(new Error(msg.error))
313
+ } else {
314
+ pending.resolve(msg.result)
315
+ }
316
+ }
317
+
318
+ const unsubscribe = ctx.onIncomingData(envelopeType, (fromPubKey, msg) => {
319
+ if (!msg || typeof msg.kind !== 'string') return
320
+ if (msg.kind === 'verify-request') {
321
+ handleVerifyRequest(fromPubKey, msg).catch((err) => {
322
+ log('mesh-verification:request-handling-failed', { from: fromPubKey, requestId: msg.requestId, error: err?.message || String(err) })
323
+ })
324
+ } else if (msg.kind === 'verify-response') {
325
+ handleVerifyResponse(msg)
326
+ }
327
+ })
328
+
329
+ const api = {
330
+ /**
331
+ * @param {object} job
332
+ * @param {object} [opts]
333
+ * @param {string[]} [opts.verifiers]
334
+ * @param {string} [opts.verifyLevel]
335
+ * @returns {Promise<{result: *, confidence: number, attestations: import('./peer-verification.mjs').Attestation[]}>}
336
+ */
337
+ submitVerified: (job, submitOpts) => quorum.submitVerified(job, submitOpts),
338
+
339
+ /** @param {object} policy */
340
+ setPolicy: (policy) => quorum.setPolicy(policy),
341
+ }
342
+
343
+ return {
344
+ api,
345
+ teardown() {
346
+ quorum.off('verified', onVerified)
347
+ quorum.off('divergent', onDivergent)
348
+ quorum.off('timeout', onTimeout)
349
+ unsubscribe()
350
+ for (const pending of pendingDispatches.values()) {
351
+ clearTimeout(pending.timer)
352
+ pending.reject(new Error('mesh-verification: service torn down while a dispatch was still in flight'))
353
+ }
354
+ pendingDispatches.clear()
355
+ },
356
+ }
357
+ },
358
+ }
359
+ }
360
+
361
+ export {
362
+ DEFAULT_VERIFICATION_ENVELOPE_TYPE,
363
+ DEFAULT_DISPATCH_TIMEOUT_MS,
364
+ DEFAULT_ACCESS_RESOURCE,
365
+ DEFAULT_ACCESS_ACTION,
366
+ DEFAULT_TRUST_THRESHOLD,
367
+ }