@cero-base/core 2.12.0 → 3.0.1

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 +803 -204
  6. package/src/database/encryption.js +25 -21
  7. package/src/database/index.js +720 -123
  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 +343 -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 +51 -7
  26. package/types/database/encryption.d.ts +13 -5
  27. package/types/database/index.d.ts +190 -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,16 +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
128
  this._expiry = null
105
- const posts = [...this._replies.values(), ...this._denials.values()]
129
+ const posts = [...this._replies.values(), ...this._denials.values(), ...this._keys.values()]
130
+ if (this._inbox) posts.push(this._inbox)
106
131
  this._replies.clear()
107
132
  this._denials.clear()
133
+ this._keys.clear()
134
+ this._inbox = null
108
135
  await Promise.allSettled(posts.map((post) => post.close()))
109
136
  }
110
137
 
@@ -114,7 +141,9 @@ export class Pairing extends ReadyResource {
114
141
  * @param {InviteOpts} [opts]
115
142
  * @returns {Promise<string>}
116
143
  */
117
- 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
118
147
  if (this.closing || this.closed) throw CeroError.CLOSED('Pairing')
119
148
  if (!this.opened) await this.ready()
120
149
  // an invite is a capability: capped at our own rank, or apply would drop the mismatch silently
@@ -124,24 +153,38 @@ export class Pairing extends ReadyResource {
124
153
  throw CeroError.INVALID(`a reusable invite admits at most member, not '${role}'`)
125
154
  }
126
155
 
127
- const invite = Invite.create({ ttl, data, key: this.db.key, address: this.db.address })
128
- 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 = {
129
160
  id: b4a.toHex(invite.id),
130
161
  role,
131
162
  reuse,
132
163
  confirm,
133
164
  expires: invite.expires,
134
- createdAt: Date.now()
135
- })
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
136
170
  invite.link = { key: this.db.writerKey, length: this.db.length }
137
171
  await this._sync()
138
172
  return invite.toString()
139
173
  }
140
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
+
141
184
  /**
142
185
  * Revoke an invite, for every member. Needs the remove permission.
143
186
  *
144
- * @param {string} invite
187
+ * @param {string} invite The code, or the id its `invites` row holds.
145
188
  * @returns {Promise<boolean>} Whether it was live.
146
189
  */
147
190
  async revoke(invite) {
@@ -152,7 +195,7 @@ export class Pairing extends ReadyResource {
152
195
  if (me && !can(me.role, REMOVE)) {
153
196
  throw CeroError.DENIED(null, 'revoking an invite needs the remove permission')
154
197
  }
155
- const id = getInviteId(invite)
198
+ const id = (await this.db.get('invites', invite)).data ? invite : getInviteId(invite)
156
199
  if (!id || !(await this.db.get('invites', id)).data) return false
157
200
  await this.db.call('del-invite', { id })
158
201
  await this._sync()
@@ -183,13 +226,16 @@ export class Pairing extends ReadyResource {
183
226
 
184
227
  /**
185
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.
186
231
  *
187
232
  * @param {string} id
188
233
  * @param {string} [reason]
189
234
  * @returns {Promise<void>}
190
235
  */
191
236
  async deny(id, reason = '') {
192
- await this._waiting(id)
237
+ const { data: row } = await this.db.get('requests', id)
238
+ if (!row?.promised) await this._waiting(id)
193
239
  await this.db.call('deny', { id, reason })
194
240
  }
195
241
 
@@ -212,23 +258,59 @@ export class Pairing extends ReadyResource {
212
258
  const spent = await this._list(SPENT)
213
259
  if (this.closing || this.closed) return
214
260
  const role = me?.role
215
- // apply has no clock: past its expiry an invite is dropped here, so the log stops admitting,
216
- // 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
217
275
  if (can(role, REMOVE)) {
218
276
  for (const row of [...invites, ...spent].filter(expired)) {
219
277
  await this.db.call('del-invite', { id: row.id }).catch(safetyCatch)
220
278
  }
221
279
  }
222
280
  this._arm([...invites, ...requests, ...spent])
223
- const inviter = can(role, INVITE)
224
- 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)) : []
225
284
  const refused = inviter ? refusals : []
226
- 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))
227
288
  const live = invites.some((row) => !expired(row))
228
289
  this.serving = inviter && (live || owed.length > 0 || refused.length > 0)
229
290
  this.emit('serving', this.serving)
230
291
  }
231
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
+
232
314
  // wakes the next _sync just past the nearest expiry: expired() only holds after it
233
315
  /** @private */
234
316
  _arm(rows) {
@@ -246,14 +328,17 @@ export class Pairing extends ReadyResource {
246
328
  }
247
329
 
248
330
  // an admitted joiner is offered its keys, and a refused one the reason, by every inviter device
249
- // online, until one is read. Past the invite's expiry the joiner has given up: a member who can
250
- // 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
251
335
  /** @private */
252
- async _answer(owed, refused, role) {
253
- // 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
254
338
  const proofs = new Map()
255
- for (const { id } of owed) {
256
- 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)
257
342
  }
258
343
  const keys = ({ id }) => ({
259
344
  status: STATUS_ACCEPTED,
@@ -270,28 +355,107 @@ export class Pairing extends ReadyResource {
270
355
  encryptionKey: null,
271
356
  epochs: null
272
357
  })
273
- for (const row of this._offer(this._replies, owed, keys, 'del-request')) {
274
- if (!can(role, REMOVE)) continue
275
- 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
+ }
276
370
  }
277
- 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')) {
278
372
  await this.db.call('del-refusal', { id: row.id }).catch(safetyCatch)
279
373
  }
280
374
  }
281
375
 
282
- // 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
283
447
  /** @private */
284
448
  _offer(posts, rows, answer, settled) {
285
- const live = new Set(rows.map((row) => row.id))
449
+ const live = new Map(rows.map((row) => [row.id, row.invite]))
286
450
  for (const [id, post] of posts) {
287
- if (live.has(id)) continue
451
+ if (live.has(id) && live.get(id) === post.invite) continue
288
452
  posts.delete(id)
289
453
  post.close().catch(safetyCatch)
290
454
  }
291
455
  const gone = []
292
456
  for (const row of rows) {
293
457
  if (!expired(row)) {
294
- 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)
295
459
  continue
296
460
  }
297
461
  // a device already offering it stops: nobody waits for it any more
@@ -304,12 +468,16 @@ export class Pairing extends ReadyResource {
304
468
 
305
469
  // kept in memory, not in the outbox: the row in the log is what outlives a restart
306
470
  /** @private */
307
- _post(posts, { id, reply }, answer, settled) {
471
+ _post(posts, { id, reply, invite }, answer, settled) {
308
472
  const { network } = this.mailbox
309
- 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
310
476
  posts.set(id, post)
311
477
  const settle = async () => {
312
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
313
481
  await post.delivered
314
482
  await this.db.call(settled, { id })
315
483
  }
@@ -318,6 +486,8 @@ export class Pairing extends ReadyResource {
318
486
 
319
487
  /** @private */
320
488
  _list(name) {
489
+ // a sync still running once its database closed ends as closed, as its other reads do
490
+ this.db.guard()
321
491
  return this.db.view.find(`@${this.db.ns}/${name}`, {}).toArray()
322
492
  }
323
493
 
@@ -368,6 +538,12 @@ export class Pairing extends ReadyResource {
368
538
  }
369
539
  const parsed = Invite.parse(invite)
370
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)
371
547
  if (mailbox.closing || mailbox.closed) throw CeroError.CLOSED('join')
372
548
  if (!mailbox.opened) await mailbox.ready()
373
549
 
@@ -376,17 +552,36 @@ export class Pairing extends ReadyResource {
376
552
  resolve = res
377
553
  fail = rej
378
554
  })
555
+ let settling = false
556
+ let expired = false
379
557
  const settle = async (answer, done) => {
380
- 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
+ }
381
566
  done(answer)
382
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
383
570
  const onreply = async (message) => {
384
- 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)
385
574
  if (response?.status === STATUS_DENIED) {
386
575
  await settle(CeroError.DENIED(response.reason || null), fail)
387
- } 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
+ ) {
388
581
  const { key, encryptionKey, epochs, proof = null } = response
389
582
  await settle({ key, encryptionKey, epochs: epochs || [], writer, proof }, resolve)
583
+ } else {
584
+ return false
390
585
  }
391
586
  }
392
587
 
@@ -397,20 +592,32 @@ export class Pairing extends ReadyResource {
397
592
  keyPair: writer,
398
593
  manifest: { version: store.manifestVersion, signers: [{ publicKey: writer.publicKey }] }
399
594
  })
400
- 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 })
401
598
  // the database pulls the join in like any optimistic append, from us or from a mirror
402
599
  const post = new Post(network, parsed.key, null, { core, mirrors: network.mirrors })
403
600
 
404
- 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'))
405
608
  if (signal?.aborted) onabort()
406
609
  signal?.addEventListener('abort', onabort)
407
610
  mailbox.once('close', onabort)
408
- 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
+ }
409
617
  const left = parsed.expires - Date.now()
410
618
  // Node's setTimeout overflows past ~24.8 days: a longer ttl expires at the next resume
411
- const expiry =
412
- parsed.expires && left < MAX_DELAY ? setTimeout(() => fail(CeroError.EXPIRED()), left) : null
413
- 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)
414
621
  .then(() => post.ready())
415
622
  .catch((err) => fail(CeroError.NETWORK_ERROR(err.message)))
416
623
  try {
@@ -423,18 +630,73 @@ export class Pairing extends ReadyResource {
423
630
  await Promise.allSettled([inbox.close(), post.close()])
424
631
  }
425
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
+ }
426
687
  }
427
688
 
428
689
  /**
429
- * A join's payload: sealed to the database's address, so only its members read who joins; proven
430
- * by the invite over the writer; signed by the joiner's device, under its chain to the identity,
431
- * 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.
432
694
  *
433
695
  * @param {Invite} invite
434
696
  * @param {import('../identity/index.js').Identity} identity
435
697
  * @param {Uint8Array} writer
436
698
  * @param {Uint8Array} reply
437
- * @returns {{ box: Uint8Array }}
699
+ * @returns {{ box: Uint8Array, invite?: Uint8Array }}
438
700
  */
439
701
  export function sealJoin(invite, identity, writer, reply) {
440
702
  const join = {
@@ -444,24 +706,48 @@ export function sealJoin(invite, identity, writer, reply) {
444
706
  proof: identity.sign(joining(invite.key, invite.id, writer, reply)),
445
707
  ts: Date.now()
446
708
  }
447
- 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))
448
721
  }
449
722
 
450
723
  // one join per invite in the writer's core: a resumed join finds its own, a fresh invite adds
451
724
  // another. Plain, since the joiner has no key yet, and linked to the invite's node, so no member
452
- // applies it before the invite
453
- 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) {
454
727
  await core.ready()
455
728
  const last = await core.getUserData('cero/join')
456
729
  if (last && b4a.equals(last, invite.id)) return
457
- const { ns = NAMESPACE, version = 1 } = spec.meta || {}
730
+ const { ns = NAMESPACE, encoding } = spec.meta || {}
458
731
  const payload = sealJoin(invite, identity, core.key, Mailbox.getAddress(writer.secretKey))
459
- 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)
460
734
  const links = [invite.link]
461
735
  await core.append(Autobee.encodeValue(op, { optimistic: true, encrypted: true, links }))
462
736
  await core.setUserData('cero/join', invite.id)
463
737
  }
464
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
+
465
751
  function expired({ expires }) {
466
752
  return expires > 0 && Date.now() > expires
467
753
  }