@johnhenry/browsermesh-apps 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +232 -1
  2. package/package.json +7 -3
  3. package/src/agent-runtime.mjs +342 -0
  4. package/src/chunk-replication.mjs +751 -0
  5. package/src/cloud-storage-backend.mjs +932 -0
  6. package/src/cloud-storage.mjs +859 -0
  7. package/src/compat.mjs +98 -0
  8. package/src/grant-log.mjs +840 -0
  9. package/src/index.mjs +34 -2
  10. package/src/key-distribution.mjs +525 -0
  11. package/src/manifest-sync.mjs +363 -0
  12. package/src/mesh-agent-swarm.mjs +376 -0
  13. package/src/mesh-bootstrap.mjs +1131 -12
  14. package/src/mesh-compute.mjs +397 -0
  15. package/src/mesh-dht.mjs +182 -0
  16. package/src/mesh-fetch.mjs +246 -0
  17. package/src/mesh-hardening.mjs +226 -0
  18. package/src/mesh-health.mjs +282 -0
  19. package/src/mesh-keepalive.mjs +353 -0
  20. package/src/mesh-kv.mjs +673 -0
  21. package/src/mesh-orchestrator-tools.mjs +251 -0
  22. package/src/mesh-orchestrator.mjs +343 -0
  23. package/src/mesh-rpc.mjs +300 -0
  24. package/src/mesh-service.mjs +403 -0
  25. package/src/mesh-swarm.mjs +677 -0
  26. package/src/mesh-timestamp.mjs +265 -0
  27. package/src/mesh-torrent.mjs +683 -0
  28. package/src/mesh-verification.mjs +367 -0
  29. package/src/mesh-websocket.mjs +722 -0
  30. package/src/observability-bridge.mjs +453 -0
  31. package/src/orchestrator.mjs +18 -5
  32. package/src/peer-agent-swarm.mjs +12 -1
  33. package/src/peer-chat.mjs +230 -61
  34. package/src/peer-compute.mjs +66 -3
  35. package/src/peer-escrow.mjs +350 -1
  36. package/src/peer-files.mjs +362 -168
  37. package/src/peer-ipfs.mjs +205 -10
  38. package/src/peer-node.mjs +33 -2
  39. package/src/peer-routing.mjs +369 -5
  40. package/src/peer-terminal.mjs +400 -130
  41. package/src/serverless-executor-andbox.mjs +136 -0
  42. package/src/serverless-fetch.mjs +70 -0
  43. package/src/serverless-functions.mjs +67 -0
  44. package/src/serverless-peer-select.mjs +69 -0
  45. package/src/serverless-proxy.mjs +127 -0
  46. package/src/serverless-router.mjs +115 -0
  47. package/src/serverless-sites.mjs +116 -0
  48. package/src/serverless-static.mjs +202 -0
  49. package/src/serverless-wire.mjs +87 -0
  50. package/src/peer-session.mjs +0 -937
package/src/index.mjs CHANGED
@@ -27,20 +27,52 @@ export * from './signaling.mjs';
27
27
  export * from './webrtc-negotiator.mjs';
28
28
  export * from './mesh-bootstrap.mjs';
29
29
  export * from './mesh-sync.mjs';
30
+ export * from './mesh-dht.mjs';
30
31
  export * from './kernel-mesh.mjs';
31
32
  export * from './mesh-relay-host.mjs';
32
33
  export * from './mesh-relay-backend.mjs';
34
+ export * from './mesh-service.mjs';
35
+ export * from './mesh-timestamp.mjs';
36
+ export * from './mesh-health.mjs';
37
+ export * from './mesh-verification.mjs';
38
+ export * from './mesh-torrent.mjs';
39
+ export * from './mesh-compute.mjs';
40
+ export * from './mesh-swarm.mjs';
41
+ export * from './mesh-agent-swarm.mjs';
42
+ export * from './mesh-orchestrator.mjs';
43
+ export * from './cloud-storage-backend.mjs';
44
+ export * from './grant-log.mjs';
45
+ export * from './key-distribution.mjs';
46
+ export * from './manifest-sync.mjs';
47
+ export * from './chunk-replication.mjs';
48
+ export * from './mesh-rpc.mjs';
49
+ export * from './mesh-keepalive.mjs';
50
+ export * from './mesh-fetch.mjs';
51
+ export * from './mesh-websocket.mjs';
52
+ export * from './cloud-storage.mjs';
53
+ export * from './serverless-wire.mjs';
54
+ export * from './serverless-static.mjs';
55
+ export * from './serverless-router.mjs';
56
+ export * from './serverless-fetch.mjs';
57
+ export * from './serverless-proxy.mjs';
58
+ export * from './serverless-functions.mjs';
59
+ export * from './serverless-executor-andbox.mjs';
60
+ export * from './serverless-peer-select.mjs';
61
+ export * from './serverless-sites.mjs';
62
+ export * from './observability-bridge.mjs';
63
+ export * from './mesh-kv.mjs';
33
64
  export * from './peer-payments.mjs';
34
65
  export * from './peer-registry.mjs';
35
66
  export * from './peer-routing.mjs';
36
67
  export * from './peer-services.mjs';
37
- export * from './peer-session.mjs';
38
68
  export * from './peer-terminal.mjs';
39
69
  export * from './peer-timestamp.mjs';
40
70
  export * from './peer-torrent.mjs';
41
71
  export * from './peer-verification.mjs';
42
72
  export * from './marketplace-ui.mjs';
43
- export { BrowserTool } from './compat.mjs';
73
+ export { BrowserTool, BrowserToolRegistry } from './compat.mjs';
74
+ export * from './agent-runtime.mjs';
75
+ export * from './mesh-orchestrator-tools.mjs';
44
76
 
45
77
  // `CreditLedger` is defined in both payments.mjs and peer-payments.mjs;
46
78
  // `EscrowManager` is defined in both payments.mjs and peer-escrow.mjs.
@@ -0,0 +1,525 @@
1
+ /**
2
+ * key-distribution.mjs -- Phase E of the mesh-native-services plan
3
+ * ("CloudStorage: S3-like object storage"): whenever a bucket's replicated
4
+ * `GrantLog` (Phase D, `grant-log.mjs`) admits a peer's first capability on a
5
+ * bucket, a peer that already holds the bucket's AES-256-GCM key sends it to
6
+ * the newly-granted peer over a **new, dedicated** point-to-point channel,
7
+ * encrypted to the recipient -- never over the manifest/chunk sync channels,
8
+ * and never in plaintext.
9
+ *
10
+ * ---------------------------------------------------------------------------
11
+ * Critical open question the plan explicitly flagged, resolved by inspection
12
+ * (not assumption) before writing this file:
13
+ *
14
+ * Does `browsermesh-core`/`browsermesh-primitives` already expose an
15
+ * asymmetric encrypt-to-pubkey primitive? YES: `browsermesh-core`'s
16
+ * `group-keys.mjs` (`wrapKeyForMember()`/`unwrapKeyForMember()`) already
17
+ * implements exactly this -- X25519 ECDH + AES-GCM key wrap, ECIES-style
18
+ * (a fresh ephemeral X25519 keypair per envelope, so a single envelope's
19
+ * compromise never exposes any other envelope or the sender's long-term
20
+ * key), built entirely on WebCrypto (`crypto.subtle`), with no third-party
21
+ * crypto dependency -- consistent with every `package.json` in this repo
22
+ * having zero crypto npm dependencies anywhere (`grep`-verified). This file
23
+ * reuses those two functions as-is rather than adding a new primitive.
24
+ *
25
+ * The one real wrinkle: `wrapKeyForMember()`/`unwrapKeyForMember()` operate
26
+ * on X25519 keys, not the Ed25519 identity keypair every peer's `podId` is
27
+ * derived from (`browsermesh-primitives/src/identity.mjs`) -- X25519 (key
28
+ * agreement) and Ed25519 (signatures) are different curves with no WebCrypto-
29
+ * exposed conversion between them, and this repo has no Ed25519-to-X25519
30
+ * conversion utility (deliberately not adding one here: that conversion is
31
+ * real elliptic-curve field arithmetic with no test-vector coverage anywhere
32
+ * in this family, a meaningfully riskier thing to hand-roll than reusing an
33
+ * already-tested primitive). So "encrypted to the recipient's identity
34
+ * public key" is implemented as: each peer generates (once, on attach) its
35
+ * own X25519 "encryption key" the same way `GroupKeyManager.initEncryption()`
36
+ * already does, and this file adds a minimal `announce`/`deliver` handshake
37
+ * (below) so a sender can learn a recipient's X25519 key before it can wrap
38
+ * anything for them -- the recipient's *identity* (`podId`) is still what
39
+ * every message is addressed to/signed by, and it's the identity's Ed25519
40
+ * key that authenticates the actual key-bearing `deliver` message (see
41
+ * below); only the wrap/unwrap step itself runs on the companion X25519 key.
42
+ *
43
+ * ---------------------------------------------------------------------------
44
+ * Wire protocol -- two message kinds sharing one envelope `type`
45
+ * (default `'bucket-key'`), both scoped to one `resource` (matching
46
+ * `GrantLog`'s `s3:<bucketId>` convention exactly, since the two logs must
47
+ * agree on the same bucket):
48
+ *
49
+ * `{ type, resource, kind: 'announce', encryptionPublicKey }`
50
+ * Advertises the sender's own X25519 public key (raw bytes, base64).
51
+ * Not itself signed -- see "Trust model" below for why that's fine.
52
+ * Sent in two situations:
53
+ * (a) by a peer that just gained its OWN first capability on this
54
+ * resource (`onGrantChange` fired with `pubKey === localPodId`),
55
+ * addressed to every currently-known admin, so they can push the
56
+ * key back; and
57
+ * (b) implicitly answered by the RECEIVING side re-checking the
58
+ * GrantLog's current effective state on every inbound `announce`
59
+ * (see `#maybeDeliverTo`) -- covers the reverse ordering, where a
60
+ * peer was granted access before it ever announced (e.g. it was
61
+ * offline, or attached this service after the grant already
62
+ * happened).
63
+ *
64
+ * `{ type, resource, kind: 'deliver', envelope: {ephemeralPublicKey,
65
+ * wrappedKey, iv}, at, signedBy, signedByPubKeyBytes, signature }`
66
+ * The actual wrapped bucket key. `envelope` is exactly
67
+ * `wrapKeyForMember()`'s return shape. The rest mirrors `grant-log.mjs`'s
68
+ * own self-verifying record shape byte-for-byte (same canonical-JSON-
69
+ * over-sorted-keys signing convention, same "derive the podId from the
70
+ * embedded raw public key bytes and require it to match the claimed
71
+ * `signedBy`" identity binding) -- deliberately duplicated rather than
72
+ * imported, matching this file's siblings' own established convention of
73
+ * small, self-contained per-file crypto helpers rather than a shared
74
+ * signing-record module.
75
+ *
76
+ * ---------------------------------------------------------------------------
77
+ * Trust model for `deliver` (this phase's actual security property, and the
78
+ * one this phase's tests exist to prove):
79
+ *
80
+ * 1. Signature + identity binding: `signedBy` must be the real podId
81
+ * derived from the embedded raw Ed25519 public key bytes, AND the
82
+ * signature over the canonical payload must verify against those same
83
+ * bytes. A record failing either check is discarded outright -- this
84
+ * alone rejects "unsigned" or "wrong key" forgeries.
85
+ * 2. Authorization: even a validly self-signed record is discarded unless
86
+ * `signedBy` is CURRENTLY (per this peer's own locally-replayed
87
+ * `GrantLog` effective state, the same trust root `PeerRegistry`
88
+ * already relies on) either this resource's admin, or holds at least
89
+ * one grant on this resource -- i.e. is someone this protocol's own
90
+ * design would legitimately have handed the key to already. This
91
+ * rejects "claiming to be from a non-admin/non-key-holder".
92
+ *
93
+ * `announce` deliberately has NO signature layer. Rationale: its only effect
94
+ * is "the sender learns an X25519 public key to wrap a key toward" -- a
95
+ * forged announce (attacker claims to be podId P with the attacker's own
96
+ * X25519 key) makes a recipient wrap the real bucket key toward the
97
+ * ATTACKER's key, but `ctx.sendTo()` (`mesh-service.mjs`) still routes the
98
+ * resulting `deliver` message through `PeerNode`'s own authenticated,
99
+ * podId-addressed session for P (`PeerNode.sendTo` throws if there is no
100
+ * active session for that pubKey) -- so the real P receives ciphertext it
101
+ * cannot unwrap (a delivery denial-of-service against P), not a
102
+ * confidentiality leak, unless the attacker has ALSO compromised the
103
+ * transport-level session binding itself, a strictly larger threat model
104
+ * this whole family's identity/session layer is already relied on to
105
+ * prevent everywhere else, not something this one file can additionally
106
+ * defend against. This is a deliberate, documented scope boundary, not an
107
+ * oversight: the actual secret-bearing message (`deliver`) is fully signed
108
+ * and authorization-checked; the key-agreement bootstrapping step
109
+ * (`announce`) is not, because its own worst case is self-limiting.
110
+ *
111
+ * ---------------------------------------------------------------------------
112
+ * Composition with `createGrantLogService()` (Phase D): this service's
113
+ * `onGrantChange` hook must be wired into the SAME `GrantLog` instance this
114
+ * service authorizes `deliver` messages against, and `GrantLog`'s
115
+ * `onGrantChange` is a single constructor-time callback (see that module's
116
+ * doc comment), not a multi-subscriber event bus -- so attach THIS service
117
+ * first (its `attach()` returns `{api}` synchronously, before anything can
118
+ * fire), then attach `createGrantLogService()` passing this service's
119
+ * `api.handleGrantChange` as `onGrantChange` and capturing the GrantLog's own
120
+ * `api` via `onReady` into a variable this service's `getEffective` closure
121
+ * reads lazily:
122
+ *
123
+ * let grantLogApi
124
+ * const keyDist = attachService(node, network, createKeyDistributionService({
125
+ * resource, getLocalKey, setReceivedKey,
126
+ * getEffective: () => grantLogApi.effective(),
127
+ * }))
128
+ * attachService(node, network, createGrantLogService({
129
+ * resource,
130
+ * onGrantChange: keyDist.api.handleGrantChange,
131
+ * onReady: (api) => { grantLogApi = api },
132
+ * }))
133
+ *
134
+ * This is the same class of ordering friction `grant-log.mjs`'s own doc
135
+ * comment already documents for `onReady` (Phase C's `attach()` being
136
+ * synchronous, non-awaited) -- not a new problem introduced here.
137
+ *
138
+ * ---------------------------------------------------------------------------
139
+ * PERMANENT, DOCUMENTED LIMITATION (also stated in `cloud-storage-backend.mjs`
140
+ * and worth restating here, since this is the file that actually ships the
141
+ * key): revoking a peer's grant stops FUTURE key distribution (this file
142
+ * simply never delivers to a peer whose effective grants are empty) and
143
+ * future chunk replication (Phase G), but cannot retroactively erase a key
144
+ * -- or any plaintext already decrypted with it -- already delivered to a
145
+ * since-revoked peer. This bucket's AES key is never rotated on revoke in
146
+ * this plan. This is a fundamental property of any such scheme, not a bug to
147
+ * fix later.
148
+ *
149
+ * ---------------------------------------------------------------------------
150
+ * Observability events (`ctx.emit()`, Phase 1 of the mesh-KV-and-
151
+ * observability plan -- see `mesh-service.mjs`'s module doc comment for the
152
+ * full convention this follows). Three curated events, not a mechanical
153
+ * conversion of this file's `onLog` calls:
154
+ *
155
+ * - `key-distribution:key-sent` `{resource, to}` -- this peer successfully
156
+ * pushed the bucket key to a newly-announced/newly-granted peer.
157
+ * - `key-distribution:key-received` `{resource, from}` -- this peer
158
+ * accepted and imported a `deliver` record (full trust-model
159
+ * verification above already passed by this point).
160
+ * - `key-distribution:delivery-rejected` `{resource, from, reason}` -- a
161
+ * `deliver` record was discarded (`reason` is one of
162
+ * `'malformed'`/`'identity-mismatch'`/`'bad-signature'`/
163
+ * `'unauthorized-sender'`); this is this file's core security property
164
+ * (see "Trust model for deliver" above), so its rejections are exactly
165
+ * the kind of transition worth a dashboard being able to see.
166
+ *
167
+ * No browser-only imports at module level.
168
+ */
169
+
170
+ import { encodeBase64url, decodeBase64url } from '@johnhenry/browsermesh-primitives'
171
+ import { generateEncryptionKeyPair, wrapKeyForMember, unwrapKeyForMember } from '@johnhenry/browsermesh-core'
172
+
173
+ /** Default `envelope.type` used to route key-distribution payloads on the shared `onIncomingData()` bus. */
174
+ const DEFAULT_ENVELOPE_TYPE = 'bucket-key'
175
+
176
+ // ---------------------------------------------------------------------------
177
+ // Canonical JSON / signing helpers -- deliberately duplicated from
178
+ // grant-log.mjs rather than imported/shared, matching this file's own doc
179
+ // comment and this family's established convention of small self-contained
180
+ // per-file crypto helpers (see e.g. cloud-storage-backend.mjs's own
181
+ // AES helpers vs. peer-encrypted-store.mjs's).
182
+ // ---------------------------------------------------------------------------
183
+
184
+ /** @param {object} obj @returns {string} */
185
+ function canonicalJSON(obj) {
186
+ return JSON.stringify(obj, (_key, value) => {
187
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
188
+ const sorted = {}
189
+ for (const k of Object.keys(value).sort()) sorted[k] = value[k]
190
+ return sorted
191
+ }
192
+ return value
193
+ })
194
+ }
195
+
196
+ /**
197
+ * The exact fields signed in a `deliver` record -- everything except
198
+ * `signedByPubKeyBytes`/`signature` themselves.
199
+ * @param {{resource: string, ephemeralPublicKey: string, wrappedKey: string, iv: string, at: number, signedBy: string}} fields
200
+ * @returns {string}
201
+ */
202
+ function signedPayloadOf(fields) {
203
+ return canonicalJSON({
204
+ resource: fields.resource,
205
+ ephemeralPublicKey: fields.ephemeralPublicKey,
206
+ wrappedKey: fields.wrappedKey,
207
+ iv: fields.iv,
208
+ at: fields.at,
209
+ signedBy: fields.signedBy,
210
+ })
211
+ }
212
+
213
+ /**
214
+ * base64url(SHA-256(rawPublicKeyBytes)) -- identical to `derivePodId()`'s own
215
+ * definition (`browsermesh-primitives/src/identity.mjs`), duplicated here for
216
+ * the same reason `grant-log.mjs` duplicates it: the raw bytes are already in
217
+ * hand (decoded from the record), importing them into a `CryptoKey` purely to
218
+ * re-export them back out would be wasted work.
219
+ * @param {Uint8Array} rawPublicKeyBytes
220
+ * @returns {Promise<string>}
221
+ */
222
+ async function podIdFromRawPublicKey(rawPublicKeyBytes) {
223
+ const hash = await crypto.subtle.digest('SHA-256', rawPublicKeyBytes)
224
+ return encodeBase64url(new Uint8Array(hash))
225
+ }
226
+
227
+ // ---------------------------------------------------------------------------
228
+ // Base64 helpers (plain base64, matching group-keys.mjs's own encoding for
229
+ // X25519 public keys and wrap envelopes -- NOT base64url, kept distinct from
230
+ // the base64url helpers above which are only ever used for the Ed25519
231
+ // identity-signature fields, matching grant-log.mjs's own convention there).
232
+ // ---------------------------------------------------------------------------
233
+
234
+ /** @param {Uint8Array} bytes @returns {string} */
235
+ function toBase64(bytes) {
236
+ if (typeof Buffer !== 'undefined') return Buffer.from(bytes).toString('base64')
237
+ let bin = ''
238
+ for (const b of bytes) bin += String.fromCharCode(b)
239
+ return btoa(bin)
240
+ }
241
+
242
+ /** @param {string} str @returns {Uint8Array} */
243
+ function fromBase64(str) {
244
+ if (typeof Buffer !== 'undefined') return new Uint8Array(Buffer.from(str, 'base64'))
245
+ const bin = atob(str)
246
+ const bytes = new Uint8Array(bin.length)
247
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
248
+ return bytes
249
+ }
250
+
251
+ // ---------------------------------------------------------------------------
252
+ // MeshService wiring
253
+ // ---------------------------------------------------------------------------
254
+
255
+ /**
256
+ * Build a `MeshService` descriptor (`mesh-service.mjs`, Phase C) that
257
+ * distributes one bucket's AES key to newly-granted peers. See the module
258
+ * doc comment for the full protocol/trust-model writeup and the required
259
+ * composition order with `createGrantLogService()`.
260
+ *
261
+ * @param {object} opts
262
+ * @param {string} opts.resource - e.g. `s3:my-bucket`. Must be the SAME
263
+ * resource string the paired `GrantLog` uses.
264
+ * @param {() => {admins: string[], grants: Object<string, string[]>}} opts.getEffective -
265
+ * Typically `() => grantLogApi.effective()`. Evaluated lazily on every
266
+ * message/change, so it's safe to pass a closure over a variable that
267
+ * isn't assigned yet at the time this descriptor is constructed (see the
268
+ * module doc comment's composition-order note).
269
+ * @param {() => Promise<Uint8Array|null>} opts.getLocalKey - Typically
270
+ * `() => backend.peekKeyRaw()` (`cloud-storage-backend.mjs`, Phase E's
271
+ * addition) -- must NOT auto-create a key as a side effect, or every peer
272
+ * that merely attaches this service would spontaneously mint its own,
273
+ * never-to-be-reconciled bucket key.
274
+ * @param {(rawKeyBytes: Uint8Array) => Promise<void>} opts.setReceivedKey -
275
+ * Typically `(bytes) => backend.importKeyRaw(bytes)`.
276
+ * @param {string} [opts.envelopeType='bucket-key']
277
+ * @param {Function} [opts.onLog]
278
+ * @returns {import('./mesh-service.mjs').MeshService}
279
+ */
280
+ export function createKeyDistributionService({
281
+ resource,
282
+ getEffective,
283
+ getLocalKey,
284
+ setReceivedKey,
285
+ envelopeType = DEFAULT_ENVELOPE_TYPE,
286
+ onLog,
287
+ } = {}) {
288
+ if (!resource || typeof resource !== 'string') {
289
+ throw new Error('createKeyDistributionService: resource is required and must be a non-empty string')
290
+ }
291
+ if (typeof getEffective !== 'function') {
292
+ throw new Error('createKeyDistributionService: getEffective is required and must be a function')
293
+ }
294
+ if (typeof getLocalKey !== 'function') {
295
+ throw new Error('createKeyDistributionService: getLocalKey is required and must be a function')
296
+ }
297
+ if (typeof setReceivedKey !== 'function') {
298
+ throw new Error('createKeyDistributionService: setReceivedKey is required and must be a function')
299
+ }
300
+ const log = onLog || (() => {})
301
+
302
+ return {
303
+ name: `key-distribution:${resource}`,
304
+
305
+ attach(peerNode, ctx) {
306
+ const localPodId = peerNode.podId
307
+
308
+ /** @type {Promise<CryptoKeyPair>|null} This peer's own X25519 encryption keypair, generated lazily on first need. */
309
+ let keyPairPromise = null
310
+ /** @type {string|null} Cached base64 raw public key for `keyPairPromise`. */
311
+ let localPublicKeyB64 = null
312
+
313
+ /** @type {Map<string, CryptoKey>} podId -> their announced X25519 public key. */
314
+ const knownEncryptionKeys = new Map()
315
+
316
+ function ensureKeyPair() {
317
+ if (!keyPairPromise) {
318
+ keyPairPromise = generateEncryptionKeyPair().then(async (kp) => {
319
+ const raw = new Uint8Array(await crypto.subtle.exportKey('raw', kp.publicKey))
320
+ localPublicKeyB64 = toBase64(raw)
321
+ return kp
322
+ })
323
+ }
324
+ return keyPairPromise
325
+ }
326
+
327
+ function hasAnyGrant(pubKey, effective) {
328
+ return effective.admins.includes(pubKey) || (effective.grants[pubKey]?.length ?? 0) > 0
329
+ }
330
+
331
+ /** Wrap `rawKeyBytes` for `recipientPublicKey` and sign a `deliver` record over the result. */
332
+ async function buildDeliverRecord(rawKeyBytes, recipientPublicKey) {
333
+ const importable = await crypto.subtle.importKey('raw', rawKeyBytes, { name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt'])
334
+ const envelope = await wrapKeyForMember(importable, recipientPublicKey)
335
+
336
+ const at = Date.now()
337
+ const signedByPubKeyBytes = await peerNode.wallet.getPublicKeyBytes(localPodId)
338
+ const unsigned = { resource, ephemeralPublicKey: envelope.ephemeralPublicKey, wrappedKey: envelope.wrappedKey, iv: envelope.iv, at, signedBy: localPodId }
339
+ const payload = new TextEncoder().encode(signedPayloadOf(unsigned))
340
+ const signature = await peerNode.wallet.sign(localPodId, payload)
341
+
342
+ return {
343
+ resource,
344
+ kind: 'deliver',
345
+ envelope,
346
+ at,
347
+ signedBy: localPodId,
348
+ signedByPubKeyBytes: encodeBase64url(signedByPubKeyBytes),
349
+ signature: encodeBase64url(signature),
350
+ }
351
+ }
352
+
353
+ /** If we hold the key and already know `targetPodId`'s X25519 pubkey, push it now. Silent no-op otherwise. */
354
+ async function maybeDeliverTo(targetPodId) {
355
+ const recipientKey = knownEncryptionKeys.get(targetPodId)
356
+ if (!recipientKey) return
357
+ const rawKey = await getLocalKey()
358
+ if (!rawKey) return
359
+
360
+ try {
361
+ const record = await buildDeliverRecord(rawKey, recipientKey)
362
+ await ctx.sendTo(targetPodId, envelopeType, record)
363
+ log('key-distribution:sent', { to: targetPodId, resource })
364
+ ctx.emit('key-distribution:key-sent', { resource, to: targetPodId })
365
+ } catch (err) {
366
+ log('key-distribution:send-error', { to: targetPodId, resource, error: err?.message || String(err) })
367
+ }
368
+ }
369
+
370
+ /** We ourselves just gained access -- announce our X25519 pubkey to every current admin so they can push us the key. */
371
+ async function announceToAdmins() {
372
+ await ensureKeyPair()
373
+ const effective = getEffective()
374
+ for (const adminPodId of effective.admins) {
375
+ if (adminPodId === localPodId) continue
376
+ try {
377
+ await ctx.sendTo(adminPodId, envelopeType, { resource, kind: 'announce', encryptionPublicKey: localPublicKeyB64 })
378
+ } catch (err) {
379
+ log('key-distribution:announce-error', { to: adminPodId, resource, error: err?.message || String(err) })
380
+ }
381
+ }
382
+ }
383
+
384
+ async function handleAnnounce(fromPubKey, msg) {
385
+ if (typeof msg.encryptionPublicKey !== 'string') {
386
+ log('key-distribution:reject-malformed-announce', { from: fromPubKey, resource })
387
+ return
388
+ }
389
+ let cryptoKey
390
+ try {
391
+ const raw = fromBase64(msg.encryptionPublicKey)
392
+ cryptoKey = await crypto.subtle.importKey('raw', raw, { name: 'X25519' }, true, [])
393
+ } catch (err) {
394
+ log('key-distribution:reject-malformed-announce', { from: fromPubKey, resource, error: err?.message || String(err) })
395
+ return
396
+ }
397
+ knownEncryptionKeys.set(fromPubKey, cryptoKey)
398
+
399
+ // The reverse ordering: fromPubKey was already granted access before
400
+ // we learned their key (or before they announced it). Catch up now.
401
+ if (hasAnyGrant(fromPubKey, getEffective())) {
402
+ await maybeDeliverTo(fromPubKey)
403
+ }
404
+ }
405
+
406
+ async function handleDeliver(fromPubKey, msg) {
407
+ const { envelope, at, signedBy, signedByPubKeyBytes, signature } = msg
408
+ if (!envelope || typeof envelope.ephemeralPublicKey !== 'string' ||
409
+ typeof envelope.wrappedKey !== 'string' || typeof envelope.iv !== 'string') {
410
+ log('key-distribution:reject-malformed-deliver', { from: fromPubKey, resource })
411
+ ctx.emit('key-distribution:delivery-rejected', { resource, from: fromPubKey, reason: 'malformed' })
412
+ return
413
+ }
414
+ if (typeof at !== 'number' || !Number.isFinite(at) ||
415
+ typeof signedBy !== 'string' || !signedBy ||
416
+ typeof signedByPubKeyBytes !== 'string' || typeof signature !== 'string') {
417
+ log('key-distribution:reject-malformed-deliver', { from: fromPubKey, resource })
418
+ ctx.emit('key-distribution:delivery-rejected', { resource, from: fromPubKey, reason: 'malformed' })
419
+ return
420
+ }
421
+
422
+ let rawPubKeyBytes
423
+ let sigBytes
424
+ try {
425
+ rawPubKeyBytes = decodeBase64url(signedByPubKeyBytes)
426
+ sigBytes = decodeBase64url(signature)
427
+ } catch {
428
+ log('key-distribution:reject-malformed-deliver', { from: fromPubKey, resource })
429
+ ctx.emit('key-distribution:delivery-rejected', { resource, from: fromPubKey, reason: 'malformed' })
430
+ return
431
+ }
432
+
433
+ // Identity binding: the claimed `signedBy` must actually be derived
434
+ // from the embedded public key bytes.
435
+ const derivedPodId = await podIdFromRawPublicKey(rawPubKeyBytes)
436
+ if (derivedPodId !== signedBy) {
437
+ log('key-distribution:reject-identity-mismatch', { from: fromPubKey, resource, signedBy })
438
+ ctx.emit('key-distribution:delivery-rejected', { resource, from: fromPubKey, reason: 'identity-mismatch' })
439
+ return
440
+ }
441
+
442
+ // Signature: the record must really have been signed by that key.
443
+ const payload = new TextEncoder().encode(signedPayloadOf({ resource, ephemeralPublicKey: envelope.ephemeralPublicKey, wrappedKey: envelope.wrappedKey, iv: envelope.iv, at, signedBy }))
444
+ let validSig = false
445
+ try {
446
+ validSig = await peerNode.wallet.verify(rawPubKeyBytes, payload, sigBytes)
447
+ } catch {
448
+ validSig = false
449
+ }
450
+ if (!validSig) {
451
+ log('key-distribution:reject-bad-signature', { from: fromPubKey, resource, signedBy })
452
+ ctx.emit('key-distribution:delivery-rejected', { resource, from: fromPubKey, reason: 'bad-signature' })
453
+ return
454
+ }
455
+
456
+ // Authorization: signedBy must currently be an admin or hold at
457
+ // least one grant on this resource -- rejects a validly self-signed
458
+ // but unauthorized (non-admin/non-key-holder) claim.
459
+ if (!hasAnyGrant(signedBy, getEffective())) {
460
+ log('key-distribution:reject-unauthorized-sender', { from: fromPubKey, resource, signedBy })
461
+ ctx.emit('key-distribution:delivery-rejected', { resource, from: fromPubKey, reason: 'unauthorized-sender' })
462
+ return
463
+ }
464
+
465
+ let rawKeyBytes
466
+ try {
467
+ const keyPair = await ensureKeyPair()
468
+ const unwrapped = await unwrapKeyForMember(envelope, keyPair.privateKey)
469
+ rawKeyBytes = new Uint8Array(await crypto.subtle.exportKey('raw', unwrapped))
470
+ } catch (err) {
471
+ log('key-distribution:unwrap-error', { from: fromPubKey, resource, error: err?.message || String(err) })
472
+ return
473
+ }
474
+
475
+ await setReceivedKey(rawKeyBytes)
476
+ log('key-distribution:received', { from: fromPubKey, resource })
477
+ ctx.emit('key-distribution:key-received', { resource, from: fromPubKey })
478
+ }
479
+
480
+ const unsubscribe = ctx.onIncomingData(envelopeType, (fromPubKey, msg) => {
481
+ if (!msg || msg.resource !== resource) return
482
+ if (msg.kind === 'announce') {
483
+ handleAnnounce(fromPubKey, msg).catch((err) => log('key-distribution:announce-handler-error', { from: fromPubKey, resource, error: err?.message || String(err) }))
484
+ } else if (msg.kind === 'deliver') {
485
+ handleDeliver(fromPubKey, msg).catch((err) => log('key-distribution:deliver-handler-error', { from: fromPubKey, resource, error: err?.message || String(err) }))
486
+ }
487
+ })
488
+
489
+ /**
490
+ * `GrantLog`'s `onGrantChange` hook (`grant-log.mjs`). See the module
491
+ * doc comment's composition-order note for how this gets wired to the
492
+ * paired `GrantLog` instance.
493
+ * @param {{pubKey: string, before: Set<string>, after: Set<string>, added: string[], removed: string[]}} change
494
+ */
495
+ function handleGrantChange({ pubKey, before, after }) {
496
+ if (!(before.size === 0 && after.size > 0)) return // only a 0 -> nonzero transition is "newly admitted"
497
+
498
+ if (pubKey === localPodId) {
499
+ announceToAdmins().catch((err) => log('key-distribution:announce-error', { resource, error: err?.message || String(err) }))
500
+ } else {
501
+ maybeDeliverTo(pubKey).catch((err) => log('key-distribution:deliver-error', { to: pubKey, resource, error: err?.message || String(err) }))
502
+ }
503
+ }
504
+
505
+ const api = {
506
+ resource,
507
+ handleGrantChange,
508
+ /** @returns {Promise<string>} This peer's own X25519 public key (base64), generating it first if needed. Exposed for tests/introspection. */
509
+ async localEncryptionPublicKey() {
510
+ await ensureKeyPair()
511
+ return localPublicKeyB64
512
+ },
513
+ }
514
+
515
+ return {
516
+ api,
517
+ teardown() {
518
+ unsubscribe()
519
+ },
520
+ }
521
+ },
522
+ }
523
+ }
524
+
525
+ export { DEFAULT_ENVELOPE_TYPE }