@cero-base/core 2.11.0 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +8 -8
- package/src/blobs/codec.js +25 -0
- package/src/blobs/index.js +5 -2
- package/src/blobs/server.js +2 -2
- package/src/database/dispatch.js +805 -208
- package/src/database/encryption.js +25 -21
- package/src/database/index.js +747 -124
- package/src/database/rotation.js +333 -38
- package/src/lib/constants.js +10 -0
- package/src/lib/errors.js +8 -0
- package/src/lib/schema.js +12 -2
- package/src/lib/spec/index.js +10 -5
- package/src/lib/spec/schema.json +13 -1
- package/src/lib/utils.js +24 -3
- package/src/mailbox/inbox.js +368 -41
- package/src/mailbox/index.js +75 -20
- package/src/mailbox/post.js +13 -8
- package/src/network/index.js +12 -5
- package/src/pairing/index.js +347 -57
- package/src/pairing/invite.js +36 -12
- package/src/pairing/response.js +78 -0
- package/src/push/index.js +20 -2
- package/types/blobs/codec.d.ts +13 -0
- package/types/blobs/index.d.ts +2 -0
- package/types/database/dispatch.d.ts +52 -7
- package/types/database/encryption.d.ts +13 -5
- package/types/database/index.d.ts +199 -19
- package/types/database/rotation.d.ts +85 -2
- package/types/lib/constants.d.ts +4 -0
- package/types/lib/errors.d.ts +6 -0
- package/types/lib/schema.d.ts +11 -0
- package/types/lib/utils.d.ts +2 -0
- package/types/mailbox/inbox.d.ts +78 -10
- package/types/mailbox/index.d.ts +42 -16
- package/types/mailbox/post.d.ts +7 -5
- package/types/pairing/index.d.ts +53 -8
- package/types/pairing/invite.d.ts +27 -8
- package/types/pairing/response.d.ts +50 -0
- package/types/push/index.d.ts +12 -2
package/src/database/dispatch.js
CHANGED
|
@@ -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,34 +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
|
+
|
|
118
|
+
// a member who left, apart from one removed and from a revoked device, in the removals: ids never hold ':'
|
|
119
|
+
export const leftId = (memberId) => `left:${memberId}`
|
|
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
|
+
|
|
46
144
|
/**
|
|
47
145
|
* Build the hyperdispatch router for a spec: wires membership, builtin, and
|
|
48
146
|
* spec-defined collection/action ops, returning the router plus an apply loop.
|
|
49
147
|
*
|
|
50
148
|
* @param {object} opts
|
|
51
|
-
* @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.
|
|
52
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.
|
|
53
155
|
* @param {(err: Error) => void} opts.onerror Called when a malformed node is skipped.
|
|
54
156
|
* @param {() => Uint8Array | null} opts.key The database key, null until the bee booted.
|
|
55
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).
|
|
56
|
-
* @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.
|
|
57
160
|
* @param {(phase: 'before' | 'after', op: string) => Function[]} opts.hooks Registered hooks for an op, run inside its transaction.
|
|
58
|
-
* @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.
|
|
59
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`.
|
|
60
|
-
* @returns {{ dispatch: (value: Buffer, ctx: object) => Promise<void>, apply: (nodes: Array<{ value: Buffer, key: Buffer }>, view: object, host: object) => Promise<
|
|
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.
|
|
61
164
|
*/
|
|
62
|
-
export function makeDispatcher({
|
|
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
|
+
}) {
|
|
63
181
|
const router = new spec.dispatch.Router()
|
|
64
182
|
|
|
65
183
|
const col = (name) => `@${ns}/${name}`
|
|
@@ -67,12 +185,10 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
67
185
|
const removals = `@${ns}/${REMOVALS}`
|
|
68
186
|
const refusals = `@${ns}/${REFUSALS}`
|
|
69
187
|
const spent = `@${ns}/${SPENT}`
|
|
188
|
+
const asks = `@${ns}/${ASKS}`
|
|
70
189
|
const getMember = (view, id) => view.get(`@${ns}/members`, { id })
|
|
71
190
|
const getDevice = (view, id) => view.get(`@${ns}/devices`, { id })
|
|
72
191
|
|
|
73
|
-
const getRole = async (view, identityKey) =>
|
|
74
|
-
identityKey ? ((await getMember(view, hid.encode(identityKey)))?.role ?? null) : null
|
|
75
|
-
|
|
76
192
|
const getSignerRole = async (view, writerKey) => {
|
|
77
193
|
if (!writerKey) return null
|
|
78
194
|
const d = await getDevice(view, hid.encode(writerKey))
|
|
@@ -104,13 +220,42 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
104
220
|
return others.length > 0 && !others.some((m) => m.role === OWNER)
|
|
105
221
|
}
|
|
106
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
|
+
|
|
107
235
|
async function bump(view, name) {
|
|
108
236
|
const value = ((await view.get(countersCol, { name }))?.value ?? 0) + 1
|
|
109
237
|
await view.insert(countersCol, { name, value })
|
|
110
238
|
return value
|
|
111
239
|
}
|
|
112
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
|
+
|
|
113
257
|
async function insert(view, name, op) {
|
|
258
|
+
checkFiles(name, op)
|
|
114
259
|
if (name !== COUNTERS) {
|
|
115
260
|
const existing = op.id != null ? await view.get(col(name), op) : null
|
|
116
261
|
// an overwrite keeps when the row was first written, whatever the op carries
|
|
@@ -132,32 +277,125 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
132
277
|
const single = (name) => spec.meta?.refs?.[name]?.kind === SINGLE
|
|
133
278
|
// a name with no route, a counter or an epoch among them, fails to encode
|
|
134
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
|
+
}
|
|
135
375
|
|
|
136
376
|
// the operators developers know, bound to this op. A write is dispatched as the op's writer
|
|
137
377
|
// would append it, so the same rank and `own` rules judge it
|
|
138
|
-
function operators(ctx
|
|
139
|
-
|
|
140
|
-
// every peer must mint the same id: hash the applying op and a per-op counter
|
|
141
|
-
const mint = () => z32.encode(crypto.hash([ctx.seed, c.encode(c.uint, n++)]).subarray(0, 16))
|
|
142
|
-
const current = (name, id) =>
|
|
143
|
-
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)
|
|
144
380
|
// held to the fields as a direct write is, before the encoder drops or chokes on one
|
|
145
381
|
const held = (name, row, stored) => {
|
|
146
382
|
checkFields(name, spec.meta?.refs?.[name], row)
|
|
147
383
|
checkRequired(name, spec.meta?.refs?.[name], stored)
|
|
148
384
|
return stored
|
|
149
385
|
}
|
|
150
|
-
|
|
151
|
-
|
|
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)
|
|
152
389
|
const value = spec.dispatch.encode(`@${ns}/${verb}-${verbOf(name)}`, row)
|
|
153
|
-
return router.dispatch(value, { ...ctx, nested: true })
|
|
390
|
+
return router.dispatch(await decode(value, ctx.stamp, ctx.view), { ...ctx, nested: true })
|
|
154
391
|
}
|
|
155
392
|
return {
|
|
156
393
|
get: (ref, query) => read(ctx.view, refName(ref), query),
|
|
157
|
-
put: (ref, row) => {
|
|
394
|
+
put: async (ref, row) => {
|
|
158
395
|
const name = refName(ref)
|
|
159
|
-
if (single(name)) return write(name, 'set', held(name, row, stamp(row, null, ts)))
|
|
160
|
-
const
|
|
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)
|
|
161
399
|
return write(name, 'add', held(name, row, stored))
|
|
162
400
|
},
|
|
163
401
|
// an upsert, as the set operator appends it
|
|
@@ -166,7 +404,7 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
166
404
|
if (!single(name) && !row.id) throw CeroError.INVALID(`set('${name}') needs an id`)
|
|
167
405
|
const verb = single(name) || BESPOKE.has(verbOf(name)) ? 'set' : 'add'
|
|
168
406
|
const was = await current(name, row.id)
|
|
169
|
-
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)))
|
|
170
408
|
},
|
|
171
409
|
del: (ref, id) => {
|
|
172
410
|
const name = refName(ref)
|
|
@@ -183,16 +421,24 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
183
421
|
}
|
|
184
422
|
|
|
185
423
|
// hooks run inside the op's transaction on every peer, so their verdict is part of the op.
|
|
186
|
-
// Resolves to the row that landed, which a before hook may have changed
|
|
187
|
-
|
|
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) {
|
|
188
429
|
if (!fns) {
|
|
189
|
-
|
|
190
|
-
|
|
430
|
+
if (rule && !meta.ranked) throw CeroError.REFUSED(rule)
|
|
431
|
+
await write(meta.row)
|
|
432
|
+
return meta.row
|
|
191
433
|
}
|
|
192
|
-
|
|
193
|
-
const
|
|
194
|
-
const hctx = {
|
|
195
|
-
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)
|
|
196
442
|
await write(hctx.row)
|
|
197
443
|
// once every row of the op landed: a join's after hooks write as a member
|
|
198
444
|
ctx.later.push(async () => {
|
|
@@ -210,11 +456,15 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
210
456
|
return hooked(fns, meta, ctx, (r) => insert(ctx.view, name, r))
|
|
211
457
|
}
|
|
212
458
|
|
|
213
|
-
// a seat taken again, as a linked device's own claim does, keeps the chain its link wrote
|
|
214
|
-
|
|
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) {
|
|
215
462
|
const id = hid.encode(writer)
|
|
216
463
|
proof ??= (await getDevice(ctx.view, id))?.proof ?? null
|
|
217
|
-
|
|
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)
|
|
218
468
|
}
|
|
219
469
|
|
|
220
470
|
// deleting a row that is not there changes nothing, and fires nothing
|
|
@@ -225,53 +475,10 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
225
475
|
await hooked(existing ? fns : null, meta, ctx, () => ctx.view.delete(col(name), { id }))
|
|
226
476
|
}
|
|
227
477
|
|
|
228
|
-
//
|
|
229
|
-
//
|
|
230
|
-
// which every rule answers for "no objection"), and refuse what rank allows, by answering false.
|
|
231
|
-
// Decided before anything moves, so a refusal leaves the member as she was. Resolves to what
|
|
232
|
-
// `landed` needs to fire the after hooks once the change lands
|
|
233
|
-
async function decide(ctx, op, { row = null, existing, ranked }, refusal) {
|
|
234
|
-
const fns = pick(op, ctx)
|
|
235
|
-
const ts = row?.updatedAt || existing?.updatedAt || 0
|
|
236
|
-
const hctx = {
|
|
237
|
-
op,
|
|
238
|
-
name: 'members',
|
|
239
|
-
row,
|
|
240
|
-
existing,
|
|
241
|
-
id: existing.id,
|
|
242
|
-
ranked,
|
|
243
|
-
...(await author(ctx)),
|
|
244
|
-
...operators(ctx, ts)
|
|
245
|
-
}
|
|
246
|
-
// a grant widens rank among the room's writers only: never for a reader, nor for someone who
|
|
247
|
-
// is no member at all
|
|
248
|
-
const canGrant = Boolean(hctx.memberId) && can(hctx.role, WRITE)
|
|
249
|
-
let granted = false
|
|
250
|
-
for (const fn of fns?.before ?? []) {
|
|
251
|
-
let verdict
|
|
252
|
-
try {
|
|
253
|
-
verdict = await fn(hctx)
|
|
254
|
-
} catch (err) {
|
|
255
|
-
throw CeroError.REFUSED('hook', err.message)
|
|
256
|
-
}
|
|
257
|
-
if (verdict === false) throw CeroError.REFUSED('hook')
|
|
258
|
-
if (verdict === 'grant' && canGrant) granted = true
|
|
259
|
-
}
|
|
260
|
-
if (!ranked && !granted) throw refusal()
|
|
261
|
-
return { fns, hctx }
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
// a change decide judged: its before hooks already ran, its after hooks fire once it landed
|
|
265
|
-
function landed(ctx, { fns, hctx }) {
|
|
266
|
-
if (!fns) return
|
|
267
|
-
ctx.later.push(async () => {
|
|
268
|
-
Object.assign(hctx, await author(ctx))
|
|
269
|
-
await fire(fns.after, hctx, false)
|
|
270
|
-
})
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
// 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
|
|
274
480
|
async function fire(fns, hctx, vote) {
|
|
481
|
+
let granted = false
|
|
275
482
|
for (const fn of fns) {
|
|
276
483
|
let verdict
|
|
277
484
|
try {
|
|
@@ -280,7 +487,9 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
280
487
|
throw CeroError.REFUSED('hook', err.message)
|
|
281
488
|
}
|
|
282
489
|
if (vote && verdict === false) throw CeroError.REFUSED('hook')
|
|
490
|
+
if (verdict === 'grant') granted = true
|
|
283
491
|
}
|
|
492
|
+
return granted
|
|
284
493
|
}
|
|
285
494
|
|
|
286
495
|
// a demoted member keeps its writer seat, so rows are gated by role; a writer with no
|
|
@@ -303,7 +512,10 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
303
512
|
const fns = pick('set', ctx)
|
|
304
513
|
const existing = fns ? await ctx.view.findOne(col(name), {}) : null
|
|
305
514
|
const meta = { op: 'set', name, row: op, existing }
|
|
306
|
-
return hooked(fns, meta, ctx, (row) =>
|
|
515
|
+
return hooked(fns, meta, ctx, (row) => {
|
|
516
|
+
checkFiles(name, row)
|
|
517
|
+
return ctx.view.insert(col(name), row)
|
|
518
|
+
})
|
|
307
519
|
}
|
|
308
520
|
// add on an existing id is an overwrite, same ownership rule as set
|
|
309
521
|
if (own) await requireOwn(ctx, await ctx.view.get(col(name), { id: op.id }))
|
|
@@ -326,14 +538,14 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
326
538
|
const meta = { op: 'del', name, id: op.id, existing }
|
|
327
539
|
return hooked(fns, meta, ctx, () => ctx.view.delete(col(name), op))
|
|
328
540
|
}
|
|
329
|
-
// only REFUSED aborts a batch: every peer derives it.
|
|
541
|
+
// only REFUSED aborts a batch: every peer derives it. A body that does not decode skips one node
|
|
330
542
|
const isRefusal = (err) => err?.isCeroError === true && err.code === 'REFUSED'
|
|
331
543
|
|
|
332
|
-
// 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
|
|
333
545
|
const add = (verb, fn) =>
|
|
334
546
|
router.add(`@${ns}/${verb}`, async (op, ctx) => {
|
|
335
547
|
const later = []
|
|
336
|
-
await fn(op, { ...ctx, later })
|
|
548
|
+
await fn(op, { ...ctx, later, mint: ctx.mint ?? minter(ctx.seed) })
|
|
337
549
|
for (const run of later) await run()
|
|
338
550
|
})
|
|
339
551
|
|
|
@@ -344,54 +556,198 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
344
556
|
if (!b4a.equals(op.writer, ctx.key)) return
|
|
345
557
|
const signed = Identity.verify(op.proof, admission(ctx.dbKey, op.writer, ctx.key), op.master)
|
|
346
558
|
if (!signed) return
|
|
347
|
-
if (await
|
|
559
|
+
if (!(await stands(ctx.view, Identity.chain(op.proof)))) throw CeroError.REFUSED('removed')
|
|
348
560
|
const { genesis } = ctx.host
|
|
349
|
-
const
|
|
350
|
-
|
|
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')
|
|
351
570
|
// only a device of the signer's own identity: another member's device seats itself through
|
|
352
571
|
// its join, or any key the signer holds would act as them.
|
|
353
572
|
// Always an indexer: autobee gc's caught-up non-indexer sessions and they miss later appends
|
|
354
|
-
const memberId = hid.encode(op.master)
|
|
355
573
|
if (op.memberId && op.memberId !== memberId) throw CeroError.REFUSED('member')
|
|
356
574
|
if (await boundElsewhere(ctx.view, op.writer, memberId)) throw CeroError.REFUSED('member')
|
|
357
|
-
|
|
358
|
-
|
|
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)
|
|
359
586
|
})
|
|
360
587
|
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
const
|
|
364
|
-
if (
|
|
365
|
-
if (!(await canRemoveMember(ctx.view, ctx.key,
|
|
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))) {
|
|
366
593
|
throw CeroError.REFUSED('remove')
|
|
367
594
|
}
|
|
368
595
|
}
|
|
369
|
-
await ctx.
|
|
370
|
-
await
|
|
371
|
-
await
|
|
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))
|
|
372
646
|
})
|
|
373
647
|
|
|
374
648
|
// a removed device's key, and any device it attests after, stays out: its chain is static, so
|
|
375
|
-
// the removal is kept here, beside the members'
|
|
376
|
-
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) {
|
|
377
651
|
if (!device?.key) return
|
|
378
652
|
const minted = (await ctx.view.get(countersCol, { name: 'invites' }))?.value ?? 0
|
|
379
|
-
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 })
|
|
380
654
|
}
|
|
381
|
-
// a
|
|
382
|
-
|
|
383
|
-
|
|
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
|
|
669
|
+
}
|
|
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))
|
|
384
677
|
}
|
|
385
678
|
|
|
386
|
-
// the
|
|
387
|
-
//
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
return
|
|
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
|
|
393
689
|
}
|
|
394
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
|
+
|
|
395
751
|
// the genesis batch names the creator; everyone after comes in through a signed join
|
|
396
752
|
add('add-member', async (op, ctx) => {
|
|
397
753
|
if (!isKey(op.key)) return
|
|
@@ -409,14 +765,28 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
409
765
|
// whose row it is decides what may change: your own is writable, another member's only
|
|
410
766
|
// for an authorised role change. Key and provenance never come off the wire
|
|
411
767
|
const isSelf = op.id === (await getSignerMember(ctx.view, ctx.key))
|
|
412
|
-
const
|
|
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)
|
|
413
783
|
next.key = existing.key
|
|
414
784
|
next.role = existing.role
|
|
415
785
|
next.createdAt = existing.createdAt
|
|
416
786
|
next.updatedAt = op.updatedAt || existing.updatedAt
|
|
417
787
|
|
|
418
788
|
let row
|
|
419
|
-
if (
|
|
789
|
+
if (ranks) {
|
|
420
790
|
// a rank cero has no name for is no rank, granted or not
|
|
421
791
|
if (!isRank(op.role)) throw CeroError.INVALID(`'${op.role}' is not a role`)
|
|
422
792
|
// the last owner keeps her rank, whatever a rule grants, as she is never removed
|
|
@@ -428,12 +798,9 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
428
798
|
const r = await getSignerRole(ctx.view, ctx.key)
|
|
429
799
|
next.role = op.role
|
|
430
800
|
const ranked = can(r, ASSIGN) && grants(r, op.role) && outranks(r, existing.role)
|
|
431
|
-
const
|
|
432
|
-
|
|
433
|
-
)
|
|
434
|
-
row = decided.hctx.row
|
|
435
|
-
await insert(ctx.view, 'members', row)
|
|
436
|
-
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')
|
|
437
804
|
} else {
|
|
438
805
|
row = await save(ctx, 'set', 'members', next)
|
|
439
806
|
}
|
|
@@ -450,11 +817,35 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
450
817
|
|
|
451
818
|
add('del-member', async (op, ctx) => {
|
|
452
819
|
const existing = await getMember(ctx.view, op.id)
|
|
453
|
-
if (!existing)
|
|
454
|
-
|
|
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
|
+
}
|
|
455
826
|
// leaving is hers: only someone else taking her out turns her older codes away
|
|
456
|
-
const
|
|
457
|
-
|
|
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 {
|
|
458
849
|
// the last owner stays, whatever a rule grants: without her nobody outranks the rest
|
|
459
850
|
if (existing.role === OWNER && (await orphans(ctx.view, op.id))) {
|
|
460
851
|
throw CeroError.INVALID(
|
|
@@ -463,29 +854,18 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
463
854
|
}
|
|
464
855
|
const r = await getSignerRole(ctx.view, ctx.key)
|
|
465
856
|
const ranked = can(r, REMOVE) && outranks(r, existing.role)
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
for (const device of await ctx.view.find(`@${ns}/devices`, {}).toArray()) {
|
|
473
|
-
if (device.memberId !== op.id) continue
|
|
474
|
-
await ctx.host.removeWriter(hid.decode(device.id))
|
|
475
|
-
await drop(ctx, 'devices', device.id)
|
|
476
|
-
await drop(ctx, 'requests', device.id)
|
|
477
|
-
}
|
|
478
|
-
if (decided) {
|
|
479
|
-
await ctx.view.delete(col('members'), { id: op.id })
|
|
480
|
-
landed(ctx, decided)
|
|
481
|
-
} else {
|
|
482
|
-
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')
|
|
483
863
|
}
|
|
484
864
|
// an invite they could hold, or saw, does not bring them back on its own: after a removal it is turned away, after
|
|
485
|
-
// leaving it waits for a member to accept her again, so leaving first never dodges a removal
|
|
486
|
-
// 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
|
|
487
866
|
const minted = (await ctx.view.get(countersCol, { name: 'invites' }))?.value ?? 0
|
|
488
|
-
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)
|
|
489
869
|
})
|
|
490
870
|
|
|
491
871
|
add('rotate-key', async (op, ctx) => {
|
|
@@ -494,11 +874,19 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
494
874
|
if (op.commit?.byteLength !== 32) return
|
|
495
875
|
// the stamp is picked before any block is written, so epochs reorder freely; uniqueness is enforced here
|
|
496
876
|
if (!Number.isInteger(op.stamp) || op.stamp <= 0 || op.stamp > 0xffffffff) return
|
|
497
|
-
|
|
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)))) {
|
|
498
883
|
throw CeroError.REFUSED('rotate', 'rotate requires the remove permission')
|
|
499
884
|
}
|
|
500
885
|
const rows = await ctx.view.find(`@${ns}/${EPOCHS}`, {}).toArray()
|
|
501
|
-
|
|
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 })
|
|
502
890
|
// sequence numbers order epochs; concurrent rotations get consecutive sequences, both readable
|
|
503
891
|
const epoch = await bump(ctx.view, EPOCHS)
|
|
504
892
|
const row = {
|
|
@@ -506,31 +894,41 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
506
894
|
stamp: op.stamp,
|
|
507
895
|
wrapped: op.wrapped,
|
|
508
896
|
createdAt: op.createdAt || 0,
|
|
509
|
-
commit: op.commit
|
|
897
|
+
commit: op.commit,
|
|
898
|
+
aside
|
|
510
899
|
}
|
|
511
900
|
await ctx.view.insert(`@${ns}/${EPOCHS}`, row)
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
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
|
|
520
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 })
|
|
521
927
|
})
|
|
522
928
|
|
|
523
929
|
add('del-device', async (op, ctx) => {
|
|
524
|
-
const
|
|
525
|
-
if (
|
|
526
|
-
if (existing.memberId !== (await getSignerMember(ctx.view, ctx.key))) {
|
|
527
|
-
if (!(await canRemoveMember(ctx.view, ctx.key, existing.memberId))) {
|
|
528
|
-
throw CeroError.REFUSED('remove')
|
|
529
|
-
}
|
|
530
|
-
}
|
|
531
|
-
await ctx.host.removeWriter(hid.decode(existing.id))
|
|
532
|
-
await revoke(ctx, existing)
|
|
533
|
-
await drop(ctx, 'devices', op.id)
|
|
930
|
+
const device = await getDevice(ctx.view, op.id)
|
|
931
|
+
if (device) await unseat(ctx, op.id, device)
|
|
534
932
|
})
|
|
535
933
|
|
|
536
934
|
// a device row is the writer→role mapping, so memberId never comes off the wire; a core no
|
|
@@ -544,26 +942,53 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
544
942
|
const selfOnly = (op, ctx) => {
|
|
545
943
|
if (!ctx.key || op.id !== hid.encode(ctx.key)) throw CeroError.REFUSED('device')
|
|
546
944
|
}
|
|
547
|
-
// the device key
|
|
945
|
+
// the device key and the chain stay what the admission proved, never what the row says
|
|
548
946
|
add('add-device', async (op, ctx) => {
|
|
549
947
|
selfOnly(op, ctx)
|
|
550
948
|
const existing = await getDevice(ctx.view, op.id)
|
|
551
|
-
|
|
949
|
+
const kept = { key: existing?.key, chain: existing?.chain }
|
|
950
|
+
await save(ctx, 'put', 'devices', { ...op, memberId: await bind(ctx), ...kept })
|
|
552
951
|
})
|
|
952
|
+
// another device of its member renames it while it stands, and changes nothing else of the row
|
|
553
953
|
add('set-device', async (op, ctx) => {
|
|
554
|
-
selfOnly(op, ctx)
|
|
555
|
-
const memberId = await bind(ctx)
|
|
556
954
|
const existing = await getDevice(ctx.view, op.id)
|
|
557
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)
|
|
558
967
|
await save(ctx, 'set', 'devices', {
|
|
559
968
|
...op,
|
|
560
969
|
memberId,
|
|
561
970
|
key: existing?.key,
|
|
971
|
+
chain: existing?.chain,
|
|
562
972
|
createdAt: existing?.createdAt || op.createdAt || ts,
|
|
563
973
|
updatedAt: ts
|
|
564
974
|
})
|
|
565
975
|
})
|
|
566
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
|
+
|
|
567
992
|
// any WRITE member mints an invite, its rank capped at admission; an existing row is never
|
|
568
993
|
// overwritten, and altering or revoking one needs REMOVE
|
|
569
994
|
const invites = `@${ns}/invites`
|
|
@@ -596,31 +1021,63 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
596
1021
|
if (!can(r, REMOVE)) throw CeroError.REFUSED('invite')
|
|
597
1022
|
await ctx.view.delete(spent, { id: op.id })
|
|
598
1023
|
})
|
|
599
|
-
// its joins still waiting for a member are turned away with it
|
|
600
|
-
//
|
|
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
|
|
601
1027
|
async function spend(ctx, invite, reason) {
|
|
602
1028
|
const expires = invite.expires || 0
|
|
603
1029
|
await drop(ctx, 'invites', invite.id)
|
|
604
|
-
|
|
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
|
+
}
|
|
605
1038
|
for (const request of await ctx.view.find(requests, {}).toArray()) {
|
|
606
|
-
if (request.invite !== invite.id || request
|
|
607
|
-
await
|
|
1039
|
+
if (request.invite !== invite.id || (await kept(request))) continue
|
|
1040
|
+
await forget(ctx, request)
|
|
608
1041
|
await refuse(ctx, request, reason)
|
|
609
1042
|
}
|
|
610
1043
|
}
|
|
611
1044
|
|
|
612
|
-
// a join turned away is answered at its reply address. A writer with a request
|
|
613
|
-
// that: one of the two per writer, or a denial could race its keys
|
|
614
|
-
|
|
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
|
+
) {
|
|
615
1055
|
if (await ctx.view.get(requests, { id })) return
|
|
616
|
-
await ctx.view.
|
|
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)
|
|
617
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))
|
|
618
1072
|
|
|
619
1073
|
// the member, when new, and its device, seated when the member writes; its request stays until
|
|
620
1074
|
// a member delivered the keys. The invite is spent unless it is reusable
|
|
621
|
-
async function admit(ctx, { invite, identity, key, writer, reply, role, ts }) {
|
|
1075
|
+
async function admit(ctx, { invite, identity, key, writer, reply, role, ts, proof }) {
|
|
622
1076
|
const memberId = hid.encode(identity)
|
|
623
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
|
+
}
|
|
624
1081
|
const member =
|
|
625
1082
|
(await getMember(ctx.view, memberId)) ??
|
|
626
1083
|
(await save(ctx, 'put', 'members', {
|
|
@@ -631,7 +1088,7 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
631
1088
|
updatedAt: ts
|
|
632
1089
|
}))
|
|
633
1090
|
if (can(member.role, WRITE)) await ctx.host.addWriter(writer, { isIndexer: true })
|
|
634
|
-
await seat(ctx, writer, memberId, ts, key)
|
|
1091
|
+
await seat(ctx, writer, memberId, ts, key, null, proof)
|
|
635
1092
|
await save(ctx, 'put', 'requests', {
|
|
636
1093
|
...request(invite, identity, key, writer, reply, ts),
|
|
637
1094
|
role,
|
|
@@ -645,8 +1102,13 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
645
1102
|
async function admitDevice(ctx, { invite, memberId, key, proof, writer, reply, ts }) {
|
|
646
1103
|
if (await boundElsewhere(ctx.view, writer, memberId)) throw CeroError.REFUSED('member')
|
|
647
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
|
+
}
|
|
648
1110
|
if (can(member.role, WRITE)) await ctx.host.addWriter(writer, { isIndexer: true })
|
|
649
|
-
await seat(ctx, writer, memberId, ts, key, proof)
|
|
1111
|
+
await seat(ctx, writer, memberId, ts, key, proof, proof)
|
|
650
1112
|
await save(ctx, 'put', 'requests', {
|
|
651
1113
|
...request(invite, hid.decode(memberId), key, writer, reply, ts),
|
|
652
1114
|
role: member.role,
|
|
@@ -655,6 +1117,31 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
655
1117
|
if (!invite.reuse) await spend(ctx, invite, 'spent')
|
|
656
1118
|
}
|
|
657
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
|
+
|
|
658
1145
|
function request(invite, identity, key, writer, reply, ts) {
|
|
659
1146
|
const expires = invite.expires || 0
|
|
660
1147
|
const id = hid.encode(writer)
|
|
@@ -662,22 +1149,30 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
662
1149
|
return { id, identity, key, invite: invite.id, role, reply, expires, createdAt: ts }
|
|
663
1150
|
}
|
|
664
1151
|
|
|
665
|
-
// null when it does not open: anyone may append a join
|
|
666
|
-
|
|
667
|
-
|
|
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()
|
|
668
1157
|
if (!pair || !box?.byteLength) return null
|
|
669
1158
|
try {
|
|
670
1159
|
const plain = crypto.decrypt(box, pair)
|
|
671
|
-
|
|
1160
|
+
const join = plain && c.decode(Join, plain)
|
|
1161
|
+
if (join && invite && !b4a.equals(join.invite, invite)) return null
|
|
1162
|
+
return join
|
|
672
1163
|
} catch {
|
|
673
1164
|
return null
|
|
674
1165
|
}
|
|
675
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
|
+
}
|
|
676
1171
|
|
|
677
1172
|
// the joiner's own core asks in: the invite proves it may, its device signs where the keys go
|
|
678
1173
|
// and the proof's chain says whose device it is
|
|
679
1174
|
add('join', async (op, ctx) => {
|
|
680
|
-
const join = open(op
|
|
1175
|
+
const join = await open(ctx.view, op)
|
|
681
1176
|
if (!join || !ctx.key) return
|
|
682
1177
|
if (!Invite.proven(join.invite, ctx.key, join.signature)) return
|
|
683
1178
|
const signed = Identity.verify(join.proof, joining(ctx.dbKey, join.invite, ctx.key, join.reply))
|
|
@@ -685,25 +1180,35 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
685
1180
|
join.identity = signed.identity
|
|
686
1181
|
const id = hid.encode(ctx.key)
|
|
687
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
|
|
688
1186
|
if (!invite) {
|
|
689
1187
|
// an invite the database never held could be anyone's: nobody answers it
|
|
690
|
-
const record = await ctx.view.get(spent, { id: b4a.toHex(join.invite) })
|
|
691
1188
|
if (!record) return
|
|
692
|
-
|
|
1189
|
+
const turned = { id, reply: join.reply, expires: record.expires, invite: record.id }
|
|
1190
|
+
return refuse(ctx, turned, record.reason, await bounded(ctx.view))
|
|
693
1191
|
}
|
|
694
1192
|
const ts = join.ts || 0
|
|
695
1193
|
const memberId = hid.encode(join.identity)
|
|
696
1194
|
const known = await getMember(ctx.view, memberId)
|
|
697
1195
|
const removal = known ? null : await ctx.view.get(removals, { id: memberId })
|
|
698
1196
|
const out =
|
|
699
|
-
(removal && (invite.index ?? 0) <= removal.index) ||
|
|
700
|
-
|
|
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
|
+
}
|
|
701
1204
|
await ctx.view.delete(refusals, { id })
|
|
702
1205
|
const gone = known ? null : await ctx.view.get(removals, { id: leftId(memberId) })
|
|
703
1206
|
const older = gone && (invite.index ?? 0) <= gone.index
|
|
704
1207
|
if ((invite.confirm || older) && !known) {
|
|
705
1208
|
const waiting = request(invite, join.identity, signed.device, ctx.key, join.reply, ts)
|
|
706
|
-
|
|
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 })
|
|
707
1212
|
}
|
|
708
1213
|
await admit(ctx, {
|
|
709
1214
|
invite,
|
|
@@ -712,7 +1217,8 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
712
1217
|
writer: ctx.key,
|
|
713
1218
|
reply: join.reply,
|
|
714
1219
|
role: invite.role,
|
|
715
|
-
ts
|
|
1220
|
+
ts,
|
|
1221
|
+
proof: join.proof
|
|
716
1222
|
})
|
|
717
1223
|
})
|
|
718
1224
|
// a waiting join, admitted at a role within the invite's and the accepter's; with a proof, as a
|
|
@@ -720,30 +1226,46 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
720
1226
|
add('accept', async (op, ctx) => {
|
|
721
1227
|
const waiting = await ctx.view.get(requests, { id: op.id })
|
|
722
1228
|
if (!waiting || waiting.admitted) return
|
|
723
|
-
const
|
|
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
|
|
724
1232
|
const r = await getSignerRole(ctx.view, ctx.key)
|
|
725
1233
|
const role = op.role || invite?.role
|
|
726
1234
|
if (!invite || !can(r, INVITE) || !grants(r, role) || !grants(invite.role, role)) {
|
|
727
1235
|
throw CeroError.REFUSED('invite')
|
|
728
1236
|
}
|
|
729
|
-
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
|
+
}
|
|
730
1242
|
const writer = hid.decode(op.id)
|
|
731
1243
|
if (op.proof) {
|
|
732
1244
|
const memberId = await getSignerMember(ctx.view, ctx.key)
|
|
733
1245
|
const linked = Identity.verify(op.proof, null, hid.decode(memberId))
|
|
734
1246
|
if (!linked || !b4a.equals(linked.device, key)) throw CeroError.REFUSED('device')
|
|
735
|
-
if (await
|
|
1247
|
+
if (!(await stands(ctx.view, Identity.chain(op.proof)))) throw CeroError.REFUSED('removed')
|
|
736
1248
|
return admitDevice(ctx, { invite, memberId, key, proof: op.proof, writer, reply, ts })
|
|
737
1249
|
}
|
|
738
|
-
await admit(ctx, { invite, identity, key, writer, reply, role, ts })
|
|
1250
|
+
await admit(ctx, { invite, identity, key, writer, reply, role, ts, proof })
|
|
739
1251
|
})
|
|
740
|
-
//
|
|
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
|
|
741
1254
|
add('deny', async (op, ctx) => {
|
|
742
|
-
const
|
|
743
|
-
if (!
|
|
744
|
-
|
|
745
|
-
await
|
|
746
|
-
|
|
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)
|
|
747
1269
|
})
|
|
748
1270
|
// only a join writes a request
|
|
749
1271
|
const joinsOnly = async () => {
|
|
@@ -751,11 +1273,25 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
751
1273
|
}
|
|
752
1274
|
add('add-request', joinsOnly)
|
|
753
1275
|
add('set-request', joinsOnly)
|
|
754
|
-
// 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
|
|
755
1279
|
add('del-request', async (op, ctx) => {
|
|
756
|
-
|
|
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')
|
|
757
1287
|
await drop(ctx, 'requests', op.id)
|
|
1288
|
+
if (open) await owe(ctx.view)
|
|
758
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
|
+
}
|
|
759
1295
|
// read by the joiner, or past its expiry with nobody waiting
|
|
760
1296
|
add('del-refusal', async (op, ctx) => {
|
|
761
1297
|
if (!can(await getSignerRole(ctx.view, ctx.key), INVITE)) throw CeroError.REFUSED('invite')
|
|
@@ -777,9 +1313,27 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
777
1313
|
add('set-file', update('files', true))
|
|
778
1314
|
add('del-file', remove('files', true))
|
|
779
1315
|
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
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
|
+
})
|
|
783
1337
|
|
|
784
1338
|
for (const [name, info] of Object.entries(spec.meta?.refs || {})) {
|
|
785
1339
|
if (info.internal) continue
|
|
@@ -813,9 +1367,16 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
813
1367
|
}
|
|
814
1368
|
|
|
815
1369
|
return {
|
|
816
|
-
|
|
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,
|
|
817
1377
|
async apply(nodes, view, host) {
|
|
818
1378
|
const dbKey = key()
|
|
1379
|
+
const before = await built(view)
|
|
819
1380
|
// a batch is one writer's contiguous run, so a refusal discards only that writer's ops
|
|
820
1381
|
const tx = view.transaction()
|
|
821
1382
|
// host calls survive a discarded transaction, so they replay once the batch commits
|
|
@@ -823,17 +1384,35 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
823
1384
|
const deferred = Object.create(host)
|
|
824
1385
|
deferred.addWriter = (...args) => void calls.push(['addWriter', args])
|
|
825
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 = []
|
|
826
1390
|
let refusal = null
|
|
1391
|
+
let changed = false
|
|
1392
|
+
const landed = []
|
|
827
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
|
+
}
|
|
828
1401
|
try {
|
|
829
|
-
const seed = crypto.hash([node.key, node.value])
|
|
830
|
-
|
|
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), {
|
|
831
1405
|
view: tx,
|
|
832
1406
|
host: deferred,
|
|
833
1407
|
key: node.key,
|
|
834
1408
|
dbKey,
|
|
835
|
-
seed
|
|
1409
|
+
seed,
|
|
1410
|
+
ts: node.timestamp,
|
|
1411
|
+
stamp,
|
|
1412
|
+
epochs,
|
|
1413
|
+
touched
|
|
836
1414
|
})
|
|
1415
|
+
landed.push(node)
|
|
837
1416
|
} catch (err) {
|
|
838
1417
|
// anything but a refusal skips one node, so an older peer never drops a batch its newer neighbour applies
|
|
839
1418
|
if (!isRefusal(err)) {
|
|
@@ -848,11 +1427,29 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
|
|
|
848
1427
|
await tx.close()
|
|
849
1428
|
onerror(refusal)
|
|
850
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
|
+
}
|
|
851
1439
|
await tx.flush()
|
|
1440
|
+
if (changed) for (const name of touched) touch(name)
|
|
852
1441
|
// before apply() returns: autobee clears host.applying right after, and addWriter reads it
|
|
853
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
|
+
}
|
|
854
1450
|
}
|
|
855
1451
|
await view.flush()
|
|
1452
|
+
return { landed: refusal ? [] : landed, changed }
|
|
856
1453
|
}
|
|
857
1454
|
}
|
|
858
1455
|
}
|