@johnhenry/browsermesh-apps 0.2.0 → 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 (41) hide show
  1. package/README.md +232 -1
  2. package/package.json +2 -2
  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/grant-log.mjs +840 -0
  9. package/src/index.mjs +25 -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/peer-session.mjs +0 -937
@@ -0,0 +1,673 @@
1
+ /**
2
+ * mesh-kv.mjs -- Phase 3 of the mesh-KV-and-observability plan
3
+ * (`mesh-kv-and-observability.md`, "Design decisions", "The KV store is
4
+ * deliberately smaller than CloudStorage"): a mesh-native, replicated
5
+ * key-value store. `LWWMap`-backed (the same CRDT `cloud-storage.mjs`'s
6
+ * manifest already uses), ACL-gated via `createGrantLogService()`
7
+ * (`grant-log.mjs`, reused directly, unmodified) under
8
+ * `kv:<storeId>:{read,write,admin}` scopes -- NO chunking, NO
9
+ * content-addressing, NO encryption-at-rest. The plan is explicit that this
10
+ * is a deliberate scope cut, not an oversight: small, low-sensitivity shared
11
+ * state is the target use case (examples/docs needing a piece of shared
12
+ * mesh state to demonstrate with), not a CloudStorage replacement.
13
+ *
14
+ * ---------------------------------------------------------------------------
15
+ * RELATIONSHIP TO `manifest-sync.mjs` (read that file's module doc comment
16
+ * first -- this one assumes it):
17
+ *
18
+ * `manifest-sync.mjs` is the closest structural precedent, but it is NOT
19
+ * generic enough to reuse directly as a class: it is hard-wired to
20
+ * `CloudStorageBackend` as a SEPARATE, independently-durable data source it
21
+ * has to keep mirroring (`getManifestSnapshot()`/`onManifestChange()`/
22
+ * `mergeManifestEntries()`), because that backend's manifest is persisted
23
+ * via its own `IndexedDBSyncStorage` and encryption pipeline -- the
24
+ * `MeshSyncEngine` in that file is purely a sync/broadcast VEHICLE mirroring
25
+ * an already-durable, already-authoritative copy that lives elsewhere.
26
+ *
27
+ * This store has no such second source of truth: there is no chunk store, no
28
+ * encryption, no separate durable backend to mirror. The `MeshSyncEngine`'s
29
+ * own `LWWMap` (`InMemorySyncStorage`-backed, in-process) IS the store's
30
+ * authoritative state, directly. That single fact eliminates an entire
31
+ * category of code `manifest-sync.mjs` needs (no `refreshEngineFromBackend()`
32
+ * step, no "did the backend's mutation land before I broadcast" ordering
33
+ * concern, no separate on-change hook to bridge local writes into the
34
+ * engine -- `MeshSyncEngine.update()` already notifies subscribers itself,
35
+ * so this file's local `set()`/`delete()` calling `engine.update()` directly
36
+ * IS the local-write-triggers-broadcast path, with no bridging in between).
37
+ *
38
+ * What IS reused near-verbatim from `manifest-sync.mjs`, because the
39
+ * property being enforced is identical regardless of what the CRDT holds:
40
+ * the wire-payload-layer ACL gate. `MeshSyncEngine.merge()` has no concept
41
+ * of trust (see `manifest-sync.mjs`'s "THE CORE DESIGN CONSTRAINT"), so the
42
+ * gate lives here, one layer above, walking `payload.crdt.entries` BEFORE
43
+ * any byte reaches `engine.merge()`: each entry's `nodeId` (the implied
44
+ * writer, exactly the field `LWWRegister`/`LWWMap.toJSON()` already carries)
45
+ * must equal the connection-authenticated sender (`fromPubKey`, rejecting
46
+ * `attribution-mismatch` otherwise -- a peer cannot claim to relay a write it
47
+ * did not itself send, same limitation `manifest-sync.mjs` documents: no
48
+ * multi-hop relay/gossip trust chain exists in this phase either), AND that
49
+ * sender must pass `ctx.registry.checkAccess(writer, 'kv:<storeId>', 'write')`
50
+ * (rejecting `unauthorized` otherwise). Only entries that pass BOTH checks
51
+ * ever reach `engine.merge()`. A key with no surviving entries after
52
+ * filtering is a no-op for that merge call.
53
+ *
54
+ * `read`/`admin` scopes are NOT independently enforced by an ACL check
55
+ * anywhere in this file's push path -- exactly the same, already-accepted
56
+ * shape `cloud-storage.mjs`'s own module doc comment documents for its
57
+ * `read`/`list` scopes (see that file's "KNOWN LIMITATION" section): "read"
58
+ * access is enforced socially/administratively, by an admin choosing who to
59
+ * `watch()`/`grant()` in the first place, not by a per-message gate on the
60
+ * receiving side. `write` is the one scope with a real, always-on
61
+ * enforcement point (the merge gate above) because it is the one property a
62
+ * receiving peer MUST be able to verify unilaterally, from data it already
63
+ * has (its own registry), independent of which peers it has chosen to trust
64
+ * enough to watch.
65
+ *
66
+ * ---------------------------------------------------------------------------
67
+ * Two layers, mirroring `cloud-storage.mjs`'s own composition pattern
68
+ * (`createGrantLogService()` + a data-sync `MeshService`, composed by one
69
+ * higher-level class) rather than `cloud-storage.mjs`'s full four-service
70
+ * stack (no key-distribution, no chunk-replication -- there is no
71
+ * encryption key to distribute and no chunk to replicate):
72
+ *
73
+ * - `createMeshKvService()` -- the low-level `MeshService` descriptor
74
+ * (`mesh-service.mjs`, Phase C). Wire-compatible with being attached
75
+ * standalone (its `api` is `{storeId, docId, resource, get, set,
76
+ * delete, keys, watch, unwatch, syncWith}`), for a caller that wants the
77
+ * bare service the way `manifest-sync.test.mjs`/`grant-log.test.mjs`
78
+ * attach their services directly rather than through a wrapper class.
79
+ * - `MeshKv` -- the ergonomic wrapper class (this phase's answer to the
80
+ * plan's open question, see below), composing
81
+ * `createGrantLogService({resource: 'kv:<storeId>'})` +
82
+ * `createMeshKvService({storeId})`, mirroring exactly how `grant()`/
83
+ * `revoke()` in `cloud-storage.mjs` also drive `manifestSyncApi.watch()`/
84
+ * `unwatch()` and an immediate grant-log + data `syncWith()` (including
85
+ * the same documented retry-on-delay workaround for the same race: the
86
+ * recipient's `GrantLog.mergeRemote()` is not awaited by its own
87
+ * dispatch handler, so a data push sent immediately after
88
+ * `grantLogApi.syncWith()` can arrive and be ACL-checked before the
89
+ * recipient's registry has actually absorbed the grant -- see
90
+ * `cloud-storage.mjs`'s `grant()` for the identical comment, reused
91
+ * verbatim here because the failure mode is identical).
92
+ *
93
+ * ---------------------------------------------------------------------------
94
+ * PUBLIC API DECISION (the plan's own open question, "decide whether this
95
+ * needs a separate ergonomic wrapper class... or whether the composed
96
+ * service's own `api`... is already clean enough to use directly"):
97
+ *
98
+ * A thin wrapper class (`MeshKv`) was chosen, NOT because the bare
99
+ * `attachService()` handle's `api` is unclean, but because -- exactly as
100
+ * `cloud-storage.mjs`'s own doc comment argues for its four services --
101
+ * composing two independently-attached services (`createGrantLogService()` +
102
+ * `createMeshKvService()`) correctly requires wiring `grant()`/`revoke()` to
103
+ * also drive `watch()`/`unwatch()`/an immediate `syncWith()` with the
104
+ * documented retry, which is real, easy-to-get-wrong sequencing a caller
105
+ * should not need to reimplement themselves every time. A caller who truly
106
+ * wants the two bare services can still get them (`createMeshKvService()` is
107
+ * exported standalone, exactly like `createManifestSyncService()` is), but
108
+ * `MeshKv` is the documented, recommended entry point:
109
+ *
110
+ * import { MeshKv } from '@johnhenry/browsermesh-apps'
111
+ * const kv = new MeshKv({ store: 'my-store', node: peerNode })
112
+ * await kv.becomeAdmin()
113
+ * await kv.set('key', 'value')
114
+ * const value = await kv.get('key')
115
+ *
116
+ * Per the task brief, the calling convention deliberately has NO
117
+ * chunking-related concepts anywhere in this surface: `get`/`set`/`delete`/
118
+ * `keys` are the entire data-plane API.
119
+ *
120
+ * ---------------------------------------------------------------------------
121
+ * Observability events (`ctx.emit()`, Phase 1 of the mesh-KV-and-
122
+ * observability plan -- see `mesh-service.mjs`'s module doc comment for the
123
+ * full convention this follows). Five curated events on
124
+ * `createMeshKvService()`'s own `attachService()` handle (the SAME
125
+ * lower-level vocabulary `MeshKv` forwards, unchanged, onto its own
126
+ * `on()`/`onEvent()` -- unlike `cloud-storage.mjs`, this store is small
127
+ * enough that inventing a second, higher-level vocabulary on top would be
128
+ * pure duplication rather than genuine abstraction):
129
+ *
130
+ * - `mesh-kv:entry-set` `{storeId, from, key}` -- a key's live value
131
+ * changed, either from this peer's own `set()` (`from` = this peer's own
132
+ * podId) or from an authorized remote merge (`from` = the writer's
133
+ * podId).
134
+ * - `mesh-kv:entry-deleted` `{storeId, from, key}` -- a key was
135
+ * tombstoned, same "local or authorized remote" `from` convention as
136
+ * above.
137
+ * - `mesh-kv:write-rejected` `{storeId, from, key, reason}` -- one remote
138
+ * entry was dropped BEFORE merge (`reason` is `'attribution-mismatch'`
139
+ * or `'unauthorized'`), the exact security-relevant transition this
140
+ * file's ACL gate exists to enforce.
141
+ * - `mesh-kv:watching` `{storeId, pubKey}` -- `api.watch()` started
142
+ * broadcasting this store's changes to `pubKey`.
143
+ * - `mesh-kv:unwatching` `{storeId, pubKey}` -- `api.unwatch()` stopped.
144
+ *
145
+ * `grant-log:*` events (`grant-log:grant-applied`, etc.) are also available,
146
+ * unchanged, on `MeshKv`'s internal `GrantLog` `attachService()` handle, but
147
+ * are NOT forwarded onto `MeshKv`'s own `on()`/`onEvent()` -- a caller that
148
+ * wants those subscribes to `createGrantLogService()` directly, matching how
149
+ * `cloud-storage.mjs` also never forwards its four internal services' raw
150
+ * event vocabularies onto its own higher-level bus verbatim.
151
+ *
152
+ * No browser-only imports at module level.
153
+ */
154
+
155
+ import { MeshSyncEngine, InMemorySyncStorage } from '@johnhenry/browsermesh-sync'
156
+ import { attachService, createEventBus } from './mesh-service.mjs'
157
+ import { createGrantLogService } from './grant-log.mjs'
158
+
159
+ /** Default `envelope.type` used to route mesh-kv sync payloads on the shared `onIncomingData()` bus. */
160
+ const DEFAULT_ENVELOPE_TYPE = 'mesh-kv'
161
+
162
+ /** Bare action-scopes `MeshKv.becomeAdmin()` self-grants beyond the `admin` scope `GrantLog.bootstrapAdmin()` itself grants. */
163
+ const SELF_GRANT_ACTIONS = ['read', 'write']
164
+
165
+ /** @param {string} storeId @returns {string} */
166
+ function docIdFor(storeId) {
167
+ return `kv:${storeId}`
168
+ }
169
+
170
+ /** @param {string} storeId @returns {string} The scope-grammar resource string GrantLog/PeerRegistry expect (`kv:<storeId>`). */
171
+ function resourceFor(storeId) {
172
+ return `kv:${storeId}`
173
+ }
174
+
175
+ // ---------------------------------------------------------------------------
176
+ // createMeshKvService -- the low-level MeshService descriptor
177
+ // ---------------------------------------------------------------------------
178
+
179
+ /**
180
+ * Build a `MeshService` descriptor (`mesh-service.mjs`, Phase C) that
181
+ * replicates one key-value store's `LWWMap` across peers via a per-store
182
+ * `MeshSyncEngine` `SyncDocument` (CRDT type `'lww-map'`), gating every
183
+ * inbound remote mutation on `ctx.registry.checkAccess(writerPubKey,
184
+ * 'kv:<storeId>', 'write')` before it ever reaches a merge -- see this
185
+ * file's module doc comment for the full design.
186
+ *
187
+ * Unlike `createManifestSyncService()`, this service's `MeshSyncEngine` copy
188
+ * IS the store's authoritative data -- there is no separate backend to keep
189
+ * mirrored, so local `set()`/`delete()` write straight into the engine and
190
+ * `engine.update()`'s own subscriber notification is what drives the
191
+ * broadcast-to-watchers path.
192
+ *
193
+ * @param {object} opts
194
+ * @param {string} opts.storeId - Store identifier. The synced document id
195
+ * and the ACL resource checked are both `kv:<storeId>`.
196
+ * @param {string} [opts.envelopeType='mesh-kv']
197
+ * @param {(api: {storeId: string, docId: string, resource: string,
198
+ * get: (key: string) => *, set: (key: string, value: *) => void,
199
+ * delete: (key: string) => void, keys: (prefix?: string) => string[],
200
+ * watch: (pubKey: string) => void, unwatch: (pubKey: string) => void,
201
+ * syncWith: (pubKey: string) => Promise<void>}) => void} [opts.onReady]
202
+ * Invoked synchronously inside `attach()` with the service's public API --
203
+ * same `onReady` workaround `createGrantLogService()`/
204
+ * `createManifestSyncService()` use (see those files' doc comments).
205
+ * New code should prefer the `{teardown, api}` return shape this
206
+ * descriptor also provides.
207
+ * @param {Function} [opts.onLog]
208
+ * @returns {import('./mesh-service.mjs').MeshService}
209
+ */
210
+ export function createMeshKvService({ storeId, envelopeType = DEFAULT_ENVELOPE_TYPE, onReady, onLog } = {}) {
211
+ if (!storeId || typeof storeId !== 'string') {
212
+ throw new Error('createMeshKvService: storeId is required and must be a non-empty string')
213
+ }
214
+
215
+ const docId = docIdFor(storeId)
216
+ const resource = resourceFor(storeId)
217
+ const log = onLog || (() => {})
218
+
219
+ return {
220
+ name: `mesh-kv:${storeId}`,
221
+
222
+ attach(peerNode, ctx) {
223
+ const engine = new MeshSyncEngine({
224
+ nodeId: peerNode.podId,
225
+ storage: new InMemorySyncStorage(),
226
+ onLog: log,
227
+ })
228
+ engine.create(docId, 'lww-map', { owner: peerNode.podId })
229
+
230
+ /** @type {Set<string>} pubKeys this service broadcasts local/merged changes to. */
231
+ const watchTargets = new Set()
232
+
233
+ /** @type {number} monotonic clock backing local write timestamps -- see #nextTimestamp() below. */
234
+ let clock = 0
235
+
236
+ /**
237
+ * A monotonic millisecond-ish clock for local `set()`/`delete()`
238
+ * timestamps, duplicated from `cloud-storage-backend.mjs`'s own
239
+ * `#nextTimestamp()` (same problem, same fix): plain `Date.now()` can
240
+ * return the same value for two writes issued in the same
241
+ * millisecond, and `LWWRegister.set()` only accepts a same-timestamp
242
+ * write when the new writer's nodeId sorts strictly higher than the
243
+ * current one -- so two same-millisecond LOCAL writes (e.g. `set()`
244
+ * immediately followed by `delete()`, very possible under `node
245
+ * --test`'s synchronous test bodies) would otherwise be silently
246
+ * dropped, since both carry this same peer's own `nodeId`. Not a
247
+ * substitute for the plan's documented caller-timestamp limitation
248
+ * (still a real limitation across peers/instances) -- only ensures
249
+ * THIS instance's own sequential writes are always strictly ordered.
250
+ * @returns {number}
251
+ */
252
+ function nextTimestamp() {
253
+ const now = Date.now()
254
+ clock = now > clock ? now : clock + 1
255
+ return clock
256
+ }
257
+
258
+ /**
259
+ * @param {string} key
260
+ * @param {boolean} tombstone
261
+ * @param {string} from
262
+ */
263
+ function emitEntryChange(key, tombstone, from) {
264
+ ctx.emit(tombstone ? 'mesh-kv:entry-deleted' : 'mesh-kv:entry-set', { storeId, from, key })
265
+ }
266
+
267
+ /**
268
+ * Send this store's current state to one peer. Safe to call
269
+ * repeatedly -- CRDT merge on the receiving end is idempotent.
270
+ * @param {string} pubKey
271
+ * @returns {Promise<void>}
272
+ */
273
+ async function syncWith(pubKey) {
274
+ const payload = engine.prepareSyncPayload(docId)
275
+ await ctx.sendTo(pubKey, envelopeType, { docId, payload })
276
+ }
277
+
278
+ // Broadcast to every watched peer whenever the engine's document
279
+ // changes, whether from a local write (below) or an accepted remote
280
+ // merge -- the latter is what makes multi-hop propagation possible.
281
+ const unsubscribeBroadcast = engine.subscribe(docId, () => {
282
+ for (const pubKey of watchTargets) {
283
+ syncWith(pubKey).catch((err) => {
284
+ log('mesh-kv:broadcast-failed', { storeId, to: pubKey, error: err?.message || String(err) })
285
+ })
286
+ }
287
+ })
288
+
289
+ // Remote input -- the ONLY path untrusted data enters this service.
290
+ // See the module doc comment for why filtering happens here, on the
291
+ // raw wire payload, strictly before any merge.
292
+ const unsubscribeIncoming = ctx.onIncomingData(envelopeType, (fromPubKey, data) => {
293
+ if (!data || data.docId !== docId || !data.payload || data.payload.type !== 'lww-map') return
294
+ handleIncoming(fromPubKey, data.payload).catch((err) => {
295
+ log('mesh-kv:merge-failed', { storeId, from: fromPubKey, error: err?.message || String(err) })
296
+ })
297
+ })
298
+
299
+ /**
300
+ * @param {string} fromPubKey
301
+ * @param {object} payload - `MeshSyncEngine.prepareSyncPayload()` shape: `{id, type, crdt, version}`.
302
+ */
303
+ async function handleIncoming(fromPubKey, payload) {
304
+ const rawEntries = payload?.crdt?.entries
305
+ if (!rawEntries || typeof rawEntries !== 'object') return
306
+
307
+ /** @type {Record<string, object>} */
308
+ const sanitizedEntries = {}
309
+ for (const [key, regState] of Object.entries(rawEntries)) {
310
+ if (!regState || typeof regState !== 'object') continue
311
+ const writer = regState.nodeId
312
+
313
+ // The implied writer must equal the connection-authenticated
314
+ // sender -- a peer cannot claim to relay a write it did not
315
+ // itself send. See the module doc comment's ACL-gate section.
316
+ if (writer !== fromPubKey) {
317
+ log('mesh-kv:reject-attribution-mismatch', { storeId, key, from: fromPubKey, claimedWriter: writer })
318
+ ctx.emit('mesh-kv:write-rejected', { storeId, from: fromPubKey, key, reason: 'attribution-mismatch' })
319
+ continue
320
+ }
321
+
322
+ const check = ctx.registry.checkAccess(writer, resource, 'write')
323
+ if (!check.allowed) {
324
+ log('mesh-kv:reject-unauthorized-write', { storeId, key, from: fromPubKey, reason: check.reason })
325
+ ctx.emit('mesh-kv:write-rejected', { storeId, from: fromPubKey, key, reason: 'unauthorized' })
326
+ continue
327
+ }
328
+
329
+ sanitizedEntries[key] = regState
330
+ }
331
+
332
+ const mergedKeys = Object.keys(sanitizedEntries)
333
+ if (mergedKeys.length === 0) return
334
+
335
+ const sanitizedPayload = { ...payload, crdt: { entries: sanitizedEntries } }
336
+ engine.merge(docId, sanitizedPayload)
337
+
338
+ for (const key of mergedKeys) {
339
+ emitEntryChange(key, Boolean(sanitizedEntries[key].tombstone), fromPubKey)
340
+ }
341
+ }
342
+
343
+ const api = {
344
+ storeId,
345
+ docId,
346
+ resource,
347
+
348
+ /** @param {string} key @returns {*} The live value, or `undefined` if missing/deleted. */
349
+ get(key) {
350
+ return engine.get(docId).crdt.get(key)
351
+ },
352
+
353
+ /** @param {string} key @param {*} value */
354
+ set(key, value) {
355
+ engine.update(docId, (crdt) => crdt.set(key, value, nextTimestamp(), peerNode.podId))
356
+ emitEntryChange(key, false, peerNode.podId)
357
+ },
358
+
359
+ /** @param {string} key */
360
+ delete(key) {
361
+ engine.update(docId, (crdt) => crdt.delete(key, nextTimestamp(), peerNode.podId))
362
+ emitEntryChange(key, true, peerNode.podId)
363
+ },
364
+
365
+ /** @param {string} [prefix=''] @returns {string[]} Live keys, optionally filtered by prefix. */
366
+ keys(prefix = '') {
367
+ return [...engine.get(docId).crdt.keys()].filter((key) => key.startsWith(prefix))
368
+ },
369
+
370
+ /** Start broadcasting local/merged store changes to `pubKey`. */
371
+ watch(pubKey) {
372
+ watchTargets.add(pubKey)
373
+ ctx.emit('mesh-kv:watching', { storeId, pubKey })
374
+ },
375
+
376
+ /** Stop broadcasting to `pubKey`. */
377
+ unwatch(pubKey) {
378
+ watchTargets.delete(pubKey)
379
+ ctx.emit('mesh-kv:unwatching', { storeId, pubKey })
380
+ },
381
+
382
+ syncWith,
383
+ }
384
+
385
+ if (typeof onReady === 'function') onReady(api)
386
+
387
+ return {
388
+ api,
389
+ teardown() {
390
+ unsubscribeBroadcast()
391
+ unsubscribeIncoming()
392
+ },
393
+ }
394
+ },
395
+ }
396
+ }
397
+
398
+ // ---------------------------------------------------------------------------
399
+ // MeshKv -- the ergonomic wrapper class
400
+ // ---------------------------------------------------------------------------
401
+
402
+ /**
403
+ * The ergonomic, small mesh-native key-value store. See this file's module
404
+ * doc comment for the full design writeup and the "PUBLIC API DECISION"
405
+ * section for why this wrapper exists.
406
+ */
407
+ export class MeshKv {
408
+ /** @type {string} */
409
+ #store
410
+
411
+ /** @type {string} */
412
+ #resource
413
+
414
+ /** @type {object} Duck-typed `{podId, wallet, registry, sendTo, onIncomingData}`, same minimal surface `cloud-storage.mjs`'s `CloudStorage` requires. */
415
+ #node
416
+
417
+ /** @type {{resource: string, grant: Function, revoke: Function, bootstrapAdmin: Function, syncWith: Function, effective: Function, toJSON: Function}} set synchronously during construction */
418
+ #grantLogApi
419
+
420
+ /** @type {{storeId: string, docId: string, resource: string, get: Function, set: Function, delete: Function, keys: Function, watch: Function, unwatch: Function, syncWith: Function}} */
421
+ #kvApi
422
+
423
+ /** @type {Array<{name: string, backendScheme: string|null, api: object|undefined, teardown: () => Promise<void>}>} */
424
+ #handles = []
425
+
426
+ /** @type {Function} */
427
+ #unsubscribeForwardedEvents
428
+
429
+ /** @type {Function} */
430
+ #onLog
431
+
432
+ /** @type {import('./mesh-service.mjs').EventBus} Forwards createMeshKvService()'s own `mesh-kv:*` vocabulary unchanged -- see module doc comment. */
433
+ #events = createEventBus()
434
+
435
+ /**
436
+ * @param {object} opts
437
+ * @param {string} opts.store - Store name. The ACL/sync resource used
438
+ * throughout is `kv:<store>`.
439
+ * @param {object} opts.node - A booted `PeerNode` (or any object providing
440
+ * the same minimal surface -- `podId`, `wallet`, `registry`, `sendTo`,
441
+ * `onIncomingData`, matching `cloud-storage.mjs`'s `CloudStorage`).
442
+ * @param {import('@johnhenry/browsermesh-netway').VirtualNetwork} [opts.network] -
443
+ * Optional. Neither internal service declares `createBackend`, so this
444
+ * is never required; passed through to `attachService()` only in case a
445
+ * future revision adds one.
446
+ * @param {Function} [opts.onLog]
447
+ */
448
+ constructor({ store, node, network, onLog } = {}) {
449
+ if (!store || typeof store !== 'string') {
450
+ throw new Error('MeshKv: store is required and must be a non-empty string')
451
+ }
452
+ if (!node || typeof node !== 'object') {
453
+ throw new Error('MeshKv: node is required (a booted PeerNode, or an equivalent duck-typed object)')
454
+ }
455
+ if (!node.podId || typeof node.podId !== 'string') {
456
+ throw new Error('MeshKv: node.podId is required')
457
+ }
458
+ if (!node.wallet || typeof node.wallet.sign !== 'function') {
459
+ throw new Error('MeshKv: node.wallet is required (needed by the GrantLog service)')
460
+ }
461
+ if (!node.registry || typeof node.registry.checkAccess !== 'function') {
462
+ throw new Error('MeshKv: node.registry is required (needed by mesh-kv for ACL checks)')
463
+ }
464
+
465
+ this.#store = store
466
+ this.#resource = resourceFor(store)
467
+ this.#node = node
468
+ this.#onLog = onLog || (() => {})
469
+
470
+ // -- Compose GrantLog + mesh-kv. Order doesn't matter the way it does
471
+ // for CloudStorage's GrantLog+key-distribution pair (no onGrantChange
472
+ // consumer here), but GrantLog first matches this family's established
473
+ // reading order (cloud-storage.mjs attaches key-distribution before
474
+ // grant-log only because key-distribution's onGrantChange hook must
475
+ // exist before grant-log's onReady fires; no such constraint here).
476
+ let grantLogApi
477
+ const grantLogHandle = attachService(node, network, createGrantLogService({
478
+ resource: this.#resource,
479
+ onReady: (api) => { grantLogApi = api },
480
+ onLog: this.#onLog,
481
+ }))
482
+ this.#grantLogApi = grantLogApi
483
+
484
+ const kvHandle = attachService(node, network, createMeshKvService({
485
+ storeId: store,
486
+ onLog: this.#onLog,
487
+ }))
488
+ this.#kvApi = kvHandle.api
489
+
490
+ this.#unsubscribeForwardedEvents = kvHandle.onEvent((event, data) => this.#events.emit(event, data))
491
+
492
+ this.#handles = [grantLogHandle, kvHandle]
493
+ }
494
+
495
+ /** The store name this instance serves. */
496
+ get store() { return this.#store }
497
+
498
+ /** The scope-grammar resource string (`kv:<store>`) this instance's ACL/sync services check against. */
499
+ get resource() { return this.#resource }
500
+
501
+ /**
502
+ * Subscribe to exactly one `mesh-kv:*` event (see module doc comment's
503
+ * "Observability events" section). Matches `attachService()`'s returned
504
+ * handle's `on()` shape.
505
+ * @param {string} event
506
+ * @param {(data: object) => void} callback
507
+ * @returns {() => void} Unsubscribe function.
508
+ */
509
+ on(event, callback) {
510
+ return this.#events.on(event, callback)
511
+ }
512
+
513
+ /**
514
+ * Subscribe to every `mesh-kv:*` event this instance emits, regardless of
515
+ * name. Matches `attachService()`'s returned handle's `onEvent()` shape.
516
+ * @param {(event: string, data: object) => void} callback
517
+ * @returns {() => void} Unsubscribe function.
518
+ */
519
+ onEvent(callback) {
520
+ return this.#events.onEvent(callback)
521
+ }
522
+
523
+ // -----------------------------------------------------------------------
524
+ // Data operations -- deliberately small; no chunking-related concept
525
+ // anywhere in this surface (see module doc comment).
526
+ // -----------------------------------------------------------------------
527
+
528
+ /**
529
+ * Read `key`'s current value.
530
+ * @param {string} key
531
+ * @returns {Promise<*>} The live value, or `undefined` if missing/deleted.
532
+ */
533
+ async get(key) {
534
+ if (!key || typeof key !== 'string') {
535
+ throw new Error('MeshKv.get: key is required and must be a non-empty string')
536
+ }
537
+ return this.#kvApi.get(key)
538
+ }
539
+
540
+ /**
541
+ * Write `value` under `key`.
542
+ * @param {string} key
543
+ * @param {*} value
544
+ * @returns {Promise<{stored: true, key: string}>}
545
+ */
546
+ async set(key, value) {
547
+ if (!key || typeof key !== 'string') {
548
+ throw new Error('MeshKv.set: key is required and must be a non-empty string')
549
+ }
550
+ this.#kvApi.set(key, value)
551
+ return { stored: true, key }
552
+ }
553
+
554
+ /**
555
+ * Delete `key` (a tombstone -- never physically removed, matching
556
+ * `LWWMap`'s own semantics).
557
+ * @param {string} key
558
+ * @returns {Promise<{deleted: true, key: string}>}
559
+ */
560
+ async delete(key) {
561
+ if (!key || typeof key !== 'string') {
562
+ throw new Error('MeshKv.delete: key is required and must be a non-empty string')
563
+ }
564
+ this.#kvApi.delete(key)
565
+ return { deleted: true, key }
566
+ }
567
+
568
+ /**
569
+ * List live keys, optionally filtered by `prefix`. Reflects this peer's
570
+ * own local CRDT state at call time -- eventually consistent with other
571
+ * peers, exactly like `CloudStorage.list()`.
572
+ * @param {string} [prefix='']
573
+ * @returns {Promise<string[]>}
574
+ */
575
+ async keys(prefix = '') {
576
+ return this.#kvApi.keys(prefix)
577
+ }
578
+
579
+ // -----------------------------------------------------------------------
580
+ // Store admin
581
+ // -----------------------------------------------------------------------
582
+
583
+ /**
584
+ * Bootstrap this identity as the store's admin, and self-grant
585
+ * `read`/`write` (mirroring `CloudStorage.becomeAdmin()`'s gap-fill --
586
+ * see that file's module doc comment, point 3: bootstrapping admin
587
+ * authority does not implicitly grant usage access to the bootstrapper's
588
+ * own store). Only call this when THIS instance is genuinely creating a
589
+ * brand-new store.
590
+ * @returns {Promise<void>}
591
+ */
592
+ async becomeAdmin() {
593
+ await this.#grantLogApi.bootstrapAdmin()
594
+ await this.#grantLogApi.grant(this.#node.podId, SELF_GRANT_ACTIONS)
595
+ }
596
+
597
+ /**
598
+ * Grant `pubKey` one or more bare capability actions on this store
599
+ * (`'read'`, `'write'`, `'admin'`). Requires this instance's identity to
600
+ * currently be an authorized admin of this store (enforced by
601
+ * `GrantLog.grant()` itself). Also drives data visibility, mirroring
602
+ * `CloudStorage.grant()` (see module doc comment): syncs the FULL grant
603
+ * log to the recipient (so their own registry learns this admin's
604
+ * pre-existing write grants too), starts watching them, and immediately
605
+ * pushes the current store state with the same retry-on-delay workaround
606
+ * `cloud-storage.mjs` documents for the identical async-merge race.
607
+ * @param {string} pubKey
608
+ * @param {string|string[]} scopes
609
+ * @returns {Promise<void>}
610
+ */
611
+ async grant(pubKey, scopes) {
612
+ const list = Array.isArray(scopes) ? scopes : [scopes]
613
+ await this.#grantLogApi.grant(pubKey, list)
614
+ await this.#grantLogApi.syncWith(pubKey)
615
+ this.#kvApi.watch(pubKey)
616
+ // Same known race/workaround as CloudStorage.grant() -- see that
617
+ // file's module doc comment, point 4: the recipient's
618
+ // GrantLog.mergeRemote() is not awaited by their own grant-log
619
+ // service's dispatch handler, so a data push sent immediately after
620
+ // grantLogApi.syncWith() can arrive and be ACL-checked before the
621
+ // recipient's registry has actually absorbed the grant. CRDT merge is
622
+ // idempotent, so resending at increasing delays is a cheap, safe
623
+ // self-heal.
624
+ for (const delayMs of [0, 20, 150]) {
625
+ if (delayMs > 0) await new Promise((r) => setTimeout(r, delayMs))
626
+ await this.#kvApi.syncWith(pubKey)
627
+ }
628
+ }
629
+
630
+ /**
631
+ * Revoke `pubKey`'s one or more bare capability actions on this store.
632
+ * @param {string} pubKey
633
+ * @param {string|string[]} scopes
634
+ * @returns {Promise<void>}
635
+ */
636
+ async revoke(pubKey, scopes) {
637
+ const list = Array.isArray(scopes) ? scopes : [scopes]
638
+ await this.#grantLogApi.revoke(pubKey, list)
639
+ await this.#grantLogApi.syncWith(pubKey)
640
+ this.#kvApi.unwatch(pubKey)
641
+ }
642
+
643
+ /**
644
+ * Introspection: this store's current admins and per-pubKey effective
645
+ * grants, per the last locally-replayed `GrantLog` state.
646
+ * @returns {{admins: string[], grants: Object<string, string[]>}}
647
+ */
648
+ effectiveGrants() {
649
+ return this.#grantLogApi.effective()
650
+ }
651
+
652
+ // -----------------------------------------------------------------------
653
+ // Teardown
654
+ // -----------------------------------------------------------------------
655
+
656
+ /**
657
+ * Detach both internally-composed services.
658
+ * @returns {Promise<void>}
659
+ */
660
+ async close() {
661
+ this.#unsubscribeForwardedEvents()
662
+ for (const handle of this.#handles) {
663
+ try {
664
+ await handle.teardown()
665
+ } catch (err) {
666
+ this.#onLog('mesh-kv:teardown-error', { store: this.#store, service: handle.name, error: err?.message || String(err) })
667
+ }
668
+ }
669
+ this.#events.closeAll()
670
+ }
671
+ }
672
+
673
+ export { DEFAULT_ENVELOPE_TYPE }