@cero-base/core 1.19.0 → 2.0.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 (43) hide show
  1. package/package.json +8 -5
  2. package/src/blobs/index.js +15 -15
  3. package/src/blobs/server.js +0 -2
  4. package/src/database/changes.js +3 -7
  5. package/src/database/dispatch.js +128 -203
  6. package/src/database/encryption.js +22 -52
  7. package/src/database/envelope.js +1 -3
  8. package/src/database/index.js +336 -387
  9. package/src/database/rotation.js +56 -70
  10. package/src/identity/index.js +5 -9
  11. package/src/index.js +5 -9
  12. package/src/lib/constants.js +3 -12
  13. package/src/lib/errors.js +6 -10
  14. package/src/lib/schema.js +2 -5
  15. package/src/lib/utils.js +9 -24
  16. package/src/network/index.js +138 -166
  17. package/src/pairing/candidate.js +2 -4
  18. package/src/pairing/index.js +41 -55
  19. package/src/pairing/invite.js +3 -4
  20. package/src/pairing/request.js +3 -9
  21. package/src/rpc/index.js +4 -14
  22. package/src/rpc/peer.js +3 -7
  23. package/src/storage/index.js +25 -31
  24. package/types/blobs/index.d.ts +5 -5
  25. package/types/blobs/server.d.ts +0 -2
  26. package/types/database/changes.d.ts +2 -5
  27. package/types/database/dispatch.d.ts +2 -6
  28. package/types/database/encryption.d.ts +8 -20
  29. package/types/database/index.d.ts +79 -96
  30. package/types/database/rotation.d.ts +14 -20
  31. package/types/identity/index.d.ts +5 -9
  32. package/types/index.d.ts +4 -3
  33. package/types/lib/errors.d.ts +6 -10
  34. package/types/lib/schema.d.ts +2 -5
  35. package/types/lib/utils.d.ts +3 -7
  36. package/types/network/index.d.ts +16 -26
  37. package/types/pairing/candidate.d.ts +1 -2
  38. package/types/pairing/index.d.ts +22 -30
  39. package/types/pairing/invite.d.ts +3 -3
  40. package/types/pairing/request.d.ts +1 -3
  41. package/types/rpc/index.d.ts +1 -4
  42. package/types/rpc/peer.d.ts +2 -4
  43. package/types/storage/index.d.ts +17 -20
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@cero-base/core",
3
- "version": "1.19.0",
3
+ "version": "2.0.0",
4
4
  "description": "cero p2p primitives — identity, storage, network, database, blobs, rpc, pairing.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "engines": {
8
- "node": ">=20"
8
+ "node": ">=22"
9
9
  },
10
10
  "repository": {
11
11
  "type": "git",
@@ -18,8 +18,7 @@
18
18
  "src",
19
19
  "types",
20
20
  "README.md",
21
- "LICENSE",
22
- "!**/CLAUDE.md"
21
+ "LICENSE"
23
22
  ],
24
23
  "publishConfig": {
25
24
  "access": "public"
@@ -121,6 +120,10 @@
121
120
  "events": {
122
121
  "bare": "bare-events",
123
122
  "default": "events"
123
+ },
124
+ "process": {
125
+ "bare": "bare-process",
126
+ "default": "process"
124
127
  }
125
128
  },
126
129
  "scripts": {
@@ -130,7 +133,7 @@
130
133
  "pretest": "npm run build:test",
131
134
  "prepublishOnly": "npm run build:types",
132
135
  "test": "npm run test:bare",
133
- "test:bare": "brittle-bare test/bare.js $(find test -name '*.test.js' | sort)",
136
+ "test:bare": "brittle-bare $(find test -name '*.test.js' | sort)",
134
137
  "pretest:bare": "npm run build:test",
135
138
  "test:node": "brittle-node $(find test -name '*.test.js' | sort)"
136
139
  },
@@ -109,21 +109,6 @@ export class Blobs extends ReadyResource {
109
109
  throw CeroError.INVALID('input must be a buffer or a Readable stream')
110
110
  }
111
111
 
112
- /**
113
- * @param {import('streamx').Readable} input
114
- * @returns {Promise<RawBlobId>}
115
- */
116
- async _putStream(input) {
117
- const ws = this.hyperblobs.createWriteStream()
118
- await new Promise((resolve, reject) => {
119
- input.on('error', reject)
120
- ws.on('error', reject)
121
- ws.on('close', resolve)
122
- input.pipe(ws)
123
- })
124
- return ws.id
125
- }
126
-
127
112
  /**
128
113
  * Resolve the blob bytes for a raw blobId. Fetches from peers if not local.
129
114
  *
@@ -159,6 +144,21 @@ export class Blobs extends ReadyResource {
159
144
  await this.hyperblobs.clear(blobId)
160
145
  }
161
146
 
147
+ /**
148
+ * @param {import('streamx').Readable} input
149
+ * @returns {Promise<RawBlobId>}
150
+ */
151
+ async _putStream(input) {
152
+ const ws = this.hyperblobs.createWriteStream()
153
+ await new Promise((resolve, reject) => {
154
+ input.on('error', reject)
155
+ ws.on('error', reject)
156
+ ws.on('close', resolve)
157
+ input.pipe(ws)
158
+ })
159
+ return ws.id
160
+ }
161
+
162
162
  _guard() {
163
163
  if (this.closed) throw CeroError.CLOSED('Blobs')
164
164
  if (!this.opened) throw CeroError.NOT_READY('Blobs', 'blobs')
@@ -7,8 +7,6 @@ import { decodeId } from './index.js'
7
7
 
8
8
  /**
9
9
  * HTTP server that turns a string file id into a renderable localhost URL.
10
- * Wraps hypercore-blob-server; the underlying store session is owned by
11
- * BlobServer and closed when `close()` is called.
12
10
  */
13
11
  export class FileServer {
14
12
  /**
@@ -2,11 +2,8 @@ import { Readable } from 'streamx'
2
2
  import b4a from 'b4a'
3
3
 
4
4
  /**
5
- * Pull-driven delta stream over a collection: batches of `{ prev, next }`
6
- * pairs diffed from the head this stream last reported. Update ticks only
7
- * mark the stream dirty, the diff runs when the reader asks, so bursts fold
8
- * into one batch and nothing is dropped. The first batch, and any batch after
9
- * the view moved to another core, is the full matching state with `reset: true`.
5
+ * Pull-driven delta stream over a collection: batches of `{ prev, next }` pairs diffed
6
+ * from the head this stream last reported.
10
7
  *
11
8
  * @param {import('./index.js').Database} db
12
9
  * @param {string} name Ref name (scopes the update ticks).
@@ -48,8 +45,7 @@ export function makeChanges(db, name, col, matches) {
48
45
 
49
46
  const diff = async () => {
50
47
  const view = db.view
51
- // snapshot() and head() are synchronous, so back to back they describe
52
- // the same state and the cursor is exactly-once
48
+ // snapshot() and head() are synchronous, so the cursor is exactly-once
53
49
  const snap = view.snapshot()
54
50
  const head = view.engine.head()
55
51
  const reset =
@@ -16,17 +16,7 @@ import { can, grants, outranks, admission, ownership } from '../lib/utils.js'
16
16
  import { CeroError } from '../lib/errors.js'
17
17
  import { Identity } from '../identity/index.js'
18
18
 
19
- // Built-in collections wired into every cero spec.
20
- export const BUILTINS = [
21
- { name: 'members', verb: 'member' },
22
- { name: 'devices', verb: 'device' },
23
- { name: 'invites', verb: 'invite' },
24
- { name: 'handles', verb: 'handle' },
25
- { name: 'files', verb: 'file' }
26
- ]
27
-
28
- // Remote op fields are variable-length buffers on the wire — reject wrong sizes
29
- // before they reach sodium/hid.encode, which throw instead of returning false.
19
+ // wire fields are variable-length: reject wrong sizes before sodium and hid throw on them
30
20
  const isKey = (b) => b?.byteLength === 32
31
21
  const isSig = (b) => b?.byteLength === 64
32
22
 
@@ -41,10 +31,10 @@ const isSig = (b) => b?.byteLength === 64
41
31
  * @param {(err: Error) => void} opts.onerror Called when a malformed node is skipped.
42
32
  * @param {() => Uint8Array | null} opts.key The database key, null until the bee booted.
43
33
  * @param {(row: { epoch: number, stamp: number, wrapped: Uint8Array, commit: Uint8Array }) => Promise<void>} opts.onepoch Per-peer side of an applied rotation (skipped in dry runs).
44
- * @returns {{ dispatcher: object, apply: (nodes: Array<{ value: Buffer, key: Buffer }>, view: object, host: object) => Promise<void> }}
34
+ * @returns {{ dispatch: (value: Buffer, ctx: object) => Promise<void>, apply: (nodes: Array<{ value: Buffer, key: Buffer }>, view: object, host: object) => Promise<void> }}
45
35
  */
46
36
  export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
47
- const dispatcher = new spec.dispatch.Router()
37
+ const router = new spec.dispatch.Router()
48
38
 
49
39
  const countersCol = `@${ns}/${COUNTERS}`
50
40
  const getMember = (view, id) => view.get(`@${ns}/members`, { id })
@@ -82,22 +72,14 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
82
72
  await view.insert(col, op)
83
73
  }
84
74
 
85
- // Being an admitted writer is not a licence to write rows: a member demoted
86
- // to reader keeps its writer seat (set-member does not revoke it), and would
87
- // otherwise keep writing every collection.
88
- //
89
- // A signer we cannot resolve to a role is allowed through: admission is
90
- // optimistic, so a recovering device's first ops can apply before its own
91
- // add-writer has been adopted in this view, and refusing those would drop
92
- // them permanently. Being an admitted writer is the gate in that window.
75
+ // a demoted member keeps its writer seat, so rows are gated by role. An unresolved signer
76
+ // passes: optimistic admission applies a recovering device's ops before its add-writer
93
77
  const requireWrite = async (ctx) => {
94
78
  const r = await getSignerRole(ctx.view, ctx.key)
95
79
  if (r !== null && !can(r, WRITE)) throw CeroError.REFUSED('write')
96
80
  }
97
81
 
98
- // Every row records the member who wrote it, so ownership is already known —
99
- // an `own` collection just enforces it: the author may change their own rows,
100
- // and anyone who can REMOVE may moderate the rest.
82
+ // own: the author may change their rows, anyone with REMOVE may moderate the rest
101
83
  const requireOwn = async (ctx, existing) => {
102
84
  if (existing?.memberId == null) return
103
85
  if (existing.memberId === (await getSignerMember(ctx.view, ctx.key))) return
@@ -109,8 +91,7 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
109
91
  const d = ctx.key && (await getDevice(ctx.view, hid.encode(ctx.key)))
110
92
  op.memberId = d?.memberId || null
111
93
  if (kind !== COLLECTION) return ctx.view.insert(col, op)
112
- // `add` on an id that already exists is an overwrite, so it answers to the
113
- // same ownership rule as `set`
94
+ // add on an existing id is an overwrite, same ownership rule as set
114
95
  if (own) await requireOwn(ctx, await ctx.view.get(col, { id: op.id }))
115
96
  await insert(ctx.view, name, col, op)
116
97
  }
@@ -119,8 +100,7 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
119
100
  const existing = await ctx.view.get(col, { id: op.id })
120
101
  if (!existing) return
121
102
  if (own) await requireOwn(ctx, existing)
122
- // memberId is attribution, so it is derived here and never merged off the
123
- // wire — otherwise an edit could leave the row credited to its victim
103
+ // memberId is attribution: derived here, never merged off the wire
124
104
  const d = ctx.key && (await getDevice(ctx.view, hid.encode(ctx.key)))
125
105
  await insert(ctx.view, name, col, { ...existing, ...op, memberId: d?.memberId || null })
126
106
  }
@@ -129,12 +109,10 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
129
109
  if (own) await requireOwn(ctx, await ctx.view.get(col, { id: op.id }))
130
110
  return ctx.view.delete(col, op)
131
111
  }
132
- // Only a REFUSED verdict may abort a batch: it is derived from the node and
133
- // the view alone, so every peer reaches it. Decode failures and unknown routes
134
- // must not — an older peer would drop a batch its newer neighbour applies.
112
+ // only REFUSED aborts a batch: every peer derives it. Decode failures and unknown routes skip one node
135
113
  const isRefusal = (err) => err?.isCeroError === true && err.code === 'REFUSED'
136
114
 
137
- const add = (verb, fn) => dispatcher.add(`@${ns}/${verb}`, fn)
115
+ const add = (verb, fn) => router.add(`@${ns}/${verb}`, fn)
138
116
 
139
117
  add('add-writer', async (op, ctx) => {
140
118
  if (!isKey(op.master) || !isKey(op.writer) || !isSig(op.sig)) return
@@ -142,18 +120,13 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
142
120
  const genesis = await isGenesis(ctx.view)
143
121
  const inviter = await getRole(ctx.view, op.master)
144
122
  if (!genesis && !can(inviter, INVITE)) throw CeroError.REFUSED('invite')
145
- // the rank is add-member's decision, made in the same transaction: a grant
146
- // it refuses discards this admission with it, host call included
147
- // always an indexer, like claim-writer below. The op's optional isIndexer
148
- // bool decodes to false when absent (nothing sets it), which silently made
149
- // every device a weight-1 writer — autobee 2.0 gc's caught-up non-indexer
150
- // sessions, and a gc'd writer misses later appends until a wakeup revives it
123
+ // the rank is add-member's decision in the same transaction: a refused grant discards this admission.
124
+ // Always an indexer: autobee gc's caught-up non-indexer sessions and they miss later appends
151
125
  await ctx.host.addWriter(op.writer, { isIndexer: true })
152
126
  const ts = op.ts || 0
153
127
  await insert(ctx.view, 'devices', `@${ns}/devices`, {
154
128
  id: hid.encode(op.writer),
155
- // bind to the joiner when the op says so: if their member row never
156
- // lands the device resolves to nobody, instead of to the inviter
129
+ // a member row that never lands must resolve to nobody, not to the inviter
157
130
  memberId: op.memberId || hid.encode(op.master),
158
131
  createdAt: ts,
159
132
  updatedAt: ts
@@ -175,8 +148,7 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
175
148
  add('claim-writer', async (op, ctx) => {
176
149
  if (!isKey(op.identity) || !isKey(op.writer) || !isSig(op.sig)) return
177
150
  if (!Identity.verify(op.identity, ownership(ctx.dbKey, op.writer), op.sig)) return
178
- // a claim is only meaningful from the claiming core — from any other it is
179
- // inapplicable, not refused, so it must not abort that writer's batch
151
+ // from any other core a claim is inapplicable, not refused: it must not abort that writer's batch
180
152
  if (!b4a.equals(ctx.key, op.writer)) return
181
153
  const memberId = hid.encode(op.identity)
182
154
  if (!can(await getRole(ctx.view, op.identity), WRITE)) throw CeroError.REFUSED('write')
@@ -213,12 +185,8 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
213
185
  add('set-member', async (op, ctx) => {
214
186
  const existing = await getMember(ctx.view, op.id)
215
187
  if (!existing) return
216
- // What the op may change is decided by WHOSE row it is, not by a list of
217
- // field names — the member row is extensible (profile-sync adds avatar and
218
- // whatever else an app declares), so a name list would silently drop them.
219
- // Your own profile is yours to write; another member's row is untouchable
220
- // apart from an authorised role change. Identity and provenance never come
221
- // off the wire, so nobody overwrites the key a member was admitted with.
188
+ // whose row it is decides what may change: your own is writable, another member's only
189
+ // for an authorised role change. Key and provenance never come off the wire
222
190
  const isSelf = op.id === (await getSignerMember(ctx.view, ctx.key))
223
191
  const next = isSelf ? { ...op } : { ...existing }
224
192
  next.key = existing.key
@@ -234,18 +202,14 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
234
202
  next.role = op.role
235
203
  }
236
204
  await insert(ctx.view, 'members', `@${ns}/members`, next)
237
- // a demotion that takes WRITE away must take the writer seat with it —
238
- // otherwise the member keeps appending, and only the apply-time WRITE
239
- // gate stands between them and every collection
205
+ // a demotion that takes WRITE away takes the writer seat with it
240
206
  if (can(existing.role, WRITE) && !can(next.role, WRITE)) {
241
207
  if (next.key) await ctx.host.removeWriter(next.key)
242
208
  for (const device of await ctx.view.find(`@${ns}/devices`, {}).toArray()) {
243
209
  if (device.memberId !== next.id) continue
244
210
  await ctx.host.removeWriter(hid.decode(device.id))
245
211
  }
246
- // the device rows stay: they are how a key resolves to a member, and
247
- // deleting them would leave the demoted writer unresolvable — which the
248
- // apply-time gate reads as "not yet enrolled" and lets through
212
+ // device rows stay: an unresolvable writer would read as not yet enrolled and pass the gate
249
213
  }
250
214
  })
251
215
 
@@ -257,8 +221,7 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
257
221
  if (!can(r, REMOVE) || !outranks(r, existing.role)) throw CeroError.REFUSED('remove')
258
222
  }
259
223
  if (existing.key) await ctx.host.removeWriter(existing.key)
260
- // every device of the member goes with them — a removed member must not
261
- // leave writers admitted or stale device rows behind
224
+ // every device of the member goes with them
262
225
  for (const device of await ctx.view.find(`@${ns}/devices`, {}).toArray()) {
263
226
  if (device.memberId !== op.id) continue
264
227
  await ctx.host.removeWriter(hid.decode(device.id))
@@ -267,54 +230,41 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
267
230
  await ctx.view.delete(`@${ns}/members`, op)
268
231
  })
269
232
 
270
- // specs built before rotation have no rotate-key route — Router.add throws
271
- // NONEXISTENT_ROUTE, and the op stays unavailable until the app rebuilds
272
- try {
273
- add('rotate-key', async (op, ctx) => {
274
- if (!op.wrapped?.byteLength) return
275
- // the commitment lets every member verify the secret their envelope
276
- // opened to — without it a rotator could seal different secrets to
277
- // different members and split the room
278
- if (op.commit?.byteLength !== 32) return
279
- // the stamp is the content-addressed uint32 written into block headers.
280
- // The rotator picks it before writing any block, so linearization can
281
- // reorder epochs freely without ever changing which key a block header
282
- // points at. Uniqueness is enforced here, deterministically.
283
- if (!Number.isInteger(op.stamp) || op.stamp <= 0 || op.stamp > 0xffffffff) return
284
- if (!can(await getSignerRole(ctx.view, ctx.key), REMOVE)) {
285
- throw CeroError.REFUSED('rotate', 'rotate requires the remove permission')
286
- }
287
- const rows = await ctx.view.find(`@${ns}/${EPOCHS}`, {}).toArray()
288
- if (rows.some((r) => r.stamp === op.stamp)) return
289
- // sequence numbers order epochs; concurrent rotations linearize as
290
- // consecutive sequences with distinct stamps — both remain readable
291
- const counter = (await ctx.view.get(countersCol, { name: EPOCHS })) ?? {
292
- name: EPOCHS,
293
- value: 0
294
- }
295
- const epoch = counter.value + 1
296
- await ctx.view.insert(countersCol, { name: EPOCHS, value: epoch })
297
- const row = {
298
- epoch,
299
- stamp: op.stamp,
300
- wrapped: op.wrapped,
301
- createdAt: op.createdAt || 0,
302
- commit: op.commit
303
- }
304
- await ctx.view.insert(`@${ns}/${EPOCHS}`, row)
305
- // per-peer hydration (unseal own envelope → keyring) — never in a dry
306
- // run: the announcement itself must be appended under the OLD epoch
307
- if (!ctx.dryRun) {
308
- try {
309
- await onepoch(row)
310
- } catch (err) {
311
- onerror(err)
312
- }
233
+ add('rotate-key', async (op, ctx) => {
234
+ if (!op.wrapped?.byteLength) return
235
+ // the commitment lets every member verify the sealed secret, so a rotator cannot split the room
236
+ if (op.commit?.byteLength !== 32) return
237
+ // the stamp is picked before any block is written, so epochs reorder freely; uniqueness is enforced here
238
+ if (!Number.isInteger(op.stamp) || op.stamp <= 0 || op.stamp > 0xffffffff) return
239
+ if (!can(await getSignerRole(ctx.view, ctx.key), REMOVE)) {
240
+ throw CeroError.REFUSED('rotate', 'rotate requires the remove permission')
241
+ }
242
+ const rows = await ctx.view.find(`@${ns}/${EPOCHS}`, {}).toArray()
243
+ if (rows.some((r) => r.stamp === op.stamp)) return
244
+ // sequence numbers order epochs; concurrent rotations get consecutive sequences, both readable
245
+ const counter = (await ctx.view.get(countersCol, { name: EPOCHS })) ?? {
246
+ name: EPOCHS,
247
+ value: 0
248
+ }
249
+ const epoch = counter.value + 1
250
+ await ctx.view.insert(countersCol, { name: EPOCHS, value: epoch })
251
+ const row = {
252
+ epoch,
253
+ stamp: op.stamp,
254
+ wrapped: op.wrapped,
255
+ createdAt: op.createdAt || 0,
256
+ commit: op.commit
257
+ }
258
+ await ctx.view.insert(`@${ns}/${EPOCHS}`, row)
259
+ // never in a dry run: the announcement itself is appended under the old epoch
260
+ if (!ctx.dryRun) {
261
+ try {
262
+ await onepoch(row)
263
+ } catch (err) {
264
+ onerror(err)
313
265
  }
314
- })
315
- } catch {
316
- // pre-rotation spec
317
- }
266
+ }
267
+ })
318
268
 
319
269
  add('del-device', async (op, ctx) => {
320
270
  const existing = await getDevice(ctx.view, op.id)
@@ -328,95 +278,80 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
328
278
  await ctx.view.delete(`@${ns}/devices`, op)
329
279
  })
330
280
 
331
- for (const b of BUILTINS) {
332
- const col = `@${ns}/${b.name}`
333
- if (b.verb === 'member') continue
334
- if (b.verb === 'device') {
335
- // A device row IS the writer→role mapping: getSignerRole resolves a
336
- // writer key through it to a member, and every permission check reads
337
- // that role. So memberId is never taken off the wire — it stays whatever
338
- // add-writer/claim-writer/add-member bound, and an unknown id can only
339
- // ever bind to the signer's own member. Otherwise one unauthenticated op
340
- // would re-point a writer at the owner and inherit their authority.
341
- const bind = async (op, ctx, existing) =>
342
- existing?.memberId ?? (await getSignerMember(ctx.view, ctx.key))
343
- add(`add-${b.verb}`, async (op, ctx) => {
344
- const existing = await getDevice(ctx.view, op.id)
345
- await insert(ctx.view, b.name, col, { ...op, memberId: await bind(op, ctx, existing) })
346
- })
347
- add(`set-${b.verb}`, async (op, ctx) => {
348
- const existing = await getDevice(ctx.view, op.id)
349
- const ts = op.updatedAt || 0
350
- await insert(ctx.view, b.name, col, {
351
- ...op,
352
- memberId: await bind(op, ctx, existing),
353
- createdAt: existing?.createdAt || op.createdAt || ts,
354
- updatedAt: ts
355
- })
356
- })
357
- continue
358
- }
359
- if (b.verb === 'invite') {
360
- // Invite rows are served by every replica, so they are shared state with
361
- // teeth. Any WRITE member may mint one — the rank it can grant is capped
362
- // at admission — but an existing row is never overwritten (that only
363
- // breaks the invite for everyone), and altering or revoking one is a
364
- // moderation act: it needs REMOVE.
365
- add(`add-${b.verb}`, async (op, ctx) => {
366
- await requireWrite(ctx)
367
- if (await ctx.view.get(col, { id: op.id })) throw CeroError.REFUSED('invite')
368
- await insert(ctx.view, b.name, col, op)
369
- })
370
- // like requireWrite, a signer with no resolvable role yet (genesis, or
371
- // the optimistic-admission window) is not refused
372
- const moderate = async (ctx) => {
373
- const r = await getSignerRole(ctx.view, ctx.key)
374
- if (r !== null && !can(r, REMOVE)) throw CeroError.REFUSED('invite')
375
- }
376
- add(`set-${b.verb}`, async (op, ctx) => {
377
- await moderate(ctx)
378
- const existing = await ctx.view.get(col, { id: op.id })
379
- if (!existing) return
380
- await insert(ctx.view, b.name, col, { ...existing, ...op })
381
- })
382
- // deleting is two different acts: revoking (moderation, REMOVE) and
383
- // consuming a single-use invite — which is done by whichever replica
384
- // served the join, so any member who may serve invites may do it
385
- add(`del-${b.verb}`, async (op, ctx) => {
386
- const existing = await ctx.view.get(col, { id: op.id })
387
- const consume = existing && existing.reuse !== true
388
- const r = await getSignerRole(ctx.view, ctx.key)
389
- if (r !== null && !can(r, REMOVE) && !(consume && can(r, INVITE))) {
390
- throw CeroError.REFUSED('invite')
391
- }
392
- return ctx.view.delete(col, op)
393
- })
394
- continue
395
- }
396
- if (b.verb === 'file') {
397
- add('add-file', async (op, ctx) => {
398
- if (!can(await getSignerRole(ctx.view, ctx.key), WRITE)) throw CeroError.REFUSED('write')
399
- const memberId = await getSignerMember(ctx.view, ctx.key)
400
- await insert(ctx.view, b.name, col, {
401
- id: op.id,
402
- name: op.name ?? null,
403
- memberId,
404
- stamp: op.stamp ?? 0
405
- })
406
- })
407
- } else {
408
- add(`add-${b.verb}`, upsert(b.name, col, COLLECTION))
409
- }
410
- add(`set-${b.verb}`, update(b.name, col))
411
- add(`del-${b.verb}`, remove(col))
281
+ // a device row is the writer→role mapping, so memberId never comes off the wire: an unknown id
282
+ // binds to the signer's own member, or one unauthenticated op could inherit the owner's authority
283
+ const devices = `@${ns}/devices`
284
+ const bind = async (ctx, existing) =>
285
+ existing?.memberId ?? (await getSignerMember(ctx.view, ctx.key))
286
+ add('add-device', async (op, ctx) => {
287
+ const existing = await getDevice(ctx.view, op.id)
288
+ await insert(ctx.view, 'devices', devices, { ...op, memberId: await bind(ctx, existing) })
289
+ })
290
+ add('set-device', async (op, ctx) => {
291
+ const existing = await getDevice(ctx.view, op.id)
292
+ const ts = op.updatedAt || 0
293
+ await insert(ctx.view, 'devices', devices, {
294
+ ...op,
295
+ memberId: await bind(ctx, existing),
296
+ createdAt: existing?.createdAt || op.createdAt || ts,
297
+ updatedAt: ts
298
+ })
299
+ })
300
+
301
+ // any WRITE member mints an invite, its rank capped at admission; an existing row is never
302
+ // overwritten, and altering or revoking one needs REMOVE
303
+ const invites = `@${ns}/invites`
304
+ add('add-invite', async (op, ctx) => {
305
+ await requireWrite(ctx)
306
+ if (await ctx.view.get(invites, { id: op.id })) throw CeroError.REFUSED('invite')
307
+ await insert(ctx.view, 'invites', invites, op)
308
+ })
309
+ // like requireWrite, a signer with no resolvable role yet is not refused
310
+ const moderate = async (ctx) => {
311
+ const r = await getSignerRole(ctx.view, ctx.key)
312
+ if (r !== null && !can(r, REMOVE)) throw CeroError.REFUSED('invite')
412
313
  }
314
+ add('set-invite', async (op, ctx) => {
315
+ await moderate(ctx)
316
+ const existing = await ctx.view.get(invites, { id: op.id })
317
+ if (!existing) return
318
+ await insert(ctx.view, 'invites', invites, { ...existing, ...op })
319
+ })
320
+ // revoking needs REMOVE; consuming a single-use invite is done by whichever replica served the join
321
+ add('del-invite', async (op, ctx) => {
322
+ const existing = await ctx.view.get(invites, { id: op.id })
323
+ const consume = existing && existing.reuse !== true
324
+ const r = await getSignerRole(ctx.view, ctx.key)
325
+ if (r !== null && !can(r, REMOVE) && !(consume && can(r, INVITE))) {
326
+ throw CeroError.REFUSED('invite')
327
+ }
328
+ return ctx.view.delete(invites, op)
329
+ })
330
+
331
+ const files = `@${ns}/files`
332
+ add('add-file', async (op, ctx) => {
333
+ if (!can(await getSignerRole(ctx.view, ctx.key), WRITE)) throw CeroError.REFUSED('write')
334
+ const memberId = await getSignerMember(ctx.view, ctx.key)
335
+ await insert(ctx.view, 'files', files, {
336
+ id: op.id,
337
+ name: op.name ?? null,
338
+ memberId,
339
+ stamp: op.stamp ?? 0
340
+ })
341
+ })
342
+ add('set-file', update('files', files))
343
+ add('del-file', remove(files))
344
+
345
+ const handles = `@${ns}/handles`
346
+ add('add-handle', upsert('handles', handles, COLLECTION))
347
+ add('set-handle', update('handles', handles))
348
+ add('del-handle', remove(handles))
413
349
 
414
350
  for (const [name, info] of Object.entries(spec.meta?.refs || {})) {
415
- if (info.builtin) continue
351
+ if (info.internal) continue
416
352
  if (info.kind === 'handle') continue
417
353
  if (info.kind === ACTION) {
418
- // a replicated action with no local route is a peer misconfiguration —
419
- // surface it instead of silently diverging from peers that ran it
354
+ // an action with no local route diverges this peer from those that ran it: surface it
420
355
  add(
421
356
  name,
422
357
  routes[name] ||
@@ -439,17 +374,12 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
439
374
  }
440
375
 
441
376
  return {
442
- dispatcher,
377
+ dispatch: (value, ctx) => router.dispatch(value, ctx),
443
378
  async apply(nodes, view, host) {
444
379
  const dbKey = key()
445
- // Nodes land in a transaction this loop owns, so a refusal can discard the
446
- // whole batch — a batch is one writer's contiguous run (autobee keys it on
447
- // batch[0].key), so an abort only ever drops the offending writer's ops.
380
+ // a batch is one writer's contiguous run, so a refusal discards only that writer's ops
448
381
  const tx = view.transaction()
449
- // Admitting or removing a writer is a host call, not a row — it would
450
- // survive a discarded transaction and leave a writer with no device row,
451
- // which the WRITE gate reads as "not yet enrolled". So host calls are
452
- // recorded and replayed only once the batch is known to commit.
382
+ // host calls survive a discarded transaction, so they replay once the batch commits
453
383
  const calls = []
454
384
  const deferred = Object.create(host)
455
385
  deferred.addWriter = (...args) => void calls.push(['addWriter', args])
@@ -457,13 +387,9 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
457
387
  let refusal = null
458
388
  for (const node of nodes) {
459
389
  try {
460
- await dispatcher.dispatch(node.value, { view: tx, host: deferred, key: node.key, dbKey })
390
+ await router.dispatch(node.value, { view: tx, host: deferred, key: node.key, dbKey })
461
391
  } catch (err) {
462
- // A refusal is the verdict every peer reaches from the same node and
463
- // the same view, so discarding the batch keeps them convergent — and
464
- // the batch is one writer's own run. Anything else (undecodable bytes,
465
- // a route this version lacks) skips a single node instead: an older
466
- // peer must not drop a batch its newer neighbour applies.
392
+ // anything but a refusal skips one node, so an older peer never drops a batch its newer neighbour applies
467
393
  if (!isRefusal(err)) {
468
394
  onerror(err)
469
395
  continue
@@ -477,8 +403,7 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
477
403
  onerror(refusal)
478
404
  } else {
479
405
  await tx.flush()
480
- // replayed before apply() returns: autobee clears host.applying right
481
- // after, and addWriter reads it (rc.31 derives coord/carrier from it)
406
+ // before apply() returns: autobee clears host.applying right after, and addWriter reads it
482
407
  for (const [fn, args] of calls) await host[fn](...args)
483
408
  }
484
409
  await view.flush()