@cero-base/core 2.3.1 → 2.3.3

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cero-base/core",
3
- "version": "2.3.1",
3
+ "version": "2.3.3",
4
4
  "description": "cero p2p primitives — identity, storage, network, database, blobs, rpc, pairing.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -148,10 +148,10 @@
148
148
  },
149
149
  "dependencies": {
150
150
  "@hyperswarm/secret-stream": "^6.9.2",
151
- "autobee": "2.11.8",
151
+ "autobee": "2.12.0",
152
152
  "b4a": "^1.9.0",
153
153
  "bare-crypto": "^1.15.3",
154
- "bare-fs": "^4.8.1",
154
+ "bare-fs": "^4.8.2",
155
155
  "bare-path": "^3.1.2",
156
156
  "bip39-mnemonic": "^2.5.0",
157
157
  "blind-peering": "^2.9.5",
@@ -11,6 +11,8 @@ import {
11
11
  COUNTERS,
12
12
  EPOCHS,
13
13
  REMOVALS,
14
+ REFUSALS,
15
+ SPENT,
14
16
  OWNER,
15
17
  INVITE,
16
18
  REMOVE,
@@ -64,6 +66,8 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
64
66
  const col = (name) => `@${ns}/${name}`
65
67
  const countersCol = `@${ns}/${COUNTERS}`
66
68
  const removals = `@${ns}/${REMOVALS}`
69
+ const refusals = `@${ns}/${REFUSALS}`
70
+ const spent = `@${ns}/${SPENT}`
67
71
  const getMember = (view, id) => view.get(`@${ns}/members`, { id })
68
72
  const getDevice = (view, id) => view.get(`@${ns}/devices`, { id })
69
73
 
@@ -483,21 +487,38 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
483
487
  if (!can(r, REMOVE) || !capped(r, next)) throw CeroError.REFUSED('invite')
484
488
  await save(ctx, 'set', 'invites', next)
485
489
  })
490
+ // a live invite is revoked; a spent one, deleted again, is forgotten
486
491
  add('del-invite', async (op, ctx) => {
487
- const existing = await ctx.view.get(invites, { id: op.id })
488
- if (!existing) return
489
492
  const r = await getSignerRole(ctx.view, ctx.key)
490
- if (!can(r, REMOVE) || !capped(r, existing)) throw CeroError.REFUSED('invite')
491
- await spend(ctx, existing)
493
+ const existing = await ctx.view.get(invites, { id: op.id })
494
+ if (existing) {
495
+ if (!can(r, REMOVE) || !capped(r, existing)) throw CeroError.REFUSED('invite')
496
+ return spend(ctx, existing, 'revoked')
497
+ }
498
+ if (!(await ctx.view.get(spent, { id: op.id }))) return
499
+ if (!can(r, REMOVE)) throw CeroError.REFUSED('invite')
500
+ await ctx.view.delete(spent, { id: op.id })
492
501
  })
493
- // its joins still waiting for a member go with it; admitted ones are still owed their keys
494
- async function spend(ctx, invite) {
502
+ // its joins still waiting for a member are turned away with it; admitted ones are still owed
503
+ // their keys. Its id stays, so a later join with it hears why
504
+ async function spend(ctx, invite, reason) {
505
+ const expires = invite.expires || 0
495
506
  await drop(ctx, 'invites', invite.id)
507
+ await ctx.view.insert(spent, { id: invite.id, reason, expires })
496
508
  for (const request of await ctx.view.find(requests, {}).toArray()) {
497
- if (request.invite === invite.id && !request.admitted) await drop(ctx, 'requests', request.id)
509
+ if (request.invite !== invite.id || request.admitted) continue
510
+ await drop(ctx, 'requests', request.id)
511
+ await refuse(ctx, request, reason)
498
512
  }
499
513
  }
500
514
 
515
+ // a join turned away is answered at its reply address. A writer with a request hears through
516
+ // that: one of the two per writer, or a denial could race its keys
517
+ async function refuse(ctx, { id, reply, expires }, reason) {
518
+ if (await ctx.view.get(requests, { id })) return
519
+ await ctx.view.insert(refusals, { id, reply, reason, expires })
520
+ }
521
+
501
522
  // the member, when new, and its device, seated when the member writes; its request stays until
502
523
  // a member delivered the keys. The invite is spent unless it is reusable
503
524
  async function admit(ctx, { invite, identity, writer, reply, role, ts }) {
@@ -519,7 +540,7 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
519
540
  role,
520
541
  admitted: true
521
542
  })
522
- if (!invite.reuse) await spend(ctx, invite)
543
+ if (!invite.reuse) await spend(ctx, invite, 'spent')
523
544
  }
524
545
 
525
546
  function request(invite, identity, writer, reply, ts) {
@@ -547,13 +568,22 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
547
568
  if (!Invite.proven(join.invite, ctx.key, join.proof)) return
548
569
  const signed = joining(ctx.dbKey, join.invite, ctx.key, join.reply)
549
570
  if (!Identity.verify(join.identity, signed, join.signature)) return
571
+ const id = hid.encode(ctx.key)
550
572
  const invite = await ctx.view.get(invites, { id: b4a.toHex(join.invite) })
551
- if (!invite) return
573
+ if (!invite) {
574
+ // an invite the room never held could be anyone's: nobody answers it
575
+ const record = await ctx.view.get(spent, { id: b4a.toHex(join.invite) })
576
+ if (!record) return
577
+ return refuse(ctx, { id, reply: join.reply, expires: record.expires }, record.reason)
578
+ }
552
579
  const ts = join.ts || 0
553
580
  const memberId = hid.encode(join.identity)
554
581
  const known = await getMember(ctx.view, memberId)
555
582
  const removal = known ? null : await ctx.view.get(removals, { id: memberId })
556
- if (removal && (invite.index ?? 0) <= removal.index) return
583
+ if (removal && (invite.index ?? 0) <= removal.index) {
584
+ return refuse(ctx, { id, reply: join.reply, expires: invite.expires || 0 }, 'removed')
585
+ }
586
+ await ctx.view.delete(refusals, { id })
557
587
  if (invite.confirm && !known) {
558
588
  const waiting = request(invite, join.identity, ctx.key, join.reply, ts)
559
589
  return save(ctx, 'put', 'requests', waiting)
@@ -591,6 +621,11 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
591
621
  if (!can(await getSignerRole(ctx.view, ctx.key), INVITE)) throw CeroError.REFUSED('invite')
592
622
  await drop(ctx, 'requests', op.id)
593
623
  })
624
+ // read by the joiner, or past its expiry with nobody waiting
625
+ add('del-refusal', async (op, ctx) => {
626
+ if (!can(await getSignerRole(ctx.view, ctx.key), INVITE)) throw CeroError.REFUSED('invite')
627
+ await ctx.view.delete(refusals, { id: op.id })
628
+ })
594
629
 
595
630
  add('add-file', async (op, ctx) => {
596
631
  await requireWrite(ctx)
@@ -102,6 +102,8 @@ export class Database extends ReadyResource {
102
102
  this.encryptionKey = opts.encryptionKey || opts.identity.encryptionKey || null
103
103
  this.keyring = new Keyring()
104
104
  if (opts.epochs) for (const e of opts.epochs) this.keyring.add(e.stamp, e.entropy, e.epoch)
105
+ /** @private */
106
+ this._delivered = !!opts.epochs?.length
105
107
  this.rotation = new Rotation(this)
106
108
  this.key = opts.key || null
107
109
  this.pinned = opts.pinned === true
@@ -196,6 +198,8 @@ export class Database extends ReadyResource {
196
198
 
197
199
  // before replication can deliver blocks at epochs we haven't learned yet
198
200
  await this.rotation.hydrate()
201
+ // epochs handed over at join are sealed to nobody this device can read later: keep them
202
+ if (this._delivered) await this.rotation._save()
199
203
 
200
204
  // REMOVE-capable devices re-key when the epoch drifts from the member set
201
205
  this.on('update', () => this.rotation.heal())
@@ -51,3 +51,7 @@ export const COUNTERS = 'counters'
51
51
  export const EPOCHS = 'epochs'
52
52
  // removed members, with the last invite minted before their removal
53
53
  export const REMOVALS = 'removals'
54
+ // joins turned away, until the joiner read why
55
+ export const REFUSALS = 'refusals'
56
+ // invites spent or revoked, until they expire
57
+ export const SPENT = 'spent'
@@ -14,7 +14,7 @@ import { wrap } from '../database/envelope.js'
14
14
  import { getEncoding } from '../lib/spec/index.js'
15
15
  import { CeroError } from '../lib/errors.js'
16
16
  import { can, grants, isRank, joining, INVITE, REMOVE } from '../lib/utils.js'
17
- import { NAMESPACE, MEMBER } from '../lib/constants.js'
17
+ import { NAMESPACE, MEMBER, REFUSALS, SPENT } from '../lib/constants.js'
18
18
 
19
19
  const Join = getEncoding('@cero/join')
20
20
  const MAX_DELAY = 2 ** 31 - 1
@@ -51,9 +51,10 @@ const MAX_DELAY = 2 ** 31 - 1
51
51
  * Invites into a database. An invite is a record in the database; a joiner writes one signed
52
52
  * `join` op into its own writer core and announces it to the database's peers, and apply admits
53
53
  * it. The admission stays in the database until the joiner has its keys: every device of a member
54
- * that may invite offers them while online, and the first one read settles it for all. A
55
- * `confirm` invite's joins wait as requests until a member accepts or denies them; `'request'`
56
- * fires for each new one.
54
+ * that may invite offers them while online, and the first one read settles it for all. A join
55
+ * turned away with an invite the database knows, spent, revoked or older than the joiner's
56
+ * removal, is answered the same way with `DENIED` and the reason. A `confirm` invite's joins wait
57
+ * as requests until a member accepts or denies them; `'request'` fires for each new one.
57
58
  * `Pairing.join` is the other side: write the join, wait for the reply.
58
59
  */
59
60
  export class Pairing extends ReadyResource {
@@ -67,7 +68,7 @@ export class Pairing extends ReadyResource {
67
68
  this.db = db
68
69
  /** @type {Set<Request>} requests not answered yet: whoever attaches after one fired goes through these first */
69
70
  this.pending = new Set()
70
- /** Whether this device answers the database's joins: it may invite, and invites or joiners owed their keys exist. */
71
+ /** Whether this device answers the database's joins: it may invite, and invites or joiners owed an answer exist. */
71
72
  this.serving = false
72
73
 
73
74
  /** @private */
@@ -75,6 +76,8 @@ export class Pairing extends ReadyResource {
75
76
  /** @private */
76
77
  this._replies = new Map() // writer id → the Post offering its keys
77
78
  /** @private */
79
+ this._denials = new Map() // writer id → the Post telling why its join was turned away
80
+ /** @private */
78
81
  this._expiry = null
79
82
  /** @private */
80
83
  this._onupdate = (touched) => {
@@ -96,8 +99,9 @@ export class Pairing extends ReadyResource {
96
99
  async _close() {
97
100
  this.db.off('update', this._onupdate)
98
101
  clearTimeout(this._expiry)
99
- const posts = [...this._replies.values()]
102
+ const posts = [...this._replies.values(), ...this._denials.values()]
100
103
  this._replies.clear()
104
+ this._denials.clear()
101
105
  await Promise.allSettled(posts.map((post) => post.close()))
102
106
  }
103
107
 
@@ -166,26 +170,31 @@ export class Pairing extends ReadyResource {
166
170
  return request
167
171
  }
168
172
 
169
- // follow the log: the invites that ran out, the joins waiting for a member, the keys owed
173
+ // follow the log: the invites that ran out, the joins waiting for a member, the answers owed
170
174
  /** @private */
171
175
  async _sync() {
172
176
  const me = await this._me()
173
177
  const { data: invites } = await this.db.get('invites')
174
178
  const { data: requests } = await this.db.get('requests')
179
+ const refusals = await this._list(REFUSALS)
180
+ const spent = await this._list(SPENT)
175
181
  if (this.closing || this.closed) return
176
182
  const role = me?.role
177
- // apply has no clock: past its expiry an invite is dropped here, so the log stops admitting
183
+ // apply has no clock: past its expiry an invite is dropped here, so the log stops admitting,
184
+ // and a spent one forgotten, since no joiner uses it past then
178
185
  if (can(role, REMOVE)) {
179
- for (const row of invites.filter(expired)) {
186
+ for (const row of [...invites, ...spent].filter(expired)) {
180
187
  await this.db.call('del-invite', { id: row.id }).catch(safetyCatch)
181
188
  }
182
189
  }
183
- this._arm([...invites, ...requests])
190
+ this._arm([...invites, ...requests, ...spent])
184
191
  const inviter = can(role, INVITE)
185
192
  const owed = inviter ? requests.filter((row) => row.admitted) : []
193
+ const refused = inviter ? refusals : []
186
194
  this._pending(inviter ? requests.filter((row) => !row.admitted) : [], invites)
187
- await this._answer(owed, role)
188
- this.serving = inviter && (invites.some((row) => !expired(row)) || owed.length > 0)
195
+ await this._answer(owed, refused, role)
196
+ const live = invites.some((row) => !expired(row))
197
+ this.serving = inviter && (live || owed.length > 0 || refused.length > 0)
189
198
  this.emit('serving', this.serving)
190
199
  }
191
200
 
@@ -221,51 +230,76 @@ export class Pairing extends ReadyResource {
221
230
  }
222
231
  }
223
232
 
224
- // an admitted joiner is offered its keys by every inviter device online, until one is read.
225
- // Past the invite's expiry the joiner has given up: a member who can remove drops it instead
233
+ // an admitted joiner is offered its keys, and a refused one the reason, by every inviter device
234
+ // online, until one is read. Past the invite's expiry the joiner has given up: a member who can
235
+ // remove drops an admitted one instead, and a refused one is forgotten
236
+ /** @private */
237
+ async _answer(owed, refused, role) {
238
+ const keys = () => ({
239
+ status: STATUS_ACCEPTED,
240
+ reason: '',
241
+ key: this.db.key,
242
+ encryptionKey: this.db.encryptionKey,
243
+ epochs: this.db.keyring.all()
244
+ })
245
+ const denied = ({ reason }) => ({
246
+ status: STATUS_DENIED,
247
+ reason,
248
+ key: null,
249
+ encryptionKey: null,
250
+ epochs: null
251
+ })
252
+ for (const row of this._offer(this._replies, owed, keys, 'del-request')) {
253
+ if (!can(role, REMOVE)) continue
254
+ await this.db.call('del-member', { id: hid.encode(row.identity) }).catch(safetyCatch)
255
+ }
256
+ for (const row of this._offer(this._denials, refused, denied, 'del-refusal')) {
257
+ await this.db.call('del-refusal', { id: row.id }).catch(safetyCatch)
258
+ }
259
+ }
260
+
261
+ // posts each live row its answer once, closes those settled elsewhere, returns those past expiry
226
262
  /** @private */
227
- async _answer(rows, role) {
228
- const owed = new Set(rows.map((row) => row.id))
229
- for (const [id, post] of this._replies) {
230
- if (owed.has(id)) continue
231
- this._replies.delete(id)
263
+ _offer(posts, rows, answer, settled) {
264
+ const live = new Set(rows.map((row) => row.id))
265
+ for (const [id, post] of posts) {
266
+ if (live.has(id)) continue
267
+ posts.delete(id)
232
268
  post.close().catch(safetyCatch)
233
269
  }
270
+ const gone = []
234
271
  for (const row of rows) {
235
272
  if (!expired(row)) {
236
- if (!this._replies.has(row.id)) this._reply(row)
273
+ if (!posts.has(row.id)) this._post(posts, row, answer(row), settled)
237
274
  continue
238
275
  }
239
- // a device already offering the keys stops: nobody waits for them any more
240
- this._replies.get(row.id)?.close().catch(safetyCatch)
241
- this._replies.delete(row.id)
242
- if (can(role, REMOVE)) {
243
- await this.db.call('del-member', { id: hid.encode(row.identity) }).catch(safetyCatch)
244
- }
276
+ // a device already offering it stops: nobody waits for it any more
277
+ posts.get(row.id)?.close().catch(safetyCatch)
278
+ posts.delete(row.id)
279
+ gone.push(row)
245
280
  }
281
+ return gone
246
282
  }
247
283
 
248
- // kept in memory, not in the outbox: the admission in the log is what outlives a restart
284
+ // kept in memory, not in the outbox: the row in the log is what outlives a restart
249
285
  /** @private */
250
- _reply({ id, reply }) {
286
+ _post(posts, { id, reply }, answer, settled) {
251
287
  const { network } = this.mailbox
252
- const keys = {
253
- status: STATUS_ACCEPTED,
254
- reason: '',
255
- key: this.db.key,
256
- encryptionKey: this.db.encryptionKey,
257
- epochs: this.db.keyring.all()
258
- }
259
- const post = new Post(network, reply, c.encode(Response, keys), { mirrors: network.mirrors })
260
- this._replies.set(id, post)
288
+ const post = new Post(network, reply, c.encode(Response, answer), { mirrors: network.mirrors })
289
+ posts.set(id, post)
261
290
  const settle = async () => {
262
291
  await post.ready()
263
292
  await post.delivered
264
- await this.db.call('del-request', { id })
293
+ await this.db.call(settled, { id })
265
294
  }
266
295
  settle().catch(safetyCatch)
267
296
  }
268
297
 
298
+ /** @private */
299
+ _list(name) {
300
+ return this.db.view.find(`@${this.db.ns}/${name}`, {}).toArray()
301
+ }
302
+
269
303
  /** @private */
270
304
  async _me() {
271
305
  return (await this.db.get('members', this.db.identity.id)).data
@@ -223,11 +223,13 @@ export class Storage extends ReadyResource {
223
223
  watch(name, query) {
224
224
  this._guard()
225
225
  this._ref(name)
226
+ // close nulls this.db, a teardown after it unwatches the db it watched
227
+ const db = this.db
226
228
  return subscribe({
227
229
  get: () => this.get(name, query),
228
230
  watch: (fn) => {
229
- this.db.watch(fn)
230
- return () => this.db.unwatch(fn)
231
+ db.watch(fn)
232
+ return () => db.unwatch(fn)
231
233
  }
232
234
  })
233
235
  }
@@ -264,9 +266,15 @@ export class Storage extends ReadyResource {
264
266
  * @private
265
267
  */
266
268
  async _read(ref, id) {
267
- if (ref.kind === SINGLE) return this.db.findOne(this._col(ref), {})
268
- if (id == null) return null
269
- return (await this.db.get(this._col(ref), { id })) ?? null
269
+ try {
270
+ if (ref.kind === SINGLE) return await this.db.findOne(this._col(ref), {})
271
+ if (id == null) return null
272
+ return (await this.db.get(this._col(ref), { id })) ?? null
273
+ } catch (err) {
274
+ // a close that began under the read answers for it
275
+ this._guard()
276
+ throw err
277
+ }
270
278
  }
271
279
 
272
280
  /**
@@ -275,8 +283,14 @@ export class Storage extends ReadyResource {
275
283
  */
276
284
  async _write(ref, row) {
277
285
  await this._serial(async () => {
278
- await this.db.insert(this._col(ref), row)
279
- await this.db.flush()
286
+ try {
287
+ await this.db.insert(this._col(ref), row)
288
+ await this.db.flush()
289
+ } catch (err) {
290
+ // queued behind a close, the write finds the db closing or gone: the close answers
291
+ this._guard()
292
+ throw err
293
+ }
280
294
  })
281
295
  }
282
296
 
@@ -226,6 +226,8 @@ export declare class Database extends ReadyResource {
226
226
  namespace: string;
227
227
  encryptionKey: Uint8Array<ArrayBufferLike>;
228
228
  keyring: Keyring;
229
+ /** @private */
230
+ _delivered;
229
231
  rotation: Rotation;
230
232
  key: Uint8Array<ArrayBufferLike>;
231
233
  pinned: boolean;
@@ -33,3 +33,5 @@ export declare const QUERY_RESERVED: Set<string>;
33
33
  export declare const COUNTERS = "counters";
34
34
  export declare const EPOCHS = "epochs";
35
35
  export declare const REMOVALS = "removals";
36
+ export declare const REFUSALS = "refusals";
37
+ export declare const SPENT = "spent";
@@ -112,9 +112,10 @@ export type JoinResult = {
112
112
  * Invites into a database. An invite is a record in the database; a joiner writes one signed
113
113
  * `join` op into its own writer core and announces it to the database's peers, and apply admits
114
114
  * it. The admission stays in the database until the joiner has its keys: every device of a member
115
- * that may invite offers them while online, and the first one read settles it for all. A
116
- * `confirm` invite's joins wait as requests until a member accepts or denies them; `'request'`
117
- * fires for each new one.
115
+ * that may invite offers them while online, and the first one read settles it for all. A join
116
+ * turned away with an invite the database knows, spent, revoked or older than the joiner's
117
+ * removal, is answered the same way with `DENIED` and the reason. A `confirm` invite's joins wait
118
+ * as requests until a member accepts or denies them; `'request'` fires for each new one.
118
119
  * `Pairing.join` is the other side: write the join, wait for the reply.
119
120
  */
120
121
  export declare class Pairing extends ReadyResource {
@@ -122,13 +123,15 @@ export declare class Pairing extends ReadyResource {
122
123
  db: import("../index.js").Database;
123
124
  /** @type {Set<Request>} requests not answered yet: whoever attaches after one fired goes through these first */
124
125
  pending: Set<Request>;
125
- /** Whether this device answers the database's joins: it may invite, and invites or joiners owed their keys exist. */
126
+ /** Whether this device answers the database's joins: it may invite, and invites or joiners owed an answer exist. */
126
127
  serving: boolean;
127
128
  /** @private */
128
129
  _requests;
129
130
  /** @private */
130
131
  _replies;
131
132
  /** @private */
133
+ _denials;
134
+ /** @private */
132
135
  _expiry;
133
136
  /** @private */
134
137
  _onupdate;
@@ -168,7 +171,11 @@ export declare class Pairing extends ReadyResource {
168
171
  /** @private */
169
172
  private _answer;
170
173
  /** @private */
171
- private _reply;
174
+ private _offer;
175
+ /** @private */
176
+ private _post;
177
+ /** @private */
178
+ private _list;
172
179
  /** @private */
173
180
  private _me;
174
181
  /** @private */