@cero-base/core 2.12.0 → 3.0.1

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 (39) hide show
  1. package/package.json +8 -8
  2. package/src/blobs/codec.js +25 -0
  3. package/src/blobs/index.js +5 -2
  4. package/src/blobs/server.js +2 -2
  5. package/src/database/dispatch.js +803 -204
  6. package/src/database/encryption.js +25 -21
  7. package/src/database/index.js +720 -123
  8. package/src/database/rotation.js +333 -38
  9. package/src/lib/constants.js +10 -0
  10. package/src/lib/errors.js +8 -0
  11. package/src/lib/schema.js +12 -2
  12. package/src/lib/spec/index.js +10 -5
  13. package/src/lib/spec/schema.json +13 -1
  14. package/src/lib/utils.js +24 -3
  15. package/src/mailbox/inbox.js +368 -41
  16. package/src/mailbox/index.js +75 -20
  17. package/src/mailbox/post.js +13 -8
  18. package/src/network/index.js +12 -5
  19. package/src/pairing/index.js +343 -57
  20. package/src/pairing/invite.js +36 -12
  21. package/src/pairing/response.js +78 -0
  22. package/src/push/index.js +20 -2
  23. package/types/blobs/codec.d.ts +13 -0
  24. package/types/blobs/index.d.ts +2 -0
  25. package/types/database/dispatch.d.ts +51 -7
  26. package/types/database/encryption.d.ts +13 -5
  27. package/types/database/index.d.ts +190 -19
  28. package/types/database/rotation.d.ts +85 -2
  29. package/types/lib/constants.d.ts +4 -0
  30. package/types/lib/errors.d.ts +6 -0
  31. package/types/lib/schema.d.ts +11 -0
  32. package/types/lib/utils.d.ts +2 -0
  33. package/types/mailbox/inbox.d.ts +78 -10
  34. package/types/mailbox/index.d.ts +42 -16
  35. package/types/mailbox/post.d.ts +7 -5
  36. package/types/pairing/index.d.ts +53 -8
  37. package/types/pairing/invite.d.ts +27 -8
  38. package/types/pairing/response.d.ts +50 -0
  39. package/types/push/index.d.ts +12 -2
@@ -9,10 +9,14 @@ import {
9
9
  COLLECTION,
10
10
  ACTION,
11
11
  COUNTERS,
12
+ VERSION,
13
+ BUILT,
14
+ OWED,
12
15
  EPOCHS,
13
16
  REMOVALS,
14
17
  REFUSALS,
15
18
  SPENT,
19
+ ASKS,
16
20
  OWNER,
17
21
  INVITE,
18
22
  REMOVE,
@@ -32,37 +36,148 @@ import {
32
36
  } from '../lib/utils.js'
33
37
  import { CeroError } from '../lib/errors.js'
34
38
  import { getEncoding } from '../lib/spec/index.js'
39
+ import { decodeId } from '../blobs/codec.js'
35
40
  import { Identity } from '../identity/index.js'
36
41
  import { Invite } from '../pairing/invite.js'
42
+ import { keyPair } from '../mailbox/inbox.js'
43
+ import { wraps } from './encryption.js'
37
44
 
38
45
  const Join = getEncoding('@cero/join')
39
46
 
40
47
  // wire fields are variable-length: reject wrong sizes before sodium and hid throw on them
41
48
  const isKey = (b) => b?.byteLength === 32
42
49
 
50
+ function sealed(wrapped) {
51
+ try {
52
+ c.decode(wraps, wrapped)
53
+ return true
54
+ } catch {
55
+ return false
56
+ }
57
+ }
58
+
43
59
  // member and device have their own set handlers, every other collection upserts via add-
44
60
  export const BESPOKE = new Set(['member', 'device'])
45
61
 
62
+ // what a member who may not write sets on her own row, as profileSync mirrors it
63
+ const PROFILE = ['name', 'avatar']
64
+ const profile = (row, op) => ({
65
+ ...row,
66
+ ...Object.fromEntries(PROFILE.filter((f) => f in op).map((f) => [f, op[f]]))
67
+ })
68
+
69
+ // the request type of each of Cero's routes that writes no ref's row
70
+ const REQUESTS = {
71
+ 'add-writer': 'writer',
72
+ 'del-writer': 'writer',
73
+ join: 'join',
74
+ accept: 'accept',
75
+ deny: 'deny',
76
+ 'rotate-key': 'epoch',
77
+ revoke: 'revoke',
78
+ 'ask-key': 'owed'
79
+ }
80
+
81
+ // the device keys a request stands on: its own, and those of the chain its join proved or a link
82
+ // wrote for it
83
+ export const chainOf = ({ key, proof }) => [...Identity.chain(proof).slice(1), key]
84
+
85
+ // the chain a link wrote, which a seat keeps and an answer carries: a join's proof signs its join,
86
+ // and alone verifies as nothing
87
+ export const linkOf = (proof) => (Identity.verify(proof, null) ? proof : null)
88
+
89
+ // where an identity stands in a handle, and where each state leads: one with none is over
90
+ const STATES = {
91
+ asking: ['joining', 'denied', 'expired', 'cancelled'],
92
+ joining: ['in', 'denied'],
93
+ in: ['leaving', 'removed'],
94
+ leaving: ['left', 'removed'],
95
+ left: [],
96
+ removed: [],
97
+ denied: [],
98
+ expired: [],
99
+ cancelled: []
100
+ }
101
+
102
+ // on its way in: such a row is not deleted. A leave ends by deleting its row
103
+ const UNSETTLED = new Set(['asking', 'joining'])
104
+
105
+ // a handles row with no state is `in`. One that is over is asked again under another invite, and
106
+ // a denied one is let in under its own, by another device of the identity
107
+ function moves(was, row) {
108
+ const to = row.state || 'in'
109
+ if (!STATES[to]) return false
110
+ if (!was) return true
111
+ const from = was.state || 'in'
112
+ if (from === to || STATES[from].includes(to)) return true
113
+ if (STATES[from].length || !row.invite) return false
114
+ if (to === 'asking') return row.invite !== was.invite
115
+ return from === 'denied' && to === 'joining' && row.invite === was.invite
116
+ }
117
+
46
118
  // a member who left, apart from one removed and from a revoked device, in the removals: ids never hold ':'
47
119
  export const leftId = (memberId) => `left:${memberId}`
48
120
 
121
+ // what an identity's devices told a room of its device keys, in the removals too
122
+ export const toldId = (memberId) => `told:${memberId}`
123
+ const MAX_REMOVED = 64
124
+
125
+ /**
126
+ * 32-byte keys back to back, or none when they are not that.
127
+ *
128
+ * @param {Uint8Array | null} [buf]
129
+ * @returns {Uint8Array[]}
130
+ */
131
+ export function keysOf(buf) {
132
+ if (!buf?.byteLength || buf.byteLength % 32) return []
133
+ return Array.from({ length: buf.byteLength / 32 }, (_, i) => buf.subarray(i * 32, i * 32 + 32))
134
+ }
135
+ const has = (keys, key) => keys.some((k) => b4a.equals(k, key))
136
+
137
+ // the chain a seat stands on, its identity first
138
+ export const seatChain = (device) => [
139
+ hid.decode(device.memberId),
140
+ ...keysOf(device.chain),
141
+ device.key
142
+ ]
143
+
49
144
  /**
50
145
  * Build the hyperdispatch router for a spec: wires membership, builtin, and
51
146
  * spec-defined collection/action ops, returning the router plus an apply loop.
52
147
  *
53
148
  * @param {object} opts
54
- * @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.
149
+ * @param {{ dispatch: { Router: Function, encode: (name: string, value: unknown, opts?: { version?: number }) => Uint8Array }, meta?: { refs?: Record<string, { kind?: string, internal?: boolean, own?: boolean, verb?: string, fields?: string[], required?: Record<string, string> }>, encoding?: Record<string, number> } }} opts.spec Generated hyperdispatch spec.
55
150
  * @param {string} opts.ns Namespace prefix for collection and op names.
151
+ * @param {number} opts.start The version of a database that holds no version row.
152
+ * @param {() => number} opts.contract This build's contract: an op whose effective stamp is past it is skipped.
153
+ * @param {(stamp: number) => void} opts.onskip Called with the effective stamp of each op skipped as past the contract.
154
+ * @param {() => number[]} opts.build The row describing this build, kept in the view it applies: its database, rules, contract and the lowest version it skipped.
56
155
  * @param {(err: Error) => void} opts.onerror Called when a malformed node is skipped.
57
156
  * @param {() => Uint8Array | null} opts.key The database key, null until the bee booted.
58
157
  * @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).
59
- * @param {() => { publicKey: Uint8Array, secretKey: Uint8Array } | null} opts.room The keypair behind the database's address, which joins are sealed to.
158
+ * @param {() => { publicKey: Uint8Array, secretKey: Uint8Array } | null} opts.room The keypair behind the database's address, which joins that name no invite are sealed to.
159
+ * @param {boolean} [opts.root] The identity's own database, where a device key past a removed one stands while seated.
60
160
  * @param {(phase: 'before' | 'after', op: string) => Function[]} opts.hooks Registered hooks for an op, run inside its transaction.
61
- * @param {(name: string) => void} opts.touch Marks a ref written by a hook, so its watchers tick.
161
+ * @param {(name: string) => void} opts.touch Marks a ref written by a hook, once its batch commits, so its watchers tick.
62
162
  * @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`.
63
- * @returns {{ dispatch: (value: Buffer, ctx: object) => Promise<void>, apply: (nodes: Array<{ value: Buffer, key: Buffer }>, view: object, host: object) => Promise<void> }}
163
+ * @returns {{ encode: (route: string, value: unknown, stamp: number) => Uint8Array, cut: (route: string, value: Record<string, unknown>, stamp: number) => Record<string, unknown>, dispatch: (value: Buffer, ctx: object) => Promise<void>, role: (view: object, writer: Uint8Array) => Promise<string | null>, stands: (view: object, chain: Uint8Array[], telling?: { removed?: Uint8Array, standing?: Uint8Array }) => Promise<boolean>, version: (view: object) => Promise<number>, built: (view: object) => Promise<Array<number | null> | null>, apply: (nodes: Array<{ value: Buffer, key: Buffer, version: number }>, view: object, host: object) => Promise<{ landed: Array<{ value: Buffer, key: Buffer, version: number }>, changed: boolean }> }} `apply` takes each op with its author's stamp, runs it at its effective stamp, and resolves to the nodes that landed and whether they changed a row.
64
164
  */
65
- export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, touch, read }) {
165
+ export function makeDispatcher({
166
+ spec,
167
+ ns,
168
+ start,
169
+ contract,
170
+ onskip,
171
+ build,
172
+ onerror,
173
+ key,
174
+ onepoch,
175
+ room,
176
+ root = false,
177
+ hooks,
178
+ touch,
179
+ read
180
+ }) {
66
181
  const router = new spec.dispatch.Router()
67
182
 
68
183
  const col = (name) => `@${ns}/${name}`
@@ -70,12 +185,10 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
70
185
  const removals = `@${ns}/${REMOVALS}`
71
186
  const refusals = `@${ns}/${REFUSALS}`
72
187
  const spent = `@${ns}/${SPENT}`
188
+ const asks = `@${ns}/${ASKS}`
73
189
  const getMember = (view, id) => view.get(`@${ns}/members`, { id })
74
190
  const getDevice = (view, id) => view.get(`@${ns}/devices`, { id })
75
191
 
76
- const getRole = async (view, identityKey) =>
77
- identityKey ? ((await getMember(view, hid.encode(identityKey)))?.role ?? null) : null
78
-
79
192
  const getSignerRole = async (view, writerKey) => {
80
193
  if (!writerKey) return null
81
194
  const d = await getDevice(view, hid.encode(writerKey))
@@ -107,13 +220,42 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
107
220
  return others.length > 0 && !others.some((m) => m.role === OWNER)
108
221
  }
109
222
 
223
+ // every peer mints the same ids: the node's seed and a count within it, past any id the
224
+ // collection already holds, so no row written before can make a derived one an overwrite
225
+ function minter(seed) {
226
+ let n = 0
227
+ return async (view, name) => {
228
+ while (true) {
229
+ const id = z32.encode(crypto.hash([seed, c.encode(c.uint, n++)]).subarray(0, 16))
230
+ if (!(await view.get(name, { id }))) return id
231
+ }
232
+ }
233
+ }
234
+
110
235
  async function bump(view, name) {
111
236
  const value = ((await view.get(countersCol, { name }))?.value ?? 0) + 1
112
237
  await view.insert(countersCol, { name, value })
113
238
  return value
114
239
  }
115
240
 
241
+ // set where someone who may hold the keys is taken out, decided again by each rotation that lands
242
+ const owe = (view, value = 1) => view.insert(countersCol, { name: OWED, value })
243
+
244
+ // every reader decodes a file id it renders: one that does not decode never lands
245
+ function checkFiles(name, row) {
246
+ const fields = name === 'files' ? ['id'] : (spec.meta?.refs?.[name]?.files ?? [])
247
+ for (const field of fields) {
248
+ if (row[field] == null) continue
249
+ try {
250
+ decodeId(row[field])
251
+ } catch (err) {
252
+ throw CeroError.REFUSED('file', err.message)
253
+ }
254
+ }
255
+ }
256
+
116
257
  async function insert(view, name, op) {
258
+ checkFiles(name, op)
117
259
  if (name !== COUNTERS) {
118
260
  const existing = op.id != null ? await view.get(col(name), op) : null
119
261
  // an overwrite keeps when the row was first written, whatever the op carries
@@ -135,32 +277,125 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
135
277
  const single = (name) => spec.meta?.refs?.[name]?.kind === SINGLE
136
278
  // a name with no route, a counter or an epoch among them, fails to encode
137
279
  const verbOf = (name) => spec.meta?.refs?.[name]?.verb || name
280
+ const stored = (view, name, id) =>
281
+ single(name) ? view.findOne(col(name), {}) : view.get(col(name), { id })
282
+
283
+ // the database's version: its row, or the start for a database that never wrote one
284
+ const versionOf = async (view) => (await view.get(countersCol, { name: VERSION }))?.value ?? start
285
+
286
+ // the build that applied a view, as the view holds it: null for an empty view, nulls for one a
287
+ // build from before the row applied
288
+ const built = async (view) => {
289
+ const row = await Promise.all(
290
+ BUILT.map(async (name) => (await view.get(countersCol, { name }))?.value ?? null)
291
+ )
292
+ if (row[0] === null && !(await view.findOne(`@${ns}/devices`, {}))) return null
293
+ return row
294
+ }
295
+
296
+ // each route's request type, and for a ref's add and set the ref its row is stored in
297
+ const routes = new Map()
298
+ for (const [name, info] of Object.entries(spec.meta?.refs || {})) {
299
+ if (info.live || info.kind === 'handle' || !info.schema) continue
300
+ if (info.kind === ACTION) {
301
+ routes.set(`@${ns}/${name}`, { type: info.schema, name: null })
302
+ continue
303
+ }
304
+ for (const verb of ['add', 'set']) {
305
+ routes.set(`@${ns}/${verb}-${info.verb || name}`, { type: info.schema, name })
306
+ }
307
+ }
308
+ for (const [route, type] of Object.entries(REQUESTS)) {
309
+ routes.set(`@${ns}/${route}`, { type: `@${ns}/${type}`, name: null })
310
+ }
311
+ const since = spec.meta?.since
312
+ const upgrade = `@${ns}/upgrade`
313
+
314
+ // the ref or action each route writes, as a refusal names it
315
+ const things = new Map()
316
+ for (const [name, info] of Object.entries(spec.meta?.refs || {})) {
317
+ if (info.kind === ACTION) {
318
+ things.set(`@${ns}/${name}`, name)
319
+ continue
320
+ }
321
+ for (const verb of ['add', 'set', 'del']) {
322
+ things.set(`@${ns}/${verb}-${info.verb || name}`, name)
323
+ }
324
+ }
325
+
326
+ // the bytes a build at `stamp` writes; the upgrade is named at every version, as decode reads it
327
+ function encode(route, value, stamp) {
328
+ if (route !== upgrade) supported(route, value, stamp)
329
+ return spec.dispatch.encode(route, value, { version: spec.meta?.encoding?.[stamp] })
330
+ }
331
+
332
+ // a write naming what its stamp does not have is refused on its device: left out, it would be
333
+ // lost without a word
334
+ function supported(route, value, stamp) {
335
+ const name = things.get(route) ?? route
336
+ if ((since?.routes[route] ?? 0) > stamp) throw CeroError.UNSUPPORTED(`'${name}'`)
337
+ const fields = since?.types[routes.get(route)?.type] ?? {}
338
+ for (const f of Object.keys(fields)) {
339
+ if (fields[f] > stamp && value?.[f] != null) {
340
+ throw CeroError.UNSUPPORTED(`'${f}' in '${name}'`)
341
+ }
342
+ }
343
+ }
344
+
345
+ // a row without the fields its stamp has none for, which apply keeps as stored
346
+ function cut(route, value, stamp) {
347
+ const fields = since?.types[routes.get(route)?.type] ?? {}
348
+ return Object.fromEntries(Object.entries(value).filter(([f]) => (fields[f] ?? 0) <= stamp))
349
+ }
350
+
351
+ // what the op's author could not name, decided from its stamp and the schema before any hook
352
+ // sees it: a route newer than the stamp, or one this build does not know, refuses its batch on
353
+ // every build, and a newer field keeps what is stored
354
+ async function decode(value, stamp, view) {
355
+ let op
356
+ try {
357
+ op = spec.dispatch.decode(value)
358
+ } catch (err) {
359
+ if (err?.code !== 'HANDLER_NOT_FOUND_BY_ID') throw err
360
+ throw CeroError.REFUSED('route', `${err.message}: a route this build does not know`)
361
+ }
362
+ // the op that moves the version is named at every version, or nothing could move it
363
+ if (op.name === upgrade) return op
364
+ if ((since?.routes[op.name] ?? 0) > stamp) {
365
+ throw CeroError.REFUSED('route', `${op.name} is newer than its op`)
366
+ }
367
+ const route = routes.get(op.name)
368
+ const fields = route ? since?.types[route.type] : null
369
+ const newer = fields ? Object.keys(fields).filter((f) => fields[f] > stamp) : []
370
+ if (newer.length === 0) return op
371
+ const row = route.name ? await stored(view, route.name, op.value.id) : null
372
+ for (const f of newer) op.value[f] = row?.[f] ?? null
373
+ return op
374
+ }
138
375
 
139
376
  // the operators developers know, bound to this op. A write is dispatched as the op's writer
140
377
  // would append it, so the same rank and `own` rules judge it
141
- function operators(ctx, ts) {
142
- let n = 0
143
- // every peer must mint the same id: hash the applying op and a per-op counter
144
- const mint = () => z32.encode(crypto.hash([ctx.seed, c.encode(c.uint, n++)]).subarray(0, 16))
145
- const current = (name, id) =>
146
- single(name) ? ctx.view.findOne(col(name), {}) : ctx.view.get(col(name), { id })
378
+ function operators(ctx) {
379
+ const current = (name, id) => stored(ctx.view, name, id)
147
380
  // held to the fields as a direct write is, before the encoder drops or chokes on one
148
381
  const held = (name, row, stored) => {
149
382
  checkFields(name, spec.meta?.refs?.[name], row)
150
383
  checkRequired(name, spec.meta?.refs?.[name], stored)
151
384
  return stored
152
385
  }
153
- const write = (name, verb, row) => {
154
- touch(name)
386
+ // as of the op it runs in: what that op's stamp has no field for keeps what is stored
387
+ const write = async (name, verb, row) => {
388
+ ctx.touched?.push(name)
155
389
  const value = spec.dispatch.encode(`@${ns}/${verb}-${verbOf(name)}`, row)
156
- return router.dispatch(value, { ...ctx, nested: true })
390
+ return router.dispatch(await decode(value, ctx.stamp, ctx.view), { ...ctx, nested: true })
157
391
  }
158
392
  return {
159
393
  get: (ref, query) => read(ctx.view, refName(ref), query),
160
- put: (ref, row) => {
394
+ put: async (ref, row) => {
161
395
  const name = refName(ref)
162
- if (single(name)) return write(name, 'set', held(name, row, stamp(row, null, ts)))
163
- const stored = stamp({ ...row, id: row.id ?? mint() }, null, ts)
396
+ if (single(name)) return write(name, 'set', held(name, row, stamp(row, null, ctx.ts)))
397
+ const id = row.id ?? (await ctx.mint(ctx.view, col(name)))
398
+ const stored = stamp({ ...row, id }, null, ctx.ts)
164
399
  return write(name, 'add', held(name, row, stored))
165
400
  },
166
401
  // an upsert, as the set operator appends it
@@ -169,7 +404,7 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
169
404
  if (!single(name) && !row.id) throw CeroError.INVALID(`set('${name}') needs an id`)
170
405
  const verb = single(name) || BESPOKE.has(verbOf(name)) ? 'set' : 'add'
171
406
  const was = await current(name, row.id)
172
- return write(name, verb, held(name, row, stamp({ ...was, ...row }, was?.createdAt, ts)))
407
+ return write(name, verb, held(name, row, stamp({ ...was, ...row }, was?.createdAt, ctx.ts)))
173
408
  },
174
409
  del: (ref, id) => {
175
410
  const name = refName(ref)
@@ -186,16 +421,24 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
186
421
  }
187
422
 
188
423
  // hooks run inside the op's transaction on every peer, so their verdict is part of the op.
189
- // Resolves to the row that landed, which a before hook may have changed
190
- async function hooked(fns, { op, name, id = null, row = null, existing = null }, ctx, write) {
424
+ // Resolves to the row that landed, which a before hook may have changed. With a `rule`, a
425
+ // member's removal or change of rank: her rank allows it, as `meta.ranked` says, or a rule on
426
+ // members answers 'grant' (never a bare true, every rule's "no objection"), and a false refuses
427
+ // either. Decided before anything moves, so a refusal leaves her as she was
428
+ async function hooked(fns, meta, ctx, write, rule = null) {
191
429
  if (!fns) {
192
- await write(row)
193
- return row
430
+ if (rule && !meta.ranked) throw CeroError.REFUSED(rule)
431
+ await write(meta.row)
432
+ return meta.row
194
433
  }
195
- // never a clock: a derived row must stamp the same timestamp on every peer
196
- const ts = row?.updatedAt || existing?.updatedAt || 0
197
- const hctx = { op, name, row, existing, id, ...(await author(ctx)), ...operators(ctx, ts) }
198
- await fire(fns.before, hctx, true)
434
+ const writer = await author(ctx)
435
+ const base = { id: null, row: null, existing: null, ...meta }
436
+ const hctx = { ...base, ...writer, ...operators(ctx) }
437
+ const granted = await fire(fns.before, hctx, true)
438
+ // a grant widens rank among the room's writers only: never for a reader, nor for someone who
439
+ // is no member at all, whatever a rule wrote on ctx
440
+ const grant = granted && Boolean(writer.memberId) && can(writer.role, WRITE)
441
+ if (rule && !meta.ranked && !grant) throw CeroError.REFUSED(rule)
199
442
  await write(hctx.row)
200
443
  // once every row of the op landed: a join's after hooks write as a member
201
444
  ctx.later.push(async () => {
@@ -213,11 +456,15 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
213
456
  return hooked(fns, meta, ctx, (r) => insert(ctx.view, name, r))
214
457
  }
215
458
 
216
- // a seat taken again, as a linked device's own claim does, keeps the chain its link wrote
217
- async function seat(ctx, writer, memberId, ts, key, proof = null) {
459
+ // a seat taken again, as a linked device's own claim does, keeps the chain its link wrote. With
460
+ // it go the device keys of the proof it was `verified` with, which a removal told later is read by
461
+ async function seat(ctx, writer, memberId, ts, key, proof, verified) {
218
462
  const id = hid.encode(writer)
219
463
  proof ??= (await getDevice(ctx.view, id))?.proof ?? null
220
- return save(ctx, 'put', 'devices', { id, memberId, createdAt: ts, updatedAt: ts, key, proof })
464
+ const keys = Identity.chain(verified).slice(1)
465
+ const chain = keys.length ? b4a.concat(keys) : null
466
+ const row = { id, memberId, createdAt: ts, updatedAt: ts, key, proof, chain }
467
+ return save(ctx, 'put', 'devices', row)
221
468
  }
222
469
 
223
470
  // deleting a row that is not there changes nothing, and fires nothing
@@ -228,53 +475,10 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
228
475
  await hooked(existing ? fns : null, meta, ctx, () => ctx.view.delete(col(name), { id }))
229
476
  }
230
477
 
231
- // Who may remove a member, or change one's rank: by default her rank, as `ranked` says. An app's
232
- // rule on members may grant what rank alone refuses, by answering 'grant' (never a bare true,
233
- // which every rule answers for "no objection"), and refuse what rank allows, by answering false.
234
- // Decided before anything moves, so a refusal leaves the member as she was. Resolves to what
235
- // `landed` needs to fire the after hooks once the change lands
236
- async function decide(ctx, op, { row = null, existing, ranked }, refusal) {
237
- const fns = pick(op, ctx)
238
- const ts = row?.updatedAt || existing?.updatedAt || 0
239
- const hctx = {
240
- op,
241
- name: 'members',
242
- row,
243
- existing,
244
- id: existing.id,
245
- ranked,
246
- ...(await author(ctx)),
247
- ...operators(ctx, ts)
248
- }
249
- // a grant widens rank among the room's writers only: never for a reader, nor for someone who
250
- // is no member at all
251
- const canGrant = Boolean(hctx.memberId) && can(hctx.role, WRITE)
252
- let granted = false
253
- for (const fn of fns?.before ?? []) {
254
- let verdict
255
- try {
256
- verdict = await fn(hctx)
257
- } catch (err) {
258
- throw CeroError.REFUSED('hook', err.message)
259
- }
260
- if (verdict === false) throw CeroError.REFUSED('hook')
261
- if (verdict === 'grant' && canGrant) granted = true
262
- }
263
- if (!ranked && !granted) throw refusal()
264
- return { fns, hctx }
265
- }
266
-
267
- // a change decide judged: its before hooks already ran, its after hooks fire once it landed
268
- function landed(ctx, { fns, hctx }) {
269
- if (!fns) return
270
- ctx.later.push(async () => {
271
- Object.assign(hctx, await author(ctx))
272
- await fire(fns.after, hctx, false)
273
- })
274
- }
275
-
276
- // a rule that errors must not diverge peers: a throw refuses exactly like a false verdict
478
+ // a rule that errors must not diverge peers: a throw refuses exactly like a false verdict.
479
+ // Resolves to whether one granted
277
480
  async function fire(fns, hctx, vote) {
481
+ let granted = false
278
482
  for (const fn of fns) {
279
483
  let verdict
280
484
  try {
@@ -283,7 +487,9 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
283
487
  throw CeroError.REFUSED('hook', err.message)
284
488
  }
285
489
  if (vote && verdict === false) throw CeroError.REFUSED('hook')
490
+ if (verdict === 'grant') granted = true
286
491
  }
492
+ return granted
287
493
  }
288
494
 
289
495
  // a demoted member keeps its writer seat, so rows are gated by role; a writer with no
@@ -306,7 +512,10 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
306
512
  const fns = pick('set', ctx)
307
513
  const existing = fns ? await ctx.view.findOne(col(name), {}) : null
308
514
  const meta = { op: 'set', name, row: op, existing }
309
- return hooked(fns, meta, ctx, (row) => ctx.view.insert(col(name), row))
515
+ return hooked(fns, meta, ctx, (row) => {
516
+ checkFiles(name, row)
517
+ return ctx.view.insert(col(name), row)
518
+ })
310
519
  }
311
520
  // add on an existing id is an overwrite, same ownership rule as set
312
521
  if (own) await requireOwn(ctx, await ctx.view.get(col(name), { id: op.id }))
@@ -329,14 +538,14 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
329
538
  const meta = { op: 'del', name, id: op.id, existing }
330
539
  return hooked(fns, meta, ctx, () => ctx.view.delete(col(name), op))
331
540
  }
332
- // only REFUSED aborts a batch: every peer derives it. Decode failures and unknown routes skip one node
541
+ // only REFUSED aborts a batch: every peer derives it. A body that does not decode skips one node
333
542
  const isRefusal = (err) => err?.isCeroError === true && err.code === 'REFUSED'
334
543
 
335
- // an op's after hooks run once all its rows landed
544
+ // an op's after hooks run once all its rows landed; its ctx writes count on its node's mint
336
545
  const add = (verb, fn) =>
337
546
  router.add(`@${ns}/${verb}`, async (op, ctx) => {
338
547
  const later = []
339
- await fn(op, { ...ctx, later })
548
+ await fn(op, { ...ctx, later, mint: ctx.mint ?? minter(ctx.seed) })
340
549
  for (const run of later) await run()
341
550
  })
342
551
 
@@ -347,49 +556,198 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
347
556
  if (!b4a.equals(op.writer, ctx.key)) return
348
557
  const signed = Identity.verify(op.proof, admission(ctx.dbKey, op.writer, ctx.key), op.master)
349
558
  if (!signed) return
350
- if (await revoked(ctx.view, op.proof)) throw CeroError.REFUSED('removed')
559
+ if (!(await stands(ctx.view, Identity.chain(op.proof)))) throw CeroError.REFUSED('removed')
351
560
  const { genesis } = ctx.host
352
- const inviter = await getRole(ctx.view, op.master)
353
- if (!genesis && !can(inviter, INVITE)) throw CeroError.REFUSED('invite')
561
+ const memberId = hid.encode(op.master)
562
+ const ts = op.ts || 0
563
+ const known = await getMember(ctx.view, memberId)
564
+ const made = genesis ? [] : await promised(ctx.view, op.master)
565
+ // a member stands on what this device was promised, or every device she links would take a
566
+ // row on one promise; who is no member yet, on any made to her
567
+ const mine = made.find((row) => b4a.equals(row.key, signed.device))
568
+ const owed = known ? mine : made[0]
569
+ if (!genesis && !can(known?.role, INVITE) && !owed) throw CeroError.REFUSED('invite')
354
570
  // only a device of the signer's own identity: another member's device seats itself through
355
571
  // its join, or any key the signer holds would act as them.
356
572
  // Always an indexer: autobee gc's caught-up non-indexer sessions and they miss later appends
357
- const memberId = hid.encode(op.master)
358
573
  if (op.memberId && op.memberId !== memberId) throw CeroError.REFUSED('member')
359
574
  if (await boundElsewhere(ctx.view, op.writer, memberId)) throw CeroError.REFUSED('member')
360
- await ctx.host.addWriter(op.writer, { isIndexer: true })
361
- await seat(ctx, op.writer, memberId, op.ts || 0, signed.device)
575
+ // a promise kept: the member it was made to, at the role of the first one made. One made to
576
+ // a member is kept at the role she holds
577
+ const role = known ? known.role : made[0]?.role
578
+ if (role && !known) {
579
+ const member = { id: memberId, key: op.writer, role, createdAt: ts, updatedAt: ts }
580
+ await save(ctx, 'put', 'members', member)
581
+ }
582
+ if (genesis || can(role, WRITE)) await ctx.host.addWriter(op.writer, { isIndexer: true })
583
+ // a linked device's seat keeps the chain its promise carries. The promises stay: a member
584
+ // who may invite settles one once it sees it kept
585
+ await seat(ctx, op.writer, memberId, ts, signed.device, linkOf(mine?.proof), op.proof)
362
586
  })
363
587
 
364
- add('del-writer', async (op, ctx) => {
365
- if (!isKey(op.writer)) return
366
- const target = await getDevice(ctx.view, hid.encode(op.writer))
367
- if (target?.memberId !== (await getSignerMember(ctx.view, ctx.key))) {
368
- if (!(await canRemoveMember(ctx.view, ctx.key, target?.memberId))) {
588
+ // a device goes with its seat and its key: by its own member, or one who may remove her
589
+ async function unseat(ctx, id, device) {
590
+ const by = await getSignerMember(ctx.view, ctx.key)
591
+ if (device?.memberId !== by) {
592
+ if (!(await canRemoveMember(ctx.view, ctx.key, device?.memberId))) {
369
593
  throw CeroError.REFUSED('remove')
370
594
  }
371
595
  }
372
- await ctx.host.removeWriter(op.writer)
373
- await revoke(ctx, target)
374
- await drop(ctx, 'devices', hid.encode(op.writer))
596
+ const may = can(await getSignerRole(ctx.view, ctx.key), REMOVE)
597
+ await ctx.host.removeWriter(hid.decode(id))
598
+ await revoke(ctx, device, by, may)
599
+ await drop(ctx, 'devices', id)
600
+ await ctx.view.delete(asks, { id })
601
+ if (device) await owe(ctx.view)
602
+ // with the seat go the keys its writer was still owed, and what its device key was promised:
603
+ // a rotation is sealed to the promised
604
+ const own = await ctx.view.get(requests, { id })
605
+ await (device ? forget(ctx, own) : withdraw(ctx, own))
606
+ const stood = (row) => chainOf(row).some((key) => b4a.equals(key, device.key))
607
+ for (const row of device?.key ? await ctx.view.find(requests, {}).toArray() : []) {
608
+ // waiting or promised: one admitted at its join has a seat of its own to lose
609
+ if (row.admitted && !row.promised) continue
610
+ if (stood(row)) await withdraw(ctx, row)
611
+ }
612
+ if (device && may) await shut(ctx)
613
+ }
614
+ // a removal by someone who may remove spends the invites that let in on their own: one the
615
+ // removed held, or saw, brings nobody in after it. Those that wait for an accept stay. A promise
616
+ // no device claimed goes too, its invite used up or not, unless a member accepted it
617
+ async function shut(ctx) {
618
+ for (const invite of await ctx.view.find(invites, {}).toArray()) {
619
+ if (invite.secret && !invite.confirm) await spend(ctx, invite, 'removed')
620
+ }
621
+ for (const row of await ctx.view.find(requests, {}).toArray()) {
622
+ if (!row.promised || row.accepted || (await ctx.view.get(invites, { id: row.invite }))) {
623
+ continue
624
+ }
625
+ if ((await ctx.view.get(spent, { id: row.invite }))?.confirm) continue
626
+ if (!(await sat(ctx.view, row))) await withdraw(ctx, row)
627
+ }
628
+ }
629
+ // a request goes: a promise among them was handed the keys, so a rotation is owed
630
+ async function forget(ctx, row) {
631
+ if (!row) return
632
+ await drop(ctx, 'requests', row.id)
633
+ if (row.promised) await owe(ctx.view)
634
+ }
635
+ // a promise goes with the member or device it stood on: one no device claimed hears why, so
636
+ // its claim ends
637
+ async function withdraw(ctx, row) {
638
+ if (!row?.promised || (await sat(ctx.view, row))) return forget(ctx, row)
639
+ await forget(ctx, row)
640
+ await refuse(ctx, row, 'removed')
641
+ }
642
+ add('del-writer', async (op, ctx) => {
643
+ if (!isKey(op.writer)) return
644
+ const id = hid.encode(op.writer)
645
+ await unseat(ctx, id, await getDevice(ctx.view, id))
375
646
  })
376
647
 
377
648
  // a removed device's key, and any device it attests after, stays out: its chain is static, so
378
- // the removal is kept here, beside the members'
379
- async function revoke(ctx, device) {
649
+ // the removal is kept here, beside the members', with whether it spent the open invites
650
+ async function revoke(ctx, device, by, spent) {
380
651
  if (!device?.key) return
381
652
  const minted = (await ctx.view.get(countersCol, { name: 'invites' }))?.value ?? 0
382
- await ctx.view.insert(removals, { id: hid.encode(device.key), index: minted })
653
+ await ctx.view.insert(removals, { id: hid.encode(device.key), index: minted, by, spent })
383
654
  }
384
- // the devices of the chain, not the identity it starts with: a member's removal is ordered by
385
- // its invites, a device's is for good
386
- async function revoked(view, proof) {
387
- for (const key of Identity.chain(proof).slice(1)) {
388
- if (await view.get(removals, { id: hid.encode(key) })) return true
655
+ // a chain, its identity first, stands unless it passes a removed device key. A key its identity
656
+ // removed, told or taken out by a device of hers, is passed by a key after it that stands: in
657
+ // the root one seated, in a room one she told stands; one another member removed, or whose
658
+ // record says not who, cuts whatever she told. With `telling`, as it will once she tells those
659
+ // lists too
660
+ async function stands(view, [identity, ...keys], telling) {
661
+ const memberId = hid.encode(identity)
662
+ const told = await view.get(removals, { id: toldId(memberId) })
663
+ const removed = [...keysOf(told?.removed), ...keysOf(telling?.removed)]
664
+ let cut = -1
665
+ for (const [i, key] of keys.entries()) {
666
+ const removal = await view.get(removals, { id: hid.encode(key) })
667
+ if (removal && removal.by !== memberId) return false
668
+ if (removal || has(removed, key)) cut = i
389
669
  }
390
- return false
670
+ if (cut < 0) return true
671
+ const standing = root
672
+ ? (await view.find(`@${ns}/devices`, {}).toArray())
673
+ .filter((d) => d.memberId === memberId && d.key)
674
+ .map((d) => d.key)
675
+ : keysOf(telling ? telling.standing : told?.standing)
676
+ return keys.slice(cut + 1).some((key) => has(standing, key))
677
+ }
678
+
679
+ // the chain of the device that tells: its seat's, or for a member's device with none here, a
680
+ // reader's other one, or one whose row keeps no key, the chain of the proof its identity signs
681
+ // over the core it tells from
682
+ async function teller(op, ctx) {
683
+ if (!ctx.key) return null
684
+ const device = await getDevice(ctx.view, hid.encode(ctx.key))
685
+ if (device?.memberId && device.key) return seatChain(device)
686
+ const chain = Identity.chain(op.proof)
687
+ if (!Identity.verify(op.proof, admission(ctx.dbKey, ctx.key, ctx.key), chain[0])) return null
688
+ return (await getMember(ctx.view, hid.encode(chain[0]))) ? chain : null
391
689
  }
392
690
 
691
+ // a device tells the room which device keys of its identity are removed and which stand. For
692
+ // its identity alone: the removed add up, the standing replace those told before, and the seats
693
+ // of the identity whose chain no longer stands go, with the joins that wait or were promised
694
+ // through one. Told by someone who may remove, a key no removal that spent the open invites
695
+ // covers is a removal by her
696
+ add('revoke', async (op, ctx) => {
697
+ const chain = await teller(op, ctx)
698
+ if (!chain) throw CeroError.REFUSED('device')
699
+ if (!(await stands(ctx.view, chain))) throw CeroError.REFUSED('removed')
700
+ const memberId = hid.encode(chain[0])
701
+ const id = toldId(memberId)
702
+ const told = await ctx.view.get(removals, { id })
703
+ const before = keysOf(told?.removed)
704
+ const added = keysOf(op.removed).filter((key) => !has(before, key))
705
+ const removed = [...before, ...added]
706
+ const rowed = (await ctx.view.find(`@${ns}/devices`, {}).toArray())
707
+ .filter((d) => d.memberId === memberId && d.key)
708
+ .map((d) => d.key)
709
+ // one with no row here is known by what it tells: itself among those that stand
710
+ const own = chain[chain.length - 1]
711
+ if (!has(rowed, own) && !has(keysOf(op.standing), own)) {
712
+ throw CeroError.REFUSED('revoke', 'a device tells itself standing')
713
+ }
714
+ // one telling is bounded, an identity's removals are not: a cap on those would let a device
715
+ // fill it with made-up keys and keep its own in
716
+ if (added.length > MAX_REMOVED && !ctx.host.genesis) {
717
+ throw CeroError.REFUSED(
718
+ 'revoke',
719
+ `at most ${MAX_REMOVED} new device keys removed per telling`
720
+ )
721
+ }
722
+ let uncovered = false
723
+ for (const key of told?.spent ? added : removed) {
724
+ if (!(await ctx.view.get(removals, { id: hid.encode(key) }))?.spent) uncovered = true
725
+ }
726
+ const spends = uncovered && can(await getSignerRole(ctx.view, ctx.key), REMOVE)
727
+ const standing = b4a.concat(keysOf(op.standing))
728
+ const spent = spends || !uncovered
729
+ const row = { id, index: 0, by: memberId, removed: b4a.concat(removed), standing, spent }
730
+ await ctx.view.insert(removals, row)
731
+ // a removed device that never sat here may hold the key through its identity's root, unless
732
+ // the room was made after the removal
733
+ if (added.length && !ctx.host.genesis) await owe(ctx.view)
734
+ for (const seated of await ctx.view.find(`@${ns}/devices`, {}).toArray()) {
735
+ if (seated.memberId !== memberId || !seated.key) continue
736
+ if (await stands(ctx.view, seatChain(seated))) continue
737
+ await ctx.host.removeWriter(hid.decode(seated.id))
738
+ await drop(ctx, 'devices', seated.id)
739
+ await ctx.view.delete(asks, { id: seated.id })
740
+ await owe(ctx.view)
741
+ await forget(ctx, await ctx.view.get(requests, { id: seated.id }))
742
+ }
743
+ for (const row of await ctx.view.find(requests, {}).toArray()) {
744
+ // waiting or promised: one admitted at its join has a seat of its own to lose
745
+ if (row.admitted && !row.promised) continue
746
+ if (!(await stands(ctx.view, [row.identity, ...chainOf(row)]))) await withdraw(ctx, row)
747
+ }
748
+ if (spends) await shut(ctx)
749
+ })
750
+
393
751
  // the genesis batch names the creator; everyone after comes in through a signed join
394
752
  add('add-member', async (op, ctx) => {
395
753
  if (!isKey(op.key)) return
@@ -407,14 +765,28 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
407
765
  // whose row it is decides what may change: your own is writable, another member's only
408
766
  // for an authorised role change. Key and provenance never come off the wire
409
767
  const isSelf = op.id === (await getSignerMember(ctx.view, ctx.key))
410
- const next = isSelf ? { ...op } : { ...existing }
768
+ const ranks = Boolean(op.role) && op.role !== existing.role
769
+ if (!isSelf && !ranks) return
770
+ // a release before seatless writes takes every field of a reader's row: below it, none goes in
771
+ if (
772
+ isSelf &&
773
+ !can(existing.role, WRITE) &&
774
+ (since?.routes[`@${ns}/ask-key`] ?? 0) > ctx.stamp
775
+ ) {
776
+ throw CeroError.REFUSED('route', 'a reader writes her row in a room at a newer version')
777
+ }
778
+ const next = !isSelf
779
+ ? { ...existing }
780
+ : can(existing.role, WRITE)
781
+ ? { ...op }
782
+ : profile(existing, op)
411
783
  next.key = existing.key
412
784
  next.role = existing.role
413
785
  next.createdAt = existing.createdAt
414
786
  next.updatedAt = op.updatedAt || existing.updatedAt
415
787
 
416
788
  let row
417
- if (op.role && op.role !== existing.role) {
789
+ if (ranks) {
418
790
  // a rank cero has no name for is no rank, granted or not
419
791
  if (!isRank(op.role)) throw CeroError.INVALID(`'${op.role}' is not a role`)
420
792
  // the last owner keeps her rank, whatever a rule grants, as she is never removed
@@ -426,12 +798,9 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
426
798
  const r = await getSignerRole(ctx.view, ctx.key)
427
799
  next.role = op.role
428
800
  const ranked = can(r, ASSIGN) && grants(r, op.role) && outranks(r, existing.role)
429
- const decided = await decide(ctx, 'set', { row: next, existing, ranked }, () =>
430
- CeroError.REFUSED('assign')
431
- )
432
- row = decided.hctx.row
433
- await insert(ctx.view, 'members', row)
434
- landed(ctx, decided)
801
+ const meta = { op: 'set', name: 'members', id: op.id, row: next, existing, ranked }
802
+ const write = (member) => insert(ctx.view, 'members', member)
803
+ row = await hooked(pick('set', ctx), meta, ctx, write, 'assign')
435
804
  } else {
436
805
  row = await save(ctx, 'set', 'members', next)
437
806
  }
@@ -448,11 +817,35 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
448
817
 
449
818
  add('del-member', async (op, ctx) => {
450
819
  const existing = await getMember(ctx.view, op.id)
451
- if (!existing) return
452
- let decided = null
820
+ if (!existing) {
821
+ // taken out after she left: leaving first dodges nothing
822
+ const left = await ctx.view.get(removals, { id: leftId(op.id) })
823
+ if (left && can(await getSignerRole(ctx.view, ctx.key), REMOVE)) await shut(ctx)
824
+ return
825
+ }
453
826
  // leaving is hers: only someone else taking her out turns her older codes away
454
- const leaving = op.id === (await getSignerMember(ctx.view, ctx.key))
455
- if (!leaving) {
827
+ const by = await getSignerMember(ctx.view, ctx.key)
828
+ const leaving = op.id === by
829
+ // every device of the member goes with them, and any keys they were still owed
830
+ const vacate = async () => {
831
+ if (existing.key) await ctx.host.removeWriter(existing.key)
832
+ for (const device of await ctx.view.find(`@${ns}/devices`, {}).toArray()) {
833
+ if (device.memberId !== op.id) continue
834
+ await ctx.host.removeWriter(hid.decode(device.id))
835
+ await drop(ctx, 'devices', device.id)
836
+ await ctx.view.delete(asks, { id: device.id })
837
+ await owe(ctx.view)
838
+ await drop(ctx, 'requests', device.id)
839
+ }
840
+ for (const row of await promised(ctx.view, hid.decode(op.id))) await withdraw(ctx, row)
841
+ }
842
+ if (leaving) {
843
+ if (existing.role === OWNER && (await orphans(ctx.view, op.id))) {
844
+ throw CeroError.INVALID('the last owner cannot leave: make another member an owner first')
845
+ }
846
+ await vacate()
847
+ await drop(ctx, 'members', op.id)
848
+ } else {
456
849
  // the last owner stays, whatever a rule grants: without her nobody outranks the rest
457
850
  if (existing.role === OWNER && (await orphans(ctx.view, op.id))) {
458
851
  throw CeroError.INVALID(
@@ -461,29 +854,18 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
461
854
  }
462
855
  const r = await getSignerRole(ctx.view, ctx.key)
463
856
  const ranked = can(r, REMOVE) && outranks(r, existing.role)
464
- decided = await decide(ctx, 'del', { existing, ranked }, () => CeroError.REFUSED('remove'))
465
- } else if (existing.role === OWNER && (await orphans(ctx.view, op.id))) {
466
- throw CeroError.INVALID('the last owner cannot leave: make another member an owner first')
467
- }
468
- if (existing.key) await ctx.host.removeWriter(existing.key)
469
- // every device of the member goes with them, and any keys they were still owed
470
- for (const device of await ctx.view.find(`@${ns}/devices`, {}).toArray()) {
471
- if (device.memberId !== op.id) continue
472
- await ctx.host.removeWriter(hid.decode(device.id))
473
- await drop(ctx, 'devices', device.id)
474
- await drop(ctx, 'requests', device.id)
475
- }
476
- if (decided) {
477
- await ctx.view.delete(col('members'), { id: op.id })
478
- landed(ctx, decided)
479
- } else {
480
- await drop(ctx, 'members', op.id)
857
+ const meta = { op: 'del', name: 'members', id: op.id, existing, ranked }
858
+ const write = async () => {
859
+ await vacate()
860
+ await ctx.view.delete(col('members'), { id: op.id })
861
+ }
862
+ await hooked(pick('del', ctx), meta, ctx, write, 'remove')
481
863
  }
482
864
  // an invite they could hold, or saw, does not bring them back on its own: after a removal it is turned away, after
483
- // leaving it waits for a member to accept her again, so leaving first never dodges a removal. Either row re-keys
484
- // the handle at its first removal (rotation.js)
865
+ // leaving it waits for a member to accept her again, so leaving first never dodges a removal
485
866
  const minted = (await ctx.view.get(countersCol, { name: 'invites' }))?.value ?? 0
486
- await ctx.view.insert(removals, { id: leaving ? leftId(op.id) : op.id, index: minted })
867
+ await ctx.view.insert(removals, { id: leaving ? leftId(op.id) : op.id, index: minted, by })
868
+ if (!leaving) await shut(ctx)
487
869
  })
488
870
 
489
871
  add('rotate-key', async (op, ctx) => {
@@ -492,11 +874,19 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
492
874
  if (op.commit?.byteLength !== 32) return
493
875
  // the stamp is picked before any block is written, so epochs reorder freely; uniqueness is enforced here
494
876
  if (!Number.isInteger(op.stamp) || op.stamp <= 0 || op.stamp > 0xffffffff) return
495
- if (!can(await getSignerRole(ctx.view, ctx.key), REMOVE)) {
877
+ // envelopes that do not decode would stop every later audit
878
+ if (!sealed(op.wrapped)) return
879
+ const role = await getSignerRole(ctx.view, ctx.key)
880
+ const aside = !can(role, REMOVE)
881
+ // a reorder can take her rank after she wrote under her key: kept, what she wrote reads
882
+ if (aside && !(can(role, WRITE) && (await asides(ctx.view)))) {
496
883
  throw CeroError.REFUSED('rotate', 'rotate requires the remove permission')
497
884
  }
498
885
  const rows = await ctx.view.find(`@${ns}/${EPOCHS}`, {}).toArray()
499
- if (rows.some((r) => r.stamp === op.stamp)) return
886
+ const taken = rows.find((r) => r.stamp === op.stamp)
887
+ // one key per stamp: a counted rotation always lands, and takes it from one set aside
888
+ if (taken && (aside || !taken.aside)) return
889
+ if (taken) await ctx.view.delete(`@${ns}/${EPOCHS}`, { epoch: taken.epoch })
500
890
  // sequence numbers order epochs; concurrent rotations get consecutive sequences, both readable
501
891
  const epoch = await bump(ctx.view, EPOCHS)
502
892
  const row = {
@@ -504,31 +894,41 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
504
894
  stamp: op.stamp,
505
895
  wrapped: op.wrapped,
506
896
  createdAt: op.createdAt || 0,
507
- commit: op.commit
897
+ commit: op.commit,
898
+ aside
508
899
  }
509
900
  await ctx.view.insert(`@${ns}/${EPOCHS}`, row)
510
- touch(EPOCHS)
511
- // never in a dry run: the announcement itself is appended under the old epoch
512
- if (!ctx.dryRun) {
513
- try {
514
- await onepoch(row)
515
- } catch (err) {
516
- onerror(err)
517
- }
901
+ // sealed before a removal it crossed, it names a device taken out since: one more is owed
902
+ if (!aside) await owe(ctx.view, (await outsider(ctx.view, op.wrapped)) ? 1 : 0)
903
+ ctx.touched?.push(EPOCHS)
904
+ // learned once its batch commits: a refused batch teaches no epoch, and a dry run commits nothing
905
+ ctx.epochs?.push(row)
906
+ })
907
+
908
+ const asides = async (view) => since?.types[`@${ns}/epoch`]?.aside <= (await versionOf(view))
909
+
910
+ // whether a rotation names a device with no seat and no promise where it lands. A promise row
911
+ // is one that stands: a removal takes those on its key, and past its invite a member withdraws it
912
+ async function outsider(view, wrapped) {
913
+ for (const { id } of c.decode(wraps, wrapped)) {
914
+ if (await getDevice(view, id)) continue
915
+ if (!(await view.get(requests, { id }))?.promised) return true
518
916
  }
917
+ return false
918
+ }
919
+
920
+ // only an owner moves the version, and only up: a lower one is no change and no error. The
921
+ // genesis batch raises first, before the member row it writes, so all of it runs at the version
922
+ add('upgrade', async (op, ctx) => {
923
+ const owner = ctx.host.genesis || (await getSignerRole(ctx.view, ctx.key)) === OWNER
924
+ if (!owner) throw CeroError.REFUSED('upgrade')
925
+ if (op.version <= (await versionOf(ctx.view))) return
926
+ await ctx.view.insert(countersCol, { name: VERSION, value: op.version })
519
927
  })
520
928
 
521
929
  add('del-device', async (op, ctx) => {
522
- const existing = await getDevice(ctx.view, op.id)
523
- if (!existing) return
524
- if (existing.memberId !== (await getSignerMember(ctx.view, ctx.key))) {
525
- if (!(await canRemoveMember(ctx.view, ctx.key, existing.memberId))) {
526
- throw CeroError.REFUSED('remove')
527
- }
528
- }
529
- await ctx.host.removeWriter(hid.decode(existing.id))
530
- await revoke(ctx, existing)
531
- await drop(ctx, 'devices', op.id)
930
+ const device = await getDevice(ctx.view, op.id)
931
+ if (device) await unseat(ctx, op.id, device)
532
932
  })
533
933
 
534
934
  // a device row is the writer→role mapping, so memberId never comes off the wire; a core no
@@ -542,26 +942,53 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
542
942
  const selfOnly = (op, ctx) => {
543
943
  if (!ctx.key || op.id !== hid.encode(ctx.key)) throw CeroError.REFUSED('device')
544
944
  }
545
- // the device key stays what the admission proved, never what the row says
945
+ // the device key and the chain stay what the admission proved, never what the row says
546
946
  add('add-device', async (op, ctx) => {
547
947
  selfOnly(op, ctx)
548
948
  const existing = await getDevice(ctx.view, op.id)
549
- await save(ctx, 'put', 'devices', { ...op, memberId: await bind(ctx), key: existing?.key })
949
+ const kept = { key: existing?.key, chain: existing?.chain }
950
+ await save(ctx, 'put', 'devices', { ...op, memberId: await bind(ctx), ...kept })
550
951
  })
952
+ // another device of its member renames it while it stands, and changes nothing else of the row
551
953
  add('set-device', async (op, ctx) => {
552
- selfOnly(op, ctx)
553
- const memberId = await bind(ctx)
554
954
  const existing = await getDevice(ctx.view, op.id)
555
955
  const ts = op.updatedAt || 0
956
+ if (ctx.key && existing && op.id !== hid.encode(ctx.key)) {
957
+ const by = await getDevice(ctx.view, hid.encode(ctx.key))
958
+ if (!by?.memberId || by.memberId !== existing.memberId) throw CeroError.REFUSED('device')
959
+ if (existing.key && !(await stands(ctx.view, seatChain(existing)))) {
960
+ throw CeroError.REFUSED('removed')
961
+ }
962
+ await save(ctx, 'set', 'devices', { ...existing, name: op.name, updatedAt: ts })
963
+ return
964
+ }
965
+ selfOnly(op, ctx)
966
+ const memberId = await bind(ctx)
556
967
  await save(ctx, 'set', 'devices', {
557
968
  ...op,
558
969
  memberId,
559
970
  key: existing?.key,
971
+ chain: existing?.chain,
560
972
  createdAt: existing?.createdAt || op.createdAt || ts,
561
973
  updatedAt: ts
562
974
  })
563
975
  })
564
976
 
977
+ // a device of a member who stands asks for the keys it lacks, from its own core whether it
978
+ // writes or only reads: one row, at the address it asked with last, that only its own op closes
979
+ add('ask-key', async (op, ctx) => {
980
+ selfOnly(op, ctx)
981
+ if (!isKey(op.reply)) return
982
+ await bind(ctx)
983
+ ctx.touched?.push(ASKS)
984
+ await ctx.view.insert(asks, { id: op.id, reply: op.reply })
985
+ })
986
+ add('del-owed', async (op, ctx) => {
987
+ selfOnly(op, ctx)
988
+ ctx.touched?.push(ASKS)
989
+ await ctx.view.delete(asks, op)
990
+ })
991
+
565
992
  // any WRITE member mints an invite, its rank capped at admission; an existing row is never
566
993
  // overwritten, and altering or revoking one needs REMOVE
567
994
  const invites = `@${ns}/invites`
@@ -594,31 +1021,63 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
594
1021
  if (!can(r, REMOVE)) throw CeroError.REFUSED('invite')
595
1022
  await ctx.view.delete(spent, { id: op.id })
596
1023
  })
597
- // its joins still waiting for a member are turned away with it; admitted ones are still owed
598
- // their keys. Its id stays, so a later join with it hears why
1024
+ // its joins still waiting for a member are turned away with it, and the promises made under it
1025
+ // withdrawn, unless it was used up by the join it let in; admitted ones are still owed their
1026
+ // keys. Its id stays, and its secret, so a later join with it is opened and hears why
599
1027
  async function spend(ctx, invite, reason) {
600
1028
  const expires = invite.expires || 0
601
1029
  await drop(ctx, 'invites', invite.id)
602
- await ctx.view.insert(spent, { id: invite.id, reason, expires })
1030
+ const { secret, confirm } = invite
1031
+ await ctx.view.insert(spent, { id: invite.id, reason, expires, secret, confirm })
1032
+ const kept = async (request) => {
1033
+ if (!request.admitted) return false
1034
+ if (!request.promised || reason === 'spent') return true
1035
+ // a removal withdraws what no device claimed: a promise kept waits for a member to settle it
1036
+ return reason === 'removed' && (request.accepted || sat(ctx.view, request))
1037
+ }
603
1038
  for (const request of await ctx.view.find(requests, {}).toArray()) {
604
- if (request.invite !== invite.id || request.admitted) continue
605
- await drop(ctx, 'requests', request.id)
1039
+ if (request.invite !== invite.id || (await kept(request))) continue
1040
+ await forget(ctx, request)
606
1041
  await refuse(ctx, request, reason)
607
1042
  }
608
1043
  }
609
1044
 
610
- // a join turned away is answered at its reply address. A writer with a request hears through
611
- // that: one of the two per writer, or a denial could race its keys
612
- async function refuse(ctx, { id, reply, expires }, reason) {
1045
+ // a join turned away is answered at its reply address, under its invite. A writer with a request
1046
+ // hears through that: one of the two per writer, or a denial could race its keys. A spent
1047
+ // invite keeps the answer to its newest join alone, and a live one the newest to each identity
1048
+ // it turns away as removed, so nobody holding one fills the log
1049
+ async function refuse(
1050
+ ctx,
1051
+ { id, reply, expires, invite, identity = null },
1052
+ reason,
1053
+ last = false
1054
+ ) {
613
1055
  if (await ctx.view.get(requests, { id })) return
614
- await ctx.view.insert(refusals, { id, reply, reason, expires })
1056
+ const rows = last ? await ctx.view.find(refusals, {}).toArray() : []
1057
+ const same = (row) =>
1058
+ identity ? row.identity && b4a.equals(row.identity, identity) : row.spent
1059
+ for (const row of rows) {
1060
+ if (row.invite === invite && same(row)) await ctx.view.delete(refusals, { id: row.id })
1061
+ }
1062
+ const row = { id, reply, reason, expires, invite, spent: last && !identity, identity }
1063
+ await ctx.view.insert(refusals, row)
615
1064
  }
1065
+ // from the version that has an invite's secret, whatever stamp a join carries
1066
+ const bounded = async (view) => since?.types[`@${ns}/invite`]?.secret <= (await versionOf(view))
1067
+ // from the version whose requests say a member accepted them
1068
+ const marked = async (view) => since?.types[`@${ns}/request`]?.accepted <= (await versionOf(view))
1069
+ // from the version whose refusals record who joined
1070
+ const recorded = async (view) =>
1071
+ since?.types[`@${ns}/refusal`]?.identity <= (await versionOf(view))
616
1072
 
617
1073
  // the member, when new, and its device, seated when the member writes; its request stays until
618
1074
  // a member delivered the keys. The invite is spent unless it is reusable
619
- async function admit(ctx, { invite, identity, key, writer, reply, role, ts }) {
1075
+ async function admit(ctx, { invite, identity, key, writer, reply, role, ts, proof }) {
620
1076
  const memberId = hid.encode(identity)
621
1077
  if (await boundElsewhere(ctx.view, writer, memberId)) throw CeroError.REFUSED('member')
1078
+ if (invite.secret) {
1079
+ return promise(ctx, { invite, identity, key, writer, reply, role, ts, proof })
1080
+ }
622
1081
  const member =
623
1082
  (await getMember(ctx.view, memberId)) ??
624
1083
  (await save(ctx, 'put', 'members', {
@@ -629,7 +1088,7 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
629
1088
  updatedAt: ts
630
1089
  }))
631
1090
  if (can(member.role, WRITE)) await ctx.host.addWriter(writer, { isIndexer: true })
632
- await seat(ctx, writer, memberId, ts, key)
1091
+ await seat(ctx, writer, memberId, ts, key, null, proof)
633
1092
  await save(ctx, 'put', 'requests', {
634
1093
  ...request(invite, identity, key, writer, reply, ts),
635
1094
  role,
@@ -643,8 +1102,13 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
643
1102
  async function admitDevice(ctx, { invite, memberId, key, proof, writer, reply, ts }) {
644
1103
  if (await boundElsewhere(ctx.view, writer, memberId)) throw CeroError.REFUSED('member')
645
1104
  const member = await getMember(ctx.view, memberId)
1105
+ if (invite.secret) {
1106
+ const identity = hid.decode(memberId)
1107
+ const { role } = member
1108
+ return promise(ctx, { invite, identity, key, writer, reply, role, ts, proof })
1109
+ }
646
1110
  if (can(member.role, WRITE)) await ctx.host.addWriter(writer, { isIndexer: true })
647
- await seat(ctx, writer, memberId, ts, key, proof)
1111
+ await seat(ctx, writer, memberId, ts, key, proof, proof)
648
1112
  await save(ctx, 'put', 'requests', {
649
1113
  ...request(invite, hid.decode(memberId), key, writer, reply, ts),
650
1114
  role: member.role,
@@ -653,6 +1117,31 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
653
1117
  if (!invite.reuse) await spend(ctx, invite, 'spent')
654
1118
  }
655
1119
 
1120
+ // let in through an invite with an address of its own: admitted, with no member and no seat
1121
+ // until a device of the identity, holding the keys, seats itself. With a link's chain for its
1122
+ // proof, that one device
1123
+ async function promise(ctx, { invite, identity, key, writer, reply, role, ts, proof }) {
1124
+ // only an accept hands a promise an invite that waits
1125
+ const accepted = !!invite.confirm && (await marked(ctx.view))
1126
+ await save(ctx, 'put', 'requests', {
1127
+ ...request(invite, identity, key, writer, reply, ts),
1128
+ role,
1129
+ admitted: true,
1130
+ promised: true,
1131
+ proof,
1132
+ ...(accepted && { accepted })
1133
+ })
1134
+ if (!invite.reuse) await spend(ctx, invite, 'spent')
1135
+ }
1136
+
1137
+ // what an identity was promised, the first made first
1138
+ async function promised(view, identity) {
1139
+ const rows = await view.find(requests, {}).toArray()
1140
+ return rows
1141
+ .filter((row) => row.promised && b4a.equals(row.identity, identity))
1142
+ .sort((a, b) => a.index - b.index)
1143
+ }
1144
+
656
1145
  function request(invite, identity, key, writer, reply, ts) {
657
1146
  const expires = invite.expires || 0
658
1147
  const id = hid.encode(writer)
@@ -660,22 +1149,30 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
660
1149
  return { id, identity, key, invite: invite.id, role, reply, expires, createdAt: ts }
661
1150
  }
662
1151
 
663
- // null when it does not open: anyone may append a join
664
- function open(box) {
665
- const pair = room()
1152
+ // null when it does not open: anyone may append a join. One that names its invite is sealed to
1153
+ // that invite's own address, and only its row, live or spent, has the secret; the name in the
1154
+ // clear is the one in the box
1155
+ async function open(view, { box, invite }) {
1156
+ const pair = invite ? await pairOf(view, b4a.toHex(invite)) : room()
666
1157
  if (!pair || !box?.byteLength) return null
667
1158
  try {
668
1159
  const plain = crypto.decrypt(box, pair)
669
- return plain && c.decode(Join, plain)
1160
+ const join = plain && c.decode(Join, plain)
1161
+ if (join && invite && !b4a.equals(join.invite, invite)) return null
1162
+ return join
670
1163
  } catch {
671
1164
  return null
672
1165
  }
673
1166
  }
1167
+ async function pairOf(view, id) {
1168
+ const row = (await view.get(invites, { id })) ?? (await view.get(spent, { id }))
1169
+ return row?.secret ? keyPair(row.secret) : null
1170
+ }
674
1171
 
675
1172
  // the joiner's own core asks in: the invite proves it may, its device signs where the keys go
676
1173
  // and the proof's chain says whose device it is
677
1174
  add('join', async (op, ctx) => {
678
- const join = open(op.box)
1175
+ const join = await open(ctx.view, op)
679
1176
  if (!join || !ctx.key) return
680
1177
  if (!Invite.proven(join.invite, ctx.key, join.signature)) return
681
1178
  const signed = Identity.verify(join.proof, joining(ctx.dbKey, join.invite, ctx.key, join.reply))
@@ -683,25 +1180,35 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
683
1180
  join.identity = signed.identity
684
1181
  const id = hid.encode(ctx.key)
685
1182
  const invite = await ctx.view.get(invites, { id: b4a.toHex(join.invite) })
1183
+ const record = invite ?? (await ctx.view.get(spent, { id: b4a.toHex(join.invite) }))
1184
+ // an invite with an address of its own is joined by name only
1185
+ if (record?.secret && !op.invite) return
686
1186
  if (!invite) {
687
1187
  // an invite the database never held could be anyone's: nobody answers it
688
- const record = await ctx.view.get(spent, { id: b4a.toHex(join.invite) })
689
1188
  if (!record) return
690
- return refuse(ctx, { id, reply: join.reply, expires: record.expires }, record.reason)
1189
+ const turned = { id, reply: join.reply, expires: record.expires, invite: record.id }
1190
+ return refuse(ctx, turned, record.reason, await bounded(ctx.view))
691
1191
  }
692
1192
  const ts = join.ts || 0
693
1193
  const memberId = hid.encode(join.identity)
694
1194
  const known = await getMember(ctx.view, memberId)
695
1195
  const removal = known ? null : await ctx.view.get(removals, { id: memberId })
696
1196
  const out =
697
- (removal && (invite.index ?? 0) <= removal.index) || (await revoked(ctx.view, join.proof))
698
- if (out) return refuse(ctx, { id, reply: join.reply, expires: invite.expires || 0 }, 'removed')
1197
+ (removal && (invite.index ?? 0) <= removal.index) ||
1198
+ !(await stands(ctx.view, Identity.chain(join.proof)))
1199
+ if (out) {
1200
+ const turned = { id, reply: join.reply, expires: invite.expires || 0, invite: invite.id }
1201
+ const last = await recorded(ctx.view)
1202
+ return refuse(ctx, { ...turned, identity: last ? join.identity : null }, 'removed', last)
1203
+ }
699
1204
  await ctx.view.delete(refusals, { id })
700
1205
  const gone = known ? null : await ctx.view.get(removals, { id: leftId(memberId) })
701
1206
  const older = gone && (invite.index ?? 0) <= gone.index
702
1207
  if ((invite.confirm || older) && !known) {
703
1208
  const waiting = request(invite, join.identity, signed.device, ctx.key, join.reply, ts)
704
- return save(ctx, 'put', 'requests', waiting)
1209
+ // a promise it writes over was handed the keys
1210
+ if ((await ctx.view.get(requests, { id }))?.promised) await owe(ctx.view)
1211
+ return save(ctx, 'put', 'requests', { ...waiting, proof: join.proof })
705
1212
  }
706
1213
  await admit(ctx, {
707
1214
  invite,
@@ -710,7 +1217,8 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
710
1217
  writer: ctx.key,
711
1218
  reply: join.reply,
712
1219
  role: invite.role,
713
- ts
1220
+ ts,
1221
+ proof: join.proof
714
1222
  })
715
1223
  })
716
1224
  // a waiting join, admitted at a role within the invite's and the accepter's; with a proof, as a
@@ -718,30 +1226,46 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
718
1226
  add('accept', async (op, ctx) => {
719
1227
  const waiting = await ctx.view.get(requests, { id: op.id })
720
1228
  if (!waiting || waiting.admitted) return
721
- const invite = await ctx.view.get(invites, { id: waiting.invite })
1229
+ const live = await ctx.view.get(invites, { id: waiting.invite })
1230
+ // spent by this, it says a member let the join in, whatever it asked for itself
1231
+ const invite = live && (await marked(ctx.view)) ? { ...live, confirm: true } : live
722
1232
  const r = await getSignerRole(ctx.view, ctx.key)
723
1233
  const role = op.role || invite?.role
724
1234
  if (!invite || !can(r, INVITE) || !grants(r, role) || !grants(invite.role, role)) {
725
1235
  throw CeroError.REFUSED('invite')
726
1236
  }
727
- const { identity, key, reply, createdAt: ts = 0 } = waiting
1237
+ const { identity, key, reply, proof, createdAt: ts = 0 } = waiting
1238
+ // a key removed since the join was made lets nobody in
1239
+ if (!(await stands(ctx.view, [identity, ...chainOf(waiting)]))) {
1240
+ throw CeroError.REFUSED('removed')
1241
+ }
728
1242
  const writer = hid.decode(op.id)
729
1243
  if (op.proof) {
730
1244
  const memberId = await getSignerMember(ctx.view, ctx.key)
731
1245
  const linked = Identity.verify(op.proof, null, hid.decode(memberId))
732
1246
  if (!linked || !b4a.equals(linked.device, key)) throw CeroError.REFUSED('device')
733
- if (await revoked(ctx.view, op.proof)) throw CeroError.REFUSED('removed')
1247
+ if (!(await stands(ctx.view, Identity.chain(op.proof)))) throw CeroError.REFUSED('removed')
734
1248
  return admitDevice(ctx, { invite, memberId, key, proof: op.proof, writer, reply, ts })
735
1249
  }
736
- await admit(ctx, { invite, identity, key, writer, reply, role, ts })
1250
+ await admit(ctx, { invite, identity, key, writer, reply, role, ts, proof })
737
1251
  })
738
- // answered through the log like every refusal; a deny that lost the race to an accept is nothing
1252
+ // a waiting join is turned away by one who may invite; a promise is withdrawn by one who may
1253
+ // remove, since its joiner may hold the keys. Answered through the log like every refusal
739
1254
  add('deny', async (op, ctx) => {
740
- const waiting = await ctx.view.get(requests, { id: op.id })
741
- if (!waiting || waiting.admitted) return
742
- if (!can(await getSignerRole(ctx.view, ctx.key), INVITE)) throw CeroError.REFUSED('invite')
743
- await drop(ctx, 'requests', op.id)
744
- await refuse(ctx, waiting, op.reason || '')
1255
+ const row = await ctx.view.get(requests, { id: op.id })
1256
+ if (!row || (row.admitted && !row.promised)) return
1257
+ const [perm, rule] = row.promised ? [REMOVE, 'remove'] : [INVITE, 'invite']
1258
+ if (!can(await getSignerRole(ctx.view, ctx.key), perm)) throw CeroError.REFUSED(rule)
1259
+ // a promise its device claimed is settled: nobody is turned away and no keys are owed
1260
+ if (row.promised && (await sat(ctx.view, row))) return drop(ctx, 'requests', row.id)
1261
+ await forget(ctx, row)
1262
+ await refuse(ctx, row, op.reason || '')
1263
+ })
1264
+ // the joiner's own core takes back its join while it waits: an accept that landed first stands
1265
+ add('cancel-join', async (op, ctx) => {
1266
+ selfOnly(op, ctx)
1267
+ const row = await ctx.view.get(requests, { id: op.id })
1268
+ if (row && !row.admitted) await drop(ctx, 'requests', row.id)
745
1269
  })
746
1270
  // only a join writes a request
747
1271
  const joinsOnly = async () => {
@@ -749,11 +1273,25 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
749
1273
  }
750
1274
  add('add-request', joinsOnly)
751
1275
  add('set-request', joinsOnly)
752
- // a denial, or keys delivered
1276
+ // a denial, or keys delivered. A promise dropped before the device it was made to sat under its
1277
+ // member is one withdrawn: its joiner may hold the keys, so it takes the right to remove, unless
1278
+ // a key of its chain was removed since
753
1279
  add('del-request', async (op, ctx) => {
754
- if (!can(await getSignerRole(ctx.view, ctx.key), INVITE)) throw CeroError.REFUSED('invite')
1280
+ const r = await getSignerRole(ctx.view, ctx.key)
1281
+ if (!can(r, INVITE)) throw CeroError.REFUSED('invite')
1282
+ const row = await ctx.view.get(requests, { id: op.id })
1283
+ if (!row) return
1284
+ const open = row.promised && !(await sat(ctx.view, row))
1285
+ const cut = open && !(await stands(ctx.view, [row.identity, ...chainOf(row)]))
1286
+ if (open && !can(r, REMOVE) && !cut) throw CeroError.REFUSED('remove')
755
1287
  await drop(ctx, 'requests', op.id)
1288
+ if (open) await owe(ctx.view)
756
1289
  })
1290
+ async function sat(view, { identity, key }) {
1291
+ const memberId = hid.encode(identity)
1292
+ const devices = await view.find(`@${ns}/devices`, {}).toArray()
1293
+ return devices.some((d) => d.memberId === memberId && d.key && b4a.equals(d.key, key))
1294
+ }
757
1295
  // read by the joiner, or past its expiry with nobody waiting
758
1296
  add('del-refusal', async (op, ctx) => {
759
1297
  if (!can(await getSignerRole(ctx.view, ctx.key), INVITE)) throw CeroError.REFUSED('invite')
@@ -775,9 +1313,27 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
775
1313
  add('set-file', update('files', true))
776
1314
  add('del-file', remove('files', true))
777
1315
 
778
- add('add-handle', upsert('handles', COLLECTION, false))
779
- add('set-handle', update('handles', false))
780
- add('del-handle', remove('handles', false))
1316
+ // held to its states on every peer, so a device with an older picture writes over no newer one
1317
+ const held = (write) => async (op, ctx) => {
1318
+ const was = await ctx.view.get(col('handles'), { id: op.id })
1319
+ // a write naming no state keeps the row's, `in` on a new row: its device may read an older one
1320
+ if (!op.state) {
1321
+ if (was) {
1322
+ const { reason, by, invite, writer } = was
1323
+ Object.assign(op, { reason, by, invite, writer })
1324
+ }
1325
+ op.state = was?.state || 'in'
1326
+ }
1327
+ if (!moves(was, op)) throw CeroError.REFUSED('state')
1328
+ return write(op, ctx)
1329
+ }
1330
+ add('add-handle', held(upsert('handles', COLLECTION, false)))
1331
+ add('set-handle', held(update('handles', false)))
1332
+ add('del-handle', async (op, ctx) => {
1333
+ const was = await ctx.view.get(col('handles'), { id: op.id })
1334
+ if (UNSETTLED.has(was?.state)) throw CeroError.REFUSED('state')
1335
+ return remove('handles', false)(op, ctx)
1336
+ })
781
1337
 
782
1338
  for (const [name, info] of Object.entries(spec.meta?.refs || {})) {
783
1339
  if (info.internal) continue
@@ -811,9 +1367,16 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
811
1367
  }
812
1368
 
813
1369
  return {
814
- dispatch: (value, ctx) => router.dispatch(value, ctx),
1370
+ encode,
1371
+ cut,
1372
+ dispatch: async (value, ctx) => router.dispatch(await decode(value, ctx.stamp, ctx.view), ctx),
1373
+ role: getSignerRole,
1374
+ stands,
1375
+ version: versionOf,
1376
+ built,
815
1377
  async apply(nodes, view, host) {
816
1378
  const dbKey = key()
1379
+ const before = await built(view)
817
1380
  // a batch is one writer's contiguous run, so a refusal discards only that writer's ops
818
1381
  const tx = view.transaction()
819
1382
  // host calls survive a discarded transaction, so they replay once the batch commits
@@ -821,17 +1384,35 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
821
1384
  const deferred = Object.create(host)
822
1385
  deferred.addWriter = (...args) => void calls.push(['addWriter', args])
823
1386
  deferred.removeWriter = (...args) => void calls.push(['removeWriter', args])
1387
+ const epochs = []
1388
+ // refs hooks wrote, marked once their batch commits: a discarded batch, or a dry run, wakes nobody
1389
+ const touched = []
824
1390
  let refusal = null
1391
+ let changed = false
1392
+ const landed = []
825
1393
  for (const node of nodes) {
1394
+ // the version as it stands at this node, an upgrade earlier in the batch included
1395
+ const stamp = Math.min(node.version, await versionOf(tx))
1396
+ // replayed once this build reaches it
1397
+ if (stamp > contract()) {
1398
+ onskip(stamp)
1399
+ continue
1400
+ }
826
1401
  try {
827
- const seed = crypto.hash([node.key, node.value])
828
- await router.dispatch(node.value, {
1402
+ const seed = crypto.hash([node.key, c.encode(c.uint, node.length), node.value])
1403
+ // never a clock: the node's time is the same on every peer
1404
+ await router.dispatch(await decode(node.value, stamp, tx), {
829
1405
  view: tx,
830
1406
  host: deferred,
831
1407
  key: node.key,
832
1408
  dbKey,
833
- seed
1409
+ seed,
1410
+ ts: node.timestamp,
1411
+ stamp,
1412
+ epochs,
1413
+ touched
834
1414
  })
1415
+ landed.push(node)
835
1416
  } catch (err) {
836
1417
  // anything but a refusal skips one node, so an older peer never drops a batch its newer neighbour applies
837
1418
  if (!isRefusal(err)) {
@@ -846,11 +1427,29 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
846
1427
  await tx.close()
847
1428
  onerror(refusal)
848
1429
  } else {
1430
+ changed = tx.updated()
1431
+ // a view another build applied keeps its row until this device applies the log again; what
1432
+ // it skipped follows this device, since a reorder takes it back in the view alone
1433
+ const own = build()
1434
+ const ours = !before || before.slice(0, 3).every((n, i) => n === own[i])
1435
+ for (let i = 0; ours && i < BUILT.length; i++) {
1436
+ if (before?.[i] === own[i]) continue
1437
+ await tx.insert(countersCol, { name: BUILT[i], value: own[i] })
1438
+ }
849
1439
  await tx.flush()
1440
+ if (changed) for (const name of touched) touch(name)
850
1441
  // before apply() returns: autobee clears host.applying right after, and addWriter reads it
851
1442
  for (const [fn, args] of calls) await host[fn](...args)
1443
+ for (const row of epochs) {
1444
+ try {
1445
+ await onepoch(row)
1446
+ } catch (err) {
1447
+ onerror(err)
1448
+ }
1449
+ }
852
1450
  }
853
1451
  await view.flush()
1452
+ return { landed: refusal ? [] : landed, changed }
854
1453
  }
855
1454
  }
856
1455
  }