@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,840 @@
1
+ /**
2
+ * grant-log.mjs -- Phase D of the CloudStorage plan: a replicated, signed
3
+ * append-log ("GrantLog") that solves the gap the plan's Context section
4
+ * names explicitly -- `PeerRegistry.grantCapabilities()` is entirely local,
5
+ * it never transmits anything, so a *replicated* resource (a CloudStorage
6
+ * bucket, or any future mesh-native service) needs authorization itself
7
+ * propagated across peers, not just decided once by one peer.
8
+ *
9
+ * Built as a `MeshService` consumer (Phase C, `mesh-service.mjs`): the log
10
+ * travels as small envelopes over `ctx.onIncomingData()`/`ctx.sendTo()`,
11
+ * matching `mesh-sync.mjs`/`mesh-relay-host.mjs`'s established pattern
12
+ * rather than hand-rolling raw `PeerNode` dispatch.
13
+ *
14
+ * ---------------------------------------------------------------------------
15
+ * Record shape (the plan's exact shape, plus one addition -- see below):
16
+ *
17
+ * {
18
+ * pubKey: string, // grantee -- who this record affects
19
+ * scope: string, // full 3-segment scope, e.g. 's3:my-bucket:read'
20
+ * action: 'grant' | 'revoke', // what this record does to `scope` for `pubKey`
21
+ * at: number, // ms epoch, caller-supplied (see Known limitations)
22
+ * signedBy: string, // admin's podId who authorized this record
23
+ * signedByPubKeyBytes: string,// base64url raw Ed25519 public key of `signedBy`
24
+ * signature: string, // base64url Ed25519 signature over the canonical
25
+ * // JSON of {pubKey, scope, action, at, signedBy}
26
+ * }
27
+ *
28
+ * `signedByPubKeyBytes` is the one addition beyond the plan's literal
29
+ * `{pubKey, scope, action, at, signedBy}` shape. Reasoning: a replicated,
30
+ * peer-to-peer log has no central directory a receiving peer could consult
31
+ * to look up "the real public key for podId X" -- unlike `AuditChain.verify()`
32
+ * (`audit.mjs`), which takes a `getPublicKey(podId)` *resolver* callback the
33
+ * caller must already have a way to satisfy. GrantLog records instead carry
34
+ * their own signer's public key bytes, and every receiving peer independently
35
+ * re-derives `signedBy` from those bytes (`base64url(SHA-256(rawBytes))`,
36
+ * exactly `derivePodId()`'s own definition in
37
+ * `browsermesh-primitives/src/identity.mjs`) before trusting the embedded
38
+ * key -- so a record is self-verifying: nobody can attach someone else's
39
+ * claimed identity to a key they don't hold, and no out-of-band key exchange
40
+ * is required for Phase D to work standalone (ahead of Phase E's dedicated
41
+ * key-distribution channel, which solves an unrelated problem: distributing
42
+ * the bucket's *symmetric* AES key, not identity verification).
43
+ *
44
+ * ---------------------------------------------------------------------------
45
+ * Replica designation: implemented as a sixth scope action, `replica`
46
+ * (`s3:<bucketId>:replica`), grant/revoke exactly like `read`/`write`/
47
+ * `delete`/`list`/`admin`. This was the plan's "either is fine" choice
48
+ * between a fifth action-scope and a distinct record type; a fifth
49
+ * action-scope was chosen because it requires zero extra record-type
50
+ * branching anywhere in this file (construction, verification, replay all
51
+ * stay ignorant of what a "capability action" string actually means to the
52
+ * consumer), which is also what keeps this module resource/service-agnostic
53
+ * (the plan's "keep it generic... this pattern may get reused" ask) --
54
+ * CloudStorage's `s3:<bucketId>` resource and its 6 actions are just this
55
+ * module's first caller-supplied values, not anything hardcoded here.
56
+ *
57
+ * ---------------------------------------------------------------------------
58
+ * Authorization-chain replay algorithm (point 3 of the plan's "Testing"
59
+ * section, and the "who is even allowed to grant" question):
60
+ *
61
+ * The underlying `ORSet` (`browsermesh-primitives/src/crdt.mjs`) is used
62
+ * PURELY ADDITIVELY -- `.remove()` is never called. A "revoke" is not a
63
+ * CRDT-level removal of a previous "grant" element; it is a new, independently
64
+ * signed record with `action: 'revoke'`. This matches the plan's own framing
65
+ * ("signed append-log") literally: nothing is ever retracted from the log,
66
+ * only appended to it. What a revoke actually does is handled entirely in
67
+ * the *interpretation* layer (`#computeEffective()` below), not in the CRDT
68
+ * layer -- keeping "is this signature/identity-binding valid" (a CRDT-merge
69
+ * admission gate) cleanly separate from "does this signer currently have the
70
+ * authority to do this" (a replay-time interpretation question that depends
71
+ * on the rest of the log).
72
+ *
73
+ * `#computeEffective()` walks every signature-valid, resource-matching
74
+ * record in one deterministic total order -- ascending `at`, ties broken
75
+ * `grant` before `revoke` (so a same-timestamp revoke always lands after,
76
+ * and therefore wins over, a same-timestamp grant of the same scope -- see
77
+ * "Concurrent grant+revoke" below), remaining ties broken by the record's
78
+ * own signature bytes (arbitrary but stable, guaranteeing every peer that
79
+ * merged the same set of records computes the identical order) -- while
80
+ * maintaining a running `adminSet`:
81
+ *
82
+ * - A record whose `scope` is this resource's admin scope
83
+ * (`<resource>:admin`), `action: 'grant'`, and `signedBy === pubKey`
84
+ * (self-signed) is treated as a BOOTSTRAP record -- applied
85
+ * unconditionally -- ONLY while `adminSet` is still empty. This is the
86
+ * one and only door into the admin set from nothing; see "Admin
87
+ * bootstrapping" below for why this is safe against forgery.
88
+ * - Every other record is applied (i.e. affects `adminSet` if it's an
89
+ * admin-scope record, or the per-pubKey/per-scope grant state
90
+ * otherwise) if and only if `signedBy` is ALREADY in `adminSet` at the
91
+ * point in the deterministic order where this record is being
92
+ * processed. A record whose `signedBy` never held admin authority (at
93
+ * the time its position in the order is reached) never affects
94
+ * anything -- exactly the "a non-admin claiming to grant is rejected"
95
+ * requirement, enforced at replay time rather than at merge time (a
96
+ * signature-valid-but-unauthorized record IS still accepted into the
97
+ * underlying `ORSet` -- the log records "this really was sent by this
98
+ * real peer" -- it just never becomes an effective grant, and
99
+ * therefore never reaches `PeerRegistry`).
100
+ *
101
+ * For each (pubKey, scope) pair, the LAST record reached in this order
102
+ * (that was actually authorized) determines the current effective action
103
+ * (`grant` or `revoke`) -- a simple per-key last-write-wins, deliberately
104
+ * mirroring `LWWMap`'s own already-accepted-as-a-known-limitation semantics
105
+ * (see the plan's Design decisions section) rather than inventing a
106
+ * different conflict model for this log.
107
+ *
108
+ * Known limitation (documented, not silently assumed correct, matching the
109
+ * family's existing convention for `LWWMap`): `at` is caller-supplied, not
110
+ * server-clock-arbitrated. A peer with a fast clock can make its own
111
+ * grant/revoke "win" a race it was not actually causally after. This is the
112
+ * same class of limitation already accepted for `LWWMap` in this plan's
113
+ * Design decisions section, applied consistently here rather than solved
114
+ * differently in one CRDT and not the other.
115
+ *
116
+ * Known limitation (revocation is not retroactive): once a record has been
117
+ * applied while its `signedBy` held admin authority, revoking that admin's
118
+ * authority *later* (in the deterministic order) does not retroactively
119
+ * invalidate grants they already issued -- each record's authorization is
120
+ * locked in using the adminSet state at the moment it is processed, not
121
+ * recomputed after the fact. Revoking what a since-demoted admin granted
122
+ * requires an explicit revoke record for those specific scopes. This
123
+ * mirrors `PeerRegistry`'s own capability-token model, where a granted
124
+ * token lives until it is itself explicitly revoked.
125
+ *
126
+ * ---------------------------------------------------------------------------
127
+ * Concurrent grant+revoke of the same scope: "sensible" is defined here as
128
+ * plain last-write-wins by `at` (see above), with `revoke` winning a same-
129
+ * `at` tie against `grant`. A later grant with a strictly greater `at` DOES
130
+ * re-authorize after a revoke (revoke is not a permanent, one-way tombstone
131
+ * the way `PeerRegistry`'s own capability tokens are for a single peer's
132
+ * local grants) -- because a replicated, multi-admin resource legitimately
133
+ * needs "un-revoke", e.g. an admin overturning another admin's revoke.
134
+ * Whichever authorized record has the latest `at` for that exact
135
+ * (pubKey, scope) pair simply wins, symmetrically in both directions.
136
+ *
137
+ * ---------------------------------------------------------------------------
138
+ * Admin bootstrapping: the peer that locally creates a bucket (or, more
139
+ * generally, this module's caller for any resource) calls
140
+ * `GrantLog.bootstrapAdmin()`, which self-signs the resource's admin scope
141
+ * to itself (`signedBy === pubKey === `the local identity`). This is the
142
+ * only record type the replay algorithm ever admits with no pre-existing
143
+ * admin, and only takes effect while `adminSet` is still empty at its
144
+ * position in the deterministic order -- so a forged self-signed
145
+ * admin-grant produced by an attacker AFTER a real bootstrap record already
146
+ * exists earlier in the merged log's order is correctly rejected (adminSet
147
+ * is non-empty by the time the forged record is reached, and the attacker's
148
+ * `signedBy` is not in it). The one sharp edge, stated plainly rather than
149
+ * silently assumed away: if two peers each believe they are the first to
150
+ * create the *same* resource id, whichever self-signed bootstrap record
151
+ * sorts first in the deterministic order (lowest `at`, then the tiebreakers
152
+ * above) wins sole admin status -- exactly the same "earliest write wins"
153
+ * exposure the plan already accepts for `LWWMap`, not a new one introduced
154
+ * here. Callers minting resource ids should make collisions practically
155
+ * impossible (e.g. include a random/content-addressed component), the same
156
+ * way this family already expects of any globally-shared identifier.
157
+ *
158
+ * ---------------------------------------------------------------------------
159
+ * Replay-diffing strategy into `PeerRegistry` (point 3's "real correctness
160
+ * question", not a style preference): every time the merged log changes
161
+ * (a local `grant()`/`revoke()`/`bootstrapAdmin()`, or a remote
162
+ * `mergeRemote()`), `#computeEffective()` is recomputed and diffed against
163
+ * the PREVIOUS effective snapshot, per pubKey, per scope. Only scopes that
164
+ * newly appear are passed to `registry.grantCapabilities()`; only scopes
165
+ * that disappeared are passed to `registry.revokeCapabilities()`; scopes
166
+ * whose state didn't change are never touched. This was a deliberate
167
+ * choice over the simpler-looking "revoke everything this pubKey ever had,
168
+ * then re-grant the fresh full set on every merge": that naive approach
169
+ * creates a real window (however small) where a concurrent `checkAccess()`
170
+ * call from another part of the running process observes the
171
+ * momentarily-fully-revoked state between the blind revoke and the
172
+ * re-grant -- a legitimate in-flight read/write could be denied for no
173
+ * real reason. Diffing means a scope that was granted before and still is
174
+ * after a merge is never revoked even transiently.
175
+ *
176
+ * ---------------------------------------------------------------------------
177
+ * Change notification (added for Phase E, `key-distribution.mjs`): an
178
+ * optional `onGrantChange` constructor callback, invoked once per affected
179
+ * `pubKey` at the end of every `#replay()` (local mutation or `mergeRemote()`
180
+ * alike -- the same single place the existing `registry.grantCapabilities()`/
181
+ * `revokeCapabilities()` diffing already runs), with `{pubKey, before, after,
182
+ * added, removed}` (`before`/`after` are the pre/post `Set<string>` of
183
+ * effective scopes for that `pubKey` on this resource; `added`/`removed` are
184
+ * arrays of the scopes that actually changed). This reuses the diff
185
+ * `#replay()` already computes for `PeerRegistry` -- no extra pass over the
186
+ * log. Phase E's key-distribution service uses `before.size === 0 &&
187
+ * after.size > 0` to detect "this pubKey just gained SOME capability on this
188
+ * resource" (equivalent to "gained any of read/write/delete/list/admin/
189
+ * replica" for an s3 resource, since those are the only six actions ever
190
+ * used -- this module still doesn't hardcode that list, staying resource-
191
+ * agnostic per its own design goal above). Follows this file's own established
192
+ * convention for optional constructor-injected callbacks (`onLog`) rather than
193
+ * introducing a new event-emitter dependency.
194
+ *
195
+ * ---------------------------------------------------------------------------
196
+ * Observability events (`ctx.emit()`, Phase 1 of the mesh-KV-and-
197
+ * observability plan -- see `mesh-service.mjs`'s module doc comment for the
198
+ * full convention this follows): `createGrantLogService()`'s `attach()`
199
+ * wraps the `onGrantChange` hook above (already the one place every
200
+ * effective grant/revoke transition is detected) to additionally emit:
201
+ *
202
+ * - `grant-log:grant-applied` `{resource, pubKey, added}` -- at least one
203
+ * new scope became effective for `pubKey` on this resource.
204
+ * - `grant-log:revoke-applied` `{resource, pubKey, removed}` -- at least
205
+ * one previously-effective scope stopped being effective for `pubKey`.
206
+ * - `grant-log:admin-changed` `{resource, pubKey, action}` (`action` is
207
+ * `'granted'` or `'revoked'`) -- fired IN ADDITION to the above when the
208
+ * specific scope that changed is this resource's admin scope, since an
209
+ * admin-authority change (including the very first bootstrap) is a
210
+ * materially more significant transition than an ordinary capability
211
+ * grant and is worth a dashboard being able to distinguish.
212
+ *
213
+ * These three are a deliberately small, curated set -- not a mechanical
214
+ * conversion of this file's `onLog` calls (which stay exactly what they are:
215
+ * reject/error-path debug logging for malformed or forged remote records).
216
+ *
217
+ * No browser-only imports at module level.
218
+ */
219
+
220
+ import { ORSet, encodeBase64url, decodeBase64url } from '@johnhenry/browsermesh-primitives'
221
+
222
+ /** Default `envelope.type` used to route GrantLog payloads on the shared `onIncomingData()` bus. */
223
+ const DEFAULT_ENVELOPE_TYPE = 'grant-log'
224
+
225
+ /** The action-scope segment reserved for admin authority (`<resource>:admin`). */
226
+ const ADMIN_ACTION = 'admin'
227
+
228
+ // ---------------------------------------------------------------------------
229
+ // Canonical JSON (mirrors audit.mjs's canonicalJSON: sorted keys, so the
230
+ // same logical record always signs/hashes to the same bytes regardless of
231
+ // property insertion order).
232
+ // ---------------------------------------------------------------------------
233
+
234
+ /**
235
+ * @param {object} obj
236
+ * @returns {string}
237
+ */
238
+ function canonicalJSON(obj) {
239
+ return JSON.stringify(obj, (_key, value) => {
240
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
241
+ const sorted = {}
242
+ for (const k of Object.keys(value).sort()) sorted[k] = value[k]
243
+ return sorted
244
+ }
245
+ return value
246
+ })
247
+ }
248
+
249
+ /**
250
+ * The exact fields that are signed -- everything in a record EXCEPT
251
+ * `signedByPubKeyBytes` and `signature` themselves.
252
+ *
253
+ * @param {{pubKey: string, scope: string, action: string, at: number, signedBy: string}} fields
254
+ * @returns {string}
255
+ */
256
+ function signedPayloadOf(fields) {
257
+ return canonicalJSON({
258
+ pubKey: fields.pubKey,
259
+ scope: fields.scope,
260
+ action: fields.action,
261
+ at: fields.at,
262
+ signedBy: fields.signedBy,
263
+ })
264
+ }
265
+
266
+ /**
267
+ * base64url(SHA-256(rawPublicKeyBytes)) -- the exact definition of
268
+ * `derivePodId()` in `browsermesh-primitives/src/identity.mjs`, duplicated
269
+ * here (one digest call) rather than imported, because that function takes
270
+ * a `CryptoKey` and re-exports the raw bytes internally; a receiving peer
271
+ * here already has the raw bytes (decoded from the record itself) and
272
+ * importing them into a `CryptoKey` purely to re-export them back out would
273
+ * be wasted work for the identical result.
274
+ *
275
+ * @param {Uint8Array} rawPublicKeyBytes
276
+ * @returns {Promise<string>}
277
+ */
278
+ async function podIdFromRawPublicKey(rawPublicKeyBytes) {
279
+ const hash = await crypto.subtle.digest('SHA-256', rawPublicKeyBytes)
280
+ return encodeBase64url(new Uint8Array(hash))
281
+ }
282
+
283
+ /** @param {string} resource @param {string} action @returns {string} */
284
+ function scopeFor(resource, action) {
285
+ return `${resource}:${action}`
286
+ }
287
+
288
+ // ---------------------------------------------------------------------------
289
+ // GrantLog
290
+ // ---------------------------------------------------------------------------
291
+
292
+ /**
293
+ * A signed, append-only, replicated grant/revoke log for one `resource`
294
+ * string (e.g. `s3:my-bucket`). Storage-agnostic and resource-agnostic by
295
+ * design -- it deals only in pubKey strings, scope strings, and signed
296
+ * records, never in the actual data a resource's capabilities gate access
297
+ * to.
298
+ */
299
+ export class GrantLog {
300
+ /** @type {string} */
301
+ #resource
302
+
303
+ /** @type {string} */
304
+ #localPodId
305
+
306
+ /** @type {import('@johnhenry/browsermesh-core').IdentityWallet} Duck-typed:
307
+ * only `.sign(podId, data)`, `.verify(pubKeyBytes, data, sig)`,
308
+ * `.getPublicKeyBytes(podId)` are used (the real `IdentityWallet`'s
309
+ * confirmed API, see identity-wallet.mjs / identity.mjs). */
310
+ #wallet
311
+
312
+ /** @type {import('./peer-registry.mjs').PeerRegistry} */
313
+ #registry
314
+
315
+ /** @type {Function} */
316
+ #onLog
317
+
318
+ /** @type {Function|null} See the module doc comment's "Change notification" section. */
319
+ #onGrantChange
320
+
321
+ /** @type {ORSet} Element type: canonical-JSON-stringified signed records. */
322
+ #orSet = new ORSet()
323
+
324
+ /** @type {{admins: Set<string>, grants: Map<string, Set<string>>}} Last replayed snapshot. */
325
+ #effective = { admins: new Set(), grants: new Map() }
326
+
327
+ /**
328
+ * The largest `at` this instance has ever issued locally. `Date.now()`'s
329
+ * millisecond resolution means two records built back-to-back from the
330
+ * SAME instance (e.g. `bootstrapAdmin()` immediately followed by
331
+ * `grant()`) can otherwise land on an identical `at`, and the
332
+ * deterministic tie-break (see `#compareRecords`) does not know these two
333
+ * came from a single, obviously-ordered call sequence -- it would resolve
334
+ * the tie the same arbitrary way it resolves a genuine cross-peer
335
+ * collision. Monotonically bumping `at` past whatever this instance has
336
+ * already issued preserves real local happens-before order for the common
337
+ * case (one admin issuing several records in a row) while leaving the
338
+ * documented, arbitrary-but-deterministic tie-break exactly as the only
339
+ * resolution for genuinely concurrent records from two different
340
+ * `GrantLog` instances (which can't see each other's clocks). This is a
341
+ * local-clock discipline, not a wire-format change -- `at` is still a
342
+ * plain number in every record.
343
+ * @type {number}
344
+ */
345
+ #lastIssuedAt = 0
346
+
347
+ /**
348
+ * @param {object} opts
349
+ * @param {string} opts.resource - e.g. `s3:my-bucket`. Every scope this
350
+ * log will ever grant/revoke/authorize is `${resource}:${action}`.
351
+ * @param {string} opts.localPodId - This peer's own identity, used as the
352
+ * CRDT node id for `ORSet.add()` and as the default admin identity for
353
+ * `grant()`/`revoke()`/`bootstrapAdmin()` when no `signedByPodId` is given.
354
+ * @param {import('@johnhenry/browsermesh-core').IdentityWallet} opts.wallet
355
+ * Real signing/verification -- see module doc comment.
356
+ * @param {import('./peer-registry.mjs').PeerRegistry} opts.registry -
357
+ * Replayed into via its existing, completely unmodified
358
+ * `grantCapabilities()`/`revokeCapabilities()`.
359
+ * @param {Function} [opts.onLog]
360
+ * @param {(change: {pubKey: string, before: Set<string>, after: Set<string>,
361
+ * added: string[], removed: string[]}) => void} [opts.onGrantChange] - See
362
+ * the module doc comment's "Change notification" section.
363
+ */
364
+ constructor({ resource, localPodId, wallet, registry, onLog, onGrantChange } = {}) {
365
+ if (!resource || typeof resource !== 'string') {
366
+ throw new Error('GrantLog: resource is required and must be a non-empty string')
367
+ }
368
+ if (!localPodId || typeof localPodId !== 'string') {
369
+ throw new Error('GrantLog: localPodId is required and must be a non-empty string')
370
+ }
371
+ if (!wallet || typeof wallet.sign !== 'function' || typeof wallet.verify !== 'function' ||
372
+ typeof wallet.getPublicKeyBytes !== 'function') {
373
+ throw new Error('GrantLog: wallet is required and must provide sign()/verify()/getPublicKeyBytes()')
374
+ }
375
+ if (!registry || typeof registry.grantCapabilities !== 'function' || typeof registry.revokeCapabilities !== 'function') {
376
+ throw new Error('GrantLog: registry is required and must provide grantCapabilities()/revokeCapabilities()')
377
+ }
378
+
379
+ this.#resource = resource
380
+ this.#localPodId = localPodId
381
+ this.#wallet = wallet
382
+ this.#registry = registry
383
+ this.#onLog = onLog || (() => {})
384
+ this.#onGrantChange = typeof onGrantChange === 'function' ? onGrantChange : null
385
+ }
386
+
387
+ /** @returns {string} */
388
+ get resource() {
389
+ return this.#resource
390
+ }
391
+
392
+ /** @returns {string} The reserved admin scope for this resource (`<resource>:admin`). */
393
+ get adminScope() {
394
+ return scopeFor(this.#resource, ADMIN_ACTION)
395
+ }
396
+
397
+ // -----------------------------------------------------------------------
398
+ // Record construction (local mutation)
399
+ // -----------------------------------------------------------------------
400
+
401
+ /**
402
+ * @param {{pubKey: string, scope: string, action: 'grant'|'revoke', signedByPodId: string}} fields
403
+ * @returns {Promise<object>} A fully signed record.
404
+ */
405
+ async #buildRecord({ pubKey, scope, action, signedByPodId }) {
406
+ const signedByPubKeyBytes = await this.#wallet.getPublicKeyBytes(signedByPodId)
407
+ const at = Math.max(Date.now(), this.#lastIssuedAt + 1)
408
+ this.#lastIssuedAt = at
409
+ const unsigned = { pubKey, scope, action, at, signedBy: signedByPodId }
410
+ const payload = new TextEncoder().encode(signedPayloadOf(unsigned))
411
+ const signature = await this.#wallet.sign(signedByPodId, payload)
412
+ return {
413
+ ...unsigned,
414
+ signedByPubKeyBytes: encodeBase64url(signedByPubKeyBytes),
415
+ signature: encodeBase64url(signature),
416
+ }
417
+ }
418
+
419
+ /** @param {object} record */
420
+ #addLocal(record) {
421
+ this.#orSet.add(canonicalJSON(record), this.#localPodId)
422
+ }
423
+
424
+ /**
425
+ * Throws unless `adminPodId` is currently an authorized admin for this
426
+ * resource (per the last computed replay), UNLESS `allowBootstrap` is set
427
+ * and there is no admin at all yet (the only case `bootstrapAdmin()` uses).
428
+ *
429
+ * @param {string} adminPodId
430
+ * @param {boolean} allowBootstrap
431
+ */
432
+ #assertCanAdminister(adminPodId, allowBootstrap) {
433
+ if (allowBootstrap && this.#effective.admins.size === 0) return
434
+ if (!this.#effective.admins.has(adminPodId)) {
435
+ throw new Error(
436
+ `GrantLog: '${adminPodId}' is not a current admin of '${this.#resource}' -- ` +
437
+ 'a record it signs would be rejected by every peer\'s replay anyway',
438
+ )
439
+ }
440
+ }
441
+
442
+ /**
443
+ * Grant one or more capability actions on this resource to `pubKey`,
444
+ * signed by `signedByPodId` (defaults to this log's `localPodId`).
445
+ * `signedByPodId` must be an identity `wallet` can sign with (i.e. a
446
+ * local identity) AND a currently authorized admin -- see
447
+ * `#assertCanAdminister()`.
448
+ *
449
+ * @param {string} pubKey - Grantee.
450
+ * @param {string|string[]} actions - Bare capability suffixes, e.g. 'read'
451
+ * or ['read', 'write']. Full scope = `${resource}:${action}`.
452
+ * @param {object} [opts]
453
+ * @param {string} [opts.signedByPodId]
454
+ * @returns {Promise<void>}
455
+ */
456
+ async grant(pubKey, actions, opts = {}) {
457
+ await this.#mutate(pubKey, actions, 'grant', opts)
458
+ }
459
+
460
+ /**
461
+ * Revoke one or more capability actions on this resource from `pubKey`.
462
+ * See `grant()` for parameters.
463
+ *
464
+ * @param {string} pubKey
465
+ * @param {string|string[]} actions
466
+ * @param {object} [opts]
467
+ * @returns {Promise<void>}
468
+ */
469
+ async revoke(pubKey, actions, opts = {}) {
470
+ await this.#mutate(pubKey, actions, 'revoke', opts)
471
+ }
472
+
473
+ /**
474
+ * @param {string} pubKey
475
+ * @param {string|string[]} actions
476
+ * @param {'grant'|'revoke'} action
477
+ * @param {object} opts
478
+ */
479
+ async #mutate(pubKey, actions, action, { signedByPodId } = {}) {
480
+ if (!pubKey || typeof pubKey !== 'string') {
481
+ throw new Error('GrantLog: pubKey is required and must be a non-empty string')
482
+ }
483
+ const list = Array.isArray(actions) ? actions : [actions]
484
+ if (list.length === 0) throw new Error('GrantLog: at least one action is required')
485
+
486
+ const adminPodId = signedByPodId || this.#localPodId
487
+ this.#assertCanAdminister(adminPodId, false)
488
+
489
+ for (const capAction of list) {
490
+ const scope = scopeFor(this.#resource, capAction)
491
+ const record = await this.#buildRecord({ pubKey, scope, action, signedByPodId: adminPodId })
492
+ this.#addLocal(record)
493
+ }
494
+ await this.#replay()
495
+ }
496
+
497
+ /**
498
+ * Seed this resource's admin scope with a self-signed record for
499
+ * `pubKey` (defaults to `localPodId`). Only ever takes effect (during
500
+ * replay, on every peer) while no admin yet exists for this resource --
501
+ * see the module doc comment's "Admin bootstrapping" section. Safe to
502
+ * call even if an admin already exists (the resulting record simply
503
+ * never becomes effective anywhere), but callers should only invoke this
504
+ * when actually creating a brand-new resource, not on every re-attach.
505
+ *
506
+ * @param {string} [pubKey]
507
+ * @returns {Promise<void>}
508
+ */
509
+ async bootstrapAdmin(pubKey = this.#localPodId) {
510
+ const record = await this.#buildRecord({
511
+ pubKey,
512
+ scope: this.adminScope,
513
+ action: 'grant',
514
+ signedByPodId: pubKey,
515
+ })
516
+ this.#addLocal(record)
517
+ await this.#replay()
518
+ }
519
+
520
+ // -----------------------------------------------------------------------
521
+ // Verification (Phase D's core security property)
522
+ // -----------------------------------------------------------------------
523
+
524
+ /**
525
+ * Verify a record's signature AND that its claimed `signedBy` identity is
526
+ * actually bound to the embedded public key bytes. Never throws --
527
+ * returns false for anything malformed, forged, or tampered.
528
+ *
529
+ * @param {*} record
530
+ * @returns {Promise<boolean>}
531
+ */
532
+ async #verifyRecord(record) {
533
+ try {
534
+ if (!record || typeof record !== 'object') return false
535
+ const { pubKey, scope, action, at, signedBy, signedByPubKeyBytes, signature } = record
536
+ if (typeof pubKey !== 'string' || !pubKey) return false
537
+ if (typeof scope !== 'string' || !scope.startsWith(`${this.#resource}:`)) return false
538
+ if (action !== 'grant' && action !== 'revoke') return false
539
+ if (typeof at !== 'number' || !Number.isFinite(at)) return false
540
+ if (typeof signedBy !== 'string' || !signedBy) return false
541
+ if (typeof signedByPubKeyBytes !== 'string' || typeof signature !== 'string') return false
542
+
543
+ const rawPubKeyBytes = decodeBase64url(signedByPubKeyBytes)
544
+ const sigBytes = decodeBase64url(signature)
545
+
546
+ // Identity binding: the claimed `signedBy` string must actually BE
547
+ // derived from the embedded public key bytes -- otherwise anyone
548
+ // could claim to be any podId while signing with their own key.
549
+ const derivedPodId = await podIdFromRawPublicKey(rawPubKeyBytes)
550
+ if (derivedPodId !== signedBy) return false
551
+
552
+ const payload = new TextEncoder().encode(signedPayloadOf({ pubKey, scope, action, at, signedBy }))
553
+ return await this.#wallet.verify(rawPubKeyBytes, payload, sigBytes)
554
+ } catch {
555
+ // Malformed base64url, wrong-length keys/signatures, etc. are all
556
+ // "reject", never a thrown error the caller has to remember to catch.
557
+ return false
558
+ }
559
+ }
560
+
561
+ // -----------------------------------------------------------------------
562
+ // Merge (remote input -- the only path untrusted data enters this log)
563
+ // -----------------------------------------------------------------------
564
+
565
+ /**
566
+ * Merge a remote peer's serialized `ORSet` state
567
+ * (`{elements: [{element, tags}], tombstones: [...]}`, as produced by
568
+ * `toJSON()`/exchanged over the wire) into this log. Every element is
569
+ * independently parsed and verified BEFORE being admitted -- a record
570
+ * that fails verification (bad signature, tampered field, forged
571
+ * identity binding) is discarded here and never reaches the underlying
572
+ * `ORSet`, let alone `PeerRegistry`.
573
+ *
574
+ * Tombstones are never honoured: this log never calls `ORSet.remove()`
575
+ * (see module doc comment), so a remote tombstone claim can only ever be
576
+ * meaningless noise, not a byte-for-byte trustworthy directive -- it is
577
+ * always ignored rather than blindly merged in.
578
+ *
579
+ * @param {{elements: Array<{element: string, tags: string[]}>, tombstones?: string[]}} remoteOrSetJSON
580
+ * @returns {Promise<void>}
581
+ */
582
+ async mergeRemote(remoteOrSetJSON) {
583
+ if (!remoteOrSetJSON || !Array.isArray(remoteOrSetJSON.elements)) return
584
+
585
+ const acceptedElements = []
586
+ for (const entry of remoteOrSetJSON.elements) {
587
+ if (!entry || typeof entry.element !== 'string' || !Array.isArray(entry.tags)) continue
588
+ let record
589
+ try {
590
+ record = JSON.parse(entry.element)
591
+ } catch {
592
+ this.#onLog('grant-log:reject-malformed', { resource: this.#resource })
593
+ continue
594
+ }
595
+ const valid = await this.#verifyRecord(record)
596
+ if (!valid) {
597
+ this.#onLog('grant-log:reject-invalid-signature', { resource: this.#resource, record })
598
+ continue
599
+ }
600
+ acceptedElements.push(entry)
601
+ }
602
+
603
+ const remoteSet = ORSet.fromJSON({ elements: acceptedElements, tombstones: [] })
604
+ this.#orSet = this.#orSet.merge(remoteSet)
605
+ await this.#replay()
606
+ }
607
+
608
+ // -----------------------------------------------------------------------
609
+ // Replay
610
+ // -----------------------------------------------------------------------
611
+
612
+ /**
613
+ * Deterministic total order comparator over live (parsed) records --
614
+ * ascending `at`; ties broken `grant` before `revoke`; remaining ties
615
+ * broken by signature bytes (arbitrary, stable, identical on every peer).
616
+ *
617
+ * @param {object} a
618
+ * @param {object} b
619
+ * @returns {number}
620
+ */
621
+ static #compareRecords(a, b) {
622
+ if (a.at !== b.at) return a.at - b.at
623
+ const rank = (r) => (r.action === 'grant' ? 0 : 1)
624
+ if (rank(a) !== rank(b)) return rank(a) - rank(b)
625
+ if (a.signature < b.signature) return -1
626
+ if (a.signature > b.signature) return 1
627
+ return 0
628
+ }
629
+
630
+ /**
631
+ * Replay every currently-held record (already merge-time verified -- see
632
+ * `mergeRemote()`/local construction, both of which only ever produce/admit
633
+ * verified records) in deterministic order, computing the current
634
+ * authorized admin set and per-pubKey effective grants.
635
+ *
636
+ * @returns {{admins: Set<string>, grants: Map<string, Set<string>>}}
637
+ */
638
+ #computeEffective() {
639
+ const records = [...this.#orSet.value].map((str) => JSON.parse(str))
640
+ records.sort(GrantLog.#compareRecords)
641
+
642
+ const adminScope = this.adminScope
643
+ const adminSet = new Set()
644
+ /** @type {Map<string, Map<string, 'grant'|'revoke'>>} pubKey -> scope -> last action */
645
+ const perPubKeyScope = new Map()
646
+
647
+ for (const record of records) {
648
+ const { pubKey, scope, action, signedBy } = record
649
+ const isAdminScope = scope === adminScope
650
+ const isBootstrap = isAdminScope && adminSet.size === 0 && action === 'grant' && signedBy === pubKey
651
+ const authorized = isBootstrap || adminSet.has(signedBy)
652
+ if (!authorized) continue
653
+
654
+ let byScope = perPubKeyScope.get(pubKey)
655
+ if (!byScope) {
656
+ byScope = new Map()
657
+ perPubKeyScope.set(pubKey, byScope)
658
+ }
659
+ byScope.set(scope, action)
660
+
661
+ if (isAdminScope) {
662
+ if (action === 'grant') adminSet.add(pubKey)
663
+ else adminSet.delete(pubKey)
664
+ }
665
+ }
666
+
667
+ const grants = new Map()
668
+ for (const [pubKey, byScope] of perPubKeyScope) {
669
+ const active = new Set()
670
+ for (const [scope, action] of byScope) {
671
+ if (action === 'grant') active.add(scope)
672
+ }
673
+ if (active.size > 0) grants.set(pubKey, active)
674
+ }
675
+
676
+ return { admins: adminSet, grants }
677
+ }
678
+
679
+ /**
680
+ * Recompute the effective state and diff it against the previous
681
+ * snapshot, calling `registry.grantCapabilities()`/`revokeCapabilities()`
682
+ * ONLY for scopes that actually appeared/disappeared for each pubKey --
683
+ * see the module doc comment's replay-diffing section for why this is
684
+ * not just "revoke everything, re-grant the fresh set".
685
+ */
686
+ async #replay() {
687
+ const next = this.#computeEffective()
688
+ const prevGrants = this.#effective.grants
689
+
690
+ const allPubKeys = new Set([...prevGrants.keys(), ...next.grants.keys()])
691
+ for (const pubKey of allPubKeys) {
692
+ const before = prevGrants.get(pubKey) || new Set()
693
+ const after = next.grants.get(pubKey) || new Set()
694
+
695
+ const added = [...after].filter((s) => !before.has(s))
696
+ const removed = [...before].filter((s) => !after.has(s))
697
+
698
+ if (added.length > 0) this.#registry.grantCapabilities(pubKey, added)
699
+ if (removed.length > 0) this.#registry.revokeCapabilities(pubKey, removed)
700
+
701
+ if ((added.length > 0 || removed.length > 0) && this.#onGrantChange) {
702
+ this.#onGrantChange({ pubKey, before, after, added, removed })
703
+ }
704
+ }
705
+
706
+ this.#effective = next
707
+ }
708
+
709
+ // -----------------------------------------------------------------------
710
+ // Introspection / serialization
711
+ // -----------------------------------------------------------------------
712
+
713
+ /** @returns {{admins: string[], grants: Object<string, string[]>}} A snapshot of the last replay. */
714
+ effective() {
715
+ const grants = {}
716
+ for (const [pubKey, scopes] of this.#effective.grants) grants[pubKey] = [...scopes]
717
+ return { admins: [...this.#effective.admins], grants }
718
+ }
719
+
720
+ /** @returns {object} The underlying `ORSet`'s serialized state, for wire transmission. */
721
+ toJSON() {
722
+ return this.#orSet.toJSON()
723
+ }
724
+ }
725
+
726
+ // ---------------------------------------------------------------------------
727
+ // MeshService wiring (Phase C consumer)
728
+ // ---------------------------------------------------------------------------
729
+
730
+ /**
731
+ * Build a `MeshService` descriptor (`mesh-service.mjs`, Phase C) that
732
+ * attaches a `GrantLog` for `resource` to a `PeerNode`, routing its wire
733
+ * payloads over `ctx.onIncomingData()`/`ctx.sendTo()` under `envelopeType`.
734
+ *
735
+ * Known Phase C friction, noted per this phase's brief rather than silently
736
+ * worked around: `attachService()`'s per-service handle is `{name,
737
+ * backendScheme, teardown}` -- there is no field carrying the constructed
738
+ * service instance back to the caller, so a `services: [...]` consumer that
739
+ * (unlike a netway `Backend`) needs to actively call methods on what it
740
+ * attached (`grant()`, `revoke()`, `bootstrapAdmin()`, `syncWith()`) has no
741
+ * route to it through `attachService()`'s own return value alone. This
742
+ * factory works around that with an `onReady(api)` callback invoked
743
+ * synchronously from inside `attach()`, which is also why `bootstrapAdmin`
744
+ * is NOT offered as an auto-run-on-attach constructor option: `MeshService.
745
+ * attach()` is called synchronously and its return value is checked with
746
+ * `typeof attachTeardown === 'function'` (`mesh-service.mjs`) -- an async
747
+ * `attach()` would return a Promise there, which is not a function, so
748
+ * `attachService()` would silently never call its teardown. Any
749
+ * async setup this kind of service needs (signing a bootstrap record
750
+ * requires `crypto.subtle`, which is inherently async) therefore has to be
751
+ * exposed as a separately-awaitable method on the instance the caller gets
752
+ * back via `onReady`, not run eagerly inside `attach()` itself. Worth
753
+ * considering for a future Phase-C revision: an optional `instance` field
754
+ * on `attachService()`'s returned handle.
755
+ *
756
+ * @param {object} opts
757
+ * @param {string} opts.resource - e.g. `s3:my-bucket`. See `GrantLog`.
758
+ * @param {string} [opts.envelopeType='grant-log']
759
+ * @param {(api: {resource: string, grant: Function, revoke: Function,
760
+ * bootstrapAdmin: Function, syncWith: Function, effective: Function,
761
+ * toJSON: Function}) => void} [opts.onReady] - Invoked synchronously
762
+ * inside `attach()` with the service's public API. This is the only way
763
+ * to get a handle back to call `grant()`/`bootstrapAdmin()`/etc. later
764
+ * (see the friction note above).
765
+ * @param {Function} [opts.onLog]
766
+ * @param {(change: {pubKey: string, before: Set<string>, after: Set<string>,
767
+ * added: string[], removed: string[]}) => void} [opts.onGrantChange] -
768
+ * Forwarded to `GrantLog`'s constructor. See that module's doc comment's
769
+ * "Change notification" section -- this is Phase E's (`key-distribution.mjs`)
770
+ * hook into "a pubKey just gained some capability on this resource".
771
+ * @returns {import('./mesh-service.mjs').MeshService}
772
+ */
773
+ export function createGrantLogService({ resource, envelopeType = DEFAULT_ENVELOPE_TYPE, onReady, onLog, onGrantChange } = {}) {
774
+ if (!resource || typeof resource !== 'string') {
775
+ throw new Error('createGrantLogService: resource is required and must be a non-empty string')
776
+ }
777
+
778
+ return {
779
+ name: `grant-log:${resource}`,
780
+
781
+ attach(peerNode, ctx) {
782
+ const grantLog = new GrantLog({
783
+ resource,
784
+ localPodId: peerNode.podId,
785
+ wallet: peerNode.wallet,
786
+ registry: ctx.registry,
787
+ onLog,
788
+ // Wrap the caller-supplied onGrantChange (if any) so Phase E's
789
+ // key-distribution wiring keeps working unmodified, while also
790
+ // publishing this file's own curated ctx.emit() vocabulary -- see
791
+ // module doc comment's "Observability events" section.
792
+ onGrantChange(change) {
793
+ const { pubKey, added, removed } = change
794
+ if (added.length > 0) {
795
+ ctx.emit('grant-log:grant-applied', { resource, pubKey, added })
796
+ if (added.includes(grantLog.adminScope)) {
797
+ ctx.emit('grant-log:admin-changed', { resource, pubKey, action: 'granted' })
798
+ }
799
+ }
800
+ if (removed.length > 0) {
801
+ ctx.emit('grant-log:revoke-applied', { resource, pubKey, removed })
802
+ if (removed.includes(grantLog.adminScope)) {
803
+ ctx.emit('grant-log:admin-changed', { resource, pubKey, action: 'revoked' })
804
+ }
805
+ }
806
+ if (typeof onGrantChange === 'function') onGrantChange(change)
807
+ },
808
+ })
809
+
810
+ const unsubscribe = ctx.onIncomingData(envelopeType, (fromPubKey, data) => {
811
+ if (!data || data.resource !== resource || !data.orSet) return
812
+ grantLog.mergeRemote(data.orSet).catch((err) => {
813
+ if (onLog) onLog('grant-log-service:merge-error', { from: fromPubKey, resource, error: err?.message || String(err) })
814
+ })
815
+ })
816
+
817
+ async function syncWith(pubKey) {
818
+ await ctx.sendTo(pubKey, envelopeType, { resource, orSet: grantLog.toJSON() })
819
+ }
820
+
821
+ const api = {
822
+ resource,
823
+ grant: (pubKey, actions, opts) => grantLog.grant(pubKey, actions, opts),
824
+ revoke: (pubKey, actions, opts) => grantLog.revoke(pubKey, actions, opts),
825
+ bootstrapAdmin: (pubKey) => grantLog.bootstrapAdmin(pubKey),
826
+ syncWith,
827
+ effective: () => grantLog.effective(),
828
+ toJSON: () => grantLog.toJSON(),
829
+ }
830
+
831
+ if (typeof onReady === 'function') onReady(api)
832
+
833
+ return () => {
834
+ unsubscribe()
835
+ }
836
+ },
837
+ }
838
+ }
839
+
840
+ export { DEFAULT_ENVELOPE_TYPE, ADMIN_ACTION }