@cero-base/core 2.2.0 → 2.3.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 (55) hide show
  1. package/README.md +32 -212
  2. package/package.json +19 -10
  3. package/src/blobs/index.js +9 -0
  4. package/src/blobs/server.js +2 -0
  5. package/src/database/changes.js +1 -1
  6. package/src/database/dispatch.js +341 -209
  7. package/src/database/encryption.js +83 -33
  8. package/src/database/index.js +184 -83
  9. package/src/database/rotation.js +43 -30
  10. package/src/identity/index.js +20 -78
  11. package/src/index.js +3 -10
  12. package/src/lib/constants.js +2 -0
  13. package/src/lib/errors.js +3 -11
  14. package/src/lib/spec/index.js +136 -132
  15. package/src/lib/spec/schema.json +84 -99
  16. package/src/lib/utils.js +57 -3
  17. package/src/mailbox/inbox.js +103 -0
  18. package/src/mailbox/index.js +146 -0
  19. package/src/mailbox/post.js +69 -0
  20. package/src/network/discovery.js +26 -1
  21. package/src/network/index.js +105 -64
  22. package/src/network/presence.js +6 -2
  23. package/src/pairing/index.js +330 -254
  24. package/src/pairing/invite.js +83 -144
  25. package/src/pairing/request.js +54 -56
  26. package/src/rpc/index.js +18 -93
  27. package/src/rpc/peer.js +4 -1
  28. package/src/storage/index.js +78 -39
  29. package/types/blobs/index.d.ts +22 -9
  30. package/types/blobs/server.d.ts +4 -2
  31. package/types/database/changes.d.ts +2 -2
  32. package/types/database/dispatch.d.ts +19 -13
  33. package/types/database/encryption.d.ts +67 -29
  34. package/types/database/index.d.ts +144 -119
  35. package/types/database/rotation.d.ts +32 -13
  36. package/types/identity/index.d.ts +6 -47
  37. package/types/index.d.ts +3 -16
  38. package/types/lib/constants.d.ts +1 -0
  39. package/types/lib/errors.d.ts +3 -9
  40. package/types/lib/spec/index.d.ts +52 -16
  41. package/types/lib/utils.d.ts +40 -8
  42. package/types/mailbox/inbox.d.ts +52 -0
  43. package/types/mailbox/index.d.ts +111 -0
  44. package/types/mailbox/post.d.ts +37 -0
  45. package/types/network/discovery.d.ts +21 -5
  46. package/types/network/index.d.ts +64 -48
  47. package/types/network/presence.d.ts +17 -4
  48. package/types/pairing/index.d.ts +143 -134
  49. package/types/pairing/invite.d.ts +70 -114
  50. package/types/pairing/request.d.ts +58 -98
  51. package/types/rpc/index.d.ts +26 -44
  52. package/types/rpc/peer.d.ts +10 -7
  53. package/types/storage/index.d.ts +64 -54
  54. package/src/pairing/candidate.js +0 -123
  55. package/types/pairing/candidate.d.ts +0 -36
@@ -1,341 +1,417 @@
1
- import BlindPairing from 'blind-pairing'
2
1
  import ReadyResource from 'ready-resource'
3
2
  import safetyCatch from 'safety-catch'
4
3
  import b4a from 'b4a'
5
4
  import c from 'compact-encoding'
6
- import { discoveryKey } from 'hypercore-crypto'
5
+ import crypto from 'hypercore-crypto'
6
+ import hid from 'hypercore-id-encoding'
7
+ import Autobee from 'autobee'
7
8
 
8
9
  import { Invite } from './invite.js'
9
- import { Candidate } from './candidate.js'
10
- import { Request } from './request.js'
11
- import { channelTopic } from '../network/index.js'
10
+ import { Request, Response, STATUS_ACCEPTED, STATUS_DENIED } from './request.js'
11
+ import { Mailbox } from '../mailbox/index.js'
12
+ import { Post } from '../mailbox/post.js'
13
+ import { wrap } from '../database/envelope.js'
14
+ import { getEncoding } from '../lib/spec/index.js'
12
15
  import { CeroError } from '../lib/errors.js'
16
+ import { can, grants, isRank, joining, INVITE, REMOVE } from '../lib/utils.js'
17
+ import { NAMESPACE, MEMBER } from '../lib/constants.js'
18
+
19
+ const Join = getEncoding('@cero/join')
20
+ const MAX_DELAY = 2 ** 31 - 1
13
21
 
14
22
  /**
23
+ * @typedef {{ publicKey: Uint8Array, secretKey: Uint8Array }} KeyPair
24
+ *
15
25
  * @typedef {object} PairingOpts
16
- * @property {import('../network/index.js').Network} network Network to host the BlindPairing member.
17
- * @property {import('../identity/index.js').Identity} identity Identity used to sign invites and derive the topic.
18
- * @property {Uint8Array} [topic] Optional override topic; defaults to `identity.publicKey`.
19
- * @property {boolean} [host] Register the member listener that serves invites (default `true`). Join-only pairings pass `false` — a listener is one-per-topic, so a joiner registering one collides with any concurrent join.
20
- * @property {any} [inviteEncoding] compact-encoding type for the invite payload `data`.
21
- * @property {any} [joinerEncoding] compact-encoding type for the joiner-supplied `userData`.
22
- * @property {(err: Error) => void} [onerror] Called when a background candidate fails to process.
26
+ * @property {Mailbox} mailbox The device's mailbox: replies are sent from there.
27
+ * @property {import('../database/index.js').Database} db The database the invites open. Its `invites` collection holds them, and apply admits their joins.
23
28
  *
24
- * @typedef {object} CreateInviteOpts
25
- * @property {string} [role] Role tag bound into the invite.
26
- * @property {number} [expiresIn] TTL in ms; `0`/omitted = no expiry.
27
- * @property {any} [data] Arbitrary payload (encoded via `inviteEncoding` when set).
28
- * @property {boolean} [reuse] Reusable until expiry/revoke; default `false` (consumed on first settle).
29
+ * @typedef {object} InviteOpts
30
+ * @property {string} [role] Role granted, at most your own. Member by default.
31
+ * @property {number | string} [ttl] How long it is valid: ms, or `'12h'`, `'2d'`… Never expires when omitted.
32
+ * @property {boolean} [reuse] Admit more than one joiner. Otherwise spent by the first.
33
+ * @property {boolean} [confirm] Its joins wait for a member to accept them, as requests.
34
+ * @property {Uint8Array | null} [data] The app's payload in the invite, readable before joining: `Invite.parse(invite).data`.
29
35
  *
30
36
  * @typedef {object} JoinOpts
31
- * @property {any} userData Payload sent with the candidate request. Required: blind-pairing derives the handshake token from it, so a candidate without one is never served.
32
- * @property {number} [timeout] Deadline for the handshake, in ms. Defaults to 30000.
37
+ * @property {import('../identity/index.js').Identity} identity Who joins: the member they become, and who signs the join.
38
+ * @property {{ dispatch: { encode: Function }, meta?: { ns?: string, version?: number } }} spec The database's spec: the join is one of its ops.
39
+ * @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.
40
+ * @property {number} [timeout] Deadline for the reply, in ms; `0` waits until the invite expires, or for good. Defaults to 30000.
41
+ * @property {AbortSignal} [signal] Stops the join, rejecting it with `CLOSED`, as closing the mailbox does.
33
42
  *
34
- * @typedef {{ key: Uint8Array, encryptionKey: Uint8Array | null, additional: Uint8Array | null }} JoinResult
43
+ * @typedef {object} JoinResult
44
+ * @property {Uint8Array} key
45
+ * @property {Uint8Array | null} encryptionKey
46
+ * @property {Array<{ epoch: number, stamp: number, entropy: Uint8Array }>} epochs
47
+ * @property {KeyPair} writer The writer the join admitted: open the database with it.
35
48
  */
36
49
 
37
50
  /**
38
- * Blind-pairing membership wrapper. Hosts invites, dispatches incoming candidates to the
39
- * application for accept/deny, and provides the joiner side of the handshake.
51
+ * Invites into a database. An invite is a record in the database; a joiner writes one signed
52
+ * `join` op into its own writer core and announces it to the database's peers, and apply admits
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.
57
+ * `Pairing.join` is the other side: write the join, wait for the reply.
40
58
  */
41
59
  export class Pairing extends ReadyResource {
42
60
  /** @param {PairingOpts} [opts] */
43
- constructor({
44
- network,
45
- identity,
46
- topic,
47
- host = true,
48
- inviteEncoding = null,
49
- joinerEncoding = null,
50
- onerror = (err) => console.error(err),
51
- onconsume = null
52
- } = {}) {
61
+ constructor({ mailbox, db } = {}) {
53
62
  super()
54
- if (!network) throw CeroError.REQUIRED('network')
55
- if (!identity) throw CeroError.REQUIRED('identity')
56
-
57
- this.network = network
58
- this.identity = identity
59
- this.topic = topic || identity.publicKey
60
- this.host = host
61
- this.inviteEncoding = inviteEncoding
62
- this.joinerEncoding = joinerEncoding
63
- this._onerror = onerror
64
- // fired when this instance stops serving an invite, so the owner drops its row
65
- this.onconsume = onconsume
66
-
67
- this._blind = null
68
- this._member = null
69
- this._invites = new Map() // inviteId.hex → record
70
- this._candidates = new Set() // active joiner candidates
71
- }
72
-
73
- /**
74
- * Whether the underlying blind-pairing layer is suspended.
75
- *
76
- * @returns {boolean}
77
- */
78
- get suspended() {
79
- return this._blind?.suspended === true
63
+ if (!mailbox) throw CeroError.REQUIRED('mailbox')
64
+ if (!db) throw CeroError.REQUIRED('db')
65
+
66
+ this.mailbox = mailbox
67
+ this.db = db
68
+ /** @type {Set<Request>} requests not answered yet: whoever attaches after one fired goes through these first */
69
+ 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
+ this.serving = false
72
+
73
+ /** @private */
74
+ this._requests = new Map() // writer id → Request
75
+ /** @private */
76
+ this._replies = new Map() // writer id → the Post offering its keys
77
+ /** @private */
78
+ this._expiry = null
79
+ /** @private */
80
+ this._onupdate = (touched) => {
81
+ if (['*', 'invites', 'requests', 'members'].some((name) => touched.has(name))) {
82
+ this._sync().catch(safetyCatch)
83
+ }
84
+ }
80
85
  }
81
86
 
87
+ /** @private */
82
88
  async _open() {
83
- await this.network.ready()
84
- // shared instance — one set of swarm/DHT listeners for every handle
85
- this._blind = await this.network.blind()
86
-
87
- // blind-pairing allows one member listener per discovery key
88
- if (this.host) {
89
- this._member = this._blind.addMember({
90
- // channel-scoped; the candidate hashes identically (no channel → identity)
91
- discoveryKey: channelTopic(discoveryKey(this.topic), this.network.channel),
92
- onadd: (req) => this._oncandidate(req).catch(this._onerror)
93
- })
94
- }
95
- await this.network.refreshInjected()
89
+ await this.mailbox.ready()
90
+ await this.db.ready()
91
+ await this._sync()
92
+ this.db.on('update', this._onupdate)
96
93
  }
97
94
 
95
+ /** @private */
98
96
  async _close() {
99
- for (const candidate of [...this._candidates]) candidate._fail(CeroError.CLOSED('Pairing'))
100
- this._candidates.clear()
101
-
102
- if (this._member) {
103
- await this._member.close()
104
- this._member = null
105
- }
106
- // the BlindPairing is network-owned and shared — never close it here
107
- this._blind = null
108
- this._invites.clear()
97
+ this.db.off('update', this._onupdate)
98
+ clearTimeout(this._expiry)
99
+ const posts = [...this._replies.values()]
100
+ this._replies.clear()
101
+ await Promise.allSettled(posts.map((post) => post.close()))
109
102
  }
110
103
 
111
104
  /**
112
- * Mint a new pairing invite. Returns its canonical wire form (z32 string).
105
+ * Mint an invite. Returns its wire form, a z32 string.
113
106
  *
114
- * @param {CreateInviteOpts} [opts]
107
+ * @param {InviteOpts} [opts]
115
108
  * @returns {Promise<string>}
116
109
  */
117
- async createInvite({ role = '', expiresIn = 0, data = null, reuse = false } = {}) {
110
+ async invite({ role = MEMBER, ttl = 0, reuse = false, confirm = false, data = null } = {}) {
118
111
  if (this.closing || this.closed) throw CeroError.CLOSED('Pairing')
119
- // a join-only pairing serves no invites
120
- if (!this.host) throw CeroError.INVALID('cannot create invites on a join-only Pairing')
121
112
  if (!this.opened) await this.ready()
113
+ // an invite is a capability: capped at our own rank, or apply would drop the mismatch silently
114
+ await this._checkGrant(role)
115
+ // a rank above member is handed out once
116
+ if (reuse && !grants(MEMBER, role)) {
117
+ throw CeroError.INVALID(`a reusable invite admits at most member, not '${role}'`)
118
+ }
122
119
 
123
- // the rendezvous key matches the member topic
124
- const blind = BlindPairing.createInvite(this.topic)
125
-
126
- const invite = Invite.create({
127
- secretKey: this.identity.secretKey,
128
- publicKey: this.identity.publicKey,
120
+ const invite = Invite.create({ ttl, data, key: this.db.key, address: this.db.address })
121
+ await this.db.call('add-invite', {
122
+ id: b4a.toHex(invite.id),
129
123
  role,
130
- expiresIn,
131
- data,
132
- blind: blind.invite,
133
- encoding: this.inviteEncoding
134
- })
135
-
136
- const id = b4a.toString(blind.id, 'hex')
137
- this._invites.set(id, {
138
- id: blind.id,
139
- seed: blind.seed,
140
- publicKey: blind.publicKey,
141
- invite,
142
124
  reuse,
143
- // minted here, maybe not persisted yet: syncRows must keep it
144
- local: true
125
+ confirm,
126
+ expires: invite.expires,
127
+ createdAt: Date.now()
145
128
  })
146
-
129
+ invite.link = { key: this.db.writerKey, length: this.db.length }
130
+ await this._sync()
147
131
  return invite.toString()
148
132
  }
149
133
 
150
134
  /**
151
- * Look up the in-memory record for a minted invite by its string form.
135
+ * Revoke an invite, for every member. Needs the remove permission.
152
136
  *
153
- * @param {string} inviteStr
154
- * @returns {{ id: Uint8Array, seed: Uint8Array, publicKey: Uint8Array, invite: import('./invite.js').Invite, reuse: boolean } | null}
137
+ * @param {string} invite
138
+ * @returns {Promise<boolean>} Whether it was live.
155
139
  */
156
- recordOf(inviteStr) {
157
- for (const record of this._invites.values()) {
158
- if (record.invite.toString() === inviteStr) return record
140
+ async revoke(invite) {
141
+ if (this.closing || this.closed) throw CeroError.CLOSED('Pairing')
142
+ if (!this.opened) await this.ready()
143
+ // apply refuses a revoke below REMOVE
144
+ const me = await this._me()
145
+ if (me && !can(me.role, REMOVE)) {
146
+ throw CeroError.DENIED(null, 'revoking an invite needs the remove permission')
159
147
  }
160
- return null
148
+ const id = getInviteId(invite)
149
+ if (!id || !(await this.db.get('invites', id)).data) return false
150
+ await this.db.call('del-invite', { id })
151
+ await this._sync()
152
+ return true
161
153
  }
162
154
 
163
155
  /**
164
- * Reconcile the served-invite set with persisted rows (the room's `invites` collection).
156
+ * A join waiting on a `confirm` invite, by its id in the `requests` collection.
165
157
  *
166
- * @param {Array<{ id: string, invite: Uint8Array, publicKey: Uint8Array, seed: Uint8Array, reuse?: boolean }>} rows
158
+ * @param {string} id
159
+ * @returns {Promise<Request>}
167
160
  */
168
- syncRows(rows) {
169
- const seen = new Set()
170
- for (const row of rows) {
171
- if (!row?.id || !row.invite || !row.publicKey || !row.seed) continue
172
- seen.add(row.id)
173
- const existing = this._invites.get(row.id)
174
- if (existing) {
175
- existing.local = false
176
- continue
177
- }
178
- let invite
179
- try {
180
- invite = Invite.parse(b4a.toString(row.invite))
181
- } catch {
182
- continue
183
- }
184
- if (invite.expired) continue
185
- this._invites.set(row.id, {
186
- id: b4a.from(row.id, 'hex'),
187
- seed: row.seed,
188
- publicKey: row.publicKey,
189
- invite,
190
- reuse: !!row.reuse,
191
- local: false
192
- })
193
- }
194
- for (const [id, record] of this._invites) {
195
- if (!seen.has(id) && !record.local) this._invites.delete(id)
196
- }
161
+ async request(id) {
162
+ // the row can be read before this device has caught up with it
163
+ if (!this._requests.has(id)) await this._sync()
164
+ const request = this._requests.get(id)
165
+ if (!request) throw CeroError.UNKNOWN('request', id)
166
+ return request
197
167
  }
198
168
 
199
- /**
200
- * Forget a previously-minted invite. New candidates carrying it will be
201
- * dropped silently.
202
- *
203
- * @param {string} inviteStr
204
- * @returns {boolean}
205
- */
206
- revoke(inviteStr) {
207
- for (const [id, record] of this._invites) {
208
- if (record.invite.toString() === inviteStr) {
209
- this._invites.delete(id)
210
- return true
169
+ // follow the log: the invites that ran out, the joins waiting for a member, the keys owed
170
+ /** @private */
171
+ async _sync() {
172
+ const me = await this._me()
173
+ const { data: invites } = await this.db.get('invites')
174
+ const { data: requests } = await this.db.get('requests')
175
+ if (this.closing || this.closed) return
176
+ const role = me?.role
177
+ // apply has no clock: past its expiry an invite is dropped here, so the log stops admitting
178
+ if (can(role, REMOVE)) {
179
+ for (const row of invites.filter(expired)) {
180
+ await this.db.call('del-invite', { id: row.id }).catch(safetyCatch)
211
181
  }
212
182
  }
213
- return false
183
+ this._arm([...invites, ...requests])
184
+ const inviter = can(role, INVITE)
185
+ const owed = inviter ? requests.filter((row) => row.admitted) : []
186
+ 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)
189
+ this.emit('serving', this.serving)
214
190
  }
215
191
 
216
- /**
217
- * Joiner side — start a pairing handshake against `inviteStr` and resolve
218
- * with the host's response when the host confirms.
219
- *
220
- * @param {string} inviteStr
221
- * @param {JoinOpts} [opts]
222
- * @returns {Promise<JoinResult>}
223
- */
224
- async join(inviteStr, { userData, timeout = 30000 } = {}) {
225
- if (this.closing || this.closed) throw CeroError.CLOSED('Pairing')
226
- if (!this.opened) await this.ready()
192
+ // wakes the next _sync just past the nearest expiry: expired() only holds after it
193
+ /** @private */
194
+ _arm(rows) {
195
+ clearTimeout(this._expiry)
196
+ const live = rows.filter((row) => row.expires > 0 && !expired(row))
197
+ const next = Math.min(...live.map((row) => row.expires))
198
+ if (!Number.isFinite(next)) return
199
+ this._expiry = setTimeout(
200
+ () => this._sync().catch(safetyCatch),
201
+ Math.min(next - Date.now() + 1, MAX_DELAY)
202
+ )
203
+ }
227
204
 
228
- let invite
229
- try {
230
- invite = Invite.parse(inviteStr, { encoding: this.inviteEncoding })
231
- } catch (err) {
232
- if (err instanceof CeroError) throw err
233
- throw CeroError.INVALID_INVITE(err.message)
205
+ /** @private */
206
+ _pending(rows, invites) {
207
+ const live = new Set(rows.map((row) => row.id))
208
+ // settled elsewhere: accepted or denied by another member, or its invite revoked
209
+ for (const [id, request] of this._requests) {
210
+ if (live.has(id)) continue
211
+ this._requests.delete(id)
212
+ this.pending.delete(request)
234
213
  }
214
+ for (const row of rows) {
215
+ const invite = invites.find((i) => i.id === row.invite)
216
+ if (!invite || this._requests.has(row.id)) continue
217
+ const request = new Request({ pairing: this, invite, row })
218
+ this._requests.set(row.id, request)
219
+ this.pending.add(request)
220
+ this.emit('request', request)
221
+ }
222
+ }
235
223
 
236
- if (invite.expired) throw CeroError.EXPIRED()
237
-
238
- const data = encodeUserData(userData, this.joinerEncoding)
239
- const candidate = new Candidate(this, invite, data, timeout)
240
- return candidate.start()
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
226
+ /** @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)
232
+ post.close().catch(safetyCatch)
233
+ }
234
+ for (const row of rows) {
235
+ if (!expired(row)) {
236
+ if (!this._replies.has(row.id)) this._reply(row)
237
+ continue
238
+ }
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
+ }
245
+ }
241
246
  }
242
247
 
243
- /**
244
- * Pause blind-pairing — keeps state, drops sockets. Idempotent.
245
- *
246
- * @returns {Promise<void>}
247
- */
248
- async suspend() {
249
- if (!this._blind || this.closing || this.closed) return
250
- if (this._blind.suspended) return
251
- await this._blind.suspend()
248
+ // kept in memory, not in the outbox: the admission in the log is what outlives a restart
249
+ /** @private */
250
+ _reply({ id, reply }) {
251
+ 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)
261
+ const settle = async () => {
262
+ await post.ready()
263
+ await post.delivered
264
+ await this.db.call('del-request', { id })
265
+ }
266
+ settle().catch(safetyCatch)
252
267
  }
253
268
 
254
- /**
255
- * Resume a suspended blind-pairing layer. Idempotent.
256
- *
257
- * @returns {Promise<void>}
258
- */
259
- async resume() {
260
- if (!this._blind || this.closing || this.closed) return
261
- if (!this._blind.suspended) return
262
- await this._blind.resume()
269
+ /** @private */
270
+ async _me() {
271
+ return (await this.db.get('members', this.db.identity.id)).data
263
272
  }
264
273
 
265
- async _oncandidate(req) {
266
- const id = b4a.toString(req.inviteId, 'hex')
267
- const record = this._invites.get(id)
268
- if (!record) return
269
- if (record.invite.expired) {
270
- this._invites.delete(id)
271
- this.onconsume?.(id)
272
- return
274
+ // `grants` treats an unknown role as "no", so an app role name must fail loudly
275
+ /** @private */
276
+ async _checkGrant(role) {
277
+ if (!isRank(role)) {
278
+ throw CeroError.INVALID(`role '${role}' is not a rank (owner, admin, member, reader)`)
273
279
  }
274
-
275
- try {
276
- req.open(record.publicKey)
277
- } catch (err) {
278
- this._onerror(err)
279
- return
280
+ const me = await this._me()
281
+ // no member row yet = genesis, nothing to cap
282
+ if (me && !grants(me.role, role)) {
283
+ throw CeroError.DENIED(null, `role '${role}' exceeds your own role '${me.role}'`)
280
284
  }
281
-
282
- const userData = decodeUserData(req.userData, this.joinerEncoding)
283
-
284
- const request = new Request({
285
- pairing: this,
286
- req,
287
- invite: record.invite,
288
- seed: record.seed,
289
- userData,
290
- onsettle: () => {
291
- if (!record.reuse) {
292
- this._invites.delete(id)
293
- this.onconsume?.(id)
294
- }
295
- }
296
- })
297
-
298
- this.emit('candidate', request)
299
285
  }
300
286
 
301
287
  /**
302
- * Resolve the resource discovery key an invite targets — without pairing.
288
+ * Join with an invite: write the join into the writer's own core, announce it to the
289
+ * database's peers, and resolve with the database's keys once a member replies.
303
290
  *
291
+ * @param {Mailbox} mailbox
304
292
  * @param {string} invite
305
- * @returns {Uint8Array | null}
293
+ * @param {JoinOpts} opts
294
+ * @returns {Promise<JoinResult>}
306
295
  */
307
- static inviteTopic(invite) {
296
+ static async join(
297
+ mailbox,
298
+ invite,
299
+ { identity, spec, writer = crypto.keyPair(), timeout = 30000, signal = null } = {}
300
+ ) {
301
+ if (!mailbox) throw CeroError.REQUIRED('mailbox')
302
+ if (typeof identity?.sign !== 'function') throw CeroError.REQUIRED('identity')
303
+ if (!spec?.dispatch) throw CeroError.REQUIRED('spec')
304
+ if (writer?.publicKey?.byteLength !== 32 || writer.secretKey?.byteLength !== 64) {
305
+ throw CeroError.INVALID('writer must be a keypair')
306
+ }
307
+ const parsed = Invite.parse(invite)
308
+ if (parsed.expired) throw CeroError.EXPIRED()
309
+ if (mailbox.closing || mailbox.closed) throw CeroError.CLOSED('join')
310
+ if (!mailbox.opened) await mailbox.ready()
311
+
312
+ let resolve, fail
313
+ const answered = new Promise((res, rej) => {
314
+ resolve = res
315
+ fail = rej
316
+ })
317
+ const onreply = (message) => {
318
+ const response = decode(Response, message)
319
+ if (response?.status === STATUS_DENIED) fail(CeroError.DENIED(response.reason || null))
320
+ else if (response?.key && b4a.equals(response.key, parsed.key)) {
321
+ const { key, encryptionKey, epochs } = response
322
+ resolve({ key, encryptionKey, epochs: epochs || [], writer })
323
+ }
324
+ }
325
+
326
+ // in the network's store, which every connection replicates: open the database from it
327
+ const { network } = mailbox
328
+ const { store } = network
329
+ const core = store.get({
330
+ keyPair: writer,
331
+ manifest: { version: store.manifestVersion, signers: [{ publicKey: writer.publicKey }] }
332
+ })
333
+ const inbox = mailbox.receive(writer.secretKey, onreply)
334
+ // the database pulls the join in like any optimistic append, from us or from a mirror
335
+ const post = new Post(network, parsed.key, null, { core, mirrors: network.mirrors })
336
+
337
+ const onabort = () => fail(CeroError.CLOSED('join'))
338
+ if (signal?.aborted) onabort()
339
+ signal?.addEventListener('abort', onabort)
340
+ mailbox.once('close', onabort)
341
+ const timer = timeout > 0 ? setTimeout(() => fail(CeroError.TIMEOUT('join')), timeout) : null
342
+ const left = parsed.expires - Date.now()
343
+ // Node's setTimeout overflows past ~24.8 days: a longer ttl expires at the next resume
344
+ const expiry =
345
+ parsed.expires && left < MAX_DELAY ? setTimeout(() => fail(CeroError.EXPIRED()), left) : null
346
+ write(core, spec, parsed, identity, writer)
347
+ .then(() => post.ready())
348
+ .catch((err) => fail(CeroError.NETWORK_ERROR(err.message)))
308
349
  try {
309
- return Invite.parse(invite).discoveryKey
310
- } catch {
311
- return null
350
+ return await answered
351
+ } finally {
352
+ clearTimeout(timer)
353
+ clearTimeout(expiry)
354
+ signal?.removeEventListener('abort', onabort)
355
+ mailbox.off('close', onabort)
356
+ await Promise.allSettled([inbox.close(), post.close()])
312
357
  }
313
358
  }
359
+ }
314
360
 
315
- /**
316
- * Cheap structural test for a candidate invite string.
317
- *
318
- * @param {unknown} str
319
- * @returns {boolean}
320
- */
321
- static isInvite(str) {
322
- return Invite.isInvite(str)
361
+ /**
362
+ * A join's payload: sealed to the database's address, so only its members read who joins; proven
363
+ * by the invite over the writer; signed by the joiner's identity for this writer and reply address.
364
+ *
365
+ * @param {Invite} invite
366
+ * @param {import('../identity/index.js').Identity} identity
367
+ * @param {Uint8Array} writer
368
+ * @param {Uint8Array} reply
369
+ * @returns {{ box: Uint8Array }}
370
+ */
371
+ export function sealJoin(invite, identity, writer, reply) {
372
+ const join = {
373
+ invite: invite.id,
374
+ reply,
375
+ proof: invite.prove(writer),
376
+ identity: identity.publicKey,
377
+ signature: identity.sign(joining(invite.key, invite.id, writer, reply)),
378
+ ts: Date.now()
323
379
  }
380
+ return { box: crypto.encrypt(c.encode(Join, join), invite.address) }
381
+ }
382
+
383
+ // one join per invite in the writer's core: a resumed join finds its own, a fresh invite adds
384
+ // another. Plain, since the joiner has no key yet, and linked to the invite's node, so no member
385
+ // applies it before the invite
386
+ async function write(core, spec, invite, identity, writer) {
387
+ await core.ready()
388
+ const last = await core.getUserData('cero/join')
389
+ if (last && b4a.equals(last, invite.id)) return
390
+ const { ns = NAMESPACE, version = 1 } = spec.meta || {}
391
+ const payload = sealJoin(invite, identity, core.key, Mailbox.getAddress(writer.secretKey))
392
+ const op = wrap(version, spec.dispatch.encode(`@${ns}/join`, payload))
393
+ const links = [invite.link]
394
+ await core.append(Autobee.encodeValue(op, { optimistic: true, encrypted: true, links }))
395
+ await core.setUserData('cero/join', invite.id)
324
396
  }
325
397
 
326
- function encodeUserData(data, encoding) {
327
- if (data == null) throw CeroError.REQUIRED('userData')
328
- if (encoding) return c.encode(encoding, data)
329
- if (b4a.isBuffer(data)) return data
330
- throw CeroError.INVALID('userData must be a buffer when no joinerEncoding is provided')
398
+ function expired({ expires }) {
399
+ return expires > 0 && Date.now() > expires
331
400
  }
332
401
 
333
- function decodeUserData(buf, encoding) {
334
- if (!buf || buf.length === 0) return null
335
- if (!encoding) return buf
402
+ // anyone can send to an address: what does not decode is dropped, never thrown
403
+ function decode(encoding, message) {
336
404
  try {
337
- return c.decode(encoding, buf)
405
+ return c.decode(encoding, message)
338
406
  } catch {
339
- return buf
407
+ return null
408
+ }
409
+ }
410
+
411
+ function getInviteId(invite) {
412
+ try {
413
+ return b4a.toHex(Invite.parse(invite).id)
414
+ } catch {
415
+ return null
340
416
  }
341
417
  }