@cero-base/core 1.19.0 → 2.1.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.
- package/README.md +1 -1
- package/package.json +9 -6
- package/src/blobs/index.js +15 -15
- package/src/blobs/server.js +0 -2
- package/src/database/changes.js +4 -8
- package/src/database/dispatch.js +296 -227
- package/src/database/encryption.js +22 -52
- package/src/database/envelope.js +1 -3
- package/src/database/index.js +406 -476
- package/src/database/rotation.js +56 -70
- package/src/identity/index.js +5 -9
- package/src/index.js +5 -9
- package/src/lib/constants.js +3 -12
- package/src/lib/errors.js +6 -10
- package/src/lib/schema.js +2 -5
- package/src/lib/utils.js +9 -24
- package/src/network/index.js +144 -167
- package/src/network/presence.js +131 -0
- package/src/pairing/candidate.js +2 -4
- package/src/pairing/index.js +41 -55
- package/src/pairing/invite.js +3 -4
- package/src/pairing/request.js +3 -9
- package/src/rpc/index.js +4 -14
- package/src/rpc/peer.js +3 -7
- package/src/storage/index.js +29 -50
- package/types/blobs/index.d.ts +5 -5
- package/types/blobs/server.d.ts +0 -2
- package/types/database/changes.d.ts +2 -5
- package/types/database/dispatch.d.ts +11 -7
- package/types/database/encryption.d.ts +8 -20
- package/types/database/index.d.ts +164 -141
- package/types/database/rotation.d.ts +14 -20
- package/types/identity/index.d.ts +5 -9
- package/types/index.d.ts +4 -3
- package/types/lib/errors.d.ts +6 -10
- package/types/lib/schema.d.ts +2 -5
- package/types/lib/utils.d.ts +3 -7
- package/types/network/index.d.ts +28 -27
- package/types/network/presence.d.ts +50 -0
- package/types/pairing/candidate.d.ts +1 -2
- package/types/pairing/index.d.ts +22 -30
- package/types/pairing/invite.d.ts +3 -3
- package/types/pairing/request.d.ts +1 -3
- package/types/rpc/index.d.ts +1 -4
- package/types/rpc/peer.d.ts +2 -4
- package/types/storage/index.d.ts +17 -30
package/src/database/dispatch.js
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import b4a from 'b4a'
|
|
2
|
+
import c from 'compact-encoding'
|
|
3
|
+
import crypto from 'hypercore-crypto'
|
|
4
|
+
import z32 from 'z32'
|
|
2
5
|
import hid from 'hypercore-id-encoding'
|
|
3
6
|
|
|
4
7
|
import {
|
|
@@ -16,17 +19,7 @@ import { can, grants, outranks, admission, ownership } from '../lib/utils.js'
|
|
|
16
19
|
import { CeroError } from '../lib/errors.js'
|
|
17
20
|
import { Identity } from '../identity/index.js'
|
|
18
21
|
|
|
19
|
-
//
|
|
20
|
-
export const BUILTINS = [
|
|
21
|
-
{ name: 'members', verb: 'member' },
|
|
22
|
-
{ name: 'devices', verb: 'device' },
|
|
23
|
-
{ name: 'invites', verb: 'invite' },
|
|
24
|
-
{ name: 'handles', verb: 'handle' },
|
|
25
|
-
{ name: 'files', verb: 'file' }
|
|
26
|
-
]
|
|
27
|
-
|
|
28
|
-
// Remote op fields are variable-length buffers on the wire — reject wrong sizes
|
|
29
|
-
// before they reach sodium/hid.encode, which throw instead of returning false.
|
|
22
|
+
// wire fields are variable-length: reject wrong sizes before sodium and hid throw on them
|
|
30
23
|
const isKey = (b) => b?.byteLength === 32
|
|
31
24
|
const isSig = (b) => b?.byteLength === 64
|
|
32
25
|
|
|
@@ -41,10 +34,25 @@ const isSig = (b) => b?.byteLength === 64
|
|
|
41
34
|
* @param {(err: Error) => void} opts.onerror Called when a malformed node is skipped.
|
|
42
35
|
* @param {() => Uint8Array | null} opts.key The database key, null until the bee booted.
|
|
43
36
|
* @param {(row: { epoch: number, stamp: number, wrapped: Uint8Array, commit: Uint8Array }) => Promise<void>} opts.onepoch Per-peer side of an applied rotation (skipped in dry runs).
|
|
44
|
-
* @
|
|
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.
|
|
41
|
+
* @returns {{ dispatch: (value: Buffer, ctx: object) => Promise<void>, apply: (nodes: Array<{ value: Buffer, key: Buffer }>, view: object, host: object) => Promise<void> }}
|
|
45
42
|
*/
|
|
46
|
-
export function makeDispatcher({
|
|
47
|
-
|
|
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
|
+
}) {
|
|
55
|
+
const router = new spec.dispatch.Router()
|
|
48
56
|
|
|
49
57
|
const countersCol = `@${ns}/${COUNTERS}`
|
|
50
58
|
const getMember = (view, id) => view.get(`@${ns}/members`, { id })
|
|
@@ -82,59 +90,149 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
|
|
|
82
90
|
await view.insert(col, op)
|
|
83
91
|
}
|
|
84
92
|
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
+
const pick = (op) => {
|
|
94
|
+
if (!hooks || !op) return null
|
|
95
|
+
const before = hooks('before', op)
|
|
96
|
+
const after = hooks('after', op)
|
|
97
|
+
return before.length || after.length ? { before, after } : null
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const refName = (ref) => (typeof ref === 'string' ? ref : ref?.name)
|
|
101
|
+
const single = (name) => spec.meta?.refs?.[name]?.kind === SINGLE
|
|
102
|
+
|
|
103
|
+
// the operators developers know, bound to the open transaction and this op's stamps
|
|
104
|
+
function operators(view, memberId, ts, seed) {
|
|
105
|
+
let n = 0
|
|
106
|
+
// 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}`
|
|
109
|
+
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)
|
|
121
|
+
}
|
|
122
|
+
return {
|
|
123
|
+
get: (ref, query) => read(view, refName(ref), query),
|
|
124
|
+
put: (ref, row) => {
|
|
125
|
+
const name = refName(ref)
|
|
126
|
+
return store(name, stamp(single(name) ? row : { ...row, id: row.id ?? mint() }, null))
|
|
127
|
+
},
|
|
128
|
+
set: async (ref, row) => {
|
|
129
|
+
const name = refName(ref)
|
|
130
|
+
if (!single(name) && !row.id) throw CeroError.INVALID(`set('${name}') needs an id`)
|
|
131
|
+
return store(name, stamp(row, await current(name, row.id)))
|
|
132
|
+
},
|
|
133
|
+
del: (ref, id) => {
|
|
134
|
+
const name = refName(ref)
|
|
135
|
+
touch?.(name)
|
|
136
|
+
return view.delete(col(name), single(name) ? {} : { id })
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
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) {
|
|
145
|
+
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 }
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
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)
|
|
154
|
+
// never a clock: a derived row must stamp the same timestamp on every peer
|
|
155
|
+
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
|
+
}
|
|
166
|
+
await fire(fns.before, hctx, true)
|
|
167
|
+
await write(hctx.row)
|
|
168
|
+
await fire(fns.after, hctx, false)
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// a rule that errors must not diverge peers: a throw refuses exactly like a false verdict
|
|
172
|
+
async function fire(fns, hctx, vote) {
|
|
173
|
+
for (const fn of fns) {
|
|
174
|
+
let verdict
|
|
175
|
+
try {
|
|
176
|
+
verdict = await fn(hctx)
|
|
177
|
+
} catch (err) {
|
|
178
|
+
throw CeroError.REFUSED('hook', err.message)
|
|
179
|
+
}
|
|
180
|
+
if (vote && verdict === false) throw CeroError.REFUSED('hook')
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// a demoted member keeps its writer seat, so rows are gated by role; a writer with no
|
|
185
|
+
// member row is not a member and writes nothing
|
|
93
186
|
const requireWrite = async (ctx) => {
|
|
94
|
-
|
|
95
|
-
if (r !== null && !can(r, WRITE)) throw CeroError.REFUSED('write')
|
|
187
|
+
if (!can(await getSignerRole(ctx.view, ctx.key), WRITE)) throw CeroError.REFUSED('write')
|
|
96
188
|
}
|
|
97
189
|
|
|
98
|
-
//
|
|
99
|
-
// an `own` collection just enforces it: the author may change their own rows,
|
|
100
|
-
// and anyone who can REMOVE may moderate the rest.
|
|
190
|
+
// own: the author may change their rows, anyone with REMOVE may moderate the rest
|
|
101
191
|
const requireOwn = async (ctx, existing) => {
|
|
102
192
|
if (existing?.memberId == null) return
|
|
103
193
|
if (existing.memberId === (await getSignerMember(ctx.view, ctx.key))) return
|
|
104
194
|
if (!can(await getSignerRole(ctx.view, ctx.key), REMOVE)) throw CeroError.REFUSED('own')
|
|
105
195
|
}
|
|
106
196
|
|
|
107
|
-
const upsert = (name, col, kind, own) => async (op, ctx) => {
|
|
197
|
+
const upsert = (name, col, kind, own, hook) => async (op, ctx) => {
|
|
108
198
|
await requireWrite(ctx)
|
|
109
199
|
const d = ctx.key && (await getDevice(ctx.view, hid.encode(ctx.key)))
|
|
110
200
|
op.memberId = d?.memberId || null
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
201
|
+
const fns = pick(hook)
|
|
202
|
+
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))
|
|
206
|
+
}
|
|
207
|
+
const existing = own || fns ? await ctx.view.get(col, { id: op.id }) : null
|
|
208
|
+
// 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))
|
|
116
212
|
}
|
|
117
|
-
const update = (name, col, own) => async (op, ctx) => {
|
|
213
|
+
const update = (name, col, own, hook) => async (op, ctx) => {
|
|
118
214
|
await requireWrite(ctx)
|
|
119
215
|
const existing = await ctx.view.get(col, { id: op.id })
|
|
120
216
|
if (!existing) return
|
|
121
217
|
if (own) await requireOwn(ctx, existing)
|
|
122
|
-
// memberId is attribution
|
|
123
|
-
// wire — otherwise an edit could leave the row credited to its victim
|
|
218
|
+
// memberId is attribution: derived here, never merged off the wire
|
|
124
219
|
const d = ctx.key && (await getDevice(ctx.view, hid.encode(ctx.key)))
|
|
125
|
-
|
|
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))
|
|
126
223
|
}
|
|
127
|
-
const remove = (col, own) => async (op, ctx) => {
|
|
224
|
+
const remove = (name, col, own, hook) => async (op, ctx) => {
|
|
128
225
|
await requireWrite(ctx)
|
|
129
|
-
|
|
130
|
-
|
|
226
|
+
const fns = pick(hook)
|
|
227
|
+
const existing = own || fns ? await ctx.view.get(col, { id: op.id }) : null
|
|
228
|
+
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))
|
|
131
231
|
}
|
|
132
|
-
//
|
|
133
|
-
// the view alone, so every peer reaches it. Decode failures and unknown routes
|
|
134
|
-
// must not — an older peer would drop a batch its newer neighbour applies.
|
|
232
|
+
// only REFUSED aborts a batch: every peer derives it. Decode failures and unknown routes skip one node
|
|
135
233
|
const isRefusal = (err) => err?.isCeroError === true && err.code === 'REFUSED'
|
|
136
234
|
|
|
137
|
-
const add = (verb, fn) =>
|
|
235
|
+
const add = (verb, fn) => router.add(`@${ns}/${verb}`, fn)
|
|
138
236
|
|
|
139
237
|
add('add-writer', async (op, ctx) => {
|
|
140
238
|
if (!isKey(op.master) || !isKey(op.writer) || !isSig(op.sig)) return
|
|
@@ -142,19 +240,18 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
|
|
|
142
240
|
const genesis = await isGenesis(ctx.view)
|
|
143
241
|
const inviter = await getRole(ctx.view, op.master)
|
|
144
242
|
if (!genesis && !can(inviter, INVITE)) throw CeroError.REFUSED('invite')
|
|
145
|
-
// the rank is add-member's decision
|
|
146
|
-
//
|
|
147
|
-
//
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
243
|
+
// the rank is add-member's decision in the same transaction: a refused grant discards this admission.
|
|
244
|
+
// 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
|
+
}
|
|
151
250
|
await ctx.host.addWriter(op.writer, { isIndexer: true })
|
|
152
251
|
const ts = op.ts || 0
|
|
153
252
|
await insert(ctx.view, 'devices', `@${ns}/devices`, {
|
|
154
253
|
id: hid.encode(op.writer),
|
|
155
|
-
|
|
156
|
-
// lands the device resolves to nobody, instead of to the inviter
|
|
157
|
-
memberId: op.memberId || hid.encode(op.master),
|
|
254
|
+
memberId,
|
|
158
255
|
createdAt: ts,
|
|
159
256
|
updatedAt: ts
|
|
160
257
|
})
|
|
@@ -175,8 +272,7 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
|
|
|
175
272
|
add('claim-writer', async (op, ctx) => {
|
|
176
273
|
if (!isKey(op.identity) || !isKey(op.writer) || !isSig(op.sig)) return
|
|
177
274
|
if (!Identity.verify(op.identity, ownership(ctx.dbKey, op.writer), op.sig)) return
|
|
178
|
-
// a claim is
|
|
179
|
-
// inapplicable, not refused, so it must not abort that writer's batch
|
|
275
|
+
// from any other core a claim is inapplicable, not refused: it must not abort that writer's batch
|
|
180
276
|
if (!b4a.equals(ctx.key, op.writer)) return
|
|
181
277
|
const memberId = hid.encode(op.identity)
|
|
182
278
|
if (!can(await getRole(ctx.view, op.identity), WRITE)) throw CeroError.REFUSED('write')
|
|
@@ -213,12 +309,8 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
|
|
|
213
309
|
add('set-member', async (op, ctx) => {
|
|
214
310
|
const existing = await getMember(ctx.view, op.id)
|
|
215
311
|
if (!existing) return
|
|
216
|
-
//
|
|
217
|
-
//
|
|
218
|
-
// whatever else an app declares), so a name list would silently drop them.
|
|
219
|
-
// Your own profile is yours to write; another member's row is untouchable
|
|
220
|
-
// apart from an authorised role change. Identity and provenance never come
|
|
221
|
-
// off the wire, so nobody overwrites the key a member was admitted with.
|
|
312
|
+
// whose row it is decides what may change: your own is writable, another member's only
|
|
313
|
+
// for an authorised role change. Key and provenance never come off the wire
|
|
222
314
|
const isSelf = op.id === (await getSignerMember(ctx.view, ctx.key))
|
|
223
315
|
const next = isSelf ? { ...op } : { ...existing }
|
|
224
316
|
next.key = existing.key
|
|
@@ -234,18 +326,14 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
|
|
|
234
326
|
next.role = op.role
|
|
235
327
|
}
|
|
236
328
|
await insert(ctx.view, 'members', `@${ns}/members`, next)
|
|
237
|
-
// a demotion that takes WRITE away
|
|
238
|
-
// otherwise the member keeps appending, and only the apply-time WRITE
|
|
239
|
-
// gate stands between them and every collection
|
|
329
|
+
// a demotion that takes WRITE away takes the writer seat with it
|
|
240
330
|
if (can(existing.role, WRITE) && !can(next.role, WRITE)) {
|
|
241
331
|
if (next.key) await ctx.host.removeWriter(next.key)
|
|
242
332
|
for (const device of await ctx.view.find(`@${ns}/devices`, {}).toArray()) {
|
|
243
333
|
if (device.memberId !== next.id) continue
|
|
244
334
|
await ctx.host.removeWriter(hid.decode(device.id))
|
|
245
335
|
}
|
|
246
|
-
//
|
|
247
|
-
// deleting them would leave the demoted writer unresolvable — which the
|
|
248
|
-
// apply-time gate reads as "not yet enrolled" and lets through
|
|
336
|
+
// device rows stay: an unresolvable writer would read as not yet enrolled and pass the gate
|
|
249
337
|
}
|
|
250
338
|
})
|
|
251
339
|
|
|
@@ -257,8 +345,7 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
|
|
|
257
345
|
if (!can(r, REMOVE) || !outranks(r, existing.role)) throw CeroError.REFUSED('remove')
|
|
258
346
|
}
|
|
259
347
|
if (existing.key) await ctx.host.removeWriter(existing.key)
|
|
260
|
-
// every device of the member goes with them
|
|
261
|
-
// leave writers admitted or stale device rows behind
|
|
348
|
+
// every device of the member goes with them
|
|
262
349
|
for (const device of await ctx.view.find(`@${ns}/devices`, {}).toArray()) {
|
|
263
350
|
if (device.memberId !== op.id) continue
|
|
264
351
|
await ctx.host.removeWriter(hid.decode(device.id))
|
|
@@ -267,54 +354,41 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
|
|
|
267
354
|
await ctx.view.delete(`@${ns}/members`, op)
|
|
268
355
|
})
|
|
269
356
|
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
commit: op.commit
|
|
303
|
-
}
|
|
304
|
-
await ctx.view.insert(`@${ns}/${EPOCHS}`, row)
|
|
305
|
-
// per-peer hydration (unseal own envelope → keyring) — never in a dry
|
|
306
|
-
// run: the announcement itself must be appended under the OLD epoch
|
|
307
|
-
if (!ctx.dryRun) {
|
|
308
|
-
try {
|
|
309
|
-
await onepoch(row)
|
|
310
|
-
} catch (err) {
|
|
311
|
-
onerror(err)
|
|
312
|
-
}
|
|
357
|
+
add('rotate-key', async (op, ctx) => {
|
|
358
|
+
if (!op.wrapped?.byteLength) return
|
|
359
|
+
// the commitment lets every member verify the sealed secret, so a rotator cannot split the room
|
|
360
|
+
if (op.commit?.byteLength !== 32) return
|
|
361
|
+
// the stamp is picked before any block is written, so epochs reorder freely; uniqueness is enforced here
|
|
362
|
+
if (!Number.isInteger(op.stamp) || op.stamp <= 0 || op.stamp > 0xffffffff) return
|
|
363
|
+
if (!can(await getSignerRole(ctx.view, ctx.key), REMOVE)) {
|
|
364
|
+
throw CeroError.REFUSED('rotate', 'rotate requires the remove permission')
|
|
365
|
+
}
|
|
366
|
+
const rows = await ctx.view.find(`@${ns}/${EPOCHS}`, {}).toArray()
|
|
367
|
+
if (rows.some((r) => r.stamp === op.stamp)) return
|
|
368
|
+
// 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 })
|
|
375
|
+
const row = {
|
|
376
|
+
epoch,
|
|
377
|
+
stamp: op.stamp,
|
|
378
|
+
wrapped: op.wrapped,
|
|
379
|
+
createdAt: op.createdAt || 0,
|
|
380
|
+
commit: op.commit
|
|
381
|
+
}
|
|
382
|
+
await ctx.view.insert(`@${ns}/${EPOCHS}`, row)
|
|
383
|
+
// never in a dry run: the announcement itself is appended under the old epoch
|
|
384
|
+
if (!ctx.dryRun) {
|
|
385
|
+
try {
|
|
386
|
+
await onepoch(row)
|
|
387
|
+
} catch (err) {
|
|
388
|
+
onerror(err)
|
|
313
389
|
}
|
|
314
|
-
}
|
|
315
|
-
}
|
|
316
|
-
// pre-rotation spec
|
|
317
|
-
}
|
|
390
|
+
}
|
|
391
|
+
})
|
|
318
392
|
|
|
319
393
|
add('del-device', async (op, ctx) => {
|
|
320
394
|
const existing = await getDevice(ctx.view, op.id)
|
|
@@ -328,128 +402,121 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
|
|
|
328
402
|
await ctx.view.delete(`@${ns}/devices`, op)
|
|
329
403
|
})
|
|
330
404
|
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
// teeth. Any WRITE member may mint one — the rank it can grant is capped
|
|
362
|
-
// at admission — but an existing row is never overwritten (that only
|
|
363
|
-
// breaks the invite for everyone), and altering or revoking one is a
|
|
364
|
-
// moderation act: it needs REMOVE.
|
|
365
|
-
add(`add-${b.verb}`, async (op, ctx) => {
|
|
366
|
-
await requireWrite(ctx)
|
|
367
|
-
if (await ctx.view.get(col, { id: op.id })) throw CeroError.REFUSED('invite')
|
|
368
|
-
await insert(ctx.view, b.name, col, op)
|
|
369
|
-
})
|
|
370
|
-
// like requireWrite, a signer with no resolvable role yet (genesis, or
|
|
371
|
-
// the optimistic-admission window) is not refused
|
|
372
|
-
const moderate = async (ctx) => {
|
|
373
|
-
const r = await getSignerRole(ctx.view, ctx.key)
|
|
374
|
-
if (r !== null && !can(r, REMOVE)) throw CeroError.REFUSED('invite')
|
|
375
|
-
}
|
|
376
|
-
add(`set-${b.verb}`, async (op, ctx) => {
|
|
377
|
-
await moderate(ctx)
|
|
378
|
-
const existing = await ctx.view.get(col, { id: op.id })
|
|
379
|
-
if (!existing) return
|
|
380
|
-
await insert(ctx.view, b.name, col, { ...existing, ...op })
|
|
381
|
-
})
|
|
382
|
-
// deleting is two different acts: revoking (moderation, REMOVE) and
|
|
383
|
-
// consuming a single-use invite — which is done by whichever replica
|
|
384
|
-
// served the join, so any member who may serve invites may do it
|
|
385
|
-
add(`del-${b.verb}`, async (op, ctx) => {
|
|
386
|
-
const existing = await ctx.view.get(col, { id: op.id })
|
|
387
|
-
const consume = existing && existing.reuse !== true
|
|
388
|
-
const r = await getSignerRole(ctx.view, ctx.key)
|
|
389
|
-
if (r !== null && !can(r, REMOVE) && !(consume && can(r, INVITE))) {
|
|
390
|
-
throw CeroError.REFUSED('invite')
|
|
391
|
-
}
|
|
392
|
-
return ctx.view.delete(col, op)
|
|
393
|
-
})
|
|
394
|
-
continue
|
|
395
|
-
}
|
|
396
|
-
if (b.verb === 'file') {
|
|
397
|
-
add('add-file', async (op, ctx) => {
|
|
398
|
-
if (!can(await getSignerRole(ctx.view, ctx.key), WRITE)) throw CeroError.REFUSED('write')
|
|
399
|
-
const memberId = await getSignerMember(ctx.view, ctx.key)
|
|
400
|
-
await insert(ctx.view, b.name, col, {
|
|
401
|
-
id: op.id,
|
|
402
|
-
name: op.name ?? null,
|
|
403
|
-
memberId,
|
|
404
|
-
stamp: op.stamp ?? 0
|
|
405
|
-
})
|
|
406
|
-
})
|
|
407
|
-
} else {
|
|
408
|
-
add(`add-${b.verb}`, upsert(b.name, col, COLLECTION))
|
|
409
|
-
}
|
|
410
|
-
add(`set-${b.verb}`, update(b.name, col))
|
|
411
|
-
add(`del-${b.verb}`, remove(col))
|
|
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))
|
|
410
|
+
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) })
|
|
413
|
+
})
|
|
414
|
+
add('set-device', async (op, ctx) => {
|
|
415
|
+
const existing = await getDevice(ctx.view, op.id)
|
|
416
|
+
const ts = op.updatedAt || 0
|
|
417
|
+
await insert(ctx.view, 'devices', devices, {
|
|
418
|
+
...op,
|
|
419
|
+
memberId: await bind(ctx, existing),
|
|
420
|
+
createdAt: existing?.createdAt || op.createdAt || ts,
|
|
421
|
+
updatedAt: ts
|
|
422
|
+
})
|
|
423
|
+
})
|
|
424
|
+
|
|
425
|
+
// any WRITE member mints an invite, its rank capped at admission; an existing row is never
|
|
426
|
+
// overwritten, and altering or revoking one needs REMOVE
|
|
427
|
+
const invites = `@${ns}/invites`
|
|
428
|
+
add('add-invite', async (op, ctx) => {
|
|
429
|
+
await requireWrite(ctx)
|
|
430
|
+
if (await ctx.view.get(invites, { id: op.id })) throw CeroError.REFUSED('invite')
|
|
431
|
+
await insert(ctx.view, 'invites', invites, op)
|
|
432
|
+
})
|
|
433
|
+
const moderate = async (ctx) => {
|
|
434
|
+
if (!can(await getSignerRole(ctx.view, ctx.key), REMOVE)) throw CeroError.REFUSED('invite')
|
|
412
435
|
}
|
|
436
|
+
add('set-invite', async (op, ctx) => {
|
|
437
|
+
await moderate(ctx)
|
|
438
|
+
const existing = await ctx.view.get(invites, { id: op.id })
|
|
439
|
+
if (!existing) return
|
|
440
|
+
await insert(ctx.view, 'invites', invites, { ...existing, ...op })
|
|
441
|
+
})
|
|
442
|
+
// revoking needs REMOVE; consuming a single-use invite is done by whichever replica served the join
|
|
443
|
+
add('del-invite', async (op, ctx) => {
|
|
444
|
+
const existing = await ctx.view.get(invites, { id: op.id })
|
|
445
|
+
const consume = existing && existing.reuse !== true
|
|
446
|
+
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)
|
|
449
|
+
})
|
|
450
|
+
|
|
451
|
+
const files = `@${ns}/files`
|
|
452
|
+
add('add-file', async (op, ctx) => {
|
|
453
|
+
if (!can(await getSignerRole(ctx.view, ctx.key), WRITE)) throw CeroError.REFUSED('write')
|
|
454
|
+
const memberId = await getSignerMember(ctx.view, ctx.key)
|
|
455
|
+
await insert(ctx.view, 'files', files, {
|
|
456
|
+
id: op.id,
|
|
457
|
+
name: op.name ?? null,
|
|
458
|
+
memberId,
|
|
459
|
+
stamp: op.stamp ?? 0
|
|
460
|
+
})
|
|
461
|
+
})
|
|
462
|
+
add('set-file', update('files', files))
|
|
463
|
+
add('del-file', remove('files', files))
|
|
464
|
+
|
|
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))
|
|
413
469
|
|
|
414
470
|
for (const [name, info] of Object.entries(spec.meta?.refs || {})) {
|
|
415
|
-
if (info.
|
|
471
|
+
if (info.internal) continue
|
|
416
472
|
if (info.kind === 'handle') continue
|
|
417
473
|
if (info.kind === ACTION) {
|
|
418
|
-
|
|
419
|
-
//
|
|
420
|
-
|
|
421
|
-
name,
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
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
|
|
481
|
+
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)
|
|
492
|
+
})
|
|
427
493
|
continue
|
|
428
494
|
}
|
|
429
495
|
const col = `@${ns}/${name}`
|
|
430
496
|
const kind = info.kind === SINGLE ? SINGLE : COLLECTION
|
|
431
|
-
|
|
497
|
+
const set =
|
|
498
|
+
kind === SINGLE ? upsert(name, col, kind, false, 'set') : update(name, col, info.own, 'set')
|
|
499
|
+
add(`set-${name}`, set)
|
|
432
500
|
if (info.kind === SINGLE) {
|
|
433
501
|
// wipe the keyless single row (the dummy id in the op is ignored)
|
|
434
|
-
add(`del-${name}`, async (op, ctx) =>
|
|
502
|
+
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, {}))
|
|
506
|
+
})
|
|
435
507
|
continue
|
|
436
508
|
}
|
|
437
|
-
add(`add-${name}`, upsert(name, col, COLLECTION, info.own))
|
|
438
|
-
add(`del-${name}`, remove(col, info.own))
|
|
509
|
+
add(`add-${name}`, upsert(name, col, COLLECTION, info.own, 'put'))
|
|
510
|
+
add(`del-${name}`, remove(name, col, info.own, 'del'))
|
|
439
511
|
}
|
|
440
512
|
|
|
441
513
|
return {
|
|
442
|
-
|
|
514
|
+
dispatch: (value, ctx) => router.dispatch(value, ctx),
|
|
443
515
|
async apply(nodes, view, host) {
|
|
444
516
|
const dbKey = key()
|
|
445
|
-
//
|
|
446
|
-
// whole batch — a batch is one writer's contiguous run (autobee keys it on
|
|
447
|
-
// batch[0].key), so an abort only ever drops the offending writer's ops.
|
|
517
|
+
// a batch is one writer's contiguous run, so a refusal discards only that writer's ops
|
|
448
518
|
const tx = view.transaction()
|
|
449
|
-
//
|
|
450
|
-
// survive a discarded transaction and leave a writer with no device row,
|
|
451
|
-
// which the WRITE gate reads as "not yet enrolled". So host calls are
|
|
452
|
-
// recorded and replayed only once the batch is known to commit.
|
|
519
|
+
// host calls survive a discarded transaction, so they replay once the batch commits
|
|
453
520
|
const calls = []
|
|
454
521
|
const deferred = Object.create(host)
|
|
455
522
|
deferred.addWriter = (...args) => void calls.push(['addWriter', args])
|
|
@@ -457,13 +524,16 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
|
|
|
457
524
|
let refusal = null
|
|
458
525
|
for (const node of nodes) {
|
|
459
526
|
try {
|
|
460
|
-
|
|
527
|
+
const seed = crypto.hash([node.key, node.value])
|
|
528
|
+
await router.dispatch(node.value, {
|
|
529
|
+
view: tx,
|
|
530
|
+
host: deferred,
|
|
531
|
+
key: node.key,
|
|
532
|
+
dbKey,
|
|
533
|
+
seed
|
|
534
|
+
})
|
|
461
535
|
} catch (err) {
|
|
462
|
-
//
|
|
463
|
-
// the same view, so discarding the batch keeps them convergent — and
|
|
464
|
-
// the batch is one writer's own run. Anything else (undecodable bytes,
|
|
465
|
-
// a route this version lacks) skips a single node instead: an older
|
|
466
|
-
// peer must not drop a batch its newer neighbour applies.
|
|
536
|
+
// anything but a refusal skips one node, so an older peer never drops a batch its newer neighbour applies
|
|
467
537
|
if (!isRefusal(err)) {
|
|
468
538
|
onerror(err)
|
|
469
539
|
continue
|
|
@@ -477,8 +547,7 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
|
|
|
477
547
|
onerror(refusal)
|
|
478
548
|
} else {
|
|
479
549
|
await tx.flush()
|
|
480
|
-
//
|
|
481
|
-
// after, and addWriter reads it (rc.31 derives coord/carrier from it)
|
|
550
|
+
// before apply() returns: autobee clears host.applying right after, and addWriter reads it
|
|
482
551
|
for (const [fn, args] of calls) await host[fn](...args)
|
|
483
552
|
}
|
|
484
553
|
await view.flush()
|