@cero-base/core 2.12.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 +803 -204
- package/src/database/encryption.js +25 -21
- package/src/database/index.js +720 -123
- 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 +343 -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 +51 -7
- package/types/database/encryption.d.ts +13 -5
- package/types/database/index.d.ts +190 -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/rotation.js
CHANGED
|
@@ -3,12 +3,22 @@ import crypto from 'hypercore-crypto'
|
|
|
3
3
|
import b4a from 'b4a'
|
|
4
4
|
import hid from 'hypercore-id-encoding'
|
|
5
5
|
|
|
6
|
-
import { REMOVE } from '../lib/constants.js'
|
|
6
|
+
import { REMOVE, COUNTERS, OWED } from '../lib/constants.js'
|
|
7
7
|
import { can } from '../lib/utils.js'
|
|
8
8
|
import { wraps, epochEntries, seal, opened } from './encryption.js'
|
|
9
|
+
import { chainOf, seatChain, keysOf } from './dispatch.js'
|
|
9
10
|
import { Identity } from '../identity/index.js'
|
|
11
|
+
import { keyPair } from '../mailbox/inbox.js'
|
|
10
12
|
import { CeroError } from '../lib/errors.js'
|
|
11
13
|
|
|
14
|
+
// the secrets one sender handed over for a stamp before its row landed, and its stamps waiting
|
|
15
|
+
const CANDIDATES = 4
|
|
16
|
+
const STAMPS = 16
|
|
17
|
+
// the blocks met under a key no row holds yet: any writer can append under any stamp
|
|
18
|
+
const MET = 64
|
|
19
|
+
// the rotations set aside that no block under them has needed yet
|
|
20
|
+
const ASIDE = 64
|
|
21
|
+
|
|
12
22
|
/**
|
|
13
23
|
* Epoch key rotation for a database: mint a secret, seal it to every device, announce it
|
|
14
24
|
* through the log, and on every peer learn the secrets addressed to it.
|
|
@@ -18,12 +28,20 @@ export class Rotation {
|
|
|
18
28
|
constructor(db) {
|
|
19
29
|
this.db = db
|
|
20
30
|
this.current = null
|
|
31
|
+
/** @type {Promise<void> | null} Pending while a removal and its rotation go in. */
|
|
32
|
+
this.carrying = null
|
|
21
33
|
/** @private */
|
|
22
34
|
this._queue = Promise.resolve()
|
|
23
35
|
/** @private */
|
|
24
36
|
this._timer = null
|
|
25
37
|
/** @private */
|
|
26
38
|
this._healedFor = null
|
|
39
|
+
/** @private */
|
|
40
|
+
this._kept = new Map() // sender → stamp → the secrets it handed over before the row landed
|
|
41
|
+
/** @private */
|
|
42
|
+
this._aside = new Map() // stamp → a row set aside, opened once a block under it is met
|
|
43
|
+
/** @private */
|
|
44
|
+
this._met = new Set() // stamps of blocks met under a key this device does not hold
|
|
27
45
|
}
|
|
28
46
|
|
|
29
47
|
close() {
|
|
@@ -38,7 +56,24 @@ export class Rotation {
|
|
|
38
56
|
* @returns {Promise<{ epoch: number }>}
|
|
39
57
|
*/
|
|
40
58
|
rotate() {
|
|
41
|
-
|
|
59
|
+
return this._queued(() => this._rotate(false))
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* A removal by a device that may remove carries its rotation: the removal, then the key sealed
|
|
64
|
+
* to the devices that stay and to those still promised a seat, with nothing else of this device
|
|
65
|
+
* in between. The key is a block of its own, so it lands even when a reorder refuses the removal.
|
|
66
|
+
*
|
|
67
|
+
* @param {Array<[string, unknown]>} ops A batch that takes a member or a device out.
|
|
68
|
+
* @returns {Promise<number | undefined>} What the removal's write resolves.
|
|
69
|
+
*/
|
|
70
|
+
carry(ops) {
|
|
71
|
+
return this._queued(() => this._carry(ops))
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** @private */
|
|
75
|
+
_queued(fn) {
|
|
76
|
+
const run = this._queue.catch(() => {}).then(fn)
|
|
42
77
|
this._queue = run
|
|
43
78
|
return run
|
|
44
79
|
}
|
|
@@ -50,8 +85,19 @@ export class Rotation {
|
|
|
50
85
|
*/
|
|
51
86
|
async learn(row) {
|
|
52
87
|
const { keyring } = this.db
|
|
53
|
-
const known =
|
|
54
|
-
|
|
88
|
+
const known = this.held(row)
|
|
89
|
+
if (row.aside && !known && !this._met.has(row.stamp)) {
|
|
90
|
+
this._aside.delete(row.stamp)
|
|
91
|
+
this._aside.set(row.stamp, row)
|
|
92
|
+
if (this._aside.size > ASIDE) this._aside.delete(this._aside.keys().next().value)
|
|
93
|
+
return
|
|
94
|
+
}
|
|
95
|
+
this._aside.delete(row.stamp)
|
|
96
|
+
// a counted rotation took its stamp from one set aside: that key reads nothing any more
|
|
97
|
+
const stale = !row.aside && !known && keyring.entropy(row.stamp)
|
|
98
|
+
if (stale) keyring.remove(row.stamp)
|
|
99
|
+
const entropy = known || this._unseal(row) || this._handed(row)
|
|
100
|
+
if (entropy) this._met.delete(row.stamp)
|
|
55
101
|
if (known) {
|
|
56
102
|
keyring.add(row.stamp, known, row.epoch) // re-applied, the sequence may be news
|
|
57
103
|
} else if (this.current && entropy && b4a.equals(entropy, this.current.entropy)) {
|
|
@@ -66,10 +112,89 @@ export class Rotation {
|
|
|
66
112
|
keyring.remove(row.stamp)
|
|
67
113
|
this.db._onerror(err)
|
|
68
114
|
}
|
|
115
|
+
} else if (stale) {
|
|
116
|
+
await this._save().catch((err) => this.db._onerror(err))
|
|
69
117
|
}
|
|
70
118
|
this.heal()
|
|
71
119
|
}
|
|
72
120
|
|
|
121
|
+
/**
|
|
122
|
+
* A block met under a key this device does not hold: a rotation set aside is opened now.
|
|
123
|
+
*
|
|
124
|
+
* @param {number} stamp
|
|
125
|
+
* @returns {Uint8Array | null}
|
|
126
|
+
*/
|
|
127
|
+
meet(stamp) {
|
|
128
|
+
const row = this._aside.get(stamp)
|
|
129
|
+
this._aside.delete(stamp)
|
|
130
|
+
const entropy = row && this._unseal(row)
|
|
131
|
+
if (entropy) {
|
|
132
|
+
this.db.keyring.add(row.stamp, entropy, row.epoch)
|
|
133
|
+
// kept like any key it holds: a restart still reads with it, and it is handed to a device that asks
|
|
134
|
+
this._save().then(
|
|
135
|
+
() => this.db.emit('epoch'),
|
|
136
|
+
(err) => this.db._onerror(err)
|
|
137
|
+
)
|
|
138
|
+
return entropy
|
|
139
|
+
}
|
|
140
|
+
this._met.delete(stamp)
|
|
141
|
+
this._met.add(stamp)
|
|
142
|
+
if (this._met.size > MET) this._met.delete(this._met.values().next().value)
|
|
143
|
+
// one set aside it was not sealed to: a device that holds it is asked
|
|
144
|
+
if (row) this.heal()
|
|
145
|
+
return null
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* A secret handed over before its announcement landed here: kept, and checked against the
|
|
150
|
+
* commitment when it does.
|
|
151
|
+
*
|
|
152
|
+
* @param {{ epoch: number, stamp: number, entropy: Uint8Array }} e
|
|
153
|
+
* @param {string} [from] The device that sent it: each sender has slots of its own.
|
|
154
|
+
*/
|
|
155
|
+
keep(e, from = '') {
|
|
156
|
+
// a seated device can hand this one anything: bounded per sender, and a forged one never
|
|
157
|
+
// pushes out the real one
|
|
158
|
+
for (const [sender, kept] of this._kept) {
|
|
159
|
+
for (const stamp of kept.keys()) if (this.db.keyring.entropy(stamp)) kept.delete(stamp)
|
|
160
|
+
if (kept.size === 0) this._kept.delete(sender)
|
|
161
|
+
}
|
|
162
|
+
if (this.db.keyring.entropy(e.stamp)) return
|
|
163
|
+
const kept = this._kept.get(from) ?? new Map()
|
|
164
|
+
const list = kept.get(e.stamp) ?? []
|
|
165
|
+
if (list.length >= CANDIDATES) return
|
|
166
|
+
kept.set(e.stamp, [...list, e.entropy])
|
|
167
|
+
if (kept.size > STAMPS) kept.delete(kept.keys().next().value)
|
|
168
|
+
this._kept.set(from, kept)
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** @private */
|
|
172
|
+
_handed(row) {
|
|
173
|
+
const candidates = []
|
|
174
|
+
for (const [sender, kept] of this._kept) {
|
|
175
|
+
candidates.push(...(kept.get(row.stamp) ?? []))
|
|
176
|
+
kept.delete(row.stamp)
|
|
177
|
+
if (kept.size === 0) this._kept.delete(sender)
|
|
178
|
+
}
|
|
179
|
+
if (!row.commit) return null
|
|
180
|
+
return candidates.find((entropy) => b4a.equals(crypto.hash(entropy), row.commit)) ?? null
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* @returns {Promise<boolean>} Whether this device cannot open the log's newest key, or one set
|
|
185
|
+
* aside that a block it met was written under.
|
|
186
|
+
*/
|
|
187
|
+
async lacks() {
|
|
188
|
+
return this._lacking(await this._epochs())
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** @private */
|
|
192
|
+
_lacking(rows) {
|
|
193
|
+
const top = newest(rows)
|
|
194
|
+
if (top !== null && !this.held(top)) return true
|
|
195
|
+
return rows.some((r) => r.aside && this._met.has(r.stamp) && !this.held(r))
|
|
196
|
+
}
|
|
197
|
+
|
|
73
198
|
/**
|
|
74
199
|
* Safety net after boot: an epoch applied but never saved, e.g. a crash between a
|
|
75
200
|
* rotation's append and its save, is learned from the epochs collection.
|
|
@@ -77,25 +202,103 @@ export class Rotation {
|
|
|
77
202
|
async hydrate() {
|
|
78
203
|
try {
|
|
79
204
|
for (const row of await this._epochs()) {
|
|
80
|
-
if (!this.
|
|
205
|
+
if (!this.held(row)) await this.learn(row)
|
|
81
206
|
}
|
|
82
207
|
} catch {
|
|
83
208
|
// rows past our newest epoch hydrate via apply
|
|
84
209
|
}
|
|
85
210
|
}
|
|
86
211
|
|
|
87
|
-
/**
|
|
212
|
+
/**
|
|
213
|
+
* The secret held for a row, if it meets the row's commitment.
|
|
214
|
+
*
|
|
215
|
+
* @param {{ stamp: number, commit: Uint8Array }} row
|
|
216
|
+
* @returns {Uint8Array | null}
|
|
217
|
+
*/
|
|
218
|
+
held(row) {
|
|
219
|
+
const entropy = this.db.keyring.entropy(row.stamp)
|
|
220
|
+
return entropy && row.commit && b4a.equals(crypto.hash(entropy), row.commit) ? entropy : null
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Write under the newest landed epoch whose secret this device holds, so a rotation a reorder
|
|
225
|
+
* dropped is never written under.
|
|
226
|
+
*
|
|
227
|
+
* @param {object} [view]
|
|
228
|
+
*/
|
|
229
|
+
async pick(view = this.db.view) {
|
|
230
|
+
let top = null
|
|
231
|
+
for await (const row of view.find(`@${this.db.ns}/epochs`, {}, { reverse: true })) {
|
|
232
|
+
if (row.aside || !this.held(row)) continue
|
|
233
|
+
top = row
|
|
234
|
+
break
|
|
235
|
+
}
|
|
236
|
+
this.db.keyring.current = top ? top.stamp : 0
|
|
237
|
+
this.db.keyring.seq = top ? top.epoch : 0
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** Debounced key check, with the owner's raise beside it, run at open and after every update. */
|
|
88
241
|
heal() {
|
|
89
242
|
const db = this.db
|
|
90
243
|
if (this._timer || db.closing || db.closed) return
|
|
91
244
|
this._timer = setTimeout(() => {
|
|
92
245
|
this._timer = null
|
|
93
|
-
|
|
246
|
+
// one its database closed under says nothing: it runs again at the next open
|
|
247
|
+
const fail = (err) => db.closing || db.closed || db._onerror(err)
|
|
248
|
+
this._audit().catch(fail)
|
|
249
|
+
db._raise().catch(fail)
|
|
94
250
|
}, 500)
|
|
95
251
|
}
|
|
96
252
|
|
|
97
253
|
/** @private */
|
|
98
|
-
async
|
|
254
|
+
async _carry(ops) {
|
|
255
|
+
const db = this.db
|
|
256
|
+
let done = null
|
|
257
|
+
this.carrying = new Promise((resolve) => (done = resolve))
|
|
258
|
+
try {
|
|
259
|
+
// a write on its way goes in first
|
|
260
|
+
await Promise.allSettled(db._writes)
|
|
261
|
+
const devices = await this._staying(ops)
|
|
262
|
+
const stamp = await db._write(ops, true)
|
|
263
|
+
if (!devices || stamp === undefined) return stamp
|
|
264
|
+
try {
|
|
265
|
+
// the promised are read now: the removal took those that stood on what it removed
|
|
266
|
+
await this._rotate(false, [...devices, ...(await this._promised())])
|
|
267
|
+
} catch (err) {
|
|
268
|
+
// the removal is in: the key check rotates. Behind, it says nothing, as that check does
|
|
269
|
+
if (!db.closing && !db.closed && db.behind === null) db._onerror(err)
|
|
270
|
+
this.heal()
|
|
271
|
+
}
|
|
272
|
+
return stamp
|
|
273
|
+
} catch (err) {
|
|
274
|
+
if (db.closing || db.closed) throw CeroError.CLOSED('Database')
|
|
275
|
+
throw err
|
|
276
|
+
} finally {
|
|
277
|
+
this.carrying = null
|
|
278
|
+
done()
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// the devices a removal leaves, read before it is appended, or null when this device carries no
|
|
283
|
+
// rotation: its own seat goes, or its member may not remove
|
|
284
|
+
/** @private */
|
|
285
|
+
async _staying(ops) {
|
|
286
|
+
const db = this.db
|
|
287
|
+
const { data: devices } = await db.get('devices')
|
|
288
|
+
const me = devices.find((d) => d.id === hid.encode(db.writerKey))
|
|
289
|
+
const seats = ops.map(([op, data]) => SEATS.get(op)?.(data, devices, db, me) ?? [])
|
|
290
|
+
const gone = new Set((await Promise.all(seats)).flat())
|
|
291
|
+
if (!me || gone.has(me.id)) return null
|
|
292
|
+
// a removed key told for the first time rotates, seat or none: the root hands every device the key
|
|
293
|
+
const revokes = ops.every(([op]) => op === 'revoke')
|
|
294
|
+
if (gone.size === 0 && revokes && !(await untold(ops, db, me))) return null
|
|
295
|
+
const { data: member } = await db.get('members', me.memberId)
|
|
296
|
+
if (!can(member?.role, REMOVE)) return null
|
|
297
|
+
return devices.filter((d) => d.key && !gone.has(d.id))
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** @private */
|
|
301
|
+
async _rotate(retried, devices) {
|
|
99
302
|
const db = this.db
|
|
100
303
|
db.guard()
|
|
101
304
|
if (!db.writable) throw CeroError.NOT_WRITABLE('Database')
|
|
@@ -103,23 +306,30 @@ export class Rotation {
|
|
|
103
306
|
if (db.bee.local.manifest?.version < 2) {
|
|
104
307
|
throw CeroError.INVALID('rotation requires manifest v2 cores')
|
|
105
308
|
}
|
|
309
|
+
// apply sets one aside, never the key: only a reorder may make one
|
|
310
|
+
const { data: me } = await db.get('devices', hid.encode(db.writerKey))
|
|
311
|
+
const member = me?.memberId ? (await db.get('members', me.memberId)).data : null
|
|
312
|
+
if (!can(member?.role, REMOVE)) {
|
|
313
|
+
throw CeroError.REFUSED('rotate', 'rotate requires the remove permission')
|
|
314
|
+
}
|
|
106
315
|
// claimed synchronously; the keyring learns the secret only after the announcement flushed
|
|
107
316
|
const entropy = Identity.randomBytes(32)
|
|
108
317
|
const stamp = this._mint()
|
|
109
318
|
this.current = { entropy, stamp, epoch: 0 }
|
|
110
319
|
try {
|
|
111
|
-
const wrapped = seal(await this._devices(), entropy)
|
|
320
|
+
const wrapped = seal(devices || (await this._devices()), entropy)
|
|
112
321
|
const epoch = await this._announce(stamp, entropy, wrapped)
|
|
113
322
|
if (!epoch) {
|
|
114
323
|
// a stamp collision (~2^-32, or an adversarial pre-claim) is not a refusal
|
|
115
324
|
if (!retried && (await this._taken(stamp))) {
|
|
116
325
|
this.current = null
|
|
117
|
-
return this._rotate(true)
|
|
326
|
+
return this._rotate(true, devices)
|
|
118
327
|
}
|
|
119
328
|
// permission is refused before the append, so the dry-run missed something
|
|
120
329
|
throw CeroError.INVALID('rotation was not applied')
|
|
121
330
|
}
|
|
122
331
|
db.keyring.add(stamp, entropy, epoch)
|
|
332
|
+
await this.pick()
|
|
123
333
|
await this._save()
|
|
124
334
|
db.emit('epoch')
|
|
125
335
|
return { epoch }
|
|
@@ -128,13 +338,29 @@ export class Rotation {
|
|
|
128
338
|
}
|
|
129
339
|
}
|
|
130
340
|
|
|
131
|
-
// every seated device, readers' too: a member keeps reading on each of its devices
|
|
341
|
+
// every seated device, readers' too: a member keeps reading on each of its devices. And every
|
|
342
|
+
// device promised a seat: let in before a rotation, it reads on once it has taken it
|
|
132
343
|
/** @private */
|
|
133
344
|
async _devices() {
|
|
134
345
|
const { data: devices } = await this.db.get('devices')
|
|
135
346
|
const keyed = devices.filter((d) => d.key)
|
|
136
347
|
if (keyed.length === 0) throw CeroError.INVALID('cannot rotate a database with no devices')
|
|
137
|
-
return keyed
|
|
348
|
+
return [...keyed, ...(await this._promised())]
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** @private */
|
|
352
|
+
async _promised() {
|
|
353
|
+
const { data: requests } = await this.db.get('requests')
|
|
354
|
+
const promised = []
|
|
355
|
+
for (const row of requests) if (await this._stands(row)) promised.push(row)
|
|
356
|
+
return promised
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// a promise stands while its invite lasts and the chain it stands on does, as the log reads it
|
|
360
|
+
/** @private */
|
|
361
|
+
async _stands(row) {
|
|
362
|
+
if (!row.promised || (row.expires > 0 && Date.now() > row.expires)) return false
|
|
363
|
+
return this.db.dispatcher.stands(this.db.view, [row.identity, ...chainOf(row)])
|
|
138
364
|
}
|
|
139
365
|
|
|
140
366
|
// resolves the sequence apply assigned, 0 if it never applied
|
|
@@ -142,13 +368,14 @@ export class Rotation {
|
|
|
142
368
|
async _announce(stamp, entropy, wrapped) {
|
|
143
369
|
const { bee } = this.db
|
|
144
370
|
const from = bee.local.length
|
|
145
|
-
|
|
371
|
+
const op = {
|
|
146
372
|
epoch: 0, // sequence assigned deterministically at apply time
|
|
147
373
|
stamp,
|
|
148
374
|
wrapped: c.encode(wraps, wrapped),
|
|
149
375
|
createdAt: Date.now(),
|
|
150
376
|
commit: crypto.hash(entropy)
|
|
151
|
-
}
|
|
377
|
+
}
|
|
378
|
+
await this.db._write([['rotate-key', op]], true)
|
|
152
379
|
await bee.update()
|
|
153
380
|
// a block appended during a rotation must not carry the stamp it announces
|
|
154
381
|
for (let i = from; i < bee.local.length; i++) {
|
|
@@ -198,44 +425,112 @@ export class Rotation {
|
|
|
198
425
|
return this.db.bee.local.setUserData('cero/epochs', entries)
|
|
199
426
|
}
|
|
200
427
|
|
|
201
|
-
// a rotation seals for the rotator's view of the members; REMOVE-capable devices
|
|
202
|
-
// when the
|
|
203
|
-
//
|
|
428
|
+
// a rotation seals for the rotator's view of the members; REMOVE-capable devices rotate
|
|
429
|
+
// when the log owes one, someone taken out since the newest key may hold it, when the newest
|
|
430
|
+
// key does not name a seated device, or when its envelope for them does not open: a rotator
|
|
431
|
+
// must not seal anyone who could heal it out
|
|
204
432
|
/** @private */
|
|
205
433
|
async _audit() {
|
|
434
|
+
if (!(await this._due())) return
|
|
435
|
+
// decided again once it holds the queue: a removal carried meanwhile brought its key
|
|
436
|
+
await this._queued(async () => {
|
|
437
|
+
const state = await this._due()
|
|
438
|
+
if (!state) return
|
|
439
|
+
this._healedFor = state
|
|
440
|
+
await this._rotate(false)
|
|
441
|
+
})
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// the (epoch, devices) state a rotation is due for, one attempt each: a failing rotate must
|
|
445
|
+
// not loop
|
|
446
|
+
/** @private */
|
|
447
|
+
async _due() {
|
|
448
|
+
const state = await this._drift()
|
|
449
|
+
return state === this._healedFor ? null : state
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** @private */
|
|
453
|
+
async _drift() {
|
|
206
454
|
const db = this.db
|
|
207
|
-
// behind, the membership this device sees is stale: the devices that read everything
|
|
208
|
-
if (db.closing || db.closed ||
|
|
455
|
+
// behind, the membership this device sees is stale: the devices that read everything rotate
|
|
456
|
+
if (db.closing || db.closed || this.current || db.behind !== null) return null
|
|
209
457
|
const { data: device } = await db.get('devices', hid.encode(db.writerKey))
|
|
210
458
|
const me = device?.memberId ? (await db.get('members', device.memberId)).data : null
|
|
211
|
-
if (!can(me?.role, REMOVE)) return
|
|
212
|
-
|
|
213
459
|
const rows = await this._epochs()
|
|
214
|
-
|
|
215
|
-
if (
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
const
|
|
220
|
-
|
|
221
|
-
const ids = new Set((await this._devices()).map((d) => d.id))
|
|
222
|
-
const sealedOut = !db.keyring.entropy(top.stamp)
|
|
223
|
-
if (!sealedOut && recipients.size === ids.size && [...recipients].every((id) => ids.has(id))) {
|
|
460
|
+
const top = newest(rows)
|
|
461
|
+
if (me && this._lacking(rows)) await this._ask()
|
|
462
|
+
if (!db.writable || !can(me?.role, REMOVE)) return null
|
|
463
|
+
|
|
464
|
+
const sealedOut = top !== null && !db.keyring.entropy(top.stamp)
|
|
465
|
+
const owed = await db.view.get(`@${db.ns}/${COUNTERS}`, { name: OWED })
|
|
466
|
+
if (!sealedOut && !owed?.value && !(top && (await this._unnamed(top)))) {
|
|
224
467
|
this._healedFor = null
|
|
225
|
-
return
|
|
468
|
+
return null
|
|
226
469
|
}
|
|
227
|
-
await this.
|
|
470
|
+
const ids = (await this._devices()).map((d) => d.id)
|
|
471
|
+
return `${top?.stamp ?? 0}:${ids.sort().join(',')}`
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// a device that lacks a key asks for them from its own core. Its row stands until it closes it:
|
|
475
|
+
// asking again changes nothing, and appends nothing
|
|
476
|
+
/** @private */
|
|
477
|
+
async _ask() {
|
|
478
|
+
const db = this.db
|
|
479
|
+
const since = db.meta.since?.routes?.[`@${db.ns}/ask-key`]
|
|
480
|
+
if (!(since <= (await db.dispatcher.version(db.view)))) return
|
|
481
|
+
const reply = keyPair(db.keyPair.secretKey).publicKey
|
|
482
|
+
await db._write([['ask-key', { id: hid.encode(db.writerKey), reply }]])
|
|
228
483
|
}
|
|
229
484
|
|
|
230
|
-
//
|
|
485
|
+
// a seated device of a member who stands that the newest key does not name: its join crossed
|
|
486
|
+
// a rotation, or a removal that sealed it out was refused
|
|
231
487
|
/** @private */
|
|
232
|
-
async
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
488
|
+
async _unnamed(top) {
|
|
489
|
+
const named = new Set(c.decode(wraps, top.wrapped).map((w) => w.id))
|
|
490
|
+
const { data: members } = await this.db.get('members')
|
|
491
|
+
const standing = new Set(members.map((m) => m.id))
|
|
492
|
+
const { data: devices } = await this.db.get('devices')
|
|
493
|
+
return devices.some((d) => d.key && standing.has(d.memberId) && !named.has(d.id))
|
|
236
494
|
}
|
|
237
495
|
}
|
|
238
496
|
|
|
497
|
+
// the seats an op takes out: a device by its row or by its writer, a member's every device, and
|
|
498
|
+
// those of the teller's member a revoke leaves standing on no chain
|
|
499
|
+
const SEATS = new Map([
|
|
500
|
+
['del-device', (op) => [op.id]],
|
|
501
|
+
['del-writer', (op) => [hid.encode(op.writer)]],
|
|
502
|
+
['del-member', (op, devices) => devices.filter((d) => d.memberId === op.id).map((d) => d.id)],
|
|
503
|
+
['revoke', cuts]
|
|
504
|
+
])
|
|
505
|
+
|
|
506
|
+
async function cuts(op, devices, db, me) {
|
|
507
|
+
const gone = []
|
|
508
|
+
for (const d of devices) {
|
|
509
|
+
if (!me || d.memberId !== me.memberId || !d.key) continue
|
|
510
|
+
if (!(await db.dispatcher.stands(db.view, seatChain(d), op))) gone.push(d.id)
|
|
511
|
+
}
|
|
512
|
+
return gone
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
async function untold(ops, db, me) {
|
|
516
|
+
const { removed } = await db.told(me.memberId)
|
|
517
|
+
const keys = ops.flatMap(([, op]) => keysOf(op.removed))
|
|
518
|
+
return keys.some((key) => !removed.some((k) => b4a.equals(k, key)))
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/**
|
|
522
|
+
* @param {Array<[string, unknown]>} ops
|
|
523
|
+
* @returns {boolean} Whether a batch takes a member or a device out.
|
|
524
|
+
*/
|
|
525
|
+
export function removes(ops) {
|
|
526
|
+
return ops.some(([op]) => SEATS.has(op))
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
function newest(rows) {
|
|
530
|
+
const counted = rows.filter((r) => !r.aside)
|
|
531
|
+
return counted.length ? counted.reduce((a, b) => (b.epoch > a.epoch ? b : a)) : null
|
|
532
|
+
}
|
|
533
|
+
|
|
239
534
|
// the epoch stamp autobee's encryption writes into every block header
|
|
240
535
|
function stampOf(raw) {
|
|
241
536
|
return b4a.readUInt32LE(raw, 4)
|
package/src/lib/constants.js
CHANGED
|
@@ -45,6 +45,14 @@ export const QUERY_RESERVED = new Set([
|
|
|
45
45
|
|
|
46
46
|
// monotonic index per collection
|
|
47
47
|
export const COUNTERS = 'counters'
|
|
48
|
+
// the database's version, a counters row under a name no collection can take
|
|
49
|
+
export const VERSION = '_version'
|
|
50
|
+
// the build that applied the view: its database, rules, contract and the lowest version it
|
|
51
|
+
// skipped, counters rows under names no collection can take
|
|
52
|
+
export const BUILT = ['_db', '_rules', '_contract', '_skipped']
|
|
53
|
+
// a rotation is owed: someone taken out may hold the keys. A counters row under a name no
|
|
54
|
+
// collection can take
|
|
55
|
+
export const OWED = '_owed'
|
|
48
56
|
// rotation announcements
|
|
49
57
|
export const EPOCHS = 'epochs'
|
|
50
58
|
// removed members, with the last invite minted before their removal
|
|
@@ -53,3 +61,5 @@ export const REMOVALS = 'removals'
|
|
|
53
61
|
export const REFUSALS = 'refusals'
|
|
54
62
|
// invites spent or revoked, until they expire
|
|
55
63
|
export const SPENT = 'spent'
|
|
64
|
+
// devices that asked for the keys they lack, until each closes its own
|
|
65
|
+
export const ASKS = 'owed'
|
package/src/lib/errors.js
CHANGED
|
@@ -152,6 +152,14 @@ export class CeroError extends Error {
|
|
|
152
152
|
static DENIED(reason = null, msg = 'pairing denied') {
|
|
153
153
|
return new CeroError('DENIED', msg, { reason })
|
|
154
154
|
}
|
|
155
|
+
/**
|
|
156
|
+
* A join given up with `cancel` before it was answered.
|
|
157
|
+
*
|
|
158
|
+
* @param {string} [msg]
|
|
159
|
+
*/
|
|
160
|
+
static CANCELLED(msg = 'join cancelled') {
|
|
161
|
+
return new CeroError('CANCELLED', msg)
|
|
162
|
+
}
|
|
155
163
|
/**
|
|
156
164
|
* An apply-time rule refused the op. Every peer reaches this verdict from the same node
|
|
157
165
|
* and the same view, so it aborts the writer's whole batch — which is what makes a
|
package/src/lib/schema.js
CHANGED
|
@@ -2,8 +2,8 @@ import { CeroError } from './errors.js'
|
|
|
2
2
|
import { SINGLE, COLLECTION, ACTION } from './constants.js'
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
* @typedef {{ prim: string, required?: boolean }} Prim
|
|
6
|
-
* @typedef {{ kind: 'single' | 'collection' | 'action', fields: Record<string, Prim>, indexes?: Record<string, string[]>, own?: boolean, push?: boolean }} TypeDef
|
|
5
|
+
* @typedef {{ prim: string, required?: boolean, later?: boolean }} Prim
|
|
6
|
+
* @typedef {{ kind: 'single' | 'collection' | 'action', fields: Record<string, Prim>, indexes?: Record<string, string[]>, own?: boolean, push?: boolean, later?: boolean }} TypeDef
|
|
7
7
|
* @typedef {{ [name: string]: TypeDef | Record<string, TypeDef> } & { local?: Record<string, TypeDef> }} SchemaDefs
|
|
8
8
|
* @typedef {{ defs: SchemaDefs }} Schema
|
|
9
9
|
*/
|
|
@@ -35,6 +35,16 @@ export const t = {
|
|
|
35
35
|
*/
|
|
36
36
|
required: (marker) => ({ ...marker, required: true }),
|
|
37
37
|
|
|
38
|
+
/**
|
|
39
|
+
* Hold back a field, a collection, a single or an action: a database starts using it once a
|
|
40
|
+
* build without the mark reaches its owner's device. What databases use already cannot be held.
|
|
41
|
+
*
|
|
42
|
+
* @template {Prim | TypeDef} T
|
|
43
|
+
* @param {T} def
|
|
44
|
+
* @returns {T}
|
|
45
|
+
*/
|
|
46
|
+
later: (def) => ({ ...def, later: true }),
|
|
47
|
+
|
|
38
48
|
/**
|
|
39
49
|
* Single-row table (one record, set/get by name).
|
|
40
50
|
*
|
package/src/lib/spec/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
// This file is autogenerated by the hyperschema compiler
|
|
2
|
-
// Schema Version:
|
|
2
|
+
// Schema Version: 3
|
|
3
3
|
/* eslint-disable camelcase */
|
|
4
4
|
/* eslint-disable quotes */
|
|
5
5
|
/* eslint-disable space-before-function-paren */
|
|
6
6
|
|
|
7
7
|
import { c } from 'hyperschema/runtime'
|
|
8
8
|
|
|
9
|
-
const VERSION =
|
|
9
|
+
const VERSION = 3
|
|
10
10
|
|
|
11
11
|
// eslint-disable-next-line no-unused-vars
|
|
12
12
|
let version = VERSION
|
|
@@ -41,12 +41,14 @@ const encoding1 = {
|
|
|
41
41
|
c.fixed32.preencode(state, m.address)
|
|
42
42
|
c.fixed32.preencode(state, m.seed)
|
|
43
43
|
encoding0.preencode(state, m.link)
|
|
44
|
-
state.end++ // max flag is
|
|
44
|
+
state.end++ // max flag is 4 so always one byte
|
|
45
45
|
|
|
46
46
|
if (m.data) c.buffer.preencode(state, m.data)
|
|
47
|
+
if (version >= 2 && m.stamp) c.uint.preencode(state, m.stamp)
|
|
47
48
|
},
|
|
48
49
|
encode(state, m) {
|
|
49
|
-
const flags =
|
|
50
|
+
const flags =
|
|
51
|
+
(m.data ? 1 : 0) | ((version >= 2 && m.stamp) ? 2 : 0) | ((version >= 3 && m.own) ? 4 : 0)
|
|
50
52
|
|
|
51
53
|
c.uint.encode(state, m.version)
|
|
52
54
|
c.uint.encode(state, m.expires)
|
|
@@ -57,6 +59,7 @@ const encoding1 = {
|
|
|
57
59
|
c.uint.encode(state, flags)
|
|
58
60
|
|
|
59
61
|
if (m.data) c.buffer.encode(state, m.data)
|
|
62
|
+
if (version >= 2 && m.stamp) c.uint.encode(state, m.stamp)
|
|
60
63
|
},
|
|
61
64
|
decode(state) {
|
|
62
65
|
const r0 = c.uint.decode(state)
|
|
@@ -74,7 +77,9 @@ const encoding1 = {
|
|
|
74
77
|
address: r3,
|
|
75
78
|
seed: r4,
|
|
76
79
|
link: r5,
|
|
77
|
-
data: (flags & 1) !== 0 ? c.buffer.decode(state) : null
|
|
80
|
+
data: (flags & 1) !== 0 ? c.buffer.decode(state) : null,
|
|
81
|
+
stamp: (version >= 2 && (flags & 2) !== 0) ? c.uint.decode(state) : 0,
|
|
82
|
+
own: (version >= 3 && (flags & 4) !== 0)
|
|
78
83
|
}
|
|
79
84
|
}
|
|
80
85
|
}
|
package/src/lib/spec/schema.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version":
|
|
2
|
+
"version": 3,
|
|
3
3
|
"schema": [
|
|
4
4
|
{
|
|
5
5
|
"name": "link",
|
|
@@ -68,6 +68,18 @@
|
|
|
68
68
|
"required": false,
|
|
69
69
|
"type": "buffer",
|
|
70
70
|
"version": 1
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
"name": "stamp",
|
|
74
|
+
"required": false,
|
|
75
|
+
"type": "uint",
|
|
76
|
+
"version": 2
|
|
77
|
+
},
|
|
78
|
+
{
|
|
79
|
+
"name": "own",
|
|
80
|
+
"required": false,
|
|
81
|
+
"type": "bool",
|
|
82
|
+
"version": 3
|
|
71
83
|
}
|
|
72
84
|
]
|
|
73
85
|
},
|