@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
@@ -0,0 +1,363 @@
1
+ /**
2
+ * manifest-sync.mjs -- Phase F of the mesh-native-services plan
3
+ * ("Cross-peer manifest CRDT sync"): converts a `CloudStorageBackend`'s
4
+ * per-bucket manifest (Phase B, an `LWWMap` persisted only via
5
+ * `IndexedDBSyncStorage`, purely local) into a `MeshSyncEngine`
6
+ * (`@johnhenry/browsermesh-sync`) `SyncDocument`, so it can actually merge
7
+ * with other peers' copies of the same bucket's manifest over the mesh.
8
+ *
9
+ * Built as a `MeshService` (Phase C, `mesh-service.mjs`), following
10
+ * `createGrantLogService()` (`grant-log.mjs`, Phase D) as the closest
11
+ * existing precedent for "a `MeshService` that wraps a CRDT-synced
12
+ * document" -- wire payloads travel over `ctx.onIncomingData()`/
13
+ * `ctx.sendTo()`, filtered by `envelope.type`, exactly like
14
+ * `mesh-sync.mjs`/`grant-log.mjs` already both do.
15
+ *
16
+ * ---------------------------------------------------------------------------
17
+ * THE CORE DESIGN CONSTRAINT (read this before touching the merge path):
18
+ *
19
+ * A peer must NEVER blindly apply a remotely-received manifest mutation.
20
+ * `MeshSyncEngine.merge()` (`browsermesh-sync/src/sync.mjs`) has no concept
21
+ * of trust at all -- it just calls `doc.crdt.merge(remoteCrdt)` on whatever
22
+ * `LWWMap` JSON it's handed. So the ACL gate cannot live inside
23
+ * `MeshSyncEngine`; it has to live in THIS file, one layer above, applied to
24
+ * the wire payload BEFORE it is ever handed to `engine.merge()` or to
25
+ * `CloudStorageBackend.mergeManifestEntries()`.
26
+ *
27
+ * The wire format makes this tractable: `LWWMap.toJSON()` (and therefore
28
+ * `MeshSyncEngine.prepareSyncPayload()`'s `crdt` field) is
29
+ * `{entries: {key: {value, timestamp, nodeId, tombstone}}}` -- i.e. every
30
+ * single key's register carries its own `nodeId`, the exact write-attribution
31
+ * field `CloudStorageBackend` already sets to the *local peer's own identity*
32
+ * when it puts/deletes a key (see that file's constructor doc comment for
33
+ * why `nodeId` must be `peerNode.podId`, not the random-UUID default, for
34
+ * this integration to work at all). That per-key `nodeId` is the "implied
35
+ * writer" the plan's design section refers to.
36
+ *
37
+ * The approach taken here (one of the two the plan's own brief anticipated):
38
+ * on receipt of a remote sync envelope, walk `payload.crdt.entries` BEFORE
39
+ * calling any merge function, and for each entry independently check
40
+ * `ctx.registry.checkAccess(entry.nodeId, 's3:<bucketId>', 'write')`. Any
41
+ * entry whose implied writer fails that check is dropped from a *sanitized
42
+ * copy* of the payload; only the surviving, ACL-passed entries are ever
43
+ * handed to `engine.merge()` (to keep this service's own `MeshSyncEngine`
44
+ * copy consistent, e.g. for later re-broadcast to other watching peers) and
45
+ * to `cloudStorageBackend.mergeManifestEntries()` (the actual persisted
46
+ * manifest every `get`/`list`/`head` op reads from). A key with NO surviving
47
+ * entries after filtering is a no-op merge -- nothing reaches either the
48
+ * engine or the backend for it. This is "merge into a scratch copy and only
49
+ * accept per-key entries whose implied writer passes the check", applied at
50
+ * the wire-payload layer rather than inside the CRDT itself, so `LWWMap`
51
+ * needs zero changes and stays exactly as trust-agnostic as every other CRDT
52
+ * in this family.
53
+ *
54
+ * Ordering, stated explicitly because it is the single most important
55
+ * property of this file: the ACL check ALWAYS runs before ANY byte of a
56
+ * remote entry touches `doc.crdt` or `CloudStorageBackend`'s manifest. There
57
+ * is no code path where an unauthorized entry is merged first and evicted
58
+ * later -- filtering happens on the plain-JSON wire payload, strictly prior
59
+ * to constructing/merging any `LWWMap` instance from it.
60
+ *
61
+ * Known, deliberate limitation of this gate (distinct from the LWW
62
+ * limitation below): manifest entries are NOT cryptographically signed the
63
+ * way `GrantLog` records are (Phase D) -- `nodeId` is a plain, unauthenticated
64
+ * string inside the LWW register. The defense this gate provides is against
65
+ * a peer acting through its own real, connection-authenticated identity
66
+ * (`ctx.onIncomingData()`'s `fromPubKey`, established at session/transport
67
+ * level, the same trust boundary every other `MeshService` in this family
68
+ * relies on) attempting to write manifest keys it was never granted access
69
+ * to -- checked here by requiring `entry.nodeId === fromPubKey` in addition
70
+ * to the ACL check itself, so a peer cannot claim to be relaying an
71
+ * authorized third party's write it never actually received (there is no
72
+ * multi-hop relay/gossip trust chain in this phase for that claim to ride
73
+ * on). It does NOT add a cryptographic proof that a given LWW entry was
74
+ * really authored by the identity it claims -- that would require signing
75
+ * manifest entries the way GrantLog signs grant records, which the plan does
76
+ * not call for in this phase and is not implemented here.
77
+ *
78
+ * ---------------------------------------------------------------------------
79
+ * DOCUMENTED KNOWN LIMITATION -- LWW conflict resolution (matches the plan's
80
+ * Design Decisions section and Phase B's manifest doc comment, restated here
81
+ * because this is the phase that actually makes it observable cross-peer):
82
+ *
83
+ * `LWWMap` resolves conflicts at whole-value granularity using
84
+ * CALLER-SUPPLIED timestamps, with a lexicographic-`nodeId` tiebreak on an
85
+ * EXACT timestamp tie (`LWWRegister.merge()`: higher timestamp wins; on a
86
+ * tie, the register whose `nodeId` string sorts greater wins). There is no
87
+ * server-clock arbitration, no per-field merge, and no surfaced conflict --
88
+ * two peers concurrently writing different content to the SAME key resolve
89
+ * to ONE SILENT WINNER, chosen only by whichever combination of
90
+ * (timestamp, nodeId) compares greater. This mirrors un-versioned S3's own
91
+ * real default behavior (plain last-write-wins, no automatic versioning) and
92
+ * is an accepted, stated limitation, not a bug to fix in this phase -- see
93
+ * `test/manifest-sync.test.mjs`'s dedicated test demonstrating this exact,
94
+ * deterministic (but not "correct" -- there is no correct answer here)
95
+ * outcome.
96
+ *
97
+ * ---------------------------------------------------------------------------
98
+ * Observability events (`ctx.emit()`, Phase 1 of the mesh-KV-and-
99
+ * observability plan -- see `mesh-service.mjs`'s module doc comment for the
100
+ * full convention this follows). Four curated events, not a mechanical
101
+ * conversion of this file's `onLog` calls:
102
+ *
103
+ * - `manifest-sync:entry-merged` `{bucketId, from, keys}` -- at least one
104
+ * remote manifest entry passed the ACL/attribution gate and was merged
105
+ * into both this service's own engine copy and the durable backend.
106
+ * - `manifest-sync:write-rejected` `{bucketId, from, key, reason}` -- one
107
+ * remote entry was dropped BEFORE merge (`reason` is
108
+ * `'attribution-mismatch'` or `'unauthorized'`); this is the gate this
109
+ * whole file exists to enforce, so its rejections are exactly the kind
110
+ * of security-relevant transition worth a dashboard being able to see.
111
+ * - `manifest-sync:watching` `{bucketId, pubKey}` -- `api.watch()` started
112
+ * broadcasting this bucket's changes to `pubKey`.
113
+ * - `manifest-sync:unwatching` `{bucketId, pubKey}` -- `api.unwatch()`
114
+ * stopped broadcasting to `pubKey`.
115
+ *
116
+ * No browser-only imports at module level.
117
+ */
118
+
119
+ import { MeshSyncEngine, InMemorySyncStorage } from '@johnhenry/browsermesh-sync'
120
+ import { LWWMap } from '@johnhenry/browsermesh-primitives'
121
+
122
+ /** Default `envelope.type` used to route manifest-sync payloads on the shared `onIncomingData()` bus. */
123
+ const DEFAULT_ENVELOPE_TYPE = 'manifest-sync'
124
+
125
+ /** @param {string} bucketId @returns {string} */
126
+ function docIdFor(bucketId) {
127
+ return `manifest:${bucketId}`
128
+ }
129
+
130
+ /** @param {string} bucketId @returns {string} The scope-grammar resource string GrantLog/PeerRegistry expect (`s3:<bucketId>`). */
131
+ function resourceFor(bucketId) {
132
+ return `s3:${bucketId}`
133
+ }
134
+
135
+ // ---------------------------------------------------------------------------
136
+ // createManifestSyncService
137
+ // ---------------------------------------------------------------------------
138
+
139
+ /**
140
+ * Build a `MeshService` descriptor (`mesh-service.mjs`, Phase C) that wires
141
+ * a `CloudStorageBackend`'s manifest into a per-bucket `MeshSyncEngine`
142
+ * `SyncDocument` (CRDT type `'lww-map'`), gating every inbound remote
143
+ * mutation on `ctx.registry.checkAccess(writerPubKey, 's3:<bucketId>',
144
+ * 'write')` before it ever reaches a merge -- see this file's module doc
145
+ * comment for the full design.
146
+ *
147
+ * The `MeshSyncEngine` this creates uses in-memory storage: durability is
148
+ * already `CloudStorageBackend`'s job (its manifest is persisted via its own
149
+ * `IndexedDBSyncStorage`, Phase B); this service's engine is purely a
150
+ * sync/broadcast vehicle mirroring that already-durable state, not a second
151
+ * persistence layer for it.
152
+ *
153
+ * @param {object} opts
154
+ * @param {string} opts.bucketId - Bucket identifier. The synced document id
155
+ * is `manifest:<bucketId>`; the ACL resource checked is `s3:<bucketId>`.
156
+ * @param {import('./cloud-storage-backend.mjs').CloudStorageBackend} opts.cloudStorageBackend
157
+ * MUST have been constructed with `nodeId` equal to the attaching peer's
158
+ * own identity (`peerNode.podId`) -- see `cloud-storage-backend.mjs`'s
159
+ * constructor doc comment. Local writes made through this backend (its
160
+ * `put`/`delete` ops) are what gets broadcast to watched peers; remote,
161
+ * ACL-passed writes from other peers are merged back into it.
162
+ * @param {string} [opts.envelopeType='manifest-sync']
163
+ * @param {(api: {bucketId: string, docId: string, watch: (pubKey: string) => void,
164
+ * unwatch: (pubKey: string) => void, syncWith: (pubKey: string) => Promise<void>}) => void} [opts.onReady]
165
+ * Invoked synchronously inside `attach()` with the service's public API --
166
+ * same `onReady` workaround `createGrantLogService()` uses (see that
167
+ * file's doc comment) for getting a live handle back through
168
+ * `attachService()`, which does not await `attach()`'s return value. New
169
+ * code should prefer the `{teardown, api}` return shape this descriptor
170
+ * also provides (PR #83) over `onReady` where both are convenient.
171
+ * @param {Function} [opts.onLog]
172
+ * @returns {import('./mesh-service.mjs').MeshService}
173
+ */
174
+ export function createManifestSyncService({ bucketId, cloudStorageBackend, envelopeType = DEFAULT_ENVELOPE_TYPE, onReady, onLog } = {}) {
175
+ if (!bucketId || typeof bucketId !== 'string') {
176
+ throw new Error('createManifestSyncService: bucketId is required and must be a non-empty string')
177
+ }
178
+ if (!cloudStorageBackend || typeof cloudStorageBackend.getManifestSnapshot !== 'function') {
179
+ throw new Error('createManifestSyncService: cloudStorageBackend is required (a CloudStorageBackend instance)')
180
+ }
181
+
182
+ const docId = docIdFor(bucketId)
183
+ const resource = resourceFor(bucketId)
184
+ const log = onLog || (() => {})
185
+
186
+ return {
187
+ name: `manifest-sync:${bucketId}`,
188
+
189
+ attach(peerNode, ctx) {
190
+ const engine = new MeshSyncEngine({
191
+ nodeId: peerNode.podId,
192
+ storage: new InMemorySyncStorage(),
193
+ onLog: log,
194
+ })
195
+ engine.create(docId, 'lww-map', { owner: peerNode.podId })
196
+
197
+ /** @type {Set<string>} pubKeys this service broadcasts local/merged changes to. */
198
+ const watchTargets = new Set()
199
+
200
+ /**
201
+ * Refresh the engine's copy of the manifest CRDT from
202
+ * `cloudStorageBackend`'s current (persisted) state. Idempotent --
203
+ * cheap enough to call before every operation that depends on the
204
+ * engine's copy actually reflecting the backend's latest state,
205
+ * rather than tracking a separate "have we seeded yet" flag that
206
+ * could drift after a `mergeManifestEntries()` call reassigns the
207
+ * backend's internal `LWWMap` instance.
208
+ * @returns {Promise<void>}
209
+ */
210
+ async function refreshEngineFromBackend() {
211
+ const snapshot = await cloudStorageBackend.getManifestSnapshot()
212
+ engine.get(docId).crdt = LWWMap.fromJSON(snapshot)
213
+ }
214
+
215
+ // Local writes (this peer's own put()/delete() through
216
+ // `cloudStorageBackend`) -- mirror the backend's now-current state
217
+ // into the engine's copy and bump/notify so watch()ing peers receive
218
+ // it. The actual mutation already happened in the backend; this
219
+ // handler's job is purely "make the sync engine aware a change
220
+ // happened", not to decide whether it was authorized (a LOCAL write
221
+ // is authorized by definition -- it's this peer acting as itself).
222
+ const unsubscribeLocal = cloudStorageBackend.onManifestChange(() => {
223
+ refreshEngineFromBackend()
224
+ .then(() => {
225
+ // The mutation is already applied (shared via the snapshot
226
+ // refresh above); this update() call's callback is a no-op --
227
+ // its only purpose is to bump the document's vector clock and
228
+ // fire MeshSyncEngine's subscriber notification, which the
229
+ // watch() broadcast below listens for.
230
+ engine.update(docId, () => {})
231
+ })
232
+ .catch((err) => {
233
+ log('manifest-sync:local-refresh-failed', { bucketId, error: err?.message || String(err) })
234
+ })
235
+ })
236
+
237
+ // Broadcast to every watched peer whenever the engine's document
238
+ // changes, whether from a local write (above) or an accepted remote
239
+ // merge (below) -- the latter is what makes multi-hop propagation
240
+ // possible (a peer that merges an authorized remote write and is
241
+ // itself watched by a third peer forwards it onward automatically).
242
+ const unsubscribeBroadcast = engine.subscribe(docId, () => {
243
+ for (const pubKey of watchTargets) {
244
+ syncWith(pubKey).catch((err) => {
245
+ log('manifest-sync:broadcast-failed', { bucketId, to: pubKey, error: err?.message || String(err) })
246
+ })
247
+ }
248
+ })
249
+
250
+ // Remote input -- the ONLY path untrusted data enters this service.
251
+ // See the module doc comment for why filtering happens here, on the
252
+ // raw wire payload, strictly before any merge.
253
+ const unsubscribeIncoming = ctx.onIncomingData(envelopeType, (fromPubKey, data) => {
254
+ if (!data || data.docId !== docId || !data.payload || data.payload.type !== 'lww-map') return
255
+
256
+ handleIncoming(fromPubKey, data.payload).catch((err) => {
257
+ log('manifest-sync:merge-failed', { bucketId, from: fromPubKey, error: err?.message || String(err) })
258
+ })
259
+ })
260
+
261
+ /**
262
+ * @param {string} fromPubKey
263
+ * @param {object} payload - `MeshSyncEngine.prepareSyncPayload()` shape: `{id, type, crdt, version}`.
264
+ */
265
+ async function handleIncoming(fromPubKey, payload) {
266
+ const rawEntries = payload?.crdt?.entries
267
+ if (!rawEntries || typeof rawEntries !== 'object') return
268
+
269
+ /** @type {Record<string, object>} */
270
+ const sanitizedEntries = {}
271
+ for (const [key, regState] of Object.entries(rawEntries)) {
272
+ if (!regState || typeof regState !== 'object') continue
273
+ const writer = regState.nodeId
274
+
275
+ // The implied writer must equal the connection-authenticated
276
+ // sender -- a peer cannot claim to relay a write it did not
277
+ // itself send (no multi-hop trust chain exists in this phase to
278
+ // justify accepting a third party's attribution from a
279
+ // non-matching sender). See the module doc comment's "Known,
280
+ // deliberate limitation of this gate" section.
281
+ if (writer !== fromPubKey) {
282
+ log('manifest-sync:reject-attribution-mismatch', { bucketId, key, from: fromPubKey, claimedWriter: writer })
283
+ ctx.emit('manifest-sync:write-rejected', { bucketId, from: fromPubKey, key, reason: 'attribution-mismatch' })
284
+ continue
285
+ }
286
+
287
+ const check = ctx.registry.checkAccess(writer, resource, 'write')
288
+ if (!check.allowed) {
289
+ log('manifest-sync:reject-unauthorized-write', {
290
+ bucketId, key, from: fromPubKey, reason: check.reason,
291
+ })
292
+ ctx.emit('manifest-sync:write-rejected', { bucketId, from: fromPubKey, key, reason: 'unauthorized' })
293
+ continue
294
+ }
295
+
296
+ sanitizedEntries[key] = regState
297
+ }
298
+
299
+ const mergedKeys = Object.keys(sanitizedEntries)
300
+ if (mergedKeys.length === 0) return
301
+
302
+ // Make sure the engine's copy reflects the backend's latest
303
+ // persisted state before merging remote input in, so the LWW
304
+ // comparison for each key is against the real current value, not a
305
+ // stale/empty engine-only copy.
306
+ await refreshEngineFromBackend()
307
+
308
+ const sanitizedPayload = { ...payload, crdt: { entries: sanitizedEntries } }
309
+ // Keep this service's own engine copy consistent (for correct
310
+ // future re-broadcast/vector-clock bookkeeping) using ONLY the
311
+ // sanitized subset -- never the raw, unfiltered payload.
312
+ engine.merge(docId, sanitizedPayload)
313
+
314
+ // Persist into the actual source of truth every get/list/head op
315
+ // reads from.
316
+ await cloudStorageBackend.mergeManifestEntries({ entries: sanitizedEntries })
317
+
318
+ ctx.emit('manifest-sync:entry-merged', { bucketId, from: fromPubKey, keys: mergedKeys })
319
+ }
320
+
321
+ /**
322
+ * Send this bucket's current manifest state to one peer. Safe to call
323
+ * repeatedly -- CRDT merge on the receiving end is idempotent.
324
+ * @param {string} pubKey
325
+ * @returns {Promise<void>}
326
+ */
327
+ async function syncWith(pubKey) {
328
+ await refreshEngineFromBackend()
329
+ const payload = engine.prepareSyncPayload(docId)
330
+ await ctx.sendTo(pubKey, envelopeType, { docId, payload })
331
+ }
332
+
333
+ const api = {
334
+ bucketId,
335
+ docId,
336
+ /** Start broadcasting local/merged manifest changes to `pubKey`. */
337
+ watch(pubKey) {
338
+ watchTargets.add(pubKey)
339
+ ctx.emit('manifest-sync:watching', { bucketId, pubKey })
340
+ },
341
+ /** Stop broadcasting to `pubKey`. */
342
+ unwatch(pubKey) {
343
+ watchTargets.delete(pubKey)
344
+ ctx.emit('manifest-sync:unwatching', { bucketId, pubKey })
345
+ },
346
+ syncWith,
347
+ }
348
+
349
+ if (typeof onReady === 'function') onReady(api)
350
+
351
+ return {
352
+ api,
353
+ teardown() {
354
+ unsubscribeLocal()
355
+ unsubscribeBroadcast()
356
+ unsubscribeIncoming()
357
+ },
358
+ }
359
+ },
360
+ }
361
+ }
362
+
363
+ export { DEFAULT_ENVELOPE_TYPE }