@cero-base/cero 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.
- package/README.md +24 -16
- package/package.json +7 -6
- package/src/build/index.js +38 -34
- package/src/build/internal.js +96 -11
- package/src/build/schemas.js +119 -19
- package/src/extensions/handle-sync.js +8 -12
- package/src/extensions/index.js +17 -63
- package/src/extensions/mirror.js +44 -0
- package/src/extensions/profile-sync.js +10 -12
- package/src/handle/index.js +499 -374
- package/src/handle/join.js +144 -0
- package/src/index.js +89 -118
- package/src/lib/bluetooth.js +83 -19
- package/src/lib/constants.js +1 -0
- package/src/lib/operators.js +298 -128
- package/src/lib/peek.js +1 -1
- package/src/lib/refs.js +7 -7
- package/src/lib/spec.js +32 -0
- package/src/local/index.js +27 -3
- package/src/rpc/client.js +240 -202
- package/src/rpc/server.js +186 -133
- package/types/build/index.d.ts +3 -8
- package/types/build/internal.d.ts +86 -27
- package/types/build/schemas.d.ts +91 -12
- package/types/extensions/handle-sync.d.ts +4 -12
- package/types/extensions/index.d.ts +59 -59
- package/types/extensions/mirror.d.ts +13 -0
- package/types/extensions/profile-sync.d.ts +4 -13
- package/types/handle/index.d.ts +229 -198
- package/types/handle/join.d.ts +63 -0
- package/types/index.d.ts +27 -55
- package/types/lib/bluetooth.d.ts +57 -19
- package/types/lib/constants.d.ts +1 -0
- package/types/lib/operators.d.ts +166 -81
- package/types/lib/peek.d.ts +2 -2
- package/types/lib/refs.d.ts +14 -15
- package/types/lib/spec.d.ts +87 -0
- package/types/local/index.d.ts +19 -9
- package/types/rpc/client.d.ts +55 -112
- package/types/rpc/server.d.ts +91 -50
- package/src/rpc/index.js +0 -8
- package/types/rpc/index.d.ts +0 -7
package/src/handle/index.js
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
1
|
import AbortController from 'bare-abort-controller'
|
|
2
2
|
import b4a from 'b4a'
|
|
3
|
-
import c from 'compact-encoding'
|
|
4
|
-
import Hypercore from 'hypercore'
|
|
5
3
|
import { discoveryKey } from 'hypercore-crypto'
|
|
6
4
|
import ReadyResource from 'ready-resource'
|
|
7
5
|
import safetyCatch from 'safety-catch'
|
|
@@ -10,10 +8,12 @@ import z32 from 'z32'
|
|
|
10
8
|
|
|
11
9
|
import { Identity } from '@cero-base/core/identity'
|
|
12
10
|
import { Database } from '@cero-base/core/database'
|
|
13
|
-
import {
|
|
11
|
+
import { blobEpochKey } from '@cero-base/core/database/encryption'
|
|
14
12
|
import { Pairing } from '@cero-base/core/pairing'
|
|
13
|
+
import { Invite } from '@cero-base/core/invite'
|
|
14
|
+
import { Mailbox } from '@cero-base/core/mailbox'
|
|
15
15
|
import hid from 'hypercore-id-encoding'
|
|
16
|
-
import {
|
|
16
|
+
import { admission, onAbort, filter } from '@cero-base/core/utils'
|
|
17
17
|
import { CeroError } from '@cero-base/core/errors'
|
|
18
18
|
import { Blobs } from '@cero-base/core/blobs'
|
|
19
19
|
import { decodeId } from '@cero-base/core/blobs/codec'
|
|
@@ -22,59 +22,54 @@ import { FileServer } from '@cero-base/core/blobs/server'
|
|
|
22
22
|
import { NS, TIMEOUT } from '../lib/constants.js'
|
|
23
23
|
|
|
24
24
|
import { Ref } from '../lib/refs.js'
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
25
|
+
import { Join, wait } from './join.js'
|
|
26
|
+
import { box } from '../local/index.js'
|
|
27
|
+
import { extensionsOf } from '../extensions/index.js'
|
|
27
28
|
|
|
28
29
|
export { Ref } from '../lib/refs.js'
|
|
29
30
|
|
|
30
31
|
/**
|
|
31
32
|
* @typedef {import('@cero-base/core/network').Network} Network
|
|
32
33
|
* @typedef {import('../local/index.js').Local} Local
|
|
34
|
+
* @typedef {import('../lib/spec.js').Spec} Spec
|
|
33
35
|
* @typedef {import('@cero-base/core/identity').KeyPair} KeyPair
|
|
34
36
|
*
|
|
35
37
|
* @typedef {object} HandleOpts
|
|
36
38
|
* @property {Handle} [parent] Parent handle when this is a child slot.
|
|
37
39
|
* @property {Identity} [identity] Long-lived user identity. Inherited from `parent` if omitted.
|
|
38
40
|
* @property {Network} [network] Shared swarm. Inherited from `parent` if omitted.
|
|
39
|
-
* @property {
|
|
40
|
-
* @property {
|
|
41
|
+
* @property {import('corestore')} [store] Pre-existing Corestore. Falls back to `parent.store.store`.
|
|
42
|
+
* @property {Spec} [spec] Built cero spec.
|
|
41
43
|
* @property {Local} [local] Local store for per-handle keypairs.
|
|
42
|
-
* @property {
|
|
43
|
-
* @property {
|
|
44
|
+
* @property {import('hypercore-storage')} [storage] Owned HypercoreStorage to close on shutdown.
|
|
45
|
+
* @property {{ destroy(): Promise<void> }} [discovery] Owned identity discovery to destroy on shutdown.
|
|
44
46
|
* @property {string} [dir] Data directory (root handles only).
|
|
45
|
-
* @property {
|
|
46
|
-
* @property {Record<string, Function>} [routes]
|
|
47
|
+
* @property {import('../index.js').CeroOpts} [opts] Pass-through cero(...) options.
|
|
47
48
|
* @property {Uint8Array} [key] Existing database key.
|
|
48
49
|
* @property {Uint8Array} [encryptionKey] Existing encryption key.
|
|
49
50
|
* @property {Array<{ epoch: number, entropy: Uint8Array }>} [epochs] Rotation epochs delivered at join.
|
|
50
51
|
* @property {string} [namespace] Corestore namespace.
|
|
51
52
|
* @property {KeyPair} [keyPair] Writer keypair.
|
|
52
53
|
* @property {boolean} [pair] When `false`, skips creating a `Pairing` session.
|
|
54
|
+
* @property {import('../lib/bluetooth.js').Bluetooth | null} [bluetooth] Root only: the radio, up before the root opens.
|
|
55
|
+
* @property {{ name?: string | null, isMobile?: boolean, recovering?: boolean, timeout?: number } | null} [bootstrap] Root only: provision this device as it opens, its genesis or its recovery.
|
|
53
56
|
*
|
|
54
57
|
* @typedef {object} CreateChildOpts
|
|
55
58
|
* @property {string | null} [name]
|
|
56
|
-
* @property {Record<string, Function>} [routes]
|
|
57
|
-
* @property {string} [role]
|
|
58
|
-
* @property {boolean} [accept]
|
|
59
59
|
*
|
|
60
60
|
* @typedef {object} JoinChildOpts
|
|
61
|
-
* @property {Record<string, Function>} [routes]
|
|
62
61
|
* @property {number} [timeout]
|
|
63
62
|
*
|
|
64
63
|
* @typedef {object} StaticJoinOpts
|
|
65
64
|
* @property {Handle} [parent]
|
|
66
65
|
* @property {Network} [network]
|
|
67
66
|
* @property {Identity} [identity]
|
|
68
|
-
* @property {
|
|
69
|
-
* @property {
|
|
67
|
+
* @property {import('corestore')} [store]
|
|
68
|
+
* @property {Spec} [spec]
|
|
70
69
|
* @property {string} [namespace]
|
|
71
|
-
* @property {
|
|
70
|
+
* @property {KeyPair} [writer] Writer keypair in the joined handle; a fresh one by default.
|
|
72
71
|
* @property {number} [timeout]
|
|
73
72
|
*
|
|
74
|
-
* @typedef {object} AcceptOpts
|
|
75
|
-
* @property {string} [role] Role to grant the joining peer. Falls back to the invite's role, then `'member'`.
|
|
76
|
-
* @property {string | null} [name]
|
|
77
|
-
*
|
|
78
73
|
* @typedef {object} HandleExtra
|
|
79
74
|
* @property {string | null} [name] Display name; set on child handles by the owner flow.
|
|
80
75
|
* @property {import('../lib/refs.js').Ref} [profile] `profile` ref, attached dynamically when the schema declares one.
|
|
@@ -82,7 +77,7 @@ export { Ref } from '../lib/refs.js'
|
|
|
82
77
|
*
|
|
83
78
|
* @typedef {Handle & HandleExtra} Child A child handle plus its dynamically-attached refs.
|
|
84
79
|
*
|
|
85
|
-
* @typedef {Handle & Record<string, import('../lib/refs.js').Ref>}
|
|
80
|
+
* @typedef {Handle & Record<string, import('../lib/refs.js').Ref>} Context A root or a room: a handle with its refs (`me.profile`, `room.messages`).
|
|
86
81
|
*/
|
|
87
82
|
|
|
88
83
|
/**
|
|
@@ -104,31 +99,51 @@ export class Handle extends ReadyResource {
|
|
|
104
99
|
if (!store) throw CeroError.REQUIRED('store')
|
|
105
100
|
if (!spec) throw CeroError.REQUIRED('spec')
|
|
106
101
|
|
|
102
|
+
/** @type {Identity} */
|
|
107
103
|
this.identity = identity
|
|
104
|
+
/** @type {Network} */
|
|
108
105
|
this.network = network
|
|
109
106
|
this.spec = spec
|
|
110
107
|
this.parent = parent
|
|
111
108
|
|
|
112
109
|
this.local = opts.local || null
|
|
110
|
+
// one per device: the root's, its boxes in the local store
|
|
111
|
+
/** @type {Mailbox} */
|
|
112
|
+
this.mailbox = parent ? parent.root.mailbox : new Mailbox(network, boxes(this.local))
|
|
113
|
+
/** @private */
|
|
113
114
|
this._storage = opts.storage || null
|
|
115
|
+
/** @private */
|
|
114
116
|
this._discovery = opts.discovery || null
|
|
117
|
+
/** @private */
|
|
115
118
|
this._dir = opts.dir || null
|
|
119
|
+
/** @private */
|
|
116
120
|
this._opts = opts.opts || {}
|
|
121
|
+
/** @type {import('../extensions/index.js').Extension[]} */
|
|
117
122
|
this.extensions = parent?.extensions || extensionsOf(spec, this._opts.extensions)
|
|
118
|
-
|
|
123
|
+
/** @private */
|
|
119
124
|
this._onerror = this._opts.onerror || ((err) => console.error(err))
|
|
125
|
+
/** @type {Set<Handle> | null} */
|
|
120
126
|
this.children = parent ? null : new Set()
|
|
127
|
+
/** @private */
|
|
121
128
|
this._typeHooks = parent ? null : new Set()
|
|
129
|
+
/** @private */
|
|
122
130
|
this._loading = parent ? null : new Map()
|
|
123
|
-
|
|
131
|
+
/** @private */
|
|
132
|
+
this._joining = parent ? null : new Map() // type/discovery key → Join
|
|
133
|
+
/** @private */
|
|
124
134
|
this._coreKeys = parent ? null : new Map()
|
|
135
|
+
/** @private */
|
|
125
136
|
this._fileServer = null
|
|
137
|
+
/** @private */
|
|
126
138
|
this._blobs = null
|
|
139
|
+
/** @private */
|
|
127
140
|
this._epochBlobs = null
|
|
128
141
|
// root only, serializes suspend/resume and converges rapid bounces
|
|
142
|
+
/** @private */
|
|
129
143
|
this._sus = parent
|
|
130
144
|
? null
|
|
131
|
-
: new Suspendify({ suspend: () => this.
|
|
145
|
+
: new Suspendify({ suspend: () => this._sleep(), resume: () => this._wake() })
|
|
146
|
+
/** @private */
|
|
132
147
|
this._owned = new Set()
|
|
133
148
|
|
|
134
149
|
this.store = new Database({
|
|
@@ -136,7 +151,6 @@ export class Handle extends ReadyResource {
|
|
|
136
151
|
identity,
|
|
137
152
|
network,
|
|
138
153
|
spec,
|
|
139
|
-
routes: opts.routes,
|
|
140
154
|
key: opts.key,
|
|
141
155
|
encryptionKey: opts.encryptionKey,
|
|
142
156
|
epochs: opts.epochs,
|
|
@@ -145,8 +159,24 @@ export class Handle extends ReadyResource {
|
|
|
145
159
|
pinned: !parent,
|
|
146
160
|
onerror: this._onerror
|
|
147
161
|
})
|
|
148
|
-
|
|
162
|
+
/** @private */
|
|
163
|
+
this._pair = null
|
|
164
|
+
/** @private */
|
|
149
165
|
this._wantsPair = opts.pair !== false
|
|
166
|
+
/** @private */
|
|
167
|
+
this._boot = opts.bootstrap || null
|
|
168
|
+
/** @private */
|
|
169
|
+
this._bluetooth = opts.bluetooth || null
|
|
170
|
+
// refs before the open, so a hook can attach before any op applies
|
|
171
|
+
Ref.attach(this, this.store.refs, this.spec.handles)
|
|
172
|
+
/** @private */
|
|
173
|
+
this._live = {
|
|
174
|
+
status: { get: () => this._status(), watch: (fn) => this._onStatus(fn) },
|
|
175
|
+
...(!this.parent && {
|
|
176
|
+
joins: { get: (q) => this._joins(q), watch: (fn) => this._onJoins(fn) },
|
|
177
|
+
nearby: { get: () => this._peers(), watch: (fn) => this._onPeers(fn) }
|
|
178
|
+
})
|
|
179
|
+
}
|
|
150
180
|
}
|
|
151
181
|
|
|
152
182
|
/**
|
|
@@ -156,6 +186,7 @@ export class Handle extends ReadyResource {
|
|
|
156
186
|
*/
|
|
157
187
|
get signal() {
|
|
158
188
|
if (!this._ac) {
|
|
189
|
+
/** @private */
|
|
159
190
|
this._ac = new AbortController()
|
|
160
191
|
if (this.closed) this._ac.abort()
|
|
161
192
|
else this.once('close', () => this._ac.abort())
|
|
@@ -209,68 +240,68 @@ export class Handle extends ReadyResource {
|
|
|
209
240
|
return this.spec.meta.type || null
|
|
210
241
|
}
|
|
211
242
|
|
|
212
|
-
/**
|
|
243
|
+
/**
|
|
244
|
+
* Canonical id: the identity id on the root, the database key on a room.
|
|
245
|
+
*
|
|
246
|
+
* @returns {string | null}
|
|
247
|
+
*/
|
|
213
248
|
get id() {
|
|
214
249
|
if (!this.parent) return this.identity.id
|
|
215
250
|
return this.store?.key ? hid.encode(this.store.key) : null
|
|
216
251
|
}
|
|
217
252
|
|
|
218
|
-
/**
|
|
253
|
+
/**
|
|
254
|
+
* This device's id and name. `null` on a room.
|
|
255
|
+
*
|
|
256
|
+
* @returns {{ id: string, name: string | null } | null}
|
|
257
|
+
*/
|
|
219
258
|
get device() {
|
|
220
259
|
if (this.parent) return null
|
|
221
260
|
const k = this.store?.writerKey
|
|
222
261
|
return k ? { id: hid.encode(k), name: this._opts.name || null } : null
|
|
223
262
|
}
|
|
224
263
|
|
|
225
|
-
|
|
226
|
-
return this._sus?.suspended === true
|
|
227
|
-
}
|
|
228
|
-
|
|
264
|
+
/** @private */
|
|
229
265
|
async _open() {
|
|
230
266
|
await this.store.ready()
|
|
267
|
+
// a fresh device takes writes only once provisioned, and an operator waits for the open
|
|
268
|
+
if (this._boot) await this.store.bootstrap(this._boot)
|
|
231
269
|
if (this._wantsPair) {
|
|
232
|
-
this.
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
await this._syncInvites().catch(safetyCatch)
|
|
244
|
-
this._invitesSync = (touched) => {
|
|
245
|
-
if (touched.has('*') || touched.has('invites')) this._syncInvites().catch(safetyCatch)
|
|
270
|
+
this._pair = new Pairing({ mailbox: this.mailbox, db: this.store })
|
|
271
|
+
await this._pair.ready()
|
|
272
|
+
}
|
|
273
|
+
this.root._coreKeys.set(b4a.toHex(this.store.key), this.store.encryptionKey)
|
|
274
|
+
if (!this.parent) {
|
|
275
|
+
await this.fileServer.listen()
|
|
276
|
+
await this.mailbox.ready()
|
|
277
|
+
if (this._bluetooth) {
|
|
278
|
+
const off = this.store.onUpdate('profile', () => this._tell().catch(this._onerror))
|
|
279
|
+
this.once('close', off)
|
|
280
|
+
await this._tell()
|
|
246
281
|
}
|
|
247
|
-
this.
|
|
282
|
+
await this._carryOn().catch(this._onerror)
|
|
283
|
+
this._reserve().catch(this._onerror)
|
|
248
284
|
}
|
|
249
|
-
Ref.attach(this, this.store.refs, this.spec.handles)
|
|
250
|
-
this.root._coreKeys.set(b4a.toString(this.store.key, 'hex'), this.store.encryptionKey)
|
|
251
|
-
if (!this.parent) await this.fileServer.listen()
|
|
252
285
|
}
|
|
253
286
|
|
|
287
|
+
/** @private */
|
|
254
288
|
async _close() {
|
|
255
|
-
this.root._coreKeys.delete(b4a.
|
|
256
|
-
if (this._blobs?.key) this.root._coreKeys.delete(b4a.
|
|
289
|
+
this.root._coreKeys.delete(b4a.toHex(this.store.key))
|
|
290
|
+
if (this._blobs?.key) this.root._coreKeys.delete(b4a.toHex(this._blobs.key))
|
|
257
291
|
for (const b of this._epochBlobs?.values() || []) {
|
|
258
|
-
if (b.key) this.root._coreKeys.delete(b4a.
|
|
292
|
+
if (b.key) this.root._coreKeys.delete(b4a.toHex(b.key))
|
|
259
293
|
}
|
|
260
294
|
for (const hex of this._blobKeys || []) this.root._coreKeys.delete(hex)
|
|
261
295
|
for (const r of [...this._owned]) r.destroy?.()
|
|
262
296
|
this._owned.clear()
|
|
263
|
-
if (this._invitesSync) {
|
|
264
|
-
this.store.off('update', this._invitesSync)
|
|
265
|
-
this._invitesSync = null
|
|
266
|
-
}
|
|
267
297
|
if (this._discovery) this._discovery.destroy().catch(safetyCatch)
|
|
268
298
|
|
|
269
299
|
const steps = [
|
|
300
|
+
...[...(this._joining?.values() || [])].map((join) => () => join.close()),
|
|
270
301
|
() => this._blobs?.close(),
|
|
271
302
|
...[...(this._epochBlobs?.values() || [])].map((b) => () => b.close()),
|
|
272
303
|
...[...(this.children || [])].map((c) => () => c.close()),
|
|
273
|
-
() => this.
|
|
304
|
+
() => this._pair?.close()
|
|
274
305
|
]
|
|
275
306
|
this._epochBlobs = null
|
|
276
307
|
this.children?.clear()
|
|
@@ -281,7 +312,8 @@ export class Handle extends ReadyResource {
|
|
|
281
312
|
} else {
|
|
282
313
|
const store = this.store.store
|
|
283
314
|
steps.push(
|
|
284
|
-
() => this.
|
|
315
|
+
() => this.mailbox.close(),
|
|
316
|
+
() => this._bluetooth?.close(),
|
|
285
317
|
() => this.local?.close(),
|
|
286
318
|
async () => {
|
|
287
319
|
await this._fileServer?.close()
|
|
@@ -315,43 +347,12 @@ export class Handle extends ReadyResource {
|
|
|
315
347
|
return resource
|
|
316
348
|
}
|
|
317
349
|
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
*
|
|
322
|
-
* @param {string} event
|
|
323
|
-
* @param {(...args: any[]) => void} fn
|
|
324
|
-
* @param {{ signal?: AbortSignal }} [opts]
|
|
325
|
-
* @returns {this}
|
|
326
|
-
*/
|
|
327
|
-
on(event, fn, opts) {
|
|
328
|
-
super.on(event, fn)
|
|
329
|
-
onAbort(opts?.signal, () => super.off(event, fn))
|
|
330
|
-
return this
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
/**
|
|
334
|
-
* Resolve a durable file id to an ephemeral download url via this identity's
|
|
335
|
-
* file server.
|
|
336
|
-
*
|
|
337
|
-
* @param {string} id
|
|
338
|
-
* @returns {string}
|
|
339
|
-
*/
|
|
340
|
-
getLink(id) {
|
|
350
|
+
// a file's url on this device's file server, for the rows that name it
|
|
351
|
+
/** @private */
|
|
352
|
+
_link(id) {
|
|
341
353
|
return this.root.fileServer.getLink(id)
|
|
342
354
|
}
|
|
343
355
|
|
|
344
|
-
/**
|
|
345
|
-
* Initialise a fresh database: write the genesis claim, derive the writer.
|
|
346
|
-
* Forwards to `Database.bootstrap`.
|
|
347
|
-
*
|
|
348
|
-
* @param {any} [opts]
|
|
349
|
-
* @returns {Promise<any>}
|
|
350
|
-
*/
|
|
351
|
-
bootstrap(opts) {
|
|
352
|
-
return this.store.bootstrap(opts)
|
|
353
|
-
}
|
|
354
|
-
|
|
355
356
|
/**
|
|
356
357
|
* Claim writer capability on an existing database (paired-device flow).
|
|
357
358
|
* Forwards to `Database.claim`.
|
|
@@ -362,189 +363,231 @@ export class Handle extends ReadyResource {
|
|
|
362
363
|
return this.store.claim()
|
|
363
364
|
}
|
|
364
365
|
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
*/
|
|
371
|
-
setActive(active) {
|
|
372
|
-
this.store.setActive(active)
|
|
366
|
+
// the verbs in lib/operators.js land here
|
|
367
|
+
|
|
368
|
+
/** @private */
|
|
369
|
+
async _invite(opts) {
|
|
370
|
+
return this._pairing().invite(opts)
|
|
373
371
|
}
|
|
374
372
|
|
|
375
|
-
/**
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
* @param {{ role?: string, expiresIn?: number, data?: any }} [opts]
|
|
379
|
-
* @returns {Promise<string>} Z32-encoded invite string.
|
|
380
|
-
*/
|
|
381
|
-
async invite(opts) {
|
|
382
|
-
if (!this.pair) {
|
|
383
|
-
throw CeroError.INVALID(
|
|
384
|
-
'invite() is not available on the root handle — open a child handle first'
|
|
385
|
-
)
|
|
386
|
-
}
|
|
387
|
-
// an invite is a capability, cap the rank or apply drops the mismatch silently
|
|
388
|
-
if (opts?.role !== undefined && opts.role !== '') await this._checkGrant(opts.role)
|
|
389
|
-
const str = await this.pair.createInvite(opts)
|
|
390
|
-
const record = this.pair.recordOf(str)
|
|
391
|
-
if (record) {
|
|
392
|
-
// persist so every member replica serves it across restarts
|
|
393
|
-
await this.store
|
|
394
|
-
.call('add-invite', {
|
|
395
|
-
id: b4a.toString(record.id, 'hex'),
|
|
396
|
-
invite: b4a.from(str),
|
|
397
|
-
publicKey: record.publicKey,
|
|
398
|
-
seed: record.seed,
|
|
399
|
-
role: record.invite.role || '',
|
|
400
|
-
expires: record.invite.expires || 0,
|
|
401
|
-
createdAt: Date.now(),
|
|
402
|
-
reuse: !!record.reuse
|
|
403
|
-
})
|
|
404
|
-
.catch(safetyCatch)
|
|
405
|
-
}
|
|
406
|
-
return str
|
|
373
|
+
/** @private */
|
|
374
|
+
async _revoke(invite) {
|
|
375
|
+
return this._pairing().revoke(invite)
|
|
407
376
|
}
|
|
408
377
|
|
|
409
|
-
/**
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
// drop the persisted row so every other member stops serving it too
|
|
426
|
-
await this.store.call('del-invite', { id: b4a.toString(record.id, 'hex') })
|
|
378
|
+
/** @private */
|
|
379
|
+
async _answer(id, { accept, role, reason }) {
|
|
380
|
+
const request = await this._pairing().request(id)
|
|
381
|
+
return accept ? request.accept({ role }) : request.deny(reason)
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/** @private */
|
|
385
|
+
_rotate() {
|
|
386
|
+
return this.store.rotate()
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
// the same context, its refs writing into one batch; a fn that ignores it would write outside
|
|
390
|
+
/** @private */
|
|
391
|
+
async _tx(fn) {
|
|
392
|
+
if (typeof fn !== 'function' || fn.length < 1) {
|
|
393
|
+
throw CeroError.INVALID('tx(ctx, fn): fn takes the batch, (tx) => ...')
|
|
427
394
|
}
|
|
428
|
-
return
|
|
395
|
+
return this.store.tx((batch) => {
|
|
396
|
+
const tx = Object.create(this)
|
|
397
|
+
tx.store = batch
|
|
398
|
+
for (const name of Object.keys(this.store.refs)) {
|
|
399
|
+
tx[name] = new Ref(tx, name, this[name].kind, this[name].schema)
|
|
400
|
+
}
|
|
401
|
+
return fn(tx)
|
|
402
|
+
})
|
|
429
403
|
}
|
|
430
404
|
|
|
431
|
-
/**
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
405
|
+
/** @private */
|
|
406
|
+
_pairing() {
|
|
407
|
+
if (!this._pair) throw CeroError.INVALID('the root has no invites, open a room first')
|
|
408
|
+
return this._pair
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/** @private */
|
|
412
|
+
async _leave() {
|
|
413
|
+
if (!this.parent) throw CeroError.INVALID('the root cannot be left')
|
|
414
|
+
await this.store.del('members', this.identity.id)
|
|
415
|
+
await this.parent.store.call('del-handle', { id: hid.encode(this.store.key) })
|
|
416
|
+
await this.close()
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// the app going to the background and back: networking, storage and the radio together
|
|
420
|
+
/** @private */
|
|
421
|
+
async _suspend() {
|
|
422
|
+
await this._lifecycle().suspend()
|
|
423
|
+
this.emit('status')
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/** @private */
|
|
427
|
+
async _resume() {
|
|
428
|
+
await this._lifecycle().resume()
|
|
429
|
+
this.emit('status')
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** @private */
|
|
433
|
+
_lifecycle() {
|
|
434
|
+
if (!this._sus) {
|
|
435
|
+
throw CeroError.INVALID("suspend and resume are the app's, on me: a room uses cero.activate")
|
|
445
436
|
}
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
437
|
+
return this._sus
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// true ranks a room as just used, false takes it off the swarm until something lands in it
|
|
441
|
+
/** @private */
|
|
442
|
+
_active(on) {
|
|
443
|
+
this.store.setActive(on)
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/** @private */
|
|
447
|
+
async _status() {
|
|
448
|
+
const { data: member } = await this.store.get('members', this.identity.id)
|
|
449
|
+
const { current, seqs } = this.store.keyring
|
|
450
|
+
const data = {
|
|
451
|
+
role: member?.role ?? null,
|
|
452
|
+
writable: this.store.writable,
|
|
453
|
+
epoch: (current && seqs.get(current)) || 0,
|
|
454
|
+
suspended: this.root._sus.suspended,
|
|
455
|
+
behind: this.store.behind || 0,
|
|
456
|
+
nearby: this.root._bluetooth?.state ?? null
|
|
450
457
|
}
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
458
|
+
return { data }
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/** @private */
|
|
462
|
+
_onStatus(fn) {
|
|
463
|
+
const sources = [
|
|
464
|
+
[this, 'status'],
|
|
465
|
+
[this.store, 'update'],
|
|
466
|
+
[this.store, 'writable'],
|
|
467
|
+
[this.store, 'unwritable'],
|
|
468
|
+
[this.store, 'behind']
|
|
469
|
+
]
|
|
470
|
+
if (this.parent) sources.push([this.root, 'status'])
|
|
471
|
+
for (const [emitter, event] of sources) emitter.on(event, fn)
|
|
472
|
+
const off = this._onRadio(fn)
|
|
473
|
+
return () => {
|
|
474
|
+
for (const [emitter, event] of sources) emitter.off(event, fn)
|
|
475
|
+
off()
|
|
454
476
|
}
|
|
477
|
+
}
|
|
455
478
|
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
479
|
+
// the radio is the device's: the mesh (true), off (false), or one invite's rendezvous (a code)
|
|
480
|
+
// until the next call or the invite expires
|
|
481
|
+
/** @private */
|
|
482
|
+
async _nearby(mode) {
|
|
483
|
+
const bt = this.root._bluetooth
|
|
484
|
+
if (!bt) throw CeroError.INVALID('nearby needs cero() to open with the bluetooth option')
|
|
485
|
+
this.root._rendezvous?.()
|
|
486
|
+
this.root._rendezvous = null
|
|
487
|
+
if (mode === false) return bt.stop()
|
|
488
|
+
await bt.start()
|
|
489
|
+
if (typeof mode === 'string') this.root._rendezvous = bt.announce(mode)
|
|
490
|
+
}
|
|
464
491
|
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
492
|
+
// what a Bluetooth peer hears: the profile's name and whether this device is a phone
|
|
493
|
+
/** @private */
|
|
494
|
+
async _tell() {
|
|
495
|
+
const profile = this.store.refs.profile ? (await this.store.get('profile')).data : null
|
|
496
|
+
const { data: device } = await this.store.get('devices', this.device.id)
|
|
497
|
+
this._bluetooth.tell({ name: profile?.name ?? null, isMobile: device?.isMobile === true })
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
// one row a person: two of their devices in range link twice
|
|
501
|
+
/** @private */
|
|
502
|
+
async _peers() {
|
|
503
|
+
const peers = this._bluetooth ? [...this._bluetooth.peers.keys()] : []
|
|
504
|
+
const data = []
|
|
505
|
+
for (const hex of peers) {
|
|
506
|
+
const peer = this._bluetooth.told(hex)
|
|
507
|
+
if (peer) data.push({ ...peer, name: peer.name ?? (await this._nameOf(peer.id)) })
|
|
474
508
|
}
|
|
509
|
+
return { data, total: data.length, size: data.length }
|
|
510
|
+
}
|
|
475
511
|
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
512
|
+
// a peer's name as its member row shows it in a room open here; a stranger has none
|
|
513
|
+
/** @private */
|
|
514
|
+
async _nameOf(id) {
|
|
515
|
+
for (const room of this.children) {
|
|
516
|
+
const { data } = await room.store.get('members', id)
|
|
517
|
+
if (data?.name) return data.name
|
|
479
518
|
}
|
|
519
|
+
return null
|
|
520
|
+
}
|
|
480
521
|
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
ts: member.updatedAt || Date.now()
|
|
491
|
-
})
|
|
492
|
-
})
|
|
522
|
+
// a link opening, closing, or a peer telling a new name
|
|
523
|
+
/** @private */
|
|
524
|
+
_onPeers(fn) {
|
|
525
|
+
const off = this._onRadio(fn)
|
|
526
|
+
this.network.on('peer-info', fn)
|
|
527
|
+
return () => {
|
|
528
|
+
off()
|
|
529
|
+
this.network.off('peer-info', fn)
|
|
530
|
+
}
|
|
493
531
|
}
|
|
494
532
|
|
|
495
|
-
/**
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
async leave() {
|
|
502
|
-
if (!this.parent) return
|
|
503
|
-
await this.parent.store.call('del-handle', { id: hid.encode(this.store.key) })
|
|
504
|
-
await this.close()
|
|
533
|
+
/** @private */
|
|
534
|
+
_onRadio(fn) {
|
|
535
|
+
const bt = this.root._bluetooth
|
|
536
|
+
if (!bt) return () => {}
|
|
537
|
+
bt.on('update', fn)
|
|
538
|
+
return () => bt.off('update', fn)
|
|
505
539
|
}
|
|
506
540
|
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
541
|
+
// the joins this device waits on, without the keys the local store keeps for them
|
|
542
|
+
/** @private */
|
|
543
|
+
async _joins(query = {}) {
|
|
544
|
+
const rows = this.local ? (await this.local.store.get('joins')).data : []
|
|
545
|
+
const data = filter(
|
|
546
|
+
rows.map(({ id, type, invite }) => ({ id, type, invite })),
|
|
547
|
+
query
|
|
548
|
+
)
|
|
549
|
+
return { data, total: data.length, size: data.length }
|
|
514
550
|
}
|
|
515
551
|
|
|
516
|
-
/**
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
552
|
+
/** @private */
|
|
553
|
+
_onJoins(fn) {
|
|
554
|
+
if (!this.local) return () => {}
|
|
555
|
+
this.local.store.db.watch(fn)
|
|
556
|
+
return () => this.local.store.db.unwatch(fn)
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/** @private */
|
|
560
|
+
async _phrase() {
|
|
561
|
+
return this.identity.toPhrase()
|
|
523
562
|
}
|
|
524
563
|
|
|
525
564
|
/**
|
|
526
565
|
* @param {Uint8Array} coreKey
|
|
527
566
|
* @param {object} info
|
|
528
567
|
* @returns {{ key: Uint8Array, encryptionKey: Uint8Array } | null}
|
|
568
|
+
* @private
|
|
529
569
|
*/
|
|
530
570
|
_resolveCore(coreKey, info) {
|
|
531
|
-
const hex = b4a.
|
|
571
|
+
const hex = b4a.toHex(coreKey)
|
|
532
572
|
const encryptionKey = this.root._coreKeys.get(hex)
|
|
533
573
|
if (encryptionKey !== undefined) return { key: coreKey, encryptionKey }
|
|
534
574
|
return null
|
|
535
575
|
}
|
|
536
576
|
|
|
577
|
+
/** @private */
|
|
537
578
|
_baseBlobs() {
|
|
538
579
|
if (!this._blobs) this._blobs = this._makeBlobs('blobs', this.store.encryptionKey, 0)
|
|
539
580
|
return this._blobs
|
|
540
581
|
}
|
|
541
582
|
|
|
583
|
+
/** @private */
|
|
542
584
|
_makeBlobs(name, encryptionKey, stamp) {
|
|
543
585
|
const blobs = new Blobs({
|
|
544
586
|
store: this.store.store,
|
|
545
587
|
network: this.network,
|
|
546
588
|
encryptionKey,
|
|
547
|
-
|
|
589
|
+
// every handle shares the device's corestore: one core per handle, or its key serves the others
|
|
590
|
+
name: this.parent ? `${name}/${this.id}` : name
|
|
548
591
|
})
|
|
549
592
|
blobs.stamp = stamp
|
|
550
593
|
blobs
|
|
@@ -552,7 +595,7 @@ export class Handle extends ReadyResource {
|
|
|
552
595
|
.then(() => {
|
|
553
596
|
// close prunes _coreKeys first, a late ready() must not re-insert the entry
|
|
554
597
|
if (this.closing || this.closed || !blobs.key) return
|
|
555
|
-
this.root._coreKeys.set(b4a.
|
|
598
|
+
this.root._coreKeys.set(b4a.toHex(blobs.key), encryptionKey)
|
|
556
599
|
})
|
|
557
600
|
.catch(this._onerror)
|
|
558
601
|
return blobs
|
|
@@ -563,12 +606,13 @@ export class Handle extends ReadyResource {
|
|
|
563
606
|
*
|
|
564
607
|
* @param {string} id
|
|
565
608
|
* @param {number} [stamp]
|
|
609
|
+
* @private
|
|
566
610
|
*/
|
|
567
611
|
_registerBlobCore(id, stamp) {
|
|
568
612
|
if (!id || !this.root?._coreKeys) return
|
|
569
613
|
try {
|
|
570
614
|
const { coreKey } = decodeId(id)
|
|
571
|
-
const hex = b4a.
|
|
615
|
+
const hex = b4a.toHex(coreKey)
|
|
572
616
|
if (!this.root._coreKeys.has(hex)) {
|
|
573
617
|
// no stamp on a file-field value, look it up (fire-and-forget, idempotent)
|
|
574
618
|
if (stamp === undefined) {
|
|
@@ -591,32 +635,35 @@ export class Handle extends ReadyResource {
|
|
|
591
635
|
}
|
|
592
636
|
}
|
|
593
637
|
|
|
638
|
+
/**
|
|
639
|
+
* The bytes of a file this handle holds, fetched from a peer when this device lacks them.
|
|
640
|
+
*
|
|
641
|
+
* @param {string} id
|
|
642
|
+
* @returns {Promise<Uint8Array>}
|
|
643
|
+
* @private
|
|
644
|
+
*/
|
|
645
|
+
async _bytes(id) {
|
|
646
|
+
const { coreKey, blobId } = decodeId(id)
|
|
647
|
+
const { data } = await this.store.get('files', id)
|
|
648
|
+
const encryptionKey = data && this._blobCoreKey(data.stamp || 0)
|
|
649
|
+
if (!encryptionKey) throw CeroError.UNKNOWN('file', id)
|
|
650
|
+
const blobs = new Blobs({ store: this.store.store, key: coreKey, encryptionKey })
|
|
651
|
+
try {
|
|
652
|
+
await blobs.ready()
|
|
653
|
+
return await blobs.get(blobId)
|
|
654
|
+
} finally {
|
|
655
|
+
await blobs.close()
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
|
|
594
659
|
// base-era cores use the OWNING handle's key, rooms have their own
|
|
660
|
+
/** @private */
|
|
595
661
|
_blobCoreKey(stamp) {
|
|
596
662
|
if (!stamp) return this.store.encryptionKey
|
|
597
663
|
const entropy = this.store.keyring.entropy(stamp)
|
|
598
664
|
return entropy ? blobEpochKey(entropy) : null
|
|
599
665
|
}
|
|
600
666
|
|
|
601
|
-
async _syncInvites() {
|
|
602
|
-
if (!this.pair) return
|
|
603
|
-
const { data } = await this.store.get('invites')
|
|
604
|
-
this.pair.syncRows(data || [])
|
|
605
|
-
}
|
|
606
|
-
|
|
607
|
-
// `grants` treats an unknown role as "no", so an app role name must fail loudly
|
|
608
|
-
async _checkGrant(role) {
|
|
609
|
-
if (!isRank(role)) {
|
|
610
|
-
throw CeroError.INVALID(`role '${role}' is not a rank (owner, admin, member, reader)`)
|
|
611
|
-
}
|
|
612
|
-
const { data: me } = await this.store.get('members', this.identity.id)
|
|
613
|
-
// no member row yet = genesis, nothing to cap
|
|
614
|
-
if (!me) return
|
|
615
|
-
if (!grants(me.role, role)) {
|
|
616
|
-
throw CeroError.DENIED(null, `role '${role}' exceeds your own role '${me.role}'`)
|
|
617
|
-
}
|
|
618
|
-
}
|
|
619
|
-
|
|
620
667
|
/**
|
|
621
668
|
* Create a new child handle of `type`. Owner-flow — generates a fresh writer, adds it as a
|
|
622
669
|
* writer + member, and registers the child on the parent's `handles` collection.
|
|
@@ -624,15 +671,14 @@ export class Handle extends ReadyResource {
|
|
|
624
671
|
* @param {string} type
|
|
625
672
|
* @param {CreateChildOpts} [opts]
|
|
626
673
|
* @returns {Promise<Handle>}
|
|
674
|
+
* @private
|
|
627
675
|
*/
|
|
628
|
-
async _create(type, { name = null
|
|
676
|
+
async _create(type, { name = null } = {}) {
|
|
629
677
|
const writer = Identity.randomKeyPair()
|
|
630
678
|
const child = /** @type {Child} */ (
|
|
631
|
-
|
|
632
|
-
parent: this,
|
|
679
|
+
this._room({
|
|
633
680
|
spec: pickHandle(this.spec, type),
|
|
634
681
|
namespace: `${NS}/handle/${type}/${writer.id}`,
|
|
635
|
-
routes,
|
|
636
682
|
keyPair: writer,
|
|
637
683
|
// inheriting identity.encryptionKey would let any member decrypt every room
|
|
638
684
|
encryptionKey: Identity.randomBytes(32)
|
|
@@ -659,7 +705,7 @@ export class Handle extends ReadyResource {
|
|
|
659
705
|
|
|
660
706
|
const ts = Date.now()
|
|
661
707
|
const writerKey = child.store.writerKey
|
|
662
|
-
//
|
|
708
|
+
// one batch, so a room's first two ops land together
|
|
663
709
|
await child.store.tx(async (tx) => {
|
|
664
710
|
await tx.call('add-writer', {
|
|
665
711
|
master: this.identity.publicKey,
|
|
@@ -686,8 +732,7 @@ export class Handle extends ReadyResource {
|
|
|
686
732
|
updatedAt: ts
|
|
687
733
|
})
|
|
688
734
|
|
|
689
|
-
|
|
690
|
-
this._adopt(child, { name, role })
|
|
735
|
+
this._adopt(child, { name })
|
|
691
736
|
publish(child)
|
|
692
737
|
this._loading?.delete(id)
|
|
693
738
|
return child
|
|
@@ -700,74 +745,97 @@ export class Handle extends ReadyResource {
|
|
|
700
745
|
}
|
|
701
746
|
|
|
702
747
|
/**
|
|
703
|
-
* Join a child handle by invite
|
|
748
|
+
* Join a child handle by invite. The caller waits up to `timeout`; the join itself goes on
|
|
749
|
+
* until it is admitted, denied or expired, across restarts, and the handle then arrives
|
|
750
|
+
* with the `handle` event.
|
|
704
751
|
*
|
|
705
752
|
* @param {string} invite
|
|
706
753
|
* @param {string} type
|
|
707
754
|
* @param {JoinChildOpts} [opts]
|
|
708
755
|
* @returns {Promise<Handle>}
|
|
756
|
+
* @private
|
|
709
757
|
*/
|
|
710
|
-
async _join(invite, type,
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
if (pending) return pending
|
|
717
|
-
const joining = this._pair(invite, type, opts, target)
|
|
718
|
-
this._joining.set(key, joining)
|
|
758
|
+
async _join(invite, type, { timeout = TIMEOUT } = {}) {
|
|
759
|
+
const known = await this._joined(type, Invite.parse(invite).discoveryKey)
|
|
760
|
+
if (known) return known
|
|
761
|
+
|
|
762
|
+
const join = this._start(invite, type)
|
|
763
|
+
join.waiting++
|
|
719
764
|
try {
|
|
720
|
-
return await
|
|
765
|
+
return await wait(join.done, timeout)
|
|
721
766
|
} finally {
|
|
722
|
-
|
|
767
|
+
join.waiting--
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
/** @private */
|
|
772
|
+
_start(invite, type) {
|
|
773
|
+
const target = Invite.parse(invite).discoveryKey
|
|
774
|
+
const key = `${type}/${b4a.toHex(target)}`
|
|
775
|
+
let join = this._joining.get(key)
|
|
776
|
+
if (!join) {
|
|
777
|
+
join = new Join(this, {
|
|
778
|
+
type,
|
|
779
|
+
spec: pickHandle(this.spec, type),
|
|
780
|
+
discoveryKey: target,
|
|
781
|
+
onend: () => this._joining.delete(key)
|
|
782
|
+
})
|
|
783
|
+
this._joining.set(key, join)
|
|
723
784
|
}
|
|
785
|
+
if (join.invite !== invite) join.start(invite)
|
|
786
|
+
return join
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
/** @private */
|
|
790
|
+
async _cancel(invite) {
|
|
791
|
+
const id = b4a.toHex(Invite.parse(invite).discoveryKey)
|
|
792
|
+
const join = [...this.root._joining.values()].find((join) => join.id === id)
|
|
793
|
+
await join?.cancel()
|
|
794
|
+
return !!join
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
// a stored writer still admitted reopens without pairing; a removed writer's core is frozen,
|
|
798
|
+
// so that one pairs again with a fresh keypair
|
|
799
|
+
/** @private */
|
|
800
|
+
async _joined(type, target) {
|
|
801
|
+
const { data: joined } = await this.store.get('handles')
|
|
802
|
+
const existing = joined.find((h) => h.type === type && b4a.equals(discoveryKey(h.key), target))
|
|
803
|
+
if (!existing) return null
|
|
804
|
+
const known = await this._load(type, existing.id)
|
|
805
|
+
const { data: me } = await known.store.get('members', this.identity.id)
|
|
806
|
+
const { data: device } = await known.store.get('devices', hid.encode(known.store.writerKey))
|
|
807
|
+
// a reader never had a seat, a removed writer lost it
|
|
808
|
+
if (me && (device || me.role === 'reader')) return known
|
|
809
|
+
await known.close().catch(safetyCatch)
|
|
810
|
+
return null
|
|
724
811
|
}
|
|
725
812
|
|
|
726
813
|
/**
|
|
727
|
-
*
|
|
814
|
+
* Open a joined handle with the keys its reply delivered, once this writer is admitted.
|
|
815
|
+
*
|
|
728
816
|
* @param {string} type
|
|
729
|
-
* @param {
|
|
730
|
-
* @param {Uint8Array | null} [target]
|
|
817
|
+
* @param {import('@cero-base/core/pairing').JoinResult} reply
|
|
731
818
|
* @returns {Promise<Handle>}
|
|
819
|
+
* @private
|
|
732
820
|
*/
|
|
733
|
-
async
|
|
734
|
-
const deadline = timeout || TIMEOUT
|
|
735
|
-
|
|
736
|
-
// a stored writer still admitted reopens without waiting; a removed writer's core is
|
|
737
|
-
// frozen, so fall through to a real pairing and a fresh keypair
|
|
738
|
-
if (target) {
|
|
739
|
-
const { data: joined } = await this.store.get('handles')
|
|
740
|
-
const existing = joined.find(
|
|
741
|
-
(h) => h.type === type && b4a.equals(discoveryKey(h.key), target)
|
|
742
|
-
)
|
|
743
|
-
if (existing) {
|
|
744
|
-
const known = await this._load(type, existing.id)
|
|
745
|
-
const { data: me } = await known.store.get('members', this.identity.id)
|
|
746
|
-
const { data: device } = await known.store.get('devices', hid.encode(known.store.writerKey))
|
|
747
|
-
if (me && device) return known
|
|
748
|
-
await known.close().catch(safetyCatch)
|
|
749
|
-
}
|
|
750
|
-
}
|
|
751
|
-
|
|
752
|
-
// offline join: rendezvous on the invite-derived BLE UUID for the join
|
|
753
|
-
const stopNearby = this.root.bluetooth ? this.root.bluetooth.announce(invite) : null
|
|
754
|
-
|
|
821
|
+
async _enter(type, reply) {
|
|
755
822
|
const child = /** @type {Child} */ (
|
|
756
|
-
|
|
757
|
-
parent: this,
|
|
823
|
+
this._room({
|
|
758
824
|
spec: pickHandle(this.spec, type),
|
|
759
825
|
namespace: `${NS}/handle/${type}/${randomNs()}`,
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
}).finally(() => stopNearby?.())
|
|
826
|
+
...delivered(reply)
|
|
827
|
+
})
|
|
763
828
|
)
|
|
764
|
-
// whenWritable timing out (host offline) is normal, don't leak the opened child
|
|
765
829
|
let publish = null
|
|
766
830
|
let abort = null
|
|
767
831
|
let inflightId = null
|
|
768
832
|
try {
|
|
769
833
|
await child.ready()
|
|
770
|
-
|
|
834
|
+
// admitted once our member row lands; the same apply seats a writer, a reader has no seat
|
|
835
|
+
const member = await admitted(child.store, this.identity.id)
|
|
836
|
+
if (member.role !== 'reader' && !child.store.writable) {
|
|
837
|
+
await child.store.whenWritable({ timeout: 0 })
|
|
838
|
+
}
|
|
771
839
|
|
|
772
840
|
const id = hid.encode(child.store.key)
|
|
773
841
|
// same create/open race as _create, a concurrent _load must share this child
|
|
@@ -790,7 +858,6 @@ export class Handle extends ReadyResource {
|
|
|
790
858
|
createdAt: ts,
|
|
791
859
|
updatedAt: ts
|
|
792
860
|
})
|
|
793
|
-
this._wireAccept(child)
|
|
794
861
|
this._adopt(child, {})
|
|
795
862
|
publish(child)
|
|
796
863
|
this._loading?.delete(id)
|
|
@@ -803,6 +870,20 @@ export class Handle extends ReadyResource {
|
|
|
803
870
|
}
|
|
804
871
|
}
|
|
805
872
|
|
|
873
|
+
// joins not answered at the last close go on, with nobody waiting; the mailbox sends what its
|
|
874
|
+
// outbox kept
|
|
875
|
+
/** @private */
|
|
876
|
+
async _carryOn() {
|
|
877
|
+
if (!this.local) return
|
|
878
|
+
for (const { id, invite, type } of (await this.local.store.get('joins')).data) {
|
|
879
|
+
if (await this._joined(type, Invite.parse(invite).discoveryKey)) {
|
|
880
|
+
await this.local.store.del('joins', id)
|
|
881
|
+
continue
|
|
882
|
+
}
|
|
883
|
+
this._start(invite, type)
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
|
|
806
887
|
/**
|
|
807
888
|
* Get an open child by id, or re-open it. Concurrent calls for the same id share one
|
|
808
889
|
* in-flight load, so the child is built — and `handle` emitted — exactly once.
|
|
@@ -810,12 +891,13 @@ export class Handle extends ReadyResource {
|
|
|
810
891
|
* @param {string} type
|
|
811
892
|
* @param {string} id
|
|
812
893
|
* @returns {Promise<Handle>}
|
|
894
|
+
* @private
|
|
813
895
|
*/
|
|
814
|
-
async _load(type, id
|
|
896
|
+
async _load(type, id) {
|
|
815
897
|
for (const c of this.children) if (c.id === id) return c
|
|
816
898
|
const existing = this._loading.get(id)
|
|
817
899
|
if (existing) return existing
|
|
818
|
-
const loading = this._reopen(type, id
|
|
900
|
+
const loading = this._reopen(type, id)
|
|
819
901
|
this._loading.set(id, loading)
|
|
820
902
|
try {
|
|
821
903
|
return await loading
|
|
@@ -831,8 +913,9 @@ export class Handle extends ReadyResource {
|
|
|
831
913
|
* @param {string} type
|
|
832
914
|
* @param {string} id
|
|
833
915
|
* @returns {Promise<Handle>}
|
|
916
|
+
* @private
|
|
834
917
|
*/
|
|
835
|
-
async _reopen(type, id
|
|
918
|
+
async _reopen(type, id) {
|
|
836
919
|
const { data } = await this.store.get('handles', id)
|
|
837
920
|
if (!data) throw CeroError.UNKNOWN('handle', id)
|
|
838
921
|
if (data.type !== type) {
|
|
@@ -843,58 +926,68 @@ export class Handle extends ReadyResource {
|
|
|
843
926
|
if (firstTime) {
|
|
844
927
|
writer = Identity.randomKeyPair()
|
|
845
928
|
}
|
|
846
|
-
const child =
|
|
847
|
-
parent: this,
|
|
929
|
+
const child = this._room({
|
|
848
930
|
spec: pickHandle(this.spec, type),
|
|
849
931
|
namespace: `${NS}/handle/${type}/${id}`,
|
|
850
932
|
key: data.key,
|
|
851
933
|
encryptionKey: data.encryptionKey,
|
|
852
934
|
keyPair: /** @type {KeyPair} */ (writer)
|
|
853
935
|
})
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
936
|
+
try {
|
|
937
|
+
await child.ready()
|
|
938
|
+
if (firstTime && !child.store.writable) {
|
|
939
|
+
await child.store.claim()
|
|
940
|
+
}
|
|
941
|
+
if (firstTime) {
|
|
942
|
+
await this._saveKeyPair(id, writer)
|
|
943
|
+
}
|
|
944
|
+
} catch (err) {
|
|
945
|
+
await child.close().catch(safetyCatch)
|
|
946
|
+
throw err
|
|
860
947
|
}
|
|
861
|
-
// `accept: false` is a host-approval gate, re-arming it silently is worse
|
|
862
|
-
if (opts?.accept !== false) this._wireAccept(child, { role: opts?.role })
|
|
863
948
|
this._adopt(child, {})
|
|
864
949
|
return child
|
|
865
950
|
}
|
|
866
951
|
|
|
867
|
-
|
|
952
|
+
// a room has its type's hooks before it opens, so no op it applies runs without them
|
|
953
|
+
/** @private */
|
|
954
|
+
_room(opts) {
|
|
955
|
+
const child = new Handle({ parent: this, ...opts })
|
|
956
|
+
for (const hook of this._typeHooks) hook.apply(child)
|
|
957
|
+
return child
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
/** @private */
|
|
961
|
+
async _sleep() {
|
|
868
962
|
if (this.closing || this.closed) return
|
|
869
|
-
await
|
|
870
|
-
await this.bluetooth?.suspend().catch(this._onerror)
|
|
963
|
+
await this._bluetooth?.suspend().catch(this._onerror)
|
|
871
964
|
await this.network.suspend().catch(this._onerror)
|
|
872
965
|
await this.store.store.suspend().catch(this._onerror)
|
|
873
966
|
}
|
|
874
967
|
|
|
875
|
-
|
|
968
|
+
/** @private */
|
|
969
|
+
async _wake() {
|
|
876
970
|
if (this.closing || this.closed) return
|
|
877
971
|
await this.store.store.resume().catch(this._onerror)
|
|
878
972
|
await this.network.resume().catch(this._onerror)
|
|
879
|
-
await this.
|
|
880
|
-
await Promise.all([...this.children].map((c) => c.pair?.resume().catch(this._onerror)))
|
|
973
|
+
await this._bluetooth?.resume().catch(this._onerror)
|
|
881
974
|
}
|
|
882
975
|
|
|
883
|
-
|
|
976
|
+
/** @private */
|
|
884
977
|
_adopt(child, info) {
|
|
885
|
-
bind(child, child.type, this.operators)
|
|
886
|
-
for (const hook of this._typeHooks) hook.apply(child)
|
|
887
978
|
this.children.add(child)
|
|
979
|
+
this._serve(child)
|
|
888
980
|
this.emit('handle', child, info)
|
|
889
981
|
}
|
|
890
982
|
|
|
891
983
|
// before(me.room.notes, fn): on every room open now and every one opened later
|
|
892
|
-
|
|
984
|
+
/** @private */
|
|
985
|
+
_hookType(ref, attach, opts) {
|
|
893
986
|
const offs = new Map()
|
|
894
987
|
const hook = {
|
|
895
988
|
apply: (child) => {
|
|
896
989
|
if (child.type !== ref.type) return
|
|
897
|
-
offs.set(child,
|
|
990
|
+
offs.set(child, attach(child))
|
|
898
991
|
child.once('close', () => offs.delete(child))
|
|
899
992
|
}
|
|
900
993
|
}
|
|
@@ -909,21 +1002,38 @@ export class Handle extends ReadyResource {
|
|
|
909
1002
|
return off
|
|
910
1003
|
}
|
|
911
1004
|
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
1005
|
+
// a room with invites is reopened at boot, so its joins are answered whenever we are online,
|
|
1006
|
+
// not only while the app has the room open
|
|
1007
|
+
/** @private */
|
|
1008
|
+
_serve(child) {
|
|
1009
|
+
if (!this.local || !child._pair) return
|
|
1010
|
+
const save = async () => {
|
|
1011
|
+
const { serving } = child._pair
|
|
1012
|
+
if (serving === child._serving) return
|
|
1013
|
+
child._serving = serving
|
|
1014
|
+
if (!serving) return this.local.store.del('serving', child.id)
|
|
1015
|
+
await this.local.store.put('serving', { id: child.id, type: child.type })
|
|
1016
|
+
}
|
|
1017
|
+
child._pair.on('serving', () => save().catch(this._onerror))
|
|
1018
|
+
save().catch(this._onerror)
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
/** @private */
|
|
1022
|
+
async _reserve() {
|
|
1023
|
+
if (!this.local) return
|
|
1024
|
+
for (const { id, type } of (await this.local.store.get('serving')).data) {
|
|
1025
|
+
this._load(type, id).catch((err) => {
|
|
1026
|
+
if (err.code === 'UNKNOWN') return this.local.store.del('serving', id).catch(safetyCatch)
|
|
1027
|
+
this._onerror(err)
|
|
1028
|
+
})
|
|
1029
|
+
}
|
|
921
1030
|
}
|
|
922
1031
|
|
|
923
1032
|
/**
|
|
924
1033
|
* @param {string} id
|
|
925
1034
|
* @param {KeyPair | { publicKey: Uint8Array, secretKey: Uint8Array } | null} keyPair
|
|
926
1035
|
* @returns {Promise<void>}
|
|
1036
|
+
* @private
|
|
927
1037
|
*/
|
|
928
1038
|
async _saveKeyPair(id, keyPair) {
|
|
929
1039
|
if (!this.local || !keyPair) return
|
|
@@ -937,6 +1047,7 @@ export class Handle extends ReadyResource {
|
|
|
937
1047
|
/**
|
|
938
1048
|
* @param {string} id
|
|
939
1049
|
* @returns {Promise<{ publicKey: Uint8Array, secretKey: Uint8Array } | null>}
|
|
1050
|
+
* @private
|
|
940
1051
|
*/
|
|
941
1052
|
async _loadKeyPair(id) {
|
|
942
1053
|
if (!this.local) return null
|
|
@@ -949,8 +1060,8 @@ export class Handle extends ReadyResource {
|
|
|
949
1060
|
}
|
|
950
1061
|
|
|
951
1062
|
/**
|
|
952
|
-
* Pair into an existing handle via an invite, returning a brand-new
|
|
953
|
-
*
|
|
1063
|
+
* Pair into an existing handle via an invite, returning a brand-new `Handle` opened with the
|
|
1064
|
+
* delivered keys. A one-shot join: the root's `_join` is the one that survives restarts.
|
|
954
1065
|
*
|
|
955
1066
|
* @param {string} invite
|
|
956
1067
|
* @param {StaticJoinOpts} [opts]
|
|
@@ -958,7 +1069,7 @@ export class Handle extends ReadyResource {
|
|
|
958
1069
|
*/
|
|
959
1070
|
static async join(
|
|
960
1071
|
invite,
|
|
961
|
-
{ parent, network, identity, store, spec, namespace,
|
|
1072
|
+
{ parent, network, identity, store, spec, namespace, writer, timeout = TIMEOUT } = {}
|
|
962
1073
|
) {
|
|
963
1074
|
const net = network || parent?.network
|
|
964
1075
|
const id = identity || parent?.identity
|
|
@@ -967,43 +1078,57 @@ export class Handle extends ReadyResource {
|
|
|
967
1078
|
if (!store && !parent) throw CeroError.REQUIRED('store')
|
|
968
1079
|
if (!spec) throw CeroError.REQUIRED('spec')
|
|
969
1080
|
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
const pair = new Pairing({ network: net, identity: id, host: false })
|
|
973
|
-
await pair.ready()
|
|
974
|
-
|
|
975
|
-
let key, encryptionKey, additional
|
|
1081
|
+
// standalone, a mailbox of its own for this one join
|
|
1082
|
+
const mailbox = parent ? null : new Mailbox(net)
|
|
976
1083
|
try {
|
|
977
|
-
const
|
|
978
|
-
|
|
1084
|
+
const reply = await Pairing.join(mailbox || parent.mailbox, invite, {
|
|
1085
|
+
identity: id,
|
|
1086
|
+
spec,
|
|
1087
|
+
writer,
|
|
1088
|
+
timeout
|
|
1089
|
+
})
|
|
1090
|
+
const opts = { parent, store, identity: id, network: net, spec, namespace }
|
|
1091
|
+
return Handle.fromReply(reply, opts)
|
|
979
1092
|
} finally {
|
|
980
|
-
await
|
|
1093
|
+
await mailbox?.close()
|
|
981
1094
|
}
|
|
1095
|
+
}
|
|
982
1096
|
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
1097
|
+
/**
|
|
1098
|
+
* A handle opened with the keys a pairing reply delivered.
|
|
1099
|
+
*
|
|
1100
|
+
* @param {import('@cero-base/core/pairing').JoinResult} reply
|
|
1101
|
+
* @param {Omit<HandleOpts, 'key' | 'encryptionKey' | 'epochs' | 'keyPair'>} opts
|
|
1102
|
+
* @returns {Handle}
|
|
1103
|
+
*/
|
|
1104
|
+
static fromReply(reply, opts) {
|
|
1105
|
+
return new Handle({ ...opts, ...delivered(reply) })
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
// the keys a pairing reply delivered, as a handle opens with them
|
|
1110
|
+
function delivered({ key, encryptionKey, epochs, writer }) {
|
|
1111
|
+
return { key, encryptionKey, epochs, keyPair: writer }
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
function admitted(db, id) {
|
|
1115
|
+
return new Promise((resolve, reject) => {
|
|
1116
|
+
const check = async () => {
|
|
1117
|
+
const { data } = await db.get('members', id)
|
|
1118
|
+
if (!data) return
|
|
1119
|
+
db.off('update', onupdate)
|
|
1120
|
+
resolve(data)
|
|
991
1121
|
}
|
|
1122
|
+
const onupdate = () => check().catch(reject)
|
|
1123
|
+
db.on('update', onupdate)
|
|
1124
|
+
onupdate()
|
|
1125
|
+
})
|
|
1126
|
+
}
|
|
992
1127
|
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
network: net,
|
|
998
|
-
spec,
|
|
999
|
-
namespace,
|
|
1000
|
-
routes,
|
|
1001
|
-
key,
|
|
1002
|
-
encryptionKey,
|
|
1003
|
-
epochs,
|
|
1004
|
-
keyPair: writer
|
|
1005
|
-
})
|
|
1006
|
-
}
|
|
1128
|
+
// a device without a local store keeps its mail in memory
|
|
1129
|
+
function boxes(local) {
|
|
1130
|
+
if (!local) return {}
|
|
1131
|
+
return { inbox: box(local.store, 'inbox'), outbox: box(local.store, 'outbox') }
|
|
1007
1132
|
}
|
|
1008
1133
|
|
|
1009
1134
|
function pickHandle(spec, type) {
|