@cero-base/core 2.2.1 → 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.
- package/README.md +32 -212
- package/package.json +18 -9
- package/src/blobs/index.js +9 -0
- package/src/blobs/server.js +2 -0
- package/src/database/changes.js +1 -1
- package/src/database/dispatch.js +341 -209
- package/src/database/encryption.js +83 -33
- package/src/database/index.js +184 -83
- package/src/database/rotation.js +43 -30
- package/src/identity/index.js +20 -78
- package/src/index.js +3 -10
- package/src/lib/constants.js +2 -0
- package/src/lib/errors.js +3 -11
- package/src/lib/spec/index.js +136 -132
- package/src/lib/spec/schema.json +84 -99
- package/src/lib/utils.js +57 -3
- package/src/mailbox/inbox.js +103 -0
- package/src/mailbox/index.js +146 -0
- package/src/mailbox/post.js +69 -0
- package/src/network/discovery.js +26 -1
- package/src/network/index.js +105 -64
- package/src/network/presence.js +6 -2
- package/src/pairing/index.js +330 -254
- package/src/pairing/invite.js +83 -144
- package/src/pairing/request.js +54 -56
- package/src/rpc/index.js +18 -93
- package/src/rpc/peer.js +4 -1
- package/src/storage/index.js +78 -39
- package/types/blobs/index.d.ts +22 -9
- package/types/blobs/server.d.ts +4 -2
- package/types/database/changes.d.ts +2 -2
- package/types/database/dispatch.d.ts +19 -13
- package/types/database/encryption.d.ts +67 -29
- package/types/database/index.d.ts +144 -119
- package/types/database/rotation.d.ts +32 -13
- package/types/identity/index.d.ts +6 -47
- package/types/index.d.ts +3 -16
- package/types/lib/constants.d.ts +1 -0
- package/types/lib/errors.d.ts +3 -9
- package/types/lib/spec/index.d.ts +52 -16
- package/types/lib/utils.d.ts +40 -8
- package/types/mailbox/inbox.d.ts +52 -0
- package/types/mailbox/index.d.ts +111 -0
- package/types/mailbox/post.d.ts +37 -0
- package/types/network/discovery.d.ts +21 -5
- package/types/network/index.d.ts +64 -48
- package/types/network/presence.d.ts +17 -4
- package/types/pairing/index.d.ts +143 -134
- package/types/pairing/invite.d.ts +70 -114
- package/types/pairing/request.d.ts +58 -98
- package/types/rpc/index.d.ts +26 -44
- package/types/rpc/peer.d.ts +10 -7
- package/types/storage/index.d.ts +64 -54
- package/src/pairing/candidate.js +0 -123
- package/types/pairing/candidate.d.ts +0 -36
package/src/pairing/index.js
CHANGED
|
@@ -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
|
|
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 {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
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 {
|
|
17
|
-
* @property {import('../
|
|
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}
|
|
25
|
-
* @property {string} [role]
|
|
26
|
-
* @property {number} [
|
|
27
|
-
* @property {
|
|
28
|
-
* @property {boolean} [
|
|
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 {
|
|
32
|
-
* @property {number}
|
|
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 {
|
|
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
|
-
*
|
|
39
|
-
*
|
|
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 (!
|
|
55
|
-
if (!
|
|
56
|
-
|
|
57
|
-
this.
|
|
58
|
-
this.
|
|
59
|
-
|
|
60
|
-
this.
|
|
61
|
-
this.
|
|
62
|
-
this.
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
this.
|
|
66
|
-
|
|
67
|
-
this.
|
|
68
|
-
|
|
69
|
-
this.
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
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.
|
|
84
|
-
|
|
85
|
-
|
|
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
|
-
|
|
100
|
-
this.
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
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
|
|
105
|
+
* Mint an invite. Returns its wire form, a z32 string.
|
|
113
106
|
*
|
|
114
|
-
* @param {
|
|
107
|
+
* @param {InviteOpts} [opts]
|
|
115
108
|
* @returns {Promise<string>}
|
|
116
109
|
*/
|
|
117
|
-
async
|
|
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
|
-
|
|
124
|
-
|
|
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
|
-
|
|
144
|
-
|
|
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
|
-
*
|
|
135
|
+
* Revoke an invite, for every member. Needs the remove permission.
|
|
152
136
|
*
|
|
153
|
-
* @param {string}
|
|
154
|
-
* @returns {
|
|
137
|
+
* @param {string} invite
|
|
138
|
+
* @returns {Promise<boolean>} Whether it was live.
|
|
155
139
|
*/
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
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
|
-
|
|
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
|
-
*
|
|
156
|
+
* A join waiting on a `confirm` invite, by its id in the `requests` collection.
|
|
165
157
|
*
|
|
166
|
-
* @param {
|
|
158
|
+
* @param {string} id
|
|
159
|
+
* @returns {Promise<Request>}
|
|
167
160
|
*/
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
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
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
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
|
-
|
|
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
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
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
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
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
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
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
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
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
|
-
|
|
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
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
if (!
|
|
269
|
-
|
|
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
|
-
|
|
276
|
-
|
|
277
|
-
|
|
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
|
-
*
|
|
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
|
-
* @
|
|
293
|
+
* @param {JoinOpts} opts
|
|
294
|
+
* @returns {Promise<JoinResult>}
|
|
306
295
|
*/
|
|
307
|
-
static
|
|
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
|
|
310
|
-
}
|
|
311
|
-
|
|
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
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
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
|
|
327
|
-
|
|
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
|
-
|
|
334
|
-
|
|
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,
|
|
405
|
+
return c.decode(encoding, message)
|
|
338
406
|
} catch {
|
|
339
|
-
return
|
|
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
|
}
|