@cero-base/core 2.2.0 → 2.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 (55) hide show
  1. package/README.md +32 -212
  2. package/package.json +19 -10
  3. package/src/blobs/index.js +9 -0
  4. package/src/blobs/server.js +2 -0
  5. package/src/database/changes.js +1 -1
  6. package/src/database/dispatch.js +341 -209
  7. package/src/database/encryption.js +83 -33
  8. package/src/database/index.js +184 -83
  9. package/src/database/rotation.js +43 -30
  10. package/src/identity/index.js +20 -78
  11. package/src/index.js +3 -10
  12. package/src/lib/constants.js +2 -0
  13. package/src/lib/errors.js +3 -11
  14. package/src/lib/spec/index.js +136 -132
  15. package/src/lib/spec/schema.json +84 -99
  16. package/src/lib/utils.js +57 -3
  17. package/src/mailbox/inbox.js +103 -0
  18. package/src/mailbox/index.js +146 -0
  19. package/src/mailbox/post.js +69 -0
  20. package/src/network/discovery.js +26 -1
  21. package/src/network/index.js +105 -64
  22. package/src/network/presence.js +6 -2
  23. package/src/pairing/index.js +330 -254
  24. package/src/pairing/invite.js +83 -144
  25. package/src/pairing/request.js +54 -56
  26. package/src/rpc/index.js +18 -93
  27. package/src/rpc/peer.js +4 -1
  28. package/src/storage/index.js +78 -39
  29. package/types/blobs/index.d.ts +22 -9
  30. package/types/blobs/server.d.ts +4 -2
  31. package/types/database/changes.d.ts +2 -2
  32. package/types/database/dispatch.d.ts +19 -13
  33. package/types/database/encryption.d.ts +67 -29
  34. package/types/database/index.d.ts +144 -119
  35. package/types/database/rotation.d.ts +32 -13
  36. package/types/identity/index.d.ts +6 -47
  37. package/types/index.d.ts +3 -16
  38. package/types/lib/constants.d.ts +1 -0
  39. package/types/lib/errors.d.ts +3 -9
  40. package/types/lib/spec/index.d.ts +52 -16
  41. package/types/lib/utils.d.ts +40 -8
  42. package/types/mailbox/inbox.d.ts +52 -0
  43. package/types/mailbox/index.d.ts +111 -0
  44. package/types/mailbox/post.d.ts +37 -0
  45. package/types/network/discovery.d.ts +21 -5
  46. package/types/network/index.d.ts +64 -48
  47. package/types/network/presence.d.ts +17 -4
  48. package/types/pairing/index.d.ts +143 -134
  49. package/types/pairing/invite.d.ts +70 -114
  50. package/types/pairing/request.d.ts +58 -98
  51. package/types/rpc/index.d.ts +26 -44
  52. package/types/rpc/peer.d.ts +10 -7
  53. package/types/storage/index.d.ts +64 -54
  54. package/src/pairing/candidate.js +0 -123
  55. package/types/pairing/candidate.d.ts +0 -36
@@ -10,51 +10,60 @@ import {
10
10
  ACTION,
11
11
  COUNTERS,
12
12
  EPOCHS,
13
+ REMOVALS,
14
+ OWNER,
13
15
  INVITE,
14
16
  REMOVE,
15
17
  ASSIGN,
16
18
  WRITE
17
19
  } from '../lib/constants.js'
18
- import { can, grants, outranks, admission, ownership } from '../lib/utils.js'
20
+ import {
21
+ can,
22
+ grants,
23
+ outranks,
24
+ admission,
25
+ ownership,
26
+ joining,
27
+ checkFields,
28
+ checkRequired,
29
+ stamp
30
+ } from '../lib/utils.js'
19
31
  import { CeroError } from '../lib/errors.js'
32
+ import { getEncoding } from '../lib/spec/index.js'
20
33
  import { Identity } from '../identity/index.js'
34
+ import { Invite } from '../pairing/invite.js'
35
+
36
+ const Join = getEncoding('@cero/join')
21
37
 
22
38
  // wire fields are variable-length: reject wrong sizes before sodium and hid throw on them
23
39
  const isKey = (b) => b?.byteLength === 32
24
40
  const isSig = (b) => b?.byteLength === 64
25
41
 
42
+ // member and device have their own set handlers, every other collection upserts via add-
43
+ export const BESPOKE = new Set(['member', 'device'])
44
+
26
45
  /**
27
46
  * Build the hyperdispatch router for a spec: wires membership, builtin, and
28
47
  * spec-defined collection/action ops, returning the router plus an apply loop.
29
48
  *
30
49
  * @param {object} opts
31
- * @param {{ dispatch: { Router: Function }, meta?: { refs?: Record<string, { kind?: string, builtin?: boolean, verb?: string }> } }} opts.spec Generated hyperdispatch spec.
50
+ * @param {{ dispatch: { Router: Function, encode: (name: string, value: unknown) => Uint8Array }, meta?: { refs?: Record<string, { kind?: string, internal?: boolean, own?: boolean, verb?: string, fields?: string[], required?: Record<string, string> }> } }} opts.spec Generated hyperdispatch spec.
32
51
  * @param {string} opts.ns Namespace prefix for collection and op names.
33
- * @param {Record<string, Function>} opts.routes Custom action handlers keyed by route name.
34
52
  * @param {(err: Error) => void} opts.onerror Called when a malformed node is skipped.
35
53
  * @param {() => Uint8Array | null} opts.key The database key, null until the bee booted.
36
54
  * @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).
37
- * @param {(phase: 'before' | 'after', op: string) => Function[]} [opts.hooks] Registered hooks for an op, run inside its transaction.
38
- * @param {(name: string) => void} [opts.touch] Marks a ref written by a hook, so its watchers tick.
39
- * @param {(view: object, name: string, query?: any) => Promise<any>} [opts.read] Planned read against a given view, for a hook's `ctx.get`.
40
- * @param {(fn: Function) => Function} [opts.inHook] Wraps a route so operators called inside it throw, like a hook.
55
+ * @param {() => { publicKey: Uint8Array, secretKey: Uint8Array } | null} opts.room The keypair behind the database's address, which joins are sealed to.
56
+ * @param {(phase: 'before' | 'after', op: string) => Function[]} opts.hooks Registered hooks for an op, run inside its transaction.
57
+ * @param {(name: string) => void} opts.touch Marks a ref written by a hook, so its watchers tick.
58
+ * @param {(view: object, name: string, query?: string | import('./index.js').Query) => Promise<import('./index.js').SingleResult | import('./index.js').ListResult>} opts.read Planned read against a given view, for a hook's `ctx.get`.
41
59
  * @returns {{ dispatch: (value: Buffer, ctx: object) => Promise<void>, apply: (nodes: Array<{ value: Buffer, key: Buffer }>, view: object, host: object) => Promise<void> }}
42
60
  */
43
- export function makeDispatcher({
44
- spec,
45
- ns,
46
- routes,
47
- onerror,
48
- key,
49
- onepoch,
50
- hooks,
51
- touch,
52
- read,
53
- inHook = (fn) => fn
54
- }) {
61
+ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, touch, read }) {
55
62
  const router = new spec.dispatch.Router()
56
63
 
64
+ const col = (name) => `@${ns}/${name}`
57
65
  const countersCol = `@${ns}/${COUNTERS}`
66
+ const removals = `@${ns}/${REMOVALS}`
58
67
  const getMember = (view, id) => view.get(`@${ns}/members`, { id })
59
68
  const getDevice = (view, id) => view.get(`@${ns}/devices`, { id })
60
69
 
@@ -66,7 +75,18 @@ export function makeDispatcher({
66
75
  const d = await getDevice(view, hid.encode(writerKey))
67
76
  return d?.memberId ? ((await getMember(view, d.memberId))?.role ?? null) : null
68
77
  }
69
- const isGenesis = async (view) => !(await view.findOne(`@${ns}/members`, {}))
78
+ const isIdentity = (id) => {
79
+ try {
80
+ return isKey(hid.decode(id))
81
+ } catch {
82
+ return false
83
+ }
84
+ }
85
+ // a writer stays with the member it was admitted for: nothing moves it to another
86
+ const boundElsewhere = async (view, writer, memberId) => {
87
+ const device = await getDevice(view, hid.encode(writer))
88
+ return !!device && device.memberId !== memberId
89
+ }
70
90
  const getSignerMember = async (view, key) =>
71
91
  (key ? (await getDevice(view, hid.encode(key)))?.memberId : null) ?? null
72
92
  const canRemoveMember = async (view, signerKey, targetMemberId) => {
@@ -75,23 +95,31 @@ export function makeDispatcher({
75
95
  const tRole = targetMemberId ? (await getMember(view, targetMemberId))?.role : null
76
96
  return !tRole || outranks(r, tRole)
77
97
  }
98
+ // without this owner the others would have nobody who outranks them all
99
+ const orphans = async (view, id) => {
100
+ const others = (await view.find(`@${ns}/members`, {}).toArray()).filter((m) => m.id !== id)
101
+ return others.length > 0 && !others.some((m) => m.role === OWNER)
102
+ }
78
103
 
79
- async function insert(view, name, col, op) {
104
+ async function bump(view, name) {
105
+ const value = ((await view.get(countersCol, { name }))?.value ?? 0) + 1
106
+ await view.insert(countersCol, { name, value })
107
+ return value
108
+ }
109
+
110
+ async function insert(view, name, op) {
80
111
  if (name !== COUNTERS) {
81
- const existing = op.id != null ? await view.get(col, op) : null
82
- if (existing && existing.index != null) {
83
- op.index = existing.index
84
- } else {
85
- const counter = (await view.get(countersCol, { name })) ?? { name, value: 0 }
86
- op.index = counter.value + 1
87
- await view.insert(countersCol, { name, value: op.index })
88
- }
112
+ const existing = op.id != null ? await view.get(col(name), op) : null
113
+ // an overwrite keeps when the row was first written, whatever the op carries
114
+ if (existing?.createdAt) op.createdAt = existing.createdAt
115
+ op.index = existing?.index ?? (await bump(view, name))
89
116
  }
90
- await view.insert(col, op)
117
+ await view.insert(col(name), op)
91
118
  }
92
119
 
93
- const pick = (op) => {
94
- if (!hooks || !op) return null
120
+ // a ctx write runs no hooks: one writing its own ref would recurse
121
+ const pick = (op, ctx) => {
122
+ if (ctx.nested) return null
95
123
  const before = hooks('before', op)
96
124
  const after = hooks('after', op)
97
125
  return before.length || after.length ? { before, after } : null
@@ -99,73 +127,97 @@ export function makeDispatcher({
99
127
 
100
128
  const refName = (ref) => (typeof ref === 'string' ? ref : ref?.name)
101
129
  const single = (name) => spec.meta?.refs?.[name]?.kind === SINGLE
130
+ // a name with no route, a counter or an epoch among them, fails to encode
131
+ const verbOf = (name) => spec.meta?.refs?.[name]?.verb || name
102
132
 
103
- // the operators developers know, bound to the open transaction and this op's stamps
104
- function operators(view, memberId, ts, seed) {
133
+ // the operators developers know, bound to this op. A write is dispatched as the op's writer
134
+ // would append it, so the same rank and `own` rules judge it
135
+ function operators(ctx, ts) {
105
136
  let n = 0
106
137
  // every peer must mint the same id: hash the applying op and a per-op counter
107
- const mint = () => z32.encode(crypto.hash([seed, c.encode(c.uint, n++)]).subarray(0, 16))
108
- const col = (name) => `@${ns}/${name}`
138
+ const mint = () => z32.encode(crypto.hash([ctx.seed, c.encode(c.uint, n++)]).subarray(0, 16))
109
139
  const current = (name, id) =>
110
- single(name) ? view.findOne(col(name), {}) : view.get(col(name), { id })
111
- const stamp = (row, was) => ({
112
- ...was,
113
- createdAt: was?.createdAt ?? ts,
114
- ...row,
115
- updatedAt: row.updatedAt ?? ts,
116
- memberId
117
- })
118
- const store = (name, row) => {
119
- touch?.(name)
120
- return single(name) ? view.insert(col(name), row) : insert(view, name, col(name), row)
140
+ single(name) ? ctx.view.findOne(col(name), {}) : ctx.view.get(col(name), { id })
141
+ // held to the fields as a direct write is, before the encoder drops or chokes on one
142
+ const held = (name, row, stored) => {
143
+ checkFields(name, spec.meta?.refs?.[name], row)
144
+ checkRequired(name, spec.meta?.refs?.[name], stored)
145
+ return stored
146
+ }
147
+ const write = (name, verb, row) => {
148
+ touch(name)
149
+ const value = spec.dispatch.encode(`@${ns}/${verb}-${verbOf(name)}`, row)
150
+ return router.dispatch(value, { ...ctx, nested: true })
121
151
  }
122
152
  return {
123
- get: (ref, query) => read(view, refName(ref), query),
153
+ get: (ref, query) => read(ctx.view, refName(ref), query),
124
154
  put: (ref, row) => {
125
155
  const name = refName(ref)
126
- return store(name, stamp(single(name) ? row : { ...row, id: row.id ?? mint() }, null))
156
+ if (single(name)) return write(name, 'set', held(name, row, stamp(row, null, ts)))
157
+ const stored = stamp({ ...row, id: row.id ?? mint() }, null, ts)
158
+ return write(name, 'add', held(name, row, stored))
127
159
  },
160
+ // an upsert, as the set operator appends it
128
161
  set: async (ref, row) => {
129
162
  const name = refName(ref)
130
163
  if (!single(name) && !row.id) throw CeroError.INVALID(`set('${name}') needs an id`)
131
- return store(name, stamp(row, await current(name, row.id)))
164
+ const verb = single(name) || BESPOKE.has(verbOf(name)) ? 'set' : 'add'
165
+ const was = await current(name, row.id)
166
+ return write(name, verb, held(name, row, stamp({ ...was, ...row }, was?.createdAt, ts)))
132
167
  },
133
168
  del: (ref, id) => {
134
169
  const name = refName(ref)
135
- touch?.(name)
136
- return view.delete(col(name), single(name) ? {} : { id })
170
+ return write(name, 'del', { id: single(name) ? '' : id })
137
171
  }
138
172
  }
139
173
  }
140
174
 
141
- // hooks run inside the op's transaction on every peer, so their verdict is part of the op
142
- // a rule never meets a nameless writer: an admitted core with no member row is refused
143
- // where a hook or route would have to judge it
144
- async function signer(ctx) {
175
+ // the writer as the view stands, null for a core no member owns yet: a join, a claim, genesis
176
+ async function author(ctx) {
145
177
  const memberId = await getSignerMember(ctx.view, ctx.key)
146
- const role = memberId ? (await getMember(ctx.view, memberId))?.role : null
147
- if (!memberId || !role) throw CeroError.REFUSED('member')
148
- return { memberId, role }
178
+ const role = memberId ? ((await getMember(ctx.view, memberId))?.role ?? null) : null
179
+ return role ? { memberId, role } : { memberId: null, role: null }
149
180
  }
150
181
 
182
+ // hooks run inside the op's transaction on every peer, so their verdict is part of the op.
183
+ // Resolves to the row that landed, which a before hook may have changed
151
184
  async function hooked(fns, { op, name, id = null, row = null, existing = null }, ctx, write) {
152
- if (!fns) return write(row)
153
- const { memberId, role } = await signer(ctx)
185
+ if (!fns) {
186
+ await write(row)
187
+ return row
188
+ }
154
189
  // never a clock: a derived row must stamp the same timestamp on every peer
155
190
  const ts = row?.updatedAt || existing?.updatedAt || 0
156
- const hctx = {
157
- op,
158
- name,
159
- row,
160
- existing,
161
- id,
162
- memberId,
163
- role,
164
- ...operators(ctx.view, memberId, ts, ctx.seed)
165
- }
191
+ const hctx = { op, name, row, existing, id, ...(await author(ctx)), ...operators(ctx, ts) }
166
192
  await fire(fns.before, hctx, true)
167
193
  await write(hctx.row)
168
- await fire(fns.after, hctx, false)
194
+ // once every row of the op landed: a join's after hooks write as a member
195
+ ctx.later.push(async () => {
196
+ Object.assign(hctx, await author(ctx))
197
+ await fire(fns.after, hctx, false)
198
+ })
199
+ return hctx.row
200
+ }
201
+
202
+ // a builtin row lands as a schema ref's does, through its ref's hooks
203
+ async function save(ctx, op, name, row) {
204
+ const fns = pick(op, ctx)
205
+ const existing = fns ? await ctx.view.get(col(name), { id: row.id }) : null
206
+ const meta = { op, name, id: row.id, row, existing }
207
+ return hooked(fns, meta, ctx, (r) => insert(ctx.view, name, r))
208
+ }
209
+
210
+ function seat(ctx, writer, memberId, ts) {
211
+ const row = { id: hid.encode(writer), memberId, createdAt: ts, updatedAt: ts }
212
+ return save(ctx, 'put', 'devices', row)
213
+ }
214
+
215
+ // deleting a row that is not there changes nothing, and fires nothing
216
+ async function drop(ctx, name, id) {
217
+ const fns = pick('del', ctx)
218
+ const existing = fns ? await ctx.view.get(col(name), { id }) : null
219
+ const meta = { op: 'del', name, id, existing }
220
+ await hooked(existing ? fns : null, meta, ctx, () => ctx.view.delete(col(name), { id }))
169
221
  }
170
222
 
171
223
  // a rule that errors must not diverge peers: a throw refuses exactly like a false verdict
@@ -194,67 +246,61 @@ export function makeDispatcher({
194
246
  if (!can(await getSignerRole(ctx.view, ctx.key), REMOVE)) throw CeroError.REFUSED('own')
195
247
  }
196
248
 
197
- const upsert = (name, col, kind, own, hook) => async (op, ctx) => {
249
+ const upsert = (name, kind, own) => async (op, ctx) => {
198
250
  await requireWrite(ctx)
199
- const d = ctx.key && (await getDevice(ctx.view, hid.encode(ctx.key)))
200
- op.memberId = d?.memberId || null
201
- const fns = pick(hook)
251
+ op.memberId = await getSignerMember(ctx.view, ctx.key)
202
252
  if (kind !== COLLECTION) {
203
- const existing = fns ? await ctx.view.findOne(col, {}) : null
204
- const meta = { op: hook, name, row: op, existing }
205
- return hooked(fns, meta, ctx, (row) => ctx.view.insert(col, row))
253
+ const fns = pick('set', ctx)
254
+ const existing = fns ? await ctx.view.findOne(col(name), {}) : null
255
+ const meta = { op: 'set', name, row: op, existing }
256
+ return hooked(fns, meta, ctx, (row) => ctx.view.insert(col(name), row))
206
257
  }
207
- const existing = own || fns ? await ctx.view.get(col, { id: op.id }) : null
208
258
  // add on an existing id is an overwrite, same ownership rule as set
209
- if (own) await requireOwn(ctx, existing)
210
- const meta = { op: hook, name, id: op.id, row: op, existing }
211
- await hooked(fns, meta, ctx, (row) => insert(ctx.view, name, col, row))
259
+ if (own) await requireOwn(ctx, await ctx.view.get(col(name), { id: op.id }))
260
+ await save(ctx, 'put', name, op)
212
261
  }
213
- const update = (name, col, own, hook) => async (op, ctx) => {
262
+ const update = (name, own) => async (op, ctx) => {
214
263
  await requireWrite(ctx)
215
- const existing = await ctx.view.get(col, { id: op.id })
264
+ const existing = await ctx.view.get(col(name), { id: op.id })
216
265
  if (!existing) return
217
266
  if (own) await requireOwn(ctx, existing)
218
267
  // memberId is attribution: derived here, never merged off the wire
219
- const d = ctx.key && (await getDevice(ctx.view, hid.encode(ctx.key)))
220
- const merged = { ...existing, ...op, memberId: d?.memberId || null }
221
- const meta = { op: hook, name, id: op.id, row: merged, existing }
222
- await hooked(pick(hook), meta, ctx, (row) => insert(ctx.view, name, col, row))
268
+ const memberId = await getSignerMember(ctx.view, ctx.key)
269
+ await save(ctx, 'set', name, { ...existing, ...op, memberId })
223
270
  }
224
- const remove = (name, col, own, hook) => async (op, ctx) => {
271
+ const remove = (name, own) => async (op, ctx) => {
225
272
  await requireWrite(ctx)
226
- const fns = pick(hook)
227
- const existing = own || fns ? await ctx.view.get(col, { id: op.id }) : null
273
+ const fns = pick('del', ctx)
274
+ const existing = own || fns ? await ctx.view.get(col(name), { id: op.id }) : null
228
275
  if (own) await requireOwn(ctx, existing)
229
- const meta = { op: hook, name, id: op.id, existing }
230
- return hooked(fns, meta, ctx, () => ctx.view.delete(col, op))
276
+ const meta = { op: 'del', name, id: op.id, existing }
277
+ return hooked(fns, meta, ctx, () => ctx.view.delete(col(name), op))
231
278
  }
232
279
  // only REFUSED aborts a batch: every peer derives it. Decode failures and unknown routes skip one node
233
280
  const isRefusal = (err) => err?.isCeroError === true && err.code === 'REFUSED'
234
281
 
235
- const add = (verb, fn) => router.add(`@${ns}/${verb}`, fn)
282
+ // an op's after hooks run once all its rows landed
283
+ const add = (verb, fn) =>
284
+ router.add(`@${ns}/${verb}`, async (op, ctx) => {
285
+ const later = []
286
+ await fn(op, { ...ctx, later })
287
+ for (const run of later) await run()
288
+ })
236
289
 
237
290
  add('add-writer', async (op, ctx) => {
238
291
  if (!isKey(op.master) || !isKey(op.writer) || !isSig(op.sig)) return
239
292
  if (!Identity.verify(op.master, admission(ctx.dbKey, op.writer, ctx.key), op.sig)) return
240
- const genesis = await isGenesis(ctx.view)
293
+ const { genesis } = ctx.host
241
294
  const inviter = await getRole(ctx.view, op.master)
242
295
  if (!genesis && !can(inviter, INVITE)) throw CeroError.REFUSED('invite')
243
- // the rank is add-member's decision in the same transaction: a refused grant discards this admission.
296
+ // only a device of the signer's own identity: another member's device seats itself through
297
+ // its join, or any key the signer holds would act as them.
244
298
  // Always an indexer: autobee gc's caught-up non-indexer sessions and they miss later appends
245
- // a writer belongs to a member: its own identity, or the member named by the op
246
- const memberId = op.memberId || hid.encode(op.master)
247
- if (op.memberId && !(await getMember(ctx.view, op.memberId))) {
248
- throw CeroError.REFUSED('member')
249
- }
299
+ const memberId = hid.encode(op.master)
300
+ if (op.memberId && op.memberId !== memberId) throw CeroError.REFUSED('member')
301
+ if (await boundElsewhere(ctx.view, op.writer, memberId)) throw CeroError.REFUSED('member')
250
302
  await ctx.host.addWriter(op.writer, { isIndexer: true })
251
- const ts = op.ts || 0
252
- await insert(ctx.view, 'devices', `@${ns}/devices`, {
253
- id: hid.encode(op.writer),
254
- memberId,
255
- createdAt: ts,
256
- updatedAt: ts
257
- })
303
+ await seat(ctx, op.writer, memberId, op.ts || 0)
258
304
  })
259
305
 
260
306
  add('del-writer', async (op, ctx) => {
@@ -266,7 +312,7 @@ export function makeDispatcher({
266
312
  }
267
313
  }
268
314
  await ctx.host.removeWriter(op.writer)
269
- await ctx.view.delete(`@${ns}/devices`, { id: hid.encode(op.writer) })
315
+ await drop(ctx, 'devices', hid.encode(op.writer))
270
316
  })
271
317
 
272
318
  add('claim-writer', async (op, ctx) => {
@@ -276,34 +322,20 @@ export function makeDispatcher({
276
322
  if (!b4a.equals(ctx.key, op.writer)) return
277
323
  const memberId = hid.encode(op.identity)
278
324
  if (!can(await getRole(ctx.view, op.identity), WRITE)) throw CeroError.REFUSED('write')
325
+ if (await boundElsewhere(ctx.view, op.writer, memberId)) throw CeroError.REFUSED('member')
279
326
  await ctx.host.addWriter(op.writer, { isIndexer: true })
280
- const ts = op.ts || 0
281
- await insert(ctx.view, 'devices', `@${ns}/devices`, {
282
- id: hid.encode(op.writer),
283
- memberId,
284
- createdAt: ts,
285
- updatedAt: ts
286
- })
327
+ await seat(ctx, op.writer, memberId, op.ts || 0)
287
328
  })
288
329
 
330
+ // the genesis batch names the creator; everyone after comes in through a signed join
289
331
  add('add-member', async (op, ctx) => {
290
332
  if (!isKey(op.key)) return
291
- if (!(await isGenesis(ctx.view))) {
292
- const r = await getSignerRole(ctx.view, ctx.key)
293
- if (!can(r, INVITE) || !grants(r, op.role)) throw CeroError.REFUSED('invite')
294
- }
295
- await insert(ctx.view, 'members', `@${ns}/members`, op)
296
- const deviceId = hid.encode(op.key)
297
- const existingDevice = await getDevice(ctx.view, deviceId)
298
- const ts = op.updatedAt || 0
299
- await insert(ctx.view, 'devices', `@${ns}/devices`, {
300
- id: deviceId,
301
- memberId: op.id,
302
- name: existingDevice?.name ?? null,
303
- isMobile: existingDevice?.isMobile ?? false,
304
- createdAt: existingDevice?.createdAt || op.createdAt || ts,
305
- updatedAt: ts
306
- })
333
+ // an existing member keeps its row: its rank changes only through set-member
334
+ if (await getMember(ctx.view, op.id)) return
335
+ if (!ctx.host.genesis) throw CeroError.REFUSED('member')
336
+ // every member id is an identity key: rotation seals to it
337
+ if (!isIdentity(op.id)) throw CeroError.REFUSED('member')
338
+ await save(ctx, 'put', 'members', op)
307
339
  })
308
340
 
309
341
  add('set-member', async (op, ctx) => {
@@ -325,16 +357,16 @@ export function makeDispatcher({
325
357
  }
326
358
  next.role = op.role
327
359
  }
328
- await insert(ctx.view, 'members', `@${ns}/members`, next)
329
- // a demotion that takes WRITE away takes the writer seat with it
330
- if (can(existing.role, WRITE) && !can(next.role, WRITE)) {
331
- if (next.key) await ctx.host.removeWriter(next.key)
332
- for (const device of await ctx.view.find(`@${ns}/devices`, {}).toArray()) {
333
- if (device.memberId !== next.id) continue
334
- await ctx.host.removeWriter(hid.decode(device.id))
335
- }
336
- // device rows stay: an unresolvable writer would read as not yet enrolled and pass the gate
337
- }
360
+ const row = await save(ctx, 'set', 'members', next)
361
+ // WRITE decides the writer seats: a demotion takes them, a promotion gives them back.
362
+ // Device rows stay: an unresolvable writer would read as not yet enrolled and pass the gate
363
+ const writes = can(row.role, WRITE)
364
+ if (can(existing.role, WRITE) === writes) return
365
+ const devices = await ctx.view.find(`@${ns}/devices`, {}).toArray()
366
+ const seats = devices.filter((d) => d.memberId === row.id).map((d) => hid.decode(d.id))
367
+ // only enrolled devices come back: a revoked writer has no device row
368
+ if (writes) for (const key of seats) await ctx.host.addWriter(key, { isIndexer: true })
369
+ else for (const key of row.key ? [row.key, ...seats] : seats) await ctx.host.removeWriter(key)
338
370
  })
339
371
 
340
372
  add('del-member', async (op, ctx) => {
@@ -343,15 +375,21 @@ export function makeDispatcher({
343
375
  if (op.id !== (await getSignerMember(ctx.view, ctx.key))) {
344
376
  const r = await getSignerRole(ctx.view, ctx.key)
345
377
  if (!can(r, REMOVE) || !outranks(r, existing.role)) throw CeroError.REFUSED('remove')
378
+ } else if (existing.role === OWNER && (await orphans(ctx.view, op.id))) {
379
+ throw CeroError.INVALID('the last owner cannot leave: hand the room to another owner first')
346
380
  }
347
381
  if (existing.key) await ctx.host.removeWriter(existing.key)
348
- // every device of the member goes with them
382
+ // every device of the member goes with them, and any keys they were still owed
349
383
  for (const device of await ctx.view.find(`@${ns}/devices`, {}).toArray()) {
350
384
  if (device.memberId !== op.id) continue
351
385
  await ctx.host.removeWriter(hid.decode(device.id))
352
- await ctx.view.delete(`@${ns}/devices`, { id: device.id })
386
+ await drop(ctx, 'devices', device.id)
387
+ await drop(ctx, 'requests', device.id)
353
388
  }
354
- await ctx.view.delete(`@${ns}/members`, op)
389
+ await drop(ctx, 'members', op.id)
390
+ // an invite they could hold, or saw, does not bring them back
391
+ const minted = (await ctx.view.get(countersCol, { name: 'invites' }))?.value ?? 0
392
+ await ctx.view.insert(removals, { id: op.id, index: minted })
355
393
  })
356
394
 
357
395
  add('rotate-key', async (op, ctx) => {
@@ -366,12 +404,7 @@ export function makeDispatcher({
366
404
  const rows = await ctx.view.find(`@${ns}/${EPOCHS}`, {}).toArray()
367
405
  if (rows.some((r) => r.stamp === op.stamp)) return
368
406
  // sequence numbers order epochs; concurrent rotations get consecutive sequences, both readable
369
- const counter = (await ctx.view.get(countersCol, { name: EPOCHS })) ?? {
370
- name: EPOCHS,
371
- value: 0
372
- }
373
- const epoch = counter.value + 1
374
- await ctx.view.insert(countersCol, { name: EPOCHS, value: epoch })
407
+ const epoch = await bump(ctx.view, EPOCHS)
375
408
  const row = {
376
409
  epoch,
377
410
  stamp: op.stamp,
@@ -399,24 +432,32 @@ export function makeDispatcher({
399
432
  }
400
433
  }
401
434
  await ctx.host.removeWriter(hid.decode(existing.id))
402
- await ctx.view.delete(`@${ns}/devices`, op)
435
+ await drop(ctx, 'devices', op.id)
403
436
  })
404
437
 
405
- // a device row is the writer→role mapping, so memberId never comes off the wire: an unknown id
406
- // binds to the signer's own member, or one unauthenticated op could inherit the owner's authority
407
- const devices = `@${ns}/devices`
408
- const bind = async (ctx, existing) =>
409
- existing?.memberId ?? (await getSignerMember(ctx.view, ctx.key))
438
+ // a device row is the writer→role mapping, so memberId never comes off the wire; a core no
439
+ // member owns writes none, or any stranger's optimistic node would plant a device in the room
440
+ const bind = async (ctx) => {
441
+ const { memberId } = await author(ctx)
442
+ if (!memberId) throw CeroError.REFUSED('member')
443
+ return memberId
444
+ }
445
+ // a device describes only itself: another's record, or a made-up id, would break removing it
446
+ const selfOnly = (op, ctx) => {
447
+ if (!ctx.key || op.id !== hid.encode(ctx.key)) throw CeroError.REFUSED('device')
448
+ }
410
449
  add('add-device', async (op, ctx) => {
411
- const existing = await getDevice(ctx.view, op.id)
412
- await insert(ctx.view, 'devices', devices, { ...op, memberId: await bind(ctx, existing) })
450
+ selfOnly(op, ctx)
451
+ await save(ctx, 'put', 'devices', { ...op, memberId: await bind(ctx) })
413
452
  })
414
453
  add('set-device', async (op, ctx) => {
454
+ selfOnly(op, ctx)
455
+ const memberId = await bind(ctx)
415
456
  const existing = await getDevice(ctx.view, op.id)
416
457
  const ts = op.updatedAt || 0
417
- await insert(ctx.view, 'devices', devices, {
458
+ await save(ctx, 'set', 'devices', {
418
459
  ...op,
419
- memberId: await bind(ctx, existing),
460
+ memberId,
420
461
  createdAt: existing?.createdAt || op.createdAt || ts,
421
462
  updatedAt: ts
422
463
  })
@@ -425,89 +466,180 @@ export function makeDispatcher({
425
466
  // any WRITE member mints an invite, its rank capped at admission; an existing row is never
426
467
  // overwritten, and altering or revoking one needs REMOVE
427
468
  const invites = `@${ns}/invites`
469
+ const requests = `@${ns}/requests`
470
+ // an invite grants at most its minter's rank, or the join it admits would grant more
471
+ const capped = (r, record) => grants(r, record.role)
428
472
  add('add-invite', async (op, ctx) => {
429
473
  await requireWrite(ctx)
430
474
  if (await ctx.view.get(invites, { id: op.id })) throw CeroError.REFUSED('invite')
431
- await insert(ctx.view, 'invites', invites, op)
475
+ if (!capped(await getSignerRole(ctx.view, ctx.key), op)) throw CeroError.REFUSED('invite')
476
+ await save(ctx, 'put', 'invites', op)
432
477
  })
433
- const moderate = async (ctx) => {
434
- if (!can(await getSignerRole(ctx.view, ctx.key), REMOVE)) throw CeroError.REFUSED('invite')
435
- }
436
478
  add('set-invite', async (op, ctx) => {
437
- await moderate(ctx)
479
+ const r = await getSignerRole(ctx.view, ctx.key)
438
480
  const existing = await ctx.view.get(invites, { id: op.id })
439
481
  if (!existing) return
440
- await insert(ctx.view, 'invites', invites, { ...existing, ...op })
482
+ const next = { ...existing, ...op }
483
+ if (!can(r, REMOVE) || !capped(r, next)) throw CeroError.REFUSED('invite')
484
+ await save(ctx, 'set', 'invites', next)
441
485
  })
442
- // revoking needs REMOVE; consuming a single-use invite is done by whichever replica served the join
443
486
  add('del-invite', async (op, ctx) => {
444
487
  const existing = await ctx.view.get(invites, { id: op.id })
445
- const consume = existing && existing.reuse !== true
488
+ if (!existing) return
489
+ const r = await getSignerRole(ctx.view, ctx.key)
490
+ if (!can(r, REMOVE) || !capped(r, existing)) throw CeroError.REFUSED('invite')
491
+ await spend(ctx, existing)
492
+ })
493
+ // its joins still waiting for a member go with it; admitted ones are still owed their keys
494
+ async function spend(ctx, invite) {
495
+ await drop(ctx, 'invites', invite.id)
496
+ for (const request of await ctx.view.find(requests, {}).toArray()) {
497
+ if (request.invite === invite.id && !request.admitted) await drop(ctx, 'requests', request.id)
498
+ }
499
+ }
500
+
501
+ // the member, when new, and its device, seated when the member writes; its request stays until
502
+ // a member delivered the keys. The invite is spent unless it is reusable
503
+ async function admit(ctx, { invite, identity, writer, reply, role, ts }) {
504
+ const memberId = hid.encode(identity)
505
+ if (await boundElsewhere(ctx.view, writer, memberId)) throw CeroError.REFUSED('member')
506
+ const member =
507
+ (await getMember(ctx.view, memberId)) ??
508
+ (await save(ctx, 'put', 'members', {
509
+ id: memberId,
510
+ key: writer,
511
+ role,
512
+ createdAt: ts,
513
+ updatedAt: ts
514
+ }))
515
+ if (can(member.role, WRITE)) await ctx.host.addWriter(writer, { isIndexer: true })
516
+ await seat(ctx, writer, memberId, ts)
517
+ await save(ctx, 'put', 'requests', {
518
+ ...request(invite, identity, writer, reply, ts),
519
+ role,
520
+ admitted: true
521
+ })
522
+ if (!invite.reuse) await spend(ctx, invite)
523
+ }
524
+
525
+ function request(invite, identity, writer, reply, ts) {
526
+ const expires = invite.expires || 0
527
+ const id = hid.encode(writer)
528
+ return { id, identity, invite: invite.id, role: invite.role, reply, expires, createdAt: ts }
529
+ }
530
+
531
+ // null when it does not open: anyone may append a join
532
+ function open(box) {
533
+ const pair = room()
534
+ if (!pair || !box?.byteLength) return null
535
+ try {
536
+ const plain = crypto.decrypt(box, pair)
537
+ return plain && c.decode(Join, plain)
538
+ } catch {
539
+ return null
540
+ }
541
+ }
542
+
543
+ // the joiner's own core asks in: the invite proves it may, its identity signs where the keys go
544
+ add('join', async (op, ctx) => {
545
+ const join = open(op.box)
546
+ if (!join || !ctx.key) return
547
+ if (!Invite.proven(join.invite, ctx.key, join.proof)) return
548
+ const signed = joining(ctx.dbKey, join.invite, ctx.key, join.reply)
549
+ if (!Identity.verify(join.identity, signed, join.signature)) return
550
+ const invite = await ctx.view.get(invites, { id: b4a.toHex(join.invite) })
551
+ if (!invite) return
552
+ const ts = join.ts || 0
553
+ const memberId = hid.encode(join.identity)
554
+ const known = await getMember(ctx.view, memberId)
555
+ const removal = known ? null : await ctx.view.get(removals, { id: memberId })
556
+ if (removal && (invite.index ?? 0) <= removal.index) return
557
+ if (invite.confirm && !known) {
558
+ const waiting = request(invite, join.identity, ctx.key, join.reply, ts)
559
+ return save(ctx, 'put', 'requests', waiting)
560
+ }
561
+ await admit(ctx, {
562
+ invite,
563
+ identity: join.identity,
564
+ writer: ctx.key,
565
+ reply: join.reply,
566
+ role: invite.role,
567
+ ts
568
+ })
569
+ })
570
+ // a waiting join, admitted at a role within the invite's and the accepter's
571
+ add('accept', async (op, ctx) => {
572
+ const waiting = await ctx.view.get(requests, { id: op.id })
573
+ if (!waiting || waiting.admitted) return
574
+ const invite = await ctx.view.get(invites, { id: waiting.invite })
446
575
  const r = await getSignerRole(ctx.view, ctx.key)
447
- if (!can(r, REMOVE) && !(consume && can(r, INVITE))) throw CeroError.REFUSED('invite')
448
- return ctx.view.delete(invites, op)
576
+ const role = op.role || invite?.role
577
+ if (!invite || !can(r, INVITE) || !grants(r, role) || !grants(invite.role, role)) {
578
+ throw CeroError.REFUSED('invite')
579
+ }
580
+ const { identity, reply, createdAt: ts = 0 } = waiting
581
+ await admit(ctx, { invite, identity, writer: hid.decode(op.id), reply, role, ts })
582
+ })
583
+ // only a join writes a request
584
+ const joinsOnly = async () => {
585
+ throw CeroError.REFUSED('request')
586
+ }
587
+ add('add-request', joinsOnly)
588
+ add('set-request', joinsOnly)
589
+ // a denial, or keys delivered
590
+ add('del-request', async (op, ctx) => {
591
+ if (!can(await getSignerRole(ctx.view, ctx.key), INVITE)) throw CeroError.REFUSED('invite')
592
+ await drop(ctx, 'requests', op.id)
449
593
  })
450
594
 
451
- const files = `@${ns}/files`
452
595
  add('add-file', async (op, ctx) => {
453
- if (!can(await getSignerRole(ctx.view, ctx.key), WRITE)) throw CeroError.REFUSED('write')
596
+ await requireWrite(ctx)
597
+ await requireOwn(ctx, await ctx.view.get(col('files'), { id: op.id }))
454
598
  const memberId = await getSignerMember(ctx.view, ctx.key)
455
- await insert(ctx.view, 'files', files, {
599
+ await save(ctx, 'put', 'files', {
456
600
  id: op.id,
457
601
  name: op.name ?? null,
458
602
  memberId,
459
- stamp: op.stamp ?? 0
603
+ stamp: op.stamp ?? 0,
604
+ from: op.from ?? null
460
605
  })
461
606
  })
462
- add('set-file', update('files', files))
463
- add('del-file', remove('files', files))
607
+ add('set-file', update('files', true))
608
+ add('del-file', remove('files', true))
464
609
 
465
- const handles = `@${ns}/handles`
466
- add('add-handle', upsert('handles', handles, COLLECTION))
467
- add('set-handle', update('handles', handles))
468
- add('del-handle', remove('handles', handles))
610
+ add('add-handle', upsert('handles', COLLECTION, false))
611
+ add('set-handle', update('handles', false))
612
+ add('del-handle', remove('handles', false))
469
613
 
470
614
  for (const [name, info] of Object.entries(spec.meta?.refs || {})) {
471
615
  if (info.internal) continue
472
616
  if (info.kind === 'handle') continue
473
617
  if (info.kind === ACTION) {
474
- const route = routes[name]
475
- // an action with no local route diverges this peer from those that ran it: surface it
476
- if (!route) {
477
- add(name, async () => onerror(CeroError.UNKNOWN('route', name)))
478
- continue
479
- }
480
- // a route is a hook with no row: the same ctx, the same refusal semantics
618
+ // an action does what its after hooks do; one with none here diverges this peer from those
619
+ // that ran them, so it surfaces
481
620
  add(name, async (op, ctx) => {
482
- const { memberId, role } = await signer(ctx)
483
- const hctx = {
484
- op: name,
485
- name,
486
- row: op,
487
- memberId,
488
- role,
489
- ...operators(ctx.view, memberId, op.updatedAt || op.ts || 0, ctx.seed)
490
- }
491
- await fire([inHook(route)], hctx, true)
621
+ const fns = pick(name, ctx)
622
+ if (!fns?.after.length) return onerror(CeroError.UNKNOWN('action hook', name))
623
+ // an action is a write: a core no member owns, or a reader's optimistic op, runs none
624
+ await requireWrite(ctx)
625
+ await hooked(fns, { op: name, name, row: op }, ctx, () => {})
492
626
  })
493
627
  continue
494
628
  }
495
- const col = `@${ns}/${name}`
496
- const kind = info.kind === SINGLE ? SINGLE : COLLECTION
497
- const set =
498
- kind === SINGLE ? upsert(name, col, kind, false, 'set') : update(name, col, info.own, 'set')
499
- add(`set-${name}`, set)
500
629
  if (info.kind === SINGLE) {
630
+ add(`set-${name}`, upsert(name, SINGLE, false))
501
631
  // wipe the keyless single row (the dummy id in the op is ignored)
502
632
  add(`del-${name}`, async (op, ctx) => {
503
- const fns = pick('del')
504
- const existing = fns ? await ctx.view.findOne(col, {}) : null
505
- return hooked(fns, { op: 'del', name, existing }, ctx, () => ctx.view.delete(col, {}))
633
+ await requireWrite(ctx)
634
+ const fns = pick('del', ctx)
635
+ const existing = fns ? await ctx.view.findOne(col(name), {}) : null
636
+ return hooked(fns, { op: 'del', name, existing }, ctx, () => ctx.view.delete(col(name), {}))
506
637
  })
507
638
  continue
508
639
  }
509
- add(`add-${name}`, upsert(name, col, COLLECTION, info.own, 'put'))
510
- add(`del-${name}`, remove(name, col, info.own, 'del'))
640
+ add(`set-${name}`, update(name, info.own))
641
+ add(`add-${name}`, upsert(name, COLLECTION, info.own))
642
+ add(`del-${name}`, remove(name, info.own))
511
643
  }
512
644
 
513
645
  return {