@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.
Files changed (39) hide show
  1. package/package.json +8 -8
  2. package/src/blobs/codec.js +25 -0
  3. package/src/blobs/index.js +5 -2
  4. package/src/blobs/server.js +2 -2
  5. package/src/database/dispatch.js +805 -208
  6. package/src/database/encryption.js +25 -21
  7. package/src/database/index.js +747 -124
  8. package/src/database/rotation.js +333 -38
  9. package/src/lib/constants.js +10 -0
  10. package/src/lib/errors.js +8 -0
  11. package/src/lib/schema.js +12 -2
  12. package/src/lib/spec/index.js +10 -5
  13. package/src/lib/spec/schema.json +13 -1
  14. package/src/lib/utils.js +24 -3
  15. package/src/mailbox/inbox.js +368 -41
  16. package/src/mailbox/index.js +75 -20
  17. package/src/mailbox/post.js +13 -8
  18. package/src/network/index.js +12 -5
  19. package/src/pairing/index.js +347 -57
  20. package/src/pairing/invite.js +36 -12
  21. package/src/pairing/response.js +78 -0
  22. package/src/push/index.js +20 -2
  23. package/types/blobs/codec.d.ts +13 -0
  24. package/types/blobs/index.d.ts +2 -0
  25. package/types/database/dispatch.d.ts +52 -7
  26. package/types/database/encryption.d.ts +13 -5
  27. package/types/database/index.d.ts +199 -19
  28. package/types/database/rotation.d.ts +85 -2
  29. package/types/lib/constants.d.ts +4 -0
  30. package/types/lib/errors.d.ts +6 -0
  31. package/types/lib/schema.d.ts +11 -0
  32. package/types/lib/utils.d.ts +2 -0
  33. package/types/mailbox/inbox.d.ts +78 -10
  34. package/types/mailbox/index.d.ts +42 -16
  35. package/types/mailbox/post.d.ts +7 -5
  36. package/types/pairing/index.d.ts +53 -8
  37. package/types/pairing/invite.d.ts +27 -8
  38. package/types/pairing/response.d.ts +50 -0
  39. package/types/push/index.d.ts +12 -2
@@ -6,17 +6,28 @@ import crypto from 'hypercore-crypto'
6
6
  import hid from 'hypercore-id-encoding'
7
7
  import Autobee from 'autobee'
8
8
 
9
- import { Invite } from './invite.js'
10
- import { Response, STATUS_ACCEPTED, STATUS_DENIED } from './response.js'
9
+ import { Invite, STAMPED } from './invite.js'
10
+ import {
11
+ Response,
12
+ STATUS_ACCEPTED,
13
+ STATUS_DENIED,
14
+ tag,
15
+ proven,
16
+ signed,
17
+ signer
18
+ } from './response.js'
11
19
  import { Mailbox } from '../mailbox/index.js'
12
20
  import { Post } from '../mailbox/post.js'
13
21
  import { wrap } from '../database/envelope.js'
22
+ import { chainOf, linkOf } from '../database/dispatch.js'
14
23
  import { getEncoding } from '../lib/spec/index.js'
15
24
  import { CeroError } from '../lib/errors.js'
16
- import { can, grants, isRank, joining, INVITE, REMOVE } from '../lib/utils.js'
17
- import { NAMESPACE, MEMBER, REFUSALS, SPENT } from '../lib/constants.js'
25
+ import { can, grants, isRank, isOptions, joining, INVITE, REMOVE } from '../lib/utils.js'
26
+ import { NAMESPACE, MEMBER, REFUSALS, SPENT, ASKS } from '../lib/constants.js'
18
27
 
19
28
  const Join = getEncoding('@cero/join')
29
+ // what a sync follows in the log
30
+ const WATCHED = ['*', 'invites', 'requests', 'members', 'devices', ASKS]
20
31
  const MAX_DELAY = 2 ** 31 - 1
21
32
 
22
33
  /**
@@ -39,7 +50,7 @@ const MAX_DELAY = 2 ** 31 - 1
39
50
  *
40
51
  * @typedef {object} JoinOpts
41
52
  * @property {import('../identity/index.js').Identity} identity Who joins: the member they become, and who signs the join.
42
- * @property {{ dispatch: { encode: Function }, meta?: { ns?: string, version?: number } }} spec The database's spec: the join is one of its ops.
53
+ * @property {{ dispatch: { encode: Function }, meta?: { ns?: string, version?: number, start?: number, encoding?: Record<string, number> } }} spec The database's spec: the join is one of its ops.
43
54
  * @property {KeyPair} [writer] Their writer keypair in the database, a fresh one by default. The join is its first block and its secret key owns the reply address: pass the same one to resume a join after a restart.
44
55
  * @property {number} [timeout] Deadline for the reply, in ms; `0` waits until the invite expires, or for good. Defaults to 30000.
45
56
  * @property {AbortSignal} [signal] Stops the join, rejecting it with `CLOSED`, as closing the mailbox does.
@@ -57,10 +68,17 @@ const MAX_DELAY = 2 ** 31 - 1
57
68
  * Invites into a database. An invite is a record in the database; a joiner writes one signed
58
69
  * `join` op into its own writer core and announces it to the database's peers, and apply admits
59
70
  * it. The admission stays in the database until the joiner has its keys: every device of a member
60
- * that may invite offers them while online, and the first one read settles it for all. A join
71
+ * that may invite offers them while online, and the first one read settles it for all. Under an
72
+ * invite with an address of its own, being let in is a promise: no member and no seat until a device
73
+ * of the joiner, holding the keys, claims its seat. Its keys are offered until a member that may
74
+ * invite sees that device seated and settles the promise, or until the invite expires, whoever
75
+ * reads them. A join
61
76
  * turned away with an invite the database knows, spent, revoked or older than the joiner's
62
77
  * removal, is answered the same way with `DENIED` and the reason. A `confirm` invite's joins wait
63
78
  * as rows of `requests` until a member accepts or denies one by its id.
79
+ * Where the database's version keeps an invite's secret on its record, the invite has an address
80
+ * of its own: its joins are sealed to it, and its answers follow the tag only that secret and the
81
+ * joiner's reply address make. Elsewhere an invite carries the database's address.
64
82
  * `Pairing.join` is the other side: write the join, wait for the reply.
65
83
  */
66
84
  export class Pairing extends ReadyResource {
@@ -80,13 +98,17 @@ export class Pairing extends ReadyResource {
80
98
  /** @private */
81
99
  this._denials = new Map() // writer id → the Post telling why its join was turned away
82
100
  /** @private */
101
+ this._keys = new Map() // writer id → the Post sending a device the keys it asked for
102
+ /** @private */
103
+ this._inbox = null
104
+ /** @private */
83
105
  this._expiry = null
84
106
  /** @private */
85
107
  this._onupdate = (touched) => {
86
- if (['*', 'invites', 'requests', 'members'].some((name) => touched.has(name))) {
87
- this._sync().catch(safetyCatch)
88
- }
108
+ if (WATCHED.some((name) => touched.has(name))) this._sync().catch(safetyCatch)
89
109
  }
110
+ /** @private */
111
+ this._onepoch = () => this._sync().catch(safetyCatch)
90
112
  }
91
113
 
92
114
  /** @private */
@@ -95,15 +117,21 @@ export class Pairing extends ReadyResource {
95
117
  await this.db.ready()
96
118
  await this._sync()
97
119
  this.db.on('update', this._onupdate)
120
+ this.db.on('epoch', this._onepoch)
98
121
  }
99
122
 
100
123
  /** @private */
101
124
  async _close() {
102
125
  this.db.off('update', this._onupdate)
126
+ this.db.off('epoch', this._onepoch)
103
127
  clearTimeout(this._expiry)
104
- const posts = [...this._replies.values(), ...this._denials.values()]
128
+ this._expiry = null
129
+ const posts = [...this._replies.values(), ...this._denials.values(), ...this._keys.values()]
130
+ if (this._inbox) posts.push(this._inbox)
105
131
  this._replies.clear()
106
132
  this._denials.clear()
133
+ this._keys.clear()
134
+ this._inbox = null
107
135
  await Promise.allSettled(posts.map((post) => post.close()))
108
136
  }
109
137
 
@@ -113,7 +141,9 @@ export class Pairing extends ReadyResource {
113
141
  * @param {InviteOpts} [opts]
114
142
  * @returns {Promise<string>}
115
143
  */
116
- async invite({ role = MEMBER, ttl = 0, reuse = false, confirm = false, data = null } = {}) {
144
+ async invite(opts = {}) {
145
+ if (!isOptions(opts)) throw CeroError.INVALID('invite options are an object')
146
+ const { role = MEMBER, ttl = 0, reuse = false, confirm = false, data = null } = opts
117
147
  if (this.closing || this.closed) throw CeroError.CLOSED('Pairing')
118
148
  if (!this.opened) await this.ready()
119
149
  // an invite is a capability: capped at our own rank, or apply would drop the mismatch silently
@@ -123,24 +153,38 @@ export class Pairing extends ReadyResource {
123
153
  throw CeroError.INVALID(`a reusable invite admits at most member, not '${role}'`)
124
154
  }
125
155
 
126
- const invite = Invite.create({ ttl, data, key: this.db.key, address: this.db.address })
127
- await this.db.call('add-invite', {
156
+ const secret = await this._secret()
157
+ const address = secret ? Mailbox.getAddress(secret) : this.db.address
158
+ const invite = Invite.create({ ttl, data, key: this.db.key, address, own: !!secret })
159
+ const row = {
128
160
  id: b4a.toHex(invite.id),
129
161
  role,
130
162
  reuse,
131
163
  confirm,
132
164
  expires: invite.expires,
133
- createdAt: Date.now()
134
- })
165
+ createdAt: Date.now(),
166
+ secret
167
+ }
168
+ invite.stamp = await this.db.write([['add-invite', row]])
169
+ if (secret || invite.stamp > this.db.start) invite.version = STAMPED
135
170
  invite.link = { key: this.db.writerKey, length: this.db.length }
136
171
  await this._sync()
137
172
  return invite.toString()
138
173
  }
139
174
 
175
+ // an invite's own address needs its secret on its row: none where the built spec has no such
176
+ // field, or the database's version has not reached it, and the invite carries the room's address
177
+ /** @private */
178
+ async _secret() {
179
+ const since = this.db.meta.since?.types[`@${this.db.ns}/invite`]?.secret
180
+ const version = await this.db.dispatcher.version(this.db.view)
181
+ return since <= version ? crypto.randomBytes(32) : null
182
+ }
183
+
140
184
  /**
141
185
  * Revoke an invite, for every member. Needs the remove permission.
142
186
  *
143
- * @param {string} invite
187
+ * @param {string} invite The code, or the id its `invites` row holds.
144
188
  * @returns {Promise<boolean>} Whether it was live.
145
189
  */
146
190
  async revoke(invite) {
@@ -151,7 +195,7 @@ export class Pairing extends ReadyResource {
151
195
  if (me && !can(me.role, REMOVE)) {
152
196
  throw CeroError.DENIED(null, 'revoking an invite needs the remove permission')
153
197
  }
154
- const id = getInviteId(invite)
198
+ const id = (await this.db.get('invites', invite)).data ? invite : getInviteId(invite)
155
199
  if (!id || !(await this.db.get('invites', id)).data) return false
156
200
  await this.db.call('del-invite', { id })
157
201
  await this._sync()
@@ -182,13 +226,16 @@ export class Pairing extends ReadyResource {
182
226
 
183
227
  /**
184
228
  * Refuse a join waiting on a `confirm` invite, by its id in `requests`, with an optional reason.
229
+ * On a join already let in by a promise, it withdraws the promise: that needs the remove
230
+ * permission.
185
231
  *
186
232
  * @param {string} id
187
233
  * @param {string} [reason]
188
234
  * @returns {Promise<void>}
189
235
  */
190
236
  async deny(id, reason = '') {
191
- await this._waiting(id)
237
+ const { data: row } = await this.db.get('requests', id)
238
+ if (!row?.promised) await this._waiting(id)
192
239
  await this.db.call('deny', { id, reason })
193
240
  }
194
241
 
@@ -211,27 +258,66 @@ export class Pairing extends ReadyResource {
211
258
  const spent = await this._list(SPENT)
212
259
  if (this.closing || this.closed) return
213
260
  const role = me?.role
214
- // apply has no clock: past its expiry an invite is dropped here, so the log stops admitting,
215
- // and a spent one forgotten, since no joiner uses it past then
261
+ // behind, this device's view of the room is stale: it answers no join until it updates
262
+ const inviter = can(role, INVITE) && this.db.behind === null
263
+ // a promise is settled here once it is kept or void, never by a read of its keys
264
+ const done = inviter ? await this._done(requests) : []
265
+ for (const { id } of done) await this.db.call('del-request', { id }).catch(safetyCatch)
266
+ // apply has no clock: past its invite, a promise nobody kept is withdrawn here
267
+ if (inviter && can(role, REMOVE)) {
268
+ for (const row of requests) {
269
+ if (!row.promised || !expired(row)) continue
270
+ await this.db.call('deny', { id: row.id, reason: 'expired' }).catch(safetyCatch)
271
+ }
272
+ }
273
+ // past its expiry an invite is dropped, so the log stops admitting, and a spent one
274
+ // forgotten, since no joiner uses it past then
216
275
  if (can(role, REMOVE)) {
217
276
  for (const row of [...invites, ...spent].filter(expired)) {
218
277
  await this.db.call('del-invite', { id: row.id }).catch(safetyCatch)
219
278
  }
220
279
  }
221
280
  this._arm([...invites, ...requests, ...spent])
222
- const inviter = can(role, INVITE)
223
- const owed = inviter ? requests.filter((row) => row.admitted) : []
281
+ // an admission is owed its keys until they are read; a promise, until done or past its invite
282
+ const over = (row) => row.promised && (done.includes(row) || expired(row))
283
+ const owed = inviter ? requests.filter((row) => row.admitted && !over(row)) : []
224
284
  const refused = inviter ? refusals : []
225
- await this._answer(owed, refused, role)
285
+ const secrets = new Map([...invites, ...spent].map((row) => [row.id, row.secret]))
286
+ await this._answer(owed, refused, role, secrets)
287
+ await this._deliver(await this._list(ASKS))
226
288
  const live = invites.some((row) => !expired(row))
227
289
  this.serving = inviter && (live || owed.length > 0 || refused.length > 0)
228
290
  this.emit('serving', this.serving)
229
291
  }
230
292
 
293
+ // the promises kept, the device each was made to sits under the member it was made to, and
294
+ // those void, their chain standing no more as the log reads it
295
+ /** @private */
296
+ async _done(requests) {
297
+ const promised = requests.filter((row) => row.promised)
298
+ if (promised.length === 0) return []
299
+ const { data: devices } = await this.db.get('devices')
300
+ const seated = ({ identity, key }) => {
301
+ const id = hid.encode(identity)
302
+ return devices.some((d) => d.memberId === id && d.key && b4a.equals(d.key, key))
303
+ }
304
+ this.db.guard()
305
+ const { dispatcher, view } = this.db
306
+ const done = []
307
+ for (const row of promised) {
308
+ const stands = await dispatcher.stands(view, [row.identity, ...chainOf(row)])
309
+ if (!stands || seated(row)) done.push(row)
310
+ }
311
+ return done
312
+ }
313
+
231
314
  // wakes the next _sync just past the nearest expiry: expired() only holds after it
232
315
  /** @private */
233
316
  _arm(rows) {
234
317
  clearTimeout(this._expiry)
318
+ this._expiry = null
319
+ // a sync that awaited past close arms nothing: _close cleared the timer already
320
+ if (this.closing || this.closed) return
235
321
  const live = rows.filter((row) => row.expires > 0 && !expired(row))
236
322
  const next = Math.min(...live.map((row) => row.expires))
237
323
  if (!Number.isFinite(next)) return
@@ -242,14 +328,17 @@ export class Pairing extends ReadyResource {
242
328
  }
243
329
 
244
330
  // an admitted joiner is offered its keys, and a refused one the reason, by every inviter device
245
- // online, until one is read. Past the invite's expiry the joiner has given up: a member who can
246
- // remove drops an admitted one instead, and a refused one is forgotten
331
+ // online, until one is read. Past the invite's expiry the joiner has given up: the answer owed to
332
+ // an extra device of a member is dropped, a member who can remove drops a new one, and a refused
333
+ // one is forgotten. A promised joiner is offered its keys until its device has seated itself: a
334
+ // read settles nothing. An answer under an invite that has a secret is tagged with it
247
335
  /** @private */
248
- async _answer(owed, refused, role) {
249
- // a device linked under a member reads its chain off its row
336
+ async _answer(owed, refused, role, secrets) {
337
+ // a device linked under a member reads its chain off its seat, or off the promise of one
250
338
  const proofs = new Map()
251
- for (const { id } of owed) {
252
- proofs.set(id, (await this.db.get('devices', id)).data?.proof ?? null)
339
+ for (const { id, promised, proof } of owed) {
340
+ const chain = promised ? linkOf(proof) : (await this.db.get('devices', id)).data?.proof
341
+ proofs.set(id, chain ?? null)
253
342
  }
254
343
  const keys = ({ id }) => ({
255
344
  status: STATUS_ACCEPTED,
@@ -266,28 +355,107 @@ export class Pairing extends ReadyResource {
266
355
  encryptionKey: null,
267
356
  epochs: null
268
357
  })
269
- for (const row of this._offer(this._replies, owed, keys, 'del-request')) {
270
- if (!can(role, REMOVE)) continue
271
- await this.db.call('del-member', { id: hid.encode(row.identity) }).catch(safetyCatch)
358
+ const sealed = (answer) => (row) => seal(answer(row), secrets.get(row.invite), row.reply)
359
+ // only a device that read its keys covers another: unread ones would keep each other in
360
+ const unread = new Map(owed.map((row) => [row.id, row]))
361
+ for (const row of this._offer(this._replies, owed, sealed(keys), 'del-request')) {
362
+ const id = hid.encode(row.identity)
363
+ const { data: devices } = await this.db.get('devices')
364
+ const others = devices.filter((d) => d.memberId === id && d.id !== row.id)
365
+ if (others.some((d) => !unread.has(d.id))) {
366
+ await this.db.call('del-request', { id: row.id }).catch(safetyCatch)
367
+ } else if (others.every((d) => expired(unread.get(d.id))) && can(role, REMOVE)) {
368
+ await this.db.call('del-member', { id }).catch(safetyCatch)
369
+ }
272
370
  }
273
- for (const row of this._offer(this._denials, refused, denied, 'del-refusal')) {
371
+ for (const row of this._offer(this._denials, refused, sealed(denied), 'del-refusal')) {
274
372
  await this.db.call('del-refusal', { id: row.id }).catch(safetyCatch)
275
373
  }
276
374
  }
277
375
 
278
- // posts each live row its answer once, closes those settled elsewhere, returns those past expiry
376
+ // a device that asked for the keys it lacks is sent them by every seated device that holds any,
377
+ // inviter or not, and again once that one learns another. Nothing is settled by it: the device
378
+ // that asked closes its own row, once it opens the newest key
379
+ /** @private */
380
+ async _deliver(asks) {
381
+ // a sync that awaited past close sends and receives nothing: _close closed them already
382
+ if (this.closing || this.closed) return
383
+ const { db } = this
384
+ const me = hid.encode(db.writerKey)
385
+ const epochs = db.keyring.all()
386
+ const seats = asks.length > 0 && db.behind === null ? await this._seats() : new Set()
387
+ const sends = epochs.length > 0 && seats.has(me)
388
+ const rows = asks
389
+ .filter((row) => sends && row.id !== me && seats.has(row.id))
390
+ // offered again when what this device holds changed
391
+ .map(({ id, reply }) => ({ id, reply, invite: epochs.length, promised: true, expires: 0 }))
392
+ const keys = { status: STATUS_ACCEPTED, reason: '', key: db.key, encryptionKey: null, epochs }
393
+ const answer = c.encode(Response, keys)
394
+ const { secretKey } = db.identity.device
395
+ const sign = (row) =>
396
+ signed(answer, { room: db.key, to: hid.decode(row.id), writer: db.writerKey, secretKey })
397
+ this._offer(this._keys, rows, sign, null)
398
+
399
+ const mine = asks.some((row) => row.id === me)
400
+ if (mine && !this._inbox) {
401
+ const onkeys = (message) => this._onkeys(message)
402
+ this._inbox = this.mailbox.receive(db.keyPair.secretKey, onkeys, { keep: false })
403
+ } else if (!mine && this._inbox) {
404
+ this._inbox.close().catch(safetyCatch)
405
+ this._inbox = null
406
+ }
407
+ if (mine && !(await db.rotation.lacks())) {
408
+ await db.call('del-owed', { id: me }).catch(safetyCatch)
409
+ }
410
+ }
411
+
412
+ // the device key of a writer seated here, of a member who stands, or null
413
+ /** @private */
414
+ async _seat(writer) {
415
+ const { data: device } = await this.db.get('devices', hid.encode(writer))
416
+ if (!device?.memberId) return null
417
+ const { data: member } = await this.db.get('members', device.memberId)
418
+ return member ? device.key : null
419
+ }
420
+
421
+ // the devices of the members who stand, by id, to the device key each was admitted with
422
+ /** @private */
423
+ async _seats() {
424
+ const { data: members } = await this.db.get('members')
425
+ const { data: devices } = await this.db.get('devices')
426
+ const standing = new Set(members.map((m) => m.id))
427
+ return new Map(devices.filter((d) => standing.has(d.memberId)).map((d) => [d.id, d.key]))
428
+ }
429
+
430
+ // the keys this device asked for, signed by a device seated here: anyone with the address can
431
+ // send to it. Each secret is held to its commitment in the log and saved, and the row is closed
432
+ // once the newest opens
433
+ /** @private */
434
+ async _onkeys(message) {
435
+ const { db } = this
436
+ // one row, the sender's own: a stranger who sends to the address costs no read of every seat
437
+ const seated = message.byteLength > 32 ? await this._seat(message.subarray(0, 32)) : null
438
+ const sent = signer(message, { room: db.key, to: db.writerKey }, () => seated)
439
+ const answer = sent && decode(Response, sent.answer)
440
+ if (!answer?.epochs) return false
441
+ await db.learn(answer.epochs, hid.encode(sent.writer))
442
+ await this._sync()
443
+ }
444
+
445
+ // posts each live row its answer once, closes those settled elsewhere or made for a row since
446
+ // written again under another invite, returns those past expiry
279
447
  /** @private */
280
448
  _offer(posts, rows, answer, settled) {
281
- const live = new Set(rows.map((row) => row.id))
449
+ const live = new Map(rows.map((row) => [row.id, row.invite]))
282
450
  for (const [id, post] of posts) {
283
- if (live.has(id)) continue
451
+ if (live.has(id) && live.get(id) === post.invite) continue
284
452
  posts.delete(id)
285
453
  post.close().catch(safetyCatch)
286
454
  }
287
455
  const gone = []
288
456
  for (const row of rows) {
289
457
  if (!expired(row)) {
290
- if (!posts.has(row.id)) this._post(posts, row, answer(row), settled)
458
+ if (!posts.has(row.id)) this._post(posts, row, answer(row), row.promised ? null : settled)
291
459
  continue
292
460
  }
293
461
  // a device already offering it stops: nobody waits for it any more
@@ -300,12 +468,16 @@ export class Pairing extends ReadyResource {
300
468
 
301
469
  // kept in memory, not in the outbox: the row in the log is what outlives a restart
302
470
  /** @private */
303
- _post(posts, { id, reply }, answer, settled) {
471
+ _post(posts, { id, reply, invite }, answer, settled) {
304
472
  const { network } = this.mailbox
305
- const post = new Post(network, reply, c.encode(Response, answer), { mirrors: network.mirrors })
473
+ const post = new Post(network, reply, answer, { mirrors: network.mirrors })
474
+ // the invite its answer is tagged under
475
+ post.invite = invite
306
476
  posts.set(id, post)
307
477
  const settle = async () => {
308
478
  await post.ready()
479
+ // a promise is kept by its device's own claim: whoever reads the keys, nothing is settled
480
+ if (!settled) return
309
481
  await post.delivered
310
482
  await this.db.call(settled, { id })
311
483
  }
@@ -314,6 +486,8 @@ export class Pairing extends ReadyResource {
314
486
 
315
487
  /** @private */
316
488
  _list(name) {
489
+ // a sync still running once its database closed ends as closed, as its other reads do
490
+ this.db.guard()
317
491
  return this.db.view.find(`@${this.db.ns}/${name}`, {}).toArray()
318
492
  }
319
493
 
@@ -364,6 +538,12 @@ export class Pairing extends ReadyResource {
364
538
  }
365
539
  const parsed = Invite.parse(invite)
366
540
  if (parsed.expired) throw CeroError.EXPIRED()
541
+ // an invite with its own address proves its answers: one without a valid tag is nobody's
542
+ const mine = parsed.own ? Mailbox.keyPair(writer.secretKey) : null
543
+ // an invite with no stamp was minted before invites carried one: at the start
544
+ const { version = 1, start = 1 } = spec.meta || {}
545
+ const stamp = parsed.stamp || start
546
+ if (stamp > version) throw CeroError.BEHIND(stamp)
367
547
  if (mailbox.closing || mailbox.closed) throw CeroError.CLOSED('join')
368
548
  if (!mailbox.opened) await mailbox.ready()
369
549
 
@@ -372,17 +552,36 @@ export class Pairing extends ReadyResource {
372
552
  resolve = res
373
553
  fail = rej
374
554
  })
555
+ let settling = false
556
+ let expired = false
375
557
  const settle = async (answer, done) => {
376
- await keep(answer)
558
+ settling = true
559
+ try {
560
+ await keep(answer)
561
+ } catch (err) {
562
+ settling = false
563
+ if (expired) stop(CeroError.EXPIRED())
564
+ throw err
565
+ }
377
566
  done(answer)
378
567
  }
568
+ // anything else sealed to the reply address, a second answer too, is turned away: the inbox
569
+ // keeps no row of it, and its core only when it was read back from a row kept across a restart
379
570
  const onreply = async (message) => {
380
- const response = decode(Response, message)
571
+ if (settling) return false
572
+ const answer = mine ? proven(message, mine.secretKey, parsed.address) : message
573
+ const response = answer && decode(Response, answer)
381
574
  if (response?.status === STATUS_DENIED) {
382
575
  await settle(CeroError.DENIED(response.reason || null), fail)
383
- } else if (response?.key && b4a.equals(response.key, parsed.key)) {
576
+ } else if (
577
+ response?.key &&
578
+ b4a.equals(response.key, parsed.key) &&
579
+ (mine || owns(response, parsed))
580
+ ) {
384
581
  const { key, encryptionKey, epochs, proof = null } = response
385
582
  await settle({ key, encryptionKey, epochs: epochs || [], writer, proof }, resolve)
583
+ } else {
584
+ return false
386
585
  }
387
586
  }
388
587
 
@@ -393,20 +592,32 @@ export class Pairing extends ReadyResource {
393
592
  keyPair: writer,
394
593
  manifest: { version: store.manifestVersion, signers: [{ publicKey: writer.publicKey }] }
395
594
  })
396
- const inbox = mailbox.receive(writer.secretKey, onreply)
595
+ // a reply read no longer than the join waits for it
596
+ const reads = timeout > 0 ? { timeout: Math.min(timeout, 30000) } : {}
597
+ const inbox = mailbox.receive(writer.secretKey, onreply, { keep: false, ...reads })
397
598
  // the database pulls the join in like any optimistic append, from us or from a mirror
398
599
  const post = new Post(network, parsed.key, null, { core, mirrors: network.mirrors })
399
600
 
400
- const onabort = () => fail(CeroError.CLOSED('join'))
601
+ // its inbox closes the moment it stops, so one that joins again at once with this writer waits for the row
602
+ // a reply being read may yet leave
603
+ const stop = (err) => {
604
+ inbox.close().catch(safetyCatch)
605
+ fail(err)
606
+ }
607
+ const onabort = () => stop(CeroError.CLOSED('join'))
401
608
  if (signal?.aborted) onabort()
402
609
  signal?.addEventListener('abort', onabort)
403
610
  mailbox.once('close', onabort)
404
- const timer = timeout > 0 ? setTimeout(() => fail(CeroError.TIMEOUT('join')), timeout) : null
611
+ const timer = timeout > 0 ? setTimeout(() => stop(CeroError.TIMEOUT('join')), timeout) : null
612
+ // a reply being kept as the invite runs out settles the join: the device it answers is let in
613
+ const expire = () => {
614
+ expired = true
615
+ if (!settling) stop(CeroError.EXPIRED())
616
+ }
405
617
  const left = parsed.expires - Date.now()
406
618
  // Node's setTimeout overflows past ~24.8 days: a longer ttl expires at the next resume
407
- const expiry =
408
- parsed.expires && left < MAX_DELAY ? setTimeout(() => fail(CeroError.EXPIRED()), left) : null
409
- write(core, spec, parsed, identity, writer)
619
+ const expiry = parsed.expires && left < MAX_DELAY ? setTimeout(expire, left) : null
620
+ write(core, spec, stamp, parsed, identity, writer)
410
621
  .then(() => post.ready())
411
622
  .catch((err) => fail(CeroError.NETWORK_ERROR(err.message)))
412
623
  try {
@@ -419,18 +630,73 @@ export class Pairing extends ReadyResource {
419
630
  await Promise.allSettled([inbox.close(), post.close()])
420
631
  }
421
632
  }
633
+
634
+ /**
635
+ * Take back a join that waits for a member: the writer's own core says so after its join, and
636
+ * the database drops the request unless a member let it in first. Announced as the join was.
637
+ * Called again with the same writer, it announces the cancel already written.
638
+ *
639
+ * @param {Mailbox} mailbox
640
+ * @param {string} invite
641
+ * @param {{ spec: JoinOpts['spec'], writer: KeyPair }} opts The writer that joined.
642
+ * @returns {Promise<void>} Resolves once a peer or a mirror holds it, rejects `CLOSED` when the mailbox closes first.
643
+ */
644
+ static async cancel(mailbox, invite, { spec, writer }) {
645
+ if (mailbox.closing || mailbox.closed) throw CeroError.CLOSED('cancel')
646
+ const { network } = mailbox
647
+ const { store } = network
648
+ let onclose = null
649
+ const closed = new Promise((resolve, reject) => {
650
+ onclose = () => reject(CeroError.CLOSED('cancel'))
651
+ })
652
+ closed.catch(safetyCatch)
653
+ mailbox.once('close', onclose)
654
+ const core = store.get({
655
+ keyPair: writer,
656
+ manifest: { version: store.manifestVersion, signers: [{ publicKey: writer.publicKey }] }
657
+ })
658
+ let post = null
659
+ try {
660
+ await core.ready()
661
+ // a writer that wrote no join has nothing to take back
662
+ if (core.length === 0) return
663
+ // stamped as the join was: a room older than the cancel skips it on every build, and none
664
+ // of its devices is put behind
665
+ const { ns = NAMESPACE, start = 1, encoding } = spec.meta || {}
666
+ const parsed = Invite.parse(invite)
667
+ const stamp = parsed.stamp || start
668
+ const id = hid.encode(core.key)
669
+ let appending = cancels.get(id)
670
+ if (!appending) {
671
+ const body = spec.dispatch.encode(
672
+ `@${ns}/cancel-join`,
673
+ { id },
674
+ { version: encoding?.[stamp] }
675
+ )
676
+ appending = retract(core, wrap(stamp, body)).finally(() => cancels.delete(id))
677
+ cancels.set(id, appending)
678
+ }
679
+ await appending
680
+ post = new Post(network, parsed.key, null, { core, mirrors: network.mirrors })
681
+ await Promise.race([post.ready().then(() => post.delivered), closed])
682
+ } finally {
683
+ mailbox.off('close', onclose)
684
+ await (post || core).close().catch(safetyCatch)
685
+ }
686
+ }
422
687
  }
423
688
 
424
689
  /**
425
- * A join's payload: sealed to the database's address, so only its members read who joins; proven
426
- * by the invite over the writer; signed by the joiner's device, under its chain to the identity,
427
- * for this writer and reply address.
690
+ * A join's payload: sealed to the invite's address, so only those who hold its row read who joins,
691
+ * every member for an invite that carries the database's address; proven by the invite over the
692
+ * writer; signed by the joiner's device, under its chain to the identity, for this writer and reply
693
+ * address. An invite with an address of its own is named in the clear, so apply finds its secret.
428
694
  *
429
695
  * @param {Invite} invite
430
696
  * @param {import('../identity/index.js').Identity} identity
431
697
  * @param {Uint8Array} writer
432
698
  * @param {Uint8Array} reply
433
- * @returns {{ box: Uint8Array }}
699
+ * @returns {{ box: Uint8Array, invite?: Uint8Array }}
434
700
  */
435
701
  export function sealJoin(invite, identity, writer, reply) {
436
702
  const join = {
@@ -440,24 +706,48 @@ export function sealJoin(invite, identity, writer, reply) {
440
706
  proof: identity.sign(joining(invite.key, invite.id, writer, reply)),
441
707
  ts: Date.now()
442
708
  }
443
- return { box: crypto.encrypt(c.encode(Join, join), invite.address) }
709
+ const box = crypto.encrypt(c.encode(Join, join), invite.address)
710
+ return invite.own ? { box, invite: invite.id } : { box }
711
+ }
712
+
713
+ // the cancel being appended, by writer: two at once on one writer append it once
714
+ const cancels = new Map()
715
+
716
+ async function retract(core, op) {
717
+ const at = await core.getUserData('cero/cancel')
718
+ if (at && c.decode(c.uint, at) === core.length) return
719
+ await core.append(Autobee.encodeValue(op, { optimistic: true, encrypted: true }))
720
+ await core.setUserData('cero/cancel', c.encode(c.uint, core.length))
444
721
  }
445
722
 
446
723
  // one join per invite in the writer's core: a resumed join finds its own, a fresh invite adds
447
724
  // another. Plain, since the joiner has no key yet, and linked to the invite's node, so no member
448
- // applies it before the invite
449
- async function write(core, spec, invite, identity, writer) {
725
+ // applies it before the invite. Written as of its invite's stamp
726
+ async function write(core, spec, stamp, invite, identity, writer) {
450
727
  await core.ready()
451
728
  const last = await core.getUserData('cero/join')
452
729
  if (last && b4a.equals(last, invite.id)) return
453
- const { ns = NAMESPACE, version = 1 } = spec.meta || {}
730
+ const { ns = NAMESPACE, encoding } = spec.meta || {}
454
731
  const payload = sealJoin(invite, identity, core.key, Mailbox.getAddress(writer.secretKey))
455
- const op = wrap(version, spec.dispatch.encode(`@${ns}/join`, payload))
732
+ const body = spec.dispatch.encode(`@${ns}/join`, payload, { version: encoding?.[stamp] })
733
+ const op = wrap(stamp, body)
456
734
  const links = [invite.link]
457
735
  await core.append(Autobee.encodeValue(op, { optimistic: true, encrypted: true, links }))
458
736
  await core.setUserData('cero/join', invite.id)
459
737
  }
460
738
 
739
+ // the database key is no secret, every mirror holds it: the encryption key must own the invite's address
740
+ function owns({ encryptionKey }, invite) {
741
+ return !!encryptionKey && b4a.equals(Mailbox.getAddress(encryptionKey), invite.address)
742
+ }
743
+
744
+ // an answer under an invite with a secret follows the tag it makes with the reply address
745
+ function seal(answer, secret, reply) {
746
+ const message = c.encode(Response, answer)
747
+ const proof = secret ? tag(message, Mailbox.keyPair(secret).secretKey, reply) : null
748
+ return proof ? b4a.concat([proof, message]) : message
749
+ }
750
+
461
751
  function expired({ expires }) {
462
752
  return expires > 0 && Date.now() > expires
463
753
  }