@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,799 @@
1
+ /**
2
+ * cloud-storage.mjs -- Phase H of the mesh-native-services plan
3
+ * ("CloudStorage: S3-like object storage"): the actual developer-facing
4
+ * class from the plan's Context section --
5
+ *
6
+ * import { CloudStorage as s3 } from '@johnhenry/browsermesh-apps'
7
+ * const store = new s3({ bucket: 'my-bucket', node: peerNode, network })
8
+ * await store.put('key', data)
9
+ *
10
+ * This file composes Phases B/D/E/F/G into one ergonomic entry point so a
11
+ * caller never needs to know `GrantLog`, `key-distribution.mjs`,
12
+ * `manifest-sync.mjs`, or `chunk-replication.mjs` exist:
13
+ *
14
+ * - `CloudStorageBackend` (Phase B) -- the local, durable, encrypted-at-
15
+ * rest single-peer object store this class talks to over its own
16
+ * private JSON-command socket (`fs-service-backend.mjs`'s convention,
17
+ * see that file's module doc comment).
18
+ * - `createKeyDistributionService()` (Phase E) + `createGrantLogService()`
19
+ * (Phase D), attached in that exact order with `onGrantChange`/`onReady`
20
+ * wired between them -- this is `grant-log.mjs`'s own documented
21
+ * composition order (see that file's "Composition with
22
+ * createGrantLogService()" section), reused verbatim here rather than
23
+ * re-derived.
24
+ * - `createManifestSyncService()` (Phase F) -- cross-peer manifest CRDT
25
+ * sync, ACL-gated against the GrantLog's replayed state.
26
+ * - `createChunkReplicationService()` (Phase G) -- eager push-to-replica
27
+ * and lazy pull/read-repair for the actual ciphertext chunk bytes.
28
+ *
29
+ * All four are attached via `attachService()` (`mesh-service.mjs`, Phase C)
30
+ * with NO `network` required -- none of D/E/F/G declare `createBackend`, so
31
+ * `attachService()` never needs one for them (see `mesh-service.mjs`'s own
32
+ * doc comment: `createBackend` is optional per-descriptor, and
33
+ * `attachService()` only throws for a descriptor that both declares it AND
34
+ * is attached with no network).
35
+ *
36
+ * ---------------------------------------------------------------------------
37
+ * DESIGN DECISIONS / GAPS THE PLAN LEFT OPEN, RESOLVED HERE (read before
38
+ * changing this file's behavior):
39
+ *
40
+ * 1. **`network` is OPTIONAL**, and this is a real simplification versus
41
+ * Phase B's original framing, not an oversight. Before this class
42
+ * existed, a caller needed `network.addBackend()` plus a netway
43
+ * `Backend`-shaped socket protocol just to talk to a bucket at all --
44
+ * that machinery is still real and still useful (e.g. another local
45
+ * process, or a debugging tool, connecting via
46
+ * `network.connect('s3-<bucket>://...')` using the raw JSON-command
47
+ * protocol), but `CloudStorage` itself never needs it: it opens its OWN
48
+ * private socket directly against `CloudStorageBackend.connect()`
49
+ * in-process (see `#sendCommand()`) to implement `put`/`get`/`delete`/
50
+ * `list`. `network`, when supplied, is used ONLY to additionally
51
+ * register the backend on it (under `opts.backendScheme`, default
52
+ * `s3-<bucket>`) for that legacy/advanced raw-socket use case -- most
53
+ * callers can omit it entirely.
54
+ *
55
+ * 2. **`get()`'s "not found yet" behavior**: a fully decentralized store has
56
+ * no server to ask "does this key exist" -- a key that was never written
57
+ * ANYWHERE and a key that was written by another peer but whose manifest
58
+ * entry has not yet propagated to THIS peer (Phase F's CRDT sync, an
59
+ * asynchronous background process) are, from this peer's own local
60
+ * vantage point, briefly indistinguishable. Rather than surface a
61
+ * separate "pending" state a caller would have to poll (and rather than
62
+ * hang forever waiting for a sync that might never come, e.g. for a
63
+ * genuinely nonexistent key), `get()` does a bounded wait
64
+ * (`manifestWaitMs`, default `DEFAULT_MANIFEST_WAIT_MS` = 3000ms,
65
+ * overridable per-constructor or per-call) polling the LOCAL manifest
66
+ * snapshot for the key before giving up. If the key never appears in
67
+ * time, `get()` throws `CloudStorageNotFoundError` -- the SAME error
68
+ * class plain absence uses, with `.reason` set to `'not-found'`
69
+ * (never appeared) or `'deleted'` (found, but tombstoned) for callers
70
+ * who want to distinguish further. This mirrors real S3's own external
71
+ * behavior (a 404 either way) while giving ordinary replication lag a
72
+ * real chance to resolve before concluding "not found" -- documented
73
+ * here as a deliberate collapsing of two cases into one bounded wait,
74
+ * not an oversight.
75
+ *
76
+ * 3. **`becomeAdmin()` also self-grants `read`/`write`/`delete`/`list`**,
77
+ * not just the `admin` scope `GrantLog.bootstrapAdmin()` itself grants.
78
+ * This is a real, deliberate gap-fill: `grant-log.mjs` treats "who can
79
+ * grant/revoke" (the `admin` scope, checked by `#assertCanAdminister()`)
80
+ * and "who can actually use this resource" (every other scope) as
81
+ * entirely separate grants by design (see that file's module doc
82
+ * comment) -- bootstrapping admin authority does NOT implicitly grant
83
+ * the bootstrapper read/write access to their own bucket. Since a
84
+ * bucket's creator obviously needs to use the bucket they just created,
85
+ * `becomeAdmin()` performs both steps. Only call this when this instance
86
+ * is genuinely creating a brand-new bucket (see `GrantLog.bootstrapAdmin()`'s
87
+ * own doc comment for what happens if two peers race to create the same
88
+ * bucket id -- the same "earliest write wins" exposure the plan already
89
+ * accepts for `LWWMap` and the GrantLog's own admin-bootstrap record).
90
+ *
91
+ * 4. **`grant()`/`revoke()` also drive manifest visibility and immediate
92
+ * propagation**, not just the GrantLog mutation the plan's brief names
93
+ * literally. Two real family-established facts make this necessary:
94
+ * neither `GrantLog` nor `manifest-sync.mjs`'s `MeshSyncEngine` binding
95
+ * auto-broadcasts on a local mutation (see `grant-log.test.mjs`'s and
96
+ * `manifest-sync.test.mjs`'s own established convention of an explicit
97
+ * `syncWith()`/`watch()` call after every mutation) -- a caller of this
98
+ * ergonomic class should not need to know that. So `grant()`:
99
+ * (a) mutates the local `GrantLog` (`grantLogApi.grant()`),
100
+ * (b) immediately `syncWith(pubKey)`s the FULL current grant log to
101
+ * the newly-granted peer (so they also learn about every
102
+ * PRE-EXISTING grant, including this bucket's admin's own
103
+ * self-grant from step 3 above -- required for the recipient's
104
+ * OWN registry to ever accept the admin's writes/pushes; see
105
+ * `manifest-sync.mjs`'s and `chunk-replication.mjs`'s ACL gates,
106
+ * both of which check the WRITER's grants on the RECEIVING peer's
107
+ * own registry),
108
+ * (c) starts watching the peer for future manifest broadcasts
109
+ * (`manifestSyncApi.watch()`), and
110
+ * (d) immediately syncs the CURRENT manifest snapshot to them too, so
111
+ * pre-existing keys are visible immediately rather than only
112
+ * becoming visible on the NEXT write.
113
+ * `revoke()` mirrors this for the negative case (`unwatch()` after the
114
+ * revoke record propagates) -- though note this is a bandwidth/hygiene
115
+ * cleanup, not itself a security boundary: the actual content-access
116
+ * security boundary is `chunk-replication.mjs`'s own per-request
117
+ * `checkAccess()` gate on `read`/`write`, independent of whether a
118
+ * manifest broadcast is still being sent.
119
+ *
120
+ * 5. **`designateReplica(pubKey)`** is simply `grant(pubKey, 'replica')` --
121
+ * `replica` is not a distinct mechanism in `grant-log.mjs` (see that
122
+ * file's "Replica designation" section: it is implemented as a sixth
123
+ * ordinary action-scope, `s3:<bucket>:replica`, granted/revoked exactly
124
+ * like `read`/`write`/etc.), so this method is a named convenience, not
125
+ * new plumbing.
126
+ *
127
+ * 6. **`replicationFactor` is advisory only, never automatic peer
128
+ * selection.** The plan's own "User decisions... not open for
129
+ * re-litigation" section is explicit: replica peers are admin-designated,
130
+ * never automatically chosen. There is no "pick N replicas from the
131
+ * network" mechanism anywhere in Phases D-G for this class to drive, and
132
+ * inventing one here would contradict that decision. `replicationFactor`
133
+ * is accepted and exposed (`get replicationFactor()`) purely so calling
134
+ * code / tooling can compare it against `replicaPeers.length` itself;
135
+ * this class only logs (via `onLog`) if they don't match, and takes no
136
+ * other action.
137
+ *
138
+ * 7. **What "node" needs to be**: the plan's sketch shows `node: peerNode`,
139
+ * a "booted PeerNode". This class only ever touches `node.podId`,
140
+ * `node.wallet` (duck-typed: `sign()`/`verify()`/`getPublicKeyBytes()`,
141
+ * required transitively by Phases D/E), `node.registry` (`PeerRegistry`,
142
+ * for `checkAccess()`), `node.sendTo()`, and `node.onIncomingData()` --
143
+ * exactly `mesh-service.mjs`'s own `createServiceContext()` needs, and
144
+ * exactly what every Phase C-G unit test's own minimal duck-typed node
145
+ * fixture already provides instead of a full, WebRTC-connected
146
+ * `PeerNode`. A real `PeerNode` (from `createMeshNode()`) satisfies this
147
+ * surface too; this class does not care which.
148
+ *
149
+ * ---------------------------------------------------------------------------
150
+ * KNOWN LIMITATION -- an unauthorized peer's `put()`: because `put()`'s
151
+ * local write can never fail (Phase G's durability contract: the local
152
+ * write is already durable before any replication is attempted), an
153
+ * unauthorized peer's OWN `CloudStorage` instance for the SAME bucket name
154
+ * always resolves `put()` successfully (`{stored: true, durability:
155
+ * 'local-only', replicatedTo: []}`) against its OWN, disconnected local
156
+ * copy -- there is no central arbiter anywhere in this design that could
157
+ * reject it up front. This is architecturally correct, not a bug: that
158
+ * write is never accepted by any OTHER peer's manifest (`manifest-sync.mjs`'s
159
+ * ACL gate rejects it before merge, the same property `manifest-sync.test.mjs`
160
+ * already proves), so it never becomes visible to any authorized reader --
161
+ * "fails cleanly" here means "never corrupts or leaks into the real,
162
+ * shared bucket", not "the promise rejects". `get()`, by contrast, DOES
163
+ * reject cleanly for an unauthorized peer, via the bounded-wait
164
+ * `CloudStorageNotFoundError` above (their local manifest never receives
165
+ * the real writer's entries in the first place, since nobody's
166
+ * `manifest-sync` service ever `watch()`es an unauthorized peer).
167
+ *
168
+ * ---------------------------------------------------------------------------
169
+ * Observability events (`ctx.emit()`/`on()`/`onEvent()`, Phase 1 of the
170
+ * mesh-KV-and-observability plan -- see `mesh-service.mjs`'s module doc
171
+ * comment for the full convention this follows). `CloudStorage` is NOT a
172
+ * `MeshService` descriptor itself -- it calls `attachService()` internally
173
+ * four times (D/E/F/G above) and each of THOSE handles already exposes its
174
+ * own low-level `ctx.emit()` vocabulary (see each service's own module doc
175
+ * comment), but `CloudStorage` has no `ctx` of its OWN to emit through.
176
+ * Rather than leave this class out of the convention, or force a caller to
177
+ * separately subscribe to all four internal handles just to observe "this
178
+ * bucket had a put", this class builds its own bus via `mesh-service.mjs`'s
179
+ * exported `createEventBus()` (the exact same `{emit, on, onEvent, closeAll}`
180
+ * shape `attachService()`'s handle uses) and exposes `on(event, callback)`/
181
+ * `onEvent(callback)` methods matching that same handle shape, so a caller
182
+ * that already knows how to subscribe to one `attachService()` handle knows
183
+ * how to subscribe to a `CloudStorage` instance too. Its own vocabulary is
184
+ * deliberately HIGHER-LEVEL than the internal services' wire-protocol
185
+ * events -- application-meaningful transitions a dashboard actually wants
186
+ * ("this bucket had a write", not "chunk X was pushed to peer Y"):
187
+ *
188
+ * - `cloud-storage:put-completed` `{bucket, key, size, durability}`
189
+ * - `cloud-storage:get-completed` `{bucket, key}`
190
+ * - `cloud-storage:delete-completed` `{bucket, key}`
191
+ * - `cloud-storage:admin-bootstrapped` `{bucket}` -- `becomeAdmin()` finished.
192
+ * - `cloud-storage:grant-issued` `{bucket, pubKey, scopes}` -- `grant()` finished.
193
+ *
194
+ * `close()` calls the bus's own `closeAll()`, stopping further delivery, the
195
+ * same as `attachService()`'s handle does on `teardown()`.
196
+ *
197
+ * No browser-only imports at module level.
198
+ */
199
+
200
+ import { attachService, createEventBus } from './mesh-service.mjs'
201
+ import { CloudStorageBackend } from './cloud-storage-backend.mjs'
202
+ import { createGrantLogService } from './grant-log.mjs'
203
+ import { createKeyDistributionService } from './key-distribution.mjs'
204
+ import { createManifestSyncService } from './manifest-sync.mjs'
205
+ import { createChunkReplicationService } from './chunk-replication.mjs'
206
+
207
+ /** Default bound (ms) `get()` waits for a key's manifest entry to appear locally before giving up -- see module doc comment, point 2. */
208
+ const DEFAULT_MANIFEST_WAIT_MS = 3000
209
+
210
+ /** How often `get()`'s bounded wait re-polls the local manifest snapshot. */
211
+ const MANIFEST_POLL_INTERVAL_MS = 25
212
+
213
+ /** Bare action-scopes `becomeAdmin()` self-grants beyond the `admin` scope `GrantLog.bootstrapAdmin()` itself grants -- see module doc comment, point 3. */
214
+ const SELF_GRANT_ACTIONS = ['read', 'write', 'delete', 'list']
215
+
216
+ /** @param {string} bucket @returns {string} The scope-grammar resource string GrantLog/PeerRegistry/manifest-sync/chunk-replication all expect. */
217
+ function resourceFor(bucket) {
218
+ return `s3:${bucket}`
219
+ }
220
+
221
+ // ---------------------------------------------------------------------------
222
+ // Errors
223
+ // ---------------------------------------------------------------------------
224
+
225
+ /**
226
+ * Thrown by `get()` when a key is not found locally after the bounded
227
+ * manifest wait (see module doc comment, point 2). `.reason` is
228
+ * `'not-found'` (the key never appeared) or `'deleted'` (it appeared, but
229
+ * tombstoned).
230
+ */
231
+ export class CloudStorageNotFoundError extends Error {
232
+ /**
233
+ * @param {string} key
234
+ * @param {object} [opts]
235
+ * @param {'not-found'|'deleted'} [opts.reason='not-found']
236
+ */
237
+ constructor(key, { reason = 'not-found' } = {}) {
238
+ super(
239
+ reason === 'deleted'
240
+ ? `CloudStorage: key '${key}' was deleted`
241
+ : `CloudStorage: key '${key}' not found (it may simply not exist, or its manifest entry has not synced to this peer yet)`,
242
+ )
243
+ this.name = 'CloudStorageNotFoundError'
244
+ this.key = key
245
+ this.reason = reason
246
+ }
247
+ }
248
+
249
+ // ---------------------------------------------------------------------------
250
+ // base64 / bytes helpers -- deliberately duplicated rather than shared,
251
+ // matching this family's established per-file convention (see
252
+ // cloud-storage-backend.mjs / key-distribution.mjs / chunk-replication.mjs,
253
+ // all of which independently define the exact same pair).
254
+ // ---------------------------------------------------------------------------
255
+
256
+ /** @param {Uint8Array} bytes @returns {string} */
257
+ function toBase64(bytes) {
258
+ if (typeof Buffer !== 'undefined') return Buffer.from(bytes).toString('base64')
259
+ let bin = ''
260
+ for (const b of bytes) bin += String.fromCharCode(b)
261
+ return btoa(bin)
262
+ }
263
+
264
+ /** @param {string} str @returns {Uint8Array} */
265
+ function fromBase64(str) {
266
+ if (typeof Buffer !== 'undefined') return new Uint8Array(Buffer.from(str, 'base64'))
267
+ const bin = atob(str)
268
+ const bytes = new Uint8Array(bin.length)
269
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
270
+ return bytes
271
+ }
272
+
273
+ /**
274
+ * Normalize `put()`'s `data` argument (a `Uint8Array`, `ArrayBuffer`, or
275
+ * `string`) into bytes.
276
+ * @param {Uint8Array|ArrayBuffer|string} data
277
+ * @returns {Uint8Array}
278
+ */
279
+ function toUint8Array(data) {
280
+ if (data instanceof Uint8Array) return data
281
+ if (data instanceof ArrayBuffer) return new Uint8Array(data)
282
+ if (typeof data === 'string') return new TextEncoder().encode(data)
283
+ throw new TypeError('CloudStorage.put: data must be a Uint8Array, ArrayBuffer, or string')
284
+ }
285
+
286
+ // ---------------------------------------------------------------------------
287
+ // CloudStorage
288
+ // ---------------------------------------------------------------------------
289
+
290
+ /**
291
+ * The ergonomic, S3-like object storage class. See this file's module doc
292
+ * comment for the full design writeup.
293
+ */
294
+ export class CloudStorage {
295
+ /** @type {string} */
296
+ #bucket
297
+
298
+ /** @type {string} */
299
+ #resource
300
+
301
+ /** @type {object} Duck-typed `{podId, wallet, registry, sendTo, onIncomingData}` -- see module doc comment, point 7. */
302
+ #node
303
+
304
+ /** @type {import('@johnhenry/browsermesh-netway').VirtualNetwork|null} */
305
+ #network
306
+
307
+ /** @type {CloudStorageBackend} */
308
+ #backend
309
+
310
+ /** @type {import('@johnhenry/browsermesh-netway').StreamSocket|null} lazily-opened private local socket to `#backend` */
311
+ #socket = null
312
+
313
+ /** @type {Promise<void>} tail of the local-socket command queue -- see #sendCommand() */
314
+ #socketQueue = Promise.resolve()
315
+
316
+ /** @type {{resource: string, grant: Function, revoke: Function, bootstrapAdmin: Function, syncWith: Function, effective: Function, toJSON: Function}} set synchronously during construction */
317
+ #grantLogApi
318
+
319
+ /** @type {{resource: string, handleGrantChange: Function, localEncryptionPublicKey: Function}} */
320
+ #keyDistApi
321
+
322
+ /** @type {{bucketId: string, docId: string, watch: Function, unwatch: Function, syncWith: Function}} */
323
+ #manifestSyncApi
324
+
325
+ /** @type {{bucketId: string, resource: string, fetchChunk: Function, syncMissingChunks: Function, listReplicaPeers: Function}} */
326
+ #chunkReplicationApi
327
+
328
+ /** @type {Array<{name: string, backendScheme: string|null, api: object|undefined, teardown: () => Promise<void>}>} */
329
+ #handles = []
330
+
331
+ /** @type {string[]} */
332
+ #replicaPeers
333
+
334
+ /** @type {number} */
335
+ #replicationFactor
336
+
337
+ /** @type {number} */
338
+ #manifestWaitMs
339
+
340
+ /** @type {Function} */
341
+ #onLog
342
+
343
+ /** @type {import('./mesh-service.mjs').EventBus} This class's OWN higher-level event bus -- see module doc comment's "Observability events" section. Not the same bus as any of the four internally-attached services' own `ctx.emit()`. */
344
+ #events = createEventBus()
345
+
346
+ /**
347
+ * @param {object} opts
348
+ * @param {string} opts.bucket - Bucket name. The ACL/sync resource used
349
+ * throughout is `s3:<bucket>`.
350
+ * @param {object} opts.node - A booted `PeerNode` (or any object providing
351
+ * the same minimal surface -- see module doc comment, point 7).
352
+ * @param {import('@johnhenry/browsermesh-netway').VirtualNetwork} [opts.network] -
353
+ * Optional -- see module doc comment, point 1. Only used to additionally
354
+ * register the internal `CloudStorageBackend` on it for raw JSON-command
355
+ * socket access.
356
+ * @param {string} [opts.backendScheme] - Scheme `#backend` is registered
357
+ * under on `network`, if supplied. Defaults to `s3-<bucket>`.
358
+ * @param {string[]} [opts.replicaPeers] - PubKeys to designate as replicas
359
+ * immediately when `becomeAdmin()` is called (see module doc comment,
360
+ * point 3). Ignored if `becomeAdmin()` is never called.
361
+ * @param {number} [opts.replicationFactor] - Advisory only -- see module
362
+ * doc comment, point 6.
363
+ * @param {number} [opts.manifestWaitMs] - Default bound for `get()`'s
364
+ * "wait for the manifest to sync" behavior (see module doc comment,
365
+ * point 2). Defaults to `DEFAULT_MANIFEST_WAIT_MS`.
366
+ * @param {Function} [opts.onLog]
367
+ * @param {string} [opts.dbName] - Passed through to `CloudStorageBackend`
368
+ * (its IndexedDB database name prefix). Defaults to `cloud-storage-<bucket>`.
369
+ * @param {import('@johnhenry/browsermesh-sync').IndexedDBChunkStore} [opts.chunkStore]
370
+ * @param {import('@johnhenry/browsermesh-sync').IndexedDBSyncStorage} [opts.manifestStorage]
371
+ * @param {import('@johnhenry/browsermesh-sync').IndexedDBSyncStorage} [opts.keyStorage]
372
+ */
373
+ constructor({
374
+ bucket,
375
+ node,
376
+ network,
377
+ backendScheme,
378
+ replicaPeers = [],
379
+ replicationFactor,
380
+ manifestWaitMs = DEFAULT_MANIFEST_WAIT_MS,
381
+ onLog,
382
+ dbName,
383
+ chunkStore,
384
+ manifestStorage,
385
+ keyStorage,
386
+ } = {}) {
387
+ if (!bucket || typeof bucket !== 'string') {
388
+ throw new Error('CloudStorage: bucket is required and must be a non-empty string')
389
+ }
390
+ if (!node || typeof node !== 'object') {
391
+ throw new Error('CloudStorage: node is required (a booted PeerNode, or an equivalent duck-typed object)')
392
+ }
393
+ if (!node.podId || typeof node.podId !== 'string') {
394
+ throw new Error('CloudStorage: node.podId is required')
395
+ }
396
+ if (!node.wallet || typeof node.wallet.sign !== 'function') {
397
+ throw new Error('CloudStorage: node.wallet is required (needed by the GrantLog/key-distribution services)')
398
+ }
399
+ if (!node.registry || typeof node.registry.checkAccess !== 'function') {
400
+ throw new Error('CloudStorage: node.registry is required (needed by manifest-sync/chunk-replication for ACL checks)')
401
+ }
402
+
403
+ this.#bucket = bucket
404
+ this.#resource = resourceFor(bucket)
405
+ this.#node = node
406
+ this.#network = network || null
407
+ this.#replicaPeers = Array.isArray(replicaPeers) ? [...replicaPeers] : []
408
+ this.#replicationFactor = typeof replicationFactor === 'number' ? replicationFactor : this.#replicaPeers.length
409
+ this.#manifestWaitMs = manifestWaitMs
410
+ this.#onLog = onLog || (() => {})
411
+
412
+ if (this.#replicationFactor > this.#replicaPeers.length) {
413
+ this.#onLog('cloud-storage:replication-factor-not-met', {
414
+ bucket, replicationFactor: this.#replicationFactor, replicaPeersProvided: this.#replicaPeers.length,
415
+ })
416
+ }
417
+
418
+ this.#backend = new CloudStorageBackend({
419
+ bucket,
420
+ dbName,
421
+ chunkStore,
422
+ manifestStorage,
423
+ keyStorage,
424
+ nodeId: node.podId,
425
+ onLog: this.#onLog,
426
+ })
427
+
428
+ if (this.#network) {
429
+ this.#network.addBackend(backendScheme || `s3-${bucket}`, this.#backend)
430
+ }
431
+
432
+ // -- Compose D/E/F/G. Order matters for D+E -- see grant-log.mjs's own
433
+ // "Composition with createGrantLogService()" doc-comment section, and
434
+ // key-distribution.test.mjs's `attachBucketServices()` fixture, which
435
+ // this mirrors exactly.
436
+ let grantLogApi
437
+ const keyDistHandle = attachService(node, network, createKeyDistributionService({
438
+ resource: this.#resource,
439
+ getEffective: () => grantLogApi.effective(),
440
+ getLocalKey: () => this.#backend.peekKeyRaw(),
441
+ setReceivedKey: (bytes) => this.#backend.importKeyRaw(bytes),
442
+ onLog: this.#onLog,
443
+ }))
444
+ const grantLogHandle = attachService(node, network, createGrantLogService({
445
+ resource: this.#resource,
446
+ onGrantChange: keyDistHandle.api.handleGrantChange,
447
+ onReady: (api) => { grantLogApi = api },
448
+ onLog: this.#onLog,
449
+ }))
450
+ // `onReady` above runs synchronously inside `attach()` (see
451
+ // grant-log.mjs's own doc comment on why it must), so `grantLogApi` is
452
+ // already assigned by the time `attachService()` returns.
453
+ this.#grantLogApi = grantLogApi
454
+ this.#keyDistApi = keyDistHandle.api
455
+
456
+ const manifestSyncHandle = attachService(node, network, createManifestSyncService({
457
+ bucketId: bucket,
458
+ cloudStorageBackend: this.#backend,
459
+ onLog: this.#onLog,
460
+ }))
461
+ this.#manifestSyncApi = manifestSyncHandle.api
462
+
463
+ const chunkReplicationHandle = attachService(node, network, createChunkReplicationService({
464
+ bucketId: bucket,
465
+ cloudStorageBackend: this.#backend,
466
+ onLog: this.#onLog,
467
+ }))
468
+ this.#chunkReplicationApi = chunkReplicationHandle.api
469
+
470
+ this.#handles = [keyDistHandle, grantLogHandle, manifestSyncHandle, chunkReplicationHandle]
471
+ }
472
+
473
+ /** The bucket name this instance serves. */
474
+ get bucket() { return this.#bucket }
475
+
476
+ /** The scope-grammar resource string (`s3:<bucket>`) this instance's ACL/sync services check against. */
477
+ get resource() { return this.#resource }
478
+
479
+ /** Advisory only -- see module doc comment, point 6. */
480
+ get replicationFactor() { return this.#replicationFactor }
481
+
482
+ /**
483
+ * Subscribe to exactly one of this instance's own higher-level events
484
+ * (`cloud-storage:*` -- see module doc comment's "Observability events"
485
+ * section). Matches `attachService()`'s returned handle's `on()` shape.
486
+ * @param {string} event
487
+ * @param {(data: object) => void} callback
488
+ * @returns {() => void} Unsubscribe function.
489
+ */
490
+ on(event, callback) {
491
+ return this.#events.on(event, callback)
492
+ }
493
+
494
+ /**
495
+ * Subscribe to every event this instance emits, regardless of name.
496
+ * Matches `attachService()`'s returned handle's `onEvent()` shape.
497
+ * @param {(event: string, data: object) => void} callback
498
+ * @returns {() => void} Unsubscribe function.
499
+ */
500
+ onEvent(callback) {
501
+ return this.#events.onEvent(callback)
502
+ }
503
+
504
+ // -----------------------------------------------------------------------
505
+ // Local command socket (put/get/delete/list all flow through here)
506
+ // -----------------------------------------------------------------------
507
+
508
+ /** @returns {Promise<import('@johnhenry/browsermesh-netway').StreamSocket>} */
509
+ async #ensureSocket() {
510
+ if (!this.#socket) {
511
+ this.#socket = await this.#backend.connect()
512
+ }
513
+ return this.#socket
514
+ }
515
+
516
+ /**
517
+ * Send one JSON command to `#backend` over its private local socket and
518
+ * return its one JSON response. The wire protocol (`fs-service-backend.mjs`'s
519
+ * convention, reused by `CloudStorageBackend`) has no request-id
520
+ * correlation -- it is strictly one command in flight at a time -- so
521
+ * concurrent callers of this class share one FIFO queue rather than
522
+ * risking interleaved writes/misattributed reads on the same socket.
523
+ * @param {object} cmd
524
+ * @returns {Promise<object>}
525
+ */
526
+ #sendCommand(cmd) {
527
+ const run = async () => {
528
+ const socket = await this.#ensureSocket()
529
+ const encoder = new TextEncoder()
530
+ const decoder = new TextDecoder()
531
+ await socket.write(encoder.encode(JSON.stringify(cmd)))
532
+ const chunk = await socket.read()
533
+ if (chunk === null) {
534
+ throw new Error('CloudStorage: local backend socket closed unexpectedly')
535
+ }
536
+ return JSON.parse(decoder.decode(chunk))
537
+ }
538
+
539
+ const result = this.#socketQueue.then(run, run)
540
+ // Keep the queue itself always-resolved regardless of a given command's
541
+ // outcome -- only `result` (returned below) carries the real
542
+ // success/failure for THIS call.
543
+ this.#socketQueue = result.then(() => {}, () => {})
544
+ return result
545
+ }
546
+
547
+ // -----------------------------------------------------------------------
548
+ // Object operations
549
+ // -----------------------------------------------------------------------
550
+
551
+ /**
552
+ * Write `data` under `key`. The local write is always durable by the time
553
+ * this resolves (Phase G's durability contract) -- `durability`/
554
+ * `replicatedTo` report whether it was ALSO pushed to connected,
555
+ * admin-designated replica peers in time, never whether the local write
556
+ * itself succeeded.
557
+ *
558
+ * @param {string} key
559
+ * @param {Uint8Array|ArrayBuffer|string} data
560
+ * @param {object} [opts]
561
+ * @param {string} [opts.contentType]
562
+ * @param {object} [opts.metadata]
563
+ * @returns {Promise<{stored: true, key: string, size: number, durability: 'local-only'|'replicated', replicatedTo: string[]}>}
564
+ */
565
+ async put(key, data, opts = {}) {
566
+ if (!key || typeof key !== 'string') {
567
+ throw new Error('CloudStorage.put: key is required and must be a non-empty string')
568
+ }
569
+ const bytes = toUint8Array(data)
570
+ const res = await this.#sendCommand({
571
+ op: 'put',
572
+ key,
573
+ data: toBase64(bytes),
574
+ contentType: opts.contentType ?? null,
575
+ metadata: opts.metadata ?? {},
576
+ })
577
+ if (res.error) throw new Error(`CloudStorage.put: ${res.error}`)
578
+ const durability = res.durability === 'replicated' ? 'replicated' : 'local-only'
579
+ this.#events.emit('cloud-storage:put-completed', { bucket: this.#bucket, key: res.key, size: res.size, durability })
580
+ return {
581
+ stored: true,
582
+ key: res.key,
583
+ size: res.size,
584
+ durability,
585
+ replicatedTo: Array.isArray(res.replicatedTo) ? res.replicatedTo : [],
586
+ }
587
+ }
588
+
589
+ /**
590
+ * Read `key`'s content. Falls back to a remote peer request (Phase G's
591
+ * lazy pull/read-repair) for any chunk not already held locally. See
592
+ * module doc comment, point 2, for exactly how "the manifest entry itself
593
+ * isn't here yet" is handled.
594
+ *
595
+ * @param {string} key
596
+ * @param {object} [opts]
597
+ * @param {number} [opts.manifestWaitMs] - Overrides the constructor default for this call only.
598
+ * @returns {Promise<Uint8Array>}
599
+ * @throws {CloudStorageNotFoundError}
600
+ */
601
+ async get(key, opts = {}) {
602
+ if (!key || typeof key !== 'string') {
603
+ throw new Error('CloudStorage.get: key is required and must be a non-empty string')
604
+ }
605
+ const waitMs = opts.manifestWaitMs ?? this.#manifestWaitMs
606
+ const deadline = Date.now() + waitMs
607
+
608
+ let reg = null
609
+ while (true) {
610
+ const snapshot = await this.#backend.getManifestSnapshot()
611
+ reg = snapshot?.entries?.[key] || null
612
+ if (reg) break
613
+ if (Date.now() >= deadline) break
614
+ await new Promise((r) => setTimeout(r, MANIFEST_POLL_INTERVAL_MS))
615
+ }
616
+
617
+ if (!reg) {
618
+ throw new CloudStorageNotFoundError(key, { reason: 'not-found' })
619
+ }
620
+ if (reg.tombstone) {
621
+ throw new CloudStorageNotFoundError(key, { reason: 'deleted' })
622
+ }
623
+
624
+ // Ensure every chunk this entry references is present locally BEFORE
625
+ // asking the backend to decrypt+assemble it -- the backend itself has
626
+ // no notion of "go fetch it from the mesh", only "read what I already
627
+ // have" (see cloud-storage-backend.mjs's #fetchAndDecrypt()).
628
+ for (const { cid } of reg.value?.chunks || []) {
629
+ const has = await this.#backend.hasChunkRaw(cid)
630
+ if (!has) {
631
+ await this.#chunkReplicationApi.fetchChunk(cid) // throws a plain Error if unreachable -- propagated as-is, not wrapped
632
+ }
633
+ }
634
+
635
+ const res = await this.#sendCommand({ op: 'get', key })
636
+ if (res.error) {
637
+ // The manifest could have raced a concurrent delete between the check
638
+ // above and now -- surface it via the same not-found contract rather
639
+ // than a raw backend error string.
640
+ throw new CloudStorageNotFoundError(key, { reason: 'deleted' })
641
+ }
642
+ this.#events.emit('cloud-storage:get-completed', { bucket: this.#bucket, key })
643
+ return fromBase64(res.data)
644
+ }
645
+
646
+ /**
647
+ * Delete `key` (a tombstone, per `CloudStorageBackend`'s manifest --
648
+ * never a chunk-store removal; see that file's own doc comment).
649
+ * @param {string} key
650
+ * @returns {Promise<{deleted: true}>}
651
+ */
652
+ async delete(key) {
653
+ if (!key || typeof key !== 'string') {
654
+ throw new Error('CloudStorage.delete: key is required and must be a non-empty string')
655
+ }
656
+ const res = await this.#sendCommand({ op: 'delete', key })
657
+ if (res.error) throw new Error(`CloudStorage.delete: ${res.error}`)
658
+ this.#events.emit('cloud-storage:delete-completed', { bucket: this.#bucket, key })
659
+ return { deleted: true }
660
+ }
661
+
662
+ /**
663
+ * List keys, optionally filtered by `prefix`. Reflects this peer's own
664
+ * local manifest state at call time -- eventually consistent with other
665
+ * peers, exactly like real S3 listing, with no special wait (unlike
666
+ * `get()`; see module doc comment, point 2 -- listing has no single key
667
+ * whose absence is ambiguous the way `get()` does).
668
+ * @param {string} [prefix='']
669
+ * @returns {Promise<Array<{key: string, size: number, updatedAt: number}>>}
670
+ */
671
+ async list(prefix = '') {
672
+ const res = await this.#sendCommand({ op: 'list', prefix })
673
+ if (res.error) throw new Error(`CloudStorage.list: ${res.error}`)
674
+ return res.keys
675
+ }
676
+
677
+ // -----------------------------------------------------------------------
678
+ // Bucket admin
679
+ // -----------------------------------------------------------------------
680
+
681
+ /**
682
+ * Bootstrap this identity as the bucket's admin, and self-grant
683
+ * `read`/`write`/`delete`/`list` (see module doc comment, point 3). Only
684
+ * call this when THIS instance is genuinely creating a brand-new bucket.
685
+ * If `replicaPeers` was supplied to the constructor, each is designated a
686
+ * replica immediately afterward.
687
+ * @returns {Promise<void>}
688
+ */
689
+ async becomeAdmin() {
690
+ await this.#grantLogApi.bootstrapAdmin()
691
+ await this.#grantLogApi.grant(this.#node.podId, SELF_GRANT_ACTIONS)
692
+ this.#events.emit('cloud-storage:admin-bootstrapped', { bucket: this.#bucket })
693
+ for (const pubKey of this.#replicaPeers) {
694
+ await this.designateReplica(pubKey)
695
+ }
696
+ }
697
+
698
+ /**
699
+ * Grant `pubKey` one or more bare capability actions on this bucket
700
+ * (`'read'`, `'write'`, `'delete'`, `'list'`, `'admin'`, `'replica'`).
701
+ * Requires this instance's identity to currently be an authorized admin
702
+ * of this bucket (enforced by `GrantLog.grant()` itself). See module doc
703
+ * comment, point 4, for why this also drives manifest visibility/sync.
704
+ * @param {string} pubKey
705
+ * @param {string|string[]} scopes
706
+ * @returns {Promise<void>}
707
+ */
708
+ async grant(pubKey, scopes) {
709
+ const list = Array.isArray(scopes) ? scopes : [scopes]
710
+ await this.#grantLogApi.grant(pubKey, list)
711
+ await this.#grantLogApi.syncWith(pubKey)
712
+ this.#manifestSyncApi.watch(pubKey)
713
+ // KNOWN RACE, worked around here rather than ignored: the recipient's
714
+ // GrantLog.mergeRemote() (crypto signature verification, genuinely
715
+ // async) is not awaited by their own grant-log service's dispatch
716
+ // handler (matching `manifest-sync.mjs`'s/`grant-log.mjs`'s own
717
+ // established "handle async work in a .catch()-guarded background
718
+ // promise, never block the dispatch loop" convention) -- so a manifest
719
+ // sync sent immediately after `grantLogApi.syncWith()` can arrive and be
720
+ // ACL-checked on the recipient's side BEFORE their own registry has
721
+ // actually been updated with this grant, and gets silently rejected by
722
+ // manifest-sync.mjs's gate. Without a retry, pre-existing content would
723
+ // then only ever become visible to the recipient on the NEXT write (the
724
+ // first one to be broadcast after the grant has genuinely landed) --
725
+ // fine for future writes, not for content that already existed at grant
726
+ // time. A CRDT manifest merge is idempotent, so resending it a few times
727
+ // at increasing delays is a cheap, safe way to self-heal this race
728
+ // without needing an acknowledgement protocol this phase doesn't have.
729
+ for (const delayMs of [0, 20, 150]) {
730
+ if (delayMs > 0) await new Promise((r) => setTimeout(r, delayMs))
731
+ await this.#manifestSyncApi.syncWith(pubKey)
732
+ }
733
+ this.#events.emit('cloud-storage:grant-issued', { bucket: this.#bucket, pubKey, scopes: list })
734
+ }
735
+
736
+ /**
737
+ * Revoke `pubKey`'s one or more bare capability actions on this bucket.
738
+ * See `cloud-storage-backend.mjs`'s and `key-distribution.mjs`'s own
739
+ * documented PERMANENT LIMITATION: this stops FUTURE key distribution and
740
+ * chunk replication to `pubKey`, but cannot retroactively erase a bucket
741
+ * key (or plaintext) already delivered to them before the revoke.
742
+ * @param {string} pubKey
743
+ * @param {string|string[]} scopes
744
+ * @returns {Promise<void>}
745
+ */
746
+ async revoke(pubKey, scopes) {
747
+ const list = Array.isArray(scopes) ? scopes : [scopes]
748
+ await this.#grantLogApi.revoke(pubKey, list)
749
+ await this.#grantLogApi.syncWith(pubKey)
750
+ this.#manifestSyncApi.unwatch(pubKey)
751
+ }
752
+
753
+ /**
754
+ * Convenience for `grant(pubKey, 'replica')` -- see module doc comment,
755
+ * point 5.
756
+ * @param {string} pubKey
757
+ * @returns {Promise<void>}
758
+ */
759
+ async designateReplica(pubKey) {
760
+ await this.grant(pubKey, 'replica')
761
+ }
762
+
763
+ /**
764
+ * Introspection: this bucket's current admins and per-pubKey effective
765
+ * grants, per the last locally-replayed `GrantLog` state.
766
+ * @returns {{admins: string[], grants: Object<string, string[]>}}
767
+ */
768
+ effectiveGrants() {
769
+ return this.#grantLogApi.effective()
770
+ }
771
+
772
+ // -----------------------------------------------------------------------
773
+ // Teardown
774
+ // -----------------------------------------------------------------------
775
+
776
+ /**
777
+ * Detach every internally-composed service and close the local backend.
778
+ * Does not (cannot -- see `mesh-service.mjs`'s own documented limitation)
779
+ * remove `#backend` from `network` if it was registered there.
780
+ * @returns {Promise<void>}
781
+ */
782
+ async close() {
783
+ if (this.#socket) {
784
+ await this.#socket.close().catch(() => {})
785
+ this.#socket = null
786
+ }
787
+ for (const handle of this.#handles) {
788
+ try {
789
+ await handle.teardown()
790
+ } catch (err) {
791
+ this.#onLog('cloud-storage:teardown-error', { bucket: this.#bucket, service: handle.name, error: err?.message || String(err) })
792
+ }
793
+ }
794
+ await this.#backend.close()
795
+ this.#events.closeAll()
796
+ }
797
+ }
798
+
799
+ export { DEFAULT_MANIFEST_WAIT_MS }