@cero-base/cero 2.4.1 → 2.6.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/package.json +25 -11
- package/src/build/index.js +3 -0
- package/src/build/internal.js +5 -2
- package/src/build/schemas.js +43 -6
- package/src/handle/index.js +140 -20
- package/src/index.js +126 -16
- package/src/lib/bluetooth.js +2 -5
- package/src/lib/operators.js +19 -0
- package/src/lib/peek.js +4 -4
- package/src/lib/spec.js +1 -0
- package/src/push/firebase.js +23 -0
- package/src/push/index.js +71 -0
- package/src/rpc/client.js +19 -4
- package/src/rpc/push.js +57 -0
- package/src/rpc/server.js +4 -2
- package/types/build/internal.d.ts +7 -0
- package/types/build/schemas.d.ts +28 -1
- package/types/extensions/index.d.ts +14 -2
- package/types/handle/index.d.ts +16 -3
- package/types/index.d.ts +10 -0
- package/types/lib/operators.d.ts +21 -0
- package/types/lib/peek.d.ts +2 -2
- package/types/lib/spec.d.ts +5 -0
- package/types/push/firebase.d.ts +12 -0
- package/types/push/index.d.ts +43 -0
- package/types/rpc/client.d.ts +19 -4
- package/types/rpc/push.d.ts +20 -0
package/src/index.js
CHANGED
|
@@ -4,14 +4,19 @@ import Corestore from 'corestore'
|
|
|
4
4
|
import safetyCatch from 'safety-catch'
|
|
5
5
|
import c from 'compact-encoding'
|
|
6
6
|
import b4a from 'b4a'
|
|
7
|
+
import hid from 'hypercore-id-encoding'
|
|
7
8
|
import fs from 'fs'
|
|
8
9
|
|
|
9
10
|
import { Identity } from '@cero-base/core/identity'
|
|
10
11
|
import { Network } from '@cero-base/core/network'
|
|
12
|
+
import { Mailbox } from '@cero-base/core/mailbox'
|
|
13
|
+
import { Pairing } from '@cero-base/core/pairing'
|
|
14
|
+
import { Invite } from '@cero-base/core/invite'
|
|
15
|
+
import { epochEntries } from '@cero-base/core/database/encryption'
|
|
11
16
|
import { CeroError } from '@cero-base/core/errors'
|
|
12
17
|
|
|
13
18
|
import { Handle, Ref } from './handle/index.js'
|
|
14
|
-
import { Local } from './local/index.js'
|
|
19
|
+
import { Local, box } from './local/index.js'
|
|
15
20
|
import { Bluetooth } from './lib/bluetooth.js'
|
|
16
21
|
import * as verbs from './lib/operators.js'
|
|
17
22
|
import { peek } from './lib/peek.js'
|
|
@@ -30,6 +35,8 @@ export { t, schema } from './lib/spec.js'
|
|
|
30
35
|
/**
|
|
31
36
|
* @typedef {object} CeroOpts
|
|
32
37
|
* @property {string} [phrase] The identity's BIP-39 phrase, as `cero.phrase(me)` gives it: on a new `dir` it recovers that identity.
|
|
38
|
+
* @property {string} [invite] A device invite, as `cero.invite(me)` gives it on another device of yours: on a new `dir` this device joins that identity once a device of it accepts, with no phrase.
|
|
39
|
+
* @property {(id: string) => void} [onrequest] With `invite`: called with the request's id as it is sent, the same id `me.requests` shows on the accepting device.
|
|
33
40
|
* @property {12 | 24} [words] Mnemonic length when generating a fresh identity.
|
|
34
41
|
* @property {string | null} [name] Friendly device name persisted on the identity claim.
|
|
35
42
|
* @property {boolean} [isMobile] Marks this device as mobile.
|
|
@@ -89,11 +96,21 @@ async function start(dir, spec, opts = {}) {
|
|
|
89
96
|
|
|
90
97
|
const device = (await local.store.get('keypair')).data
|
|
91
98
|
const done = !!device && !device.setup
|
|
92
|
-
|
|
99
|
+
if (done && opts.invite) {
|
|
100
|
+
throw CeroError.INVALID('dir holds an identity: a device invite needs a fresh one')
|
|
101
|
+
}
|
|
102
|
+
// a device invite, this launch's or the one a killed launch was waiting on
|
|
103
|
+
const pending = done || opts.phrase ? null : await pendingLink(local)
|
|
104
|
+
const linking = !done && !opts.phrase && !!(opts.invite || pending)
|
|
105
|
+
if (device?.setup === 'link' && !linking && !opts.phrase) {
|
|
106
|
+
throw CeroError.REQUIRED('invite: this dir waits for a device invite, or a phrase')
|
|
107
|
+
}
|
|
108
|
+
const resolved = linking ? null : await resolveIdentity(opts, local, done)
|
|
93
109
|
// cero creates only an identity it minted, in this launch or in the killed one it resumes
|
|
94
|
-
const creating =
|
|
95
|
-
|
|
96
|
-
const
|
|
110
|
+
const creating =
|
|
111
|
+
!done && !linking && !opts.phrase && (resolved.fresh || device?.setup === 'create')
|
|
112
|
+
const recovering = !done && !linking && !creating
|
|
113
|
+
const setup = done ? null : linking ? 'link' : creating ? 'create' : 'recover'
|
|
97
114
|
const keyPair =
|
|
98
115
|
done || device?.setup === setup
|
|
99
116
|
? { publicKey: device.publicKey, secretKey: device.secretKey }
|
|
@@ -102,8 +119,11 @@ async function start(dir, spec, opts = {}) {
|
|
|
102
119
|
if (!done && device?.setup !== setup) {
|
|
103
120
|
await local.store.set('keypair', { ...keyPair, setup })
|
|
104
121
|
}
|
|
105
|
-
if (
|
|
106
|
-
|
|
122
|
+
if (resolved?.minted) {
|
|
123
|
+
await local.store.set('master', { seed: resolved.identity.seed })
|
|
124
|
+
await local.store.set('device', pack(resolved.identity))
|
|
125
|
+
}
|
|
126
|
+
const timeout = opts.recoveryTimeout ?? TIMEOUT
|
|
107
127
|
|
|
108
128
|
// a storage remembers its channel; reopening under another would silently rejoin the global network
|
|
109
129
|
const stored = (await local.store.get('environment')).data?.channel ?? null
|
|
@@ -122,6 +142,12 @@ async function start(dir, spec, opts = {}) {
|
|
|
122
142
|
onerror
|
|
123
143
|
})
|
|
124
144
|
await network.ready()
|
|
145
|
+
// the link first: who this device is comes with the reply
|
|
146
|
+
const linked = linking
|
|
147
|
+
? await link(local, network, spec, { ...opts, writer: keyPair, timeout }, pending)
|
|
148
|
+
: null
|
|
149
|
+
const identity = linked ? linked.identity : resolved.identity
|
|
150
|
+
const fresh = resolved?.fresh === true
|
|
125
151
|
// the radio before the pointer read: a phrase recovers from a device in range, no internet
|
|
126
152
|
bluetooth = new Bluetooth(network, { ...bt, identity, keyPair })
|
|
127
153
|
await bluetooth.ready()
|
|
@@ -133,13 +159,13 @@ async function start(dir, spec, opts = {}) {
|
|
|
133
159
|
const manifest = pointerManifest(store, identity)
|
|
134
160
|
const pointer = store.get(
|
|
135
161
|
creating
|
|
136
|
-
? { keyPair:
|
|
162
|
+
? { keyPair: await Identity.keyPair(identity.seed), manifest }
|
|
137
163
|
: { key: Hypercore.key(manifest) }
|
|
138
164
|
)
|
|
139
165
|
await pointer.ready()
|
|
140
166
|
network.attach(pointer)
|
|
141
167
|
|
|
142
|
-
const key = recovering ? await readPointer(pointer, timeout) :
|
|
168
|
+
const key = recovering ? await readPointer(pointer, timeout) : linked?.key
|
|
143
169
|
|
|
144
170
|
me = new Handle({
|
|
145
171
|
storage,
|
|
@@ -153,10 +179,16 @@ async function start(dir, spec, opts = {}) {
|
|
|
153
179
|
dir,
|
|
154
180
|
key,
|
|
155
181
|
keyPair,
|
|
182
|
+
epochs: linked?.epochs,
|
|
156
183
|
bluetooth,
|
|
157
184
|
bootstrap: done
|
|
158
185
|
? null
|
|
159
|
-
: {
|
|
186
|
+
: {
|
|
187
|
+
name: opts.name || null,
|
|
188
|
+
isMobile: opts.isMobile === true,
|
|
189
|
+
recovering: recovering || linking,
|
|
190
|
+
timeout
|
|
191
|
+
}
|
|
160
192
|
})
|
|
161
193
|
// an extension's hooks see every op the root applies; what else it calls waits for the open
|
|
162
194
|
const setups = Promise.all(me.extensions.map(async (ext) => ext.setup?.(me)))
|
|
@@ -168,6 +200,10 @@ async function start(dir, spec, opts = {}) {
|
|
|
168
200
|
if (creating && pointer.length === 0) {
|
|
169
201
|
await pointer.append(c.encode(c.fixed32, me.store.key))
|
|
170
202
|
}
|
|
203
|
+
if (linked) {
|
|
204
|
+
await local.store.set('device', pack(identity))
|
|
205
|
+
await local.store.del('joins', linked.id)
|
|
206
|
+
}
|
|
171
207
|
await local.store.set('keypair', { setup: null })
|
|
172
208
|
}
|
|
173
209
|
|
|
@@ -231,14 +267,88 @@ async function readPointer(pointer, timeout) {
|
|
|
231
267
|
}
|
|
232
268
|
}
|
|
233
269
|
|
|
234
|
-
//
|
|
270
|
+
// the identity as this device holds it: stored, or minted now from the phrase or afresh
|
|
235
271
|
async function resolveIdentity(opts, local, done) {
|
|
236
272
|
const provided = opts.phrase ? Identity.toSeed(opts.phrase) : null
|
|
237
|
-
const
|
|
273
|
+
const seed = (await local.store.get('master')).data?.seed ?? null
|
|
274
|
+
const row = (await local.store.get('device')).data
|
|
275
|
+
if (seed && !row) throw CeroError.INVALID('this storage predates device keys: recreate it')
|
|
276
|
+
const same =
|
|
277
|
+
row && provided ? b4a.equals((await Identity.keyPair(provided)).publicKey, row.identity) : true
|
|
238
278
|
// another identity comes in only through restore, which wipes this one first
|
|
239
|
-
if (done &&
|
|
240
|
-
|
|
279
|
+
if (done && !same) throw CeroError.INVALID('dir holds another identity: switch with cero.restore')
|
|
280
|
+
// a phrase given to an unfinished setup takes over from the identity it minted
|
|
281
|
+
if (row && same) return { identity: unpack(row, seed), fresh: false, minted: false }
|
|
282
|
+
const identity = await Identity.create({ seed: provided, words: opts.words })
|
|
283
|
+
return { identity, fresh: !provided, minted: true }
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// the root's own join in the joins rows
|
|
287
|
+
const LINK = 'root'
|
|
288
|
+
|
|
289
|
+
async function pendingLink(local) {
|
|
290
|
+
const { data: rows } = await local.store.get('joins')
|
|
291
|
+
return rows.find((row) => row.type === LINK) ?? null
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// the root's join: this device, bare, knocks with the invite and waits for a device of the identity
|
|
295
|
+
// to let it in. What it learns is kept in its joins row, so a killed launch resumes it
|
|
296
|
+
async function link(local, network, spec, { invite, writer, onrequest, timeout }, pending) {
|
|
297
|
+
const parsed = Invite.parse(invite ?? pending.invite)
|
|
298
|
+
if (parsed.data?.byteLength !== 32) throw CeroError.INVALID_INVITE('not a device invite')
|
|
299
|
+
const secret = pending?.device ?? Identity.randomKeyPair().secretKey
|
|
300
|
+
const device = { publicKey: secret.subarray(32), secretKey: secret }
|
|
301
|
+
const row = {
|
|
302
|
+
...pending,
|
|
303
|
+
id: b4a.toHex(parsed.discoveryKey),
|
|
304
|
+
type: LINK,
|
|
305
|
+
invite: invite ?? pending.invite,
|
|
306
|
+
publicKey: writer.publicKey,
|
|
307
|
+
secretKey: writer.secretKey,
|
|
308
|
+
device: secret
|
|
241
309
|
}
|
|
242
|
-
|
|
243
|
-
|
|
310
|
+
await local.store.put('joins', row)
|
|
311
|
+
let reply = row.key
|
|
312
|
+
? { ...row, epochs: row.epochs ? c.decode(epochEntries, row.epochs) : [] }
|
|
313
|
+
: null
|
|
314
|
+
if (!reply) {
|
|
315
|
+
const { store } = network
|
|
316
|
+
const inbox = box(local.store, 'inbox')
|
|
317
|
+
const outbox = box(local.store, 'outbox')
|
|
318
|
+
const mailbox = new Mailbox(network, { inbox, outbox })
|
|
319
|
+
await mailbox.ready()
|
|
320
|
+
try {
|
|
321
|
+
const signers = [{ publicKey: writer.publicKey }]
|
|
322
|
+
onrequest?.(hid.encode(Hypercore.key({ version: store.manifestVersion, signers })))
|
|
323
|
+
// the reply is kept before the join settles, a denial forgets the join
|
|
324
|
+
const keep = async (answer) => {
|
|
325
|
+
if (answer instanceof Error) return local.store.del('joins', row.id)
|
|
326
|
+
const { key, encryptionKey, epochs, proof } = answer
|
|
327
|
+
const kept = { ...row, key, encryptionKey, epochs: c.encode(epochEntries, epochs), proof }
|
|
328
|
+
await local.store.put('joins', kept)
|
|
329
|
+
}
|
|
330
|
+
const identity = await Identity.bare(device)
|
|
331
|
+
reply = await Pairing.join(mailbox, row.invite, { identity, spec, writer, timeout, keep })
|
|
332
|
+
} finally {
|
|
333
|
+
await mailbox.close()
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
// the chain the accepting device wrote ends at this device, under the identity the invite named
|
|
337
|
+
const chained = Identity.verify(reply.proof, null, parsed.data)
|
|
338
|
+
if (!chained || !b4a.equals(chained.device, device.publicKey)) {
|
|
339
|
+
throw CeroError.INVALID('the reply does not link this device to the identity of the invite')
|
|
340
|
+
}
|
|
341
|
+
const { encryptionKey, proof } = reply
|
|
342
|
+
const identity = Identity.from({ publicKey: parsed.data, encryptionKey, device, proof })
|
|
343
|
+
return { identity, key: reply.key, epochs: reply.epochs, id: row.id }
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
function pack({ device, proof, publicKey, encryptionKey }) {
|
|
347
|
+
const { publicKey: key, secretKey } = device
|
|
348
|
+
return { publicKey: key, secretKey, proof, identity: publicKey, encryptionKey }
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function unpack({ publicKey, secretKey, proof, identity, encryptionKey }, seed) {
|
|
352
|
+
const device = { publicKey, secretKey }
|
|
353
|
+
return Identity.from({ publicKey: identity, encryptionKey, device, proof, seed })
|
|
244
354
|
}
|
package/src/lib/bluetooth.js
CHANGED
|
@@ -234,11 +234,8 @@ function topicOf(base, topic) {
|
|
|
234
234
|
function signed(info, key) {
|
|
235
235
|
if (typeof info?.id !== 'string' || typeof info.proof !== 'string') return false
|
|
236
236
|
try {
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
b4a.concat([DEVICE, key]),
|
|
240
|
-
b4a.from(info.proof, 'hex')
|
|
241
|
-
)
|
|
237
|
+
const proof = b4a.from(info.proof, 'hex')
|
|
238
|
+
return Identity.verify(proof, b4a.concat([DEVICE, key]), hid.decode(info.id)) !== null
|
|
242
239
|
} catch {
|
|
243
240
|
return false
|
|
244
241
|
}
|
package/src/lib/operators.js
CHANGED
|
@@ -106,6 +106,12 @@ const WRITES = { single: ['set', 'del'], collection: ['put', 'set', 'del'] }
|
|
|
106
106
|
* opens; register in an extension's `setup` to see every op the root applies too. The imported
|
|
107
107
|
* operators throw inside a hook; use the ones on `ctx`. Not available over RPC.
|
|
108
108
|
*
|
|
109
|
+
* On `members`, removing someone or changing her rank is the rank's call by default: the writer
|
|
110
|
+
* outranks whom she acts on, and `ctx.ranked` says whether she does. A rule there may return
|
|
111
|
+
* `'grant'` to allow what rank alone refuses (a bare `true` grants nothing), or `false` to refuse
|
|
112
|
+
* what it allows, and only a writer's grant counts. It is decided before anything moves. The
|
|
113
|
+
* last owner is never removed nor demoted.
|
|
114
|
+
*
|
|
109
115
|
* @param {Ref} ref
|
|
110
116
|
* @param {(ctx: HookContext) => unknown} fn
|
|
111
117
|
* @param {{ signal?: AbortSignal }} [opts]
|
|
@@ -484,6 +490,19 @@ export async function deactivate(ctx) {
|
|
|
484
490
|
return ctx._active(false)
|
|
485
491
|
}
|
|
486
492
|
|
|
493
|
+
/**
|
|
494
|
+
* A push the platform delivered, as bytes: the handle it is about and the ref the write was on,
|
|
495
|
+
* verified against this device's own data, or `null` for a forged one or one about no handle here.
|
|
496
|
+
*
|
|
497
|
+
* @param {Context} me
|
|
498
|
+
* @param {Uint8Array} payload
|
|
499
|
+
* @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean, ref: string | null } | null>}
|
|
500
|
+
*/
|
|
501
|
+
export async function receive(me, payload) {
|
|
502
|
+
if (me.parent) throw CeroError.INVALID("receive is the app's, on me")
|
|
503
|
+
return me._receive(payload)
|
|
504
|
+
}
|
|
505
|
+
|
|
487
506
|
/**
|
|
488
507
|
* Reveal the recovery phrase.
|
|
489
508
|
*
|
package/src/lib/peek.js
CHANGED
|
@@ -10,11 +10,11 @@ import { Local } from '../local/index.js'
|
|
|
10
10
|
|
|
11
11
|
/**
|
|
12
12
|
* Quickly check whether the on-disk directory at `dir` already holds an initialised cero
|
|
13
|
-
* identity (i.e. a stored
|
|
13
|
+
* identity (i.e. a stored device key with its proof).
|
|
14
14
|
*
|
|
15
15
|
* @param {string} dir Cero data directory.
|
|
16
16
|
* @param {import('./spec.js').Spec} spec Built spec, the value passed to `cero(dir, spec)`.
|
|
17
|
-
* @returns {Promise<boolean>} `true` if a
|
|
17
|
+
* @returns {Promise<boolean>} `true` if a device of an identity exists on disk.
|
|
18
18
|
*/
|
|
19
19
|
export async function peek(dir, spec) {
|
|
20
20
|
if (typeof dir !== 'string' || !dir) throw CeroError.INVALID('dir must be a non-empty string')
|
|
@@ -28,8 +28,8 @@ export async function peek(dir, spec) {
|
|
|
28
28
|
await root.ready()
|
|
29
29
|
await store.ready()
|
|
30
30
|
await local.ready()
|
|
31
|
-
const { data } = await local.store.get('
|
|
32
|
-
return !!data
|
|
31
|
+
const { data } = await local.store.get('device')
|
|
32
|
+
return !!data
|
|
33
33
|
} finally {
|
|
34
34
|
await local.close().catch(safetyCatch)
|
|
35
35
|
await store.close().catch(safetyCatch)
|
package/src/lib/spec.js
CHANGED
|
@@ -15,6 +15,7 @@ export { t, schema } from '@cero-base/core/schema'
|
|
|
15
15
|
* @property {Record<string, string>} [required] The required fields and their types.
|
|
16
16
|
* @property {string[]} [files] The fields holding file ids.
|
|
17
17
|
* @property {string} [verb]
|
|
18
|
+
* @property {boolean} [push] Whether a write to this ref pushes a notification.
|
|
18
19
|
*
|
|
19
20
|
* @typedef {object} SpecMeta
|
|
20
21
|
* @property {string} [ns]
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import b4a from 'b4a'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* `@react-native-firebase/messaging` as the messaging service `connect` takes for push: pass `messaging()`. Pushes to the app in
|
|
5
|
+
* front; the push worklet answers the ones the OS delivers while it is not.
|
|
6
|
+
*
|
|
7
|
+
* @param {{ subscribeToTopic: (topic: string) => Promise<void>, unsubscribeFromTopic: (topic: string) => Promise<void>, onMessage: (fn: (message: object) => void) => () => void }} messaging
|
|
8
|
+
* @returns {import('../rpc/push.js').Messaging}
|
|
9
|
+
*/
|
|
10
|
+
export function firebase(messaging) {
|
|
11
|
+
const payload = (message) => message?.data?.payload && b4a.from(message.data.payload, 'base64')
|
|
12
|
+
return {
|
|
13
|
+
subscribe: (topic) => messaging.subscribeToTopic(topic),
|
|
14
|
+
unsubscribe: (topic) => messaging.unsubscribeFromTopic(topic),
|
|
15
|
+
on(event, fn) {
|
|
16
|
+
if (event !== 'push') return () => {}
|
|
17
|
+
return messaging.onMessage((message) => {
|
|
18
|
+
const bytes = payload(message)
|
|
19
|
+
if (bytes) fn(bytes)
|
|
20
|
+
})
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import HypercoreStorage from 'hypercore-storage'
|
|
2
|
+
import Corestore from 'corestore'
|
|
3
|
+
import b4a from 'b4a'
|
|
4
|
+
import safetyCatch from 'safety-catch'
|
|
5
|
+
|
|
6
|
+
import { verify } from '@cero-base/core/push'
|
|
7
|
+
import { CeroError } from '@cero-base/core/errors'
|
|
8
|
+
|
|
9
|
+
import { Local } from '../local/index.js'
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* A push the platform delivered while the app is dead, verified from its storage opened
|
|
13
|
+
* read-only. `null` while the live app holds the storage, which shows the activity itself, and
|
|
14
|
+
* for a push that is forged or about no handle here.
|
|
15
|
+
*
|
|
16
|
+
* @param {string} dir The directory `cero()` opened.
|
|
17
|
+
* @param {import('../lib/spec.js').Spec} spec
|
|
18
|
+
* @param {Uint8Array} payload
|
|
19
|
+
* @param {{ storageKey?: Uint8Array }} [opts] The key `cero()` encrypts the local store with, if any.
|
|
20
|
+
* @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean, ref: string | null } | null>}
|
|
21
|
+
*/
|
|
22
|
+
export async function receive(dir, spec, payload, { storageKey } = {}) {
|
|
23
|
+
const storage = new HypercoreStorage(`${dir}/main`, { readOnly: true })
|
|
24
|
+
let store = null
|
|
25
|
+
let local = null
|
|
26
|
+
try {
|
|
27
|
+
await storage.ready()
|
|
28
|
+
store = new Corestore(storage, { manifestVersion: 2 })
|
|
29
|
+
local = new Local(null, spec, { store, storageKey })
|
|
30
|
+
await local.ready()
|
|
31
|
+
const { data: rows } = await local.store.get('topics')
|
|
32
|
+
const handles = rows.map(({ handle, key, type, name }) => ({ id: handle, key, type, name }))
|
|
33
|
+
const hit = await verify(storage, payload, handles)
|
|
34
|
+
return hit && { id: hit.id, type: hit.type, name: hit.name, newer: hit.newer, ref: hit.ref }
|
|
35
|
+
} catch (err) {
|
|
36
|
+
safetyCatch(err)
|
|
37
|
+
return null
|
|
38
|
+
} finally {
|
|
39
|
+
await local?.close().catch(safetyCatch)
|
|
40
|
+
await store?.close().catch(safetyCatch)
|
|
41
|
+
await storage.close().catch(safetyCatch)
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The bare-kit push entry: on each push the OS hands this worklet, verify it and, for one about
|
|
47
|
+
* new data on a handle this device holds, answer with what `show` returns: the notification,
|
|
48
|
+
* `{ title, body }`, or nothing. The request carries `storage`, `payload` (base64) and, when the
|
|
49
|
+
* app encrypts its local store, `storageKey` (base64).
|
|
50
|
+
*
|
|
51
|
+
* @param {import('../lib/spec.js').Spec} spec
|
|
52
|
+
* @param {(push: { id: string, type: string, name: string | null, newer: boolean, ref: string | null }) => { title: string, body: string } | null | undefined | Promise<{ title: string, body: string } | null | undefined>} show What to show for a verified push, as `cero.receive` would give it to the app.
|
|
53
|
+
* @returns {void}
|
|
54
|
+
*/
|
|
55
|
+
export function push(spec, show) {
|
|
56
|
+
if (typeof show !== 'function') throw CeroError.INVALID('push: show(push) says what to show')
|
|
57
|
+
globalThis.BareKit.on('push', async (json, reply) => {
|
|
58
|
+
let shown = null
|
|
59
|
+
try {
|
|
60
|
+
const { storage, storageKey, payload } = JSON.parse(json)
|
|
61
|
+
const hit = await receive(storage, spec, b4a.from(payload, 'base64'), {
|
|
62
|
+
storageKey: storageKey ? b4a.from(storageKey, 'base64') : undefined
|
|
63
|
+
})
|
|
64
|
+
if (hit?.newer) shown = await show(hit)
|
|
65
|
+
} catch {
|
|
66
|
+
// the OS waits for an answer: whatever went wrong, no notification
|
|
67
|
+
shown = null
|
|
68
|
+
}
|
|
69
|
+
reply(null, shown ? JSON.stringify(shown) : null)
|
|
70
|
+
})
|
|
71
|
+
}
|
package/src/rpc/client.js
CHANGED
|
@@ -8,6 +8,7 @@ import z32 from 'z32'
|
|
|
8
8
|
import { decodeId } from '@cero-base/core/blobs/codec'
|
|
9
9
|
|
|
10
10
|
import { Ref } from '../lib/refs.js'
|
|
11
|
+
import { follow } from './push.js'
|
|
11
12
|
import * as verbs from '../lib/operators.js'
|
|
12
13
|
import { t, schema } from '../lib/spec.js'
|
|
13
14
|
|
|
@@ -389,6 +390,11 @@ const operators = {
|
|
|
389
390
|
return this._verb('phrase')
|
|
390
391
|
},
|
|
391
392
|
|
|
393
|
+
/** @private */
|
|
394
|
+
_receive(payload) {
|
|
395
|
+
return this._verb('receive', payload)
|
|
396
|
+
},
|
|
397
|
+
|
|
392
398
|
/** @private */
|
|
393
399
|
_nearby(on, opts) {
|
|
394
400
|
return this._verb('nearby', on, opts)
|
|
@@ -459,10 +465,12 @@ export class Client extends RPCClient {
|
|
|
459
465
|
/**
|
|
460
466
|
* @param {import('streamx').Duplex} ipc Framed IPC stream (must be writable).
|
|
461
467
|
* @param {Spec} spec Compiled cero spec (schema + rpc + handles).
|
|
462
|
-
* @param {{ onerror?: (err: Error) => void }} [opts] Where the worker's background errors go
|
|
468
|
+
* @param {{ onerror?: (err: Error) => void, push?: import('./push.js').Messaging }} [opts] Where the worker's background errors go, the console without one; `push`: the platform's messaging service, to follow the handles' push topics.
|
|
463
469
|
*/
|
|
464
|
-
constructor(ipc, spec, { onerror } = {}) {
|
|
470
|
+
constructor(ipc, spec, { onerror, push } = {}) {
|
|
465
471
|
super(ipc, spec)
|
|
472
|
+
/** @private */
|
|
473
|
+
this._push = push || null
|
|
466
474
|
if (spec.local?.schema && !spec.local.codec) bindCodec(spec.local)
|
|
467
475
|
Object.assign(this, operators)
|
|
468
476
|
/** @private */
|
|
@@ -503,6 +511,13 @@ export class Client extends RPCClient {
|
|
|
503
511
|
Ref.attach(this, /** @type {Spec} */ (this.spec).meta.refs)
|
|
504
512
|
if (/** @type {Spec} */ (this.spec).meta.local?.refs) this.local = new LocalRefs(this)
|
|
505
513
|
this._pumpErrors()
|
|
514
|
+
if (this._push) this._unfollow = follow(this, this._push)
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/** @private */
|
|
518
|
+
async _close() {
|
|
519
|
+
if (this._unfollow) this._unfollow()
|
|
520
|
+
await super._close()
|
|
506
521
|
}
|
|
507
522
|
// the worker's answer to init and to restore: who this UI is, and where its files are served
|
|
508
523
|
/** @private */
|
|
@@ -599,7 +614,7 @@ class Handle {
|
|
|
599
614
|
*
|
|
600
615
|
* @param {import('streamx').Duplex} ipc
|
|
601
616
|
* @param {Spec} spec
|
|
602
|
-
* @param {{ onerror?: (err: Error) => void }} [opts]
|
|
617
|
+
* @param {{ onerror?: (err: Error) => void, push?: import('./push.js').Messaging }} [opts]
|
|
603
618
|
* @returns {Promise<Client>}
|
|
604
619
|
*/
|
|
605
620
|
export async function connect(ipc, spec, opts) {
|
|
@@ -614,7 +629,7 @@ export async function connect(ipc, spec, opts) {
|
|
|
614
629
|
*
|
|
615
630
|
* @param {import('streamx').Duplex} ipc Framed IPC duplex stream.
|
|
616
631
|
* @param {Spec} spec Built cero spec.
|
|
617
|
-
* @param {{ onerror?: (err: Error) => void }} [opts]
|
|
632
|
+
* @param {{ onerror?: (err: Error) => void, push?: import('./push.js').Messaging }} [opts]
|
|
618
633
|
* @returns {Promise<Context>}
|
|
619
634
|
*/
|
|
620
635
|
function start(ipc, spec, opts) {
|
package/src/rpc/push.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { watch, get, open, activate, receive } from '../lib/operators.js'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @typedef {object} Messaging The platform's messaging service, as `connect` takes it for push.
|
|
5
|
+
* @property {(topic: string) => Promise<void>} subscribe
|
|
6
|
+
* @property {(topic: string) => Promise<void>} unsubscribe
|
|
7
|
+
* @property {(event: 'push', fn: (payload: Uint8Array) => void) => (() => void) | void} on
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Keep the device on the push topics of its handles, one subscription per handle, dropped when it
|
|
12
|
+
* leaves; and act on a push: the handle it is about ranks first on the swarm.
|
|
13
|
+
*
|
|
14
|
+
* @param {import('./client.js').Client} me
|
|
15
|
+
* @param {Messaging} messaging
|
|
16
|
+
* @returns {() => void}
|
|
17
|
+
*/
|
|
18
|
+
export function follow(me, messaging) {
|
|
19
|
+
const topics = new Set()
|
|
20
|
+
const stream = watch(me.topics)
|
|
21
|
+
let closed = false
|
|
22
|
+
const sync = async () => {
|
|
23
|
+
for await (const { data } of stream) {
|
|
24
|
+
const wanted = new Set(data.map((row) => row.id))
|
|
25
|
+
// a subscribe that fails is left out, so the next change tries it again
|
|
26
|
+
for (const topic of wanted) {
|
|
27
|
+
if (topics.has(topic)) continue
|
|
28
|
+
try {
|
|
29
|
+
await messaging.subscribe(topic)
|
|
30
|
+
topics.add(topic)
|
|
31
|
+
} catch (err) {
|
|
32
|
+
me._onerror(err)
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
for (const topic of topics) {
|
|
36
|
+
if (wanted.has(topic)) continue
|
|
37
|
+
topics.delete(topic)
|
|
38
|
+
await messaging.unsubscribe(topic).catch(me._onerror)
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
sync().catch((err) => closed || me._onerror(err))
|
|
43
|
+
const off = messaging.on('push', (payload) => wake(me, payload).catch(me._onerror))
|
|
44
|
+
return () => {
|
|
45
|
+
closed = true
|
|
46
|
+
stream.destroy()
|
|
47
|
+
if (off) off()
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// while the app sleeps the OS shows the push; the handle syncs first once it wakes on its own
|
|
52
|
+
async function wake(me, payload) {
|
|
53
|
+
if ((await get(me.status)).data.suspended) return
|
|
54
|
+
const hit = await receive(me, payload)
|
|
55
|
+
if (!hit?.newer) return
|
|
56
|
+
await activate(await open(me[hit.type], { id: hit.id }))
|
|
57
|
+
}
|
package/src/rpc/server.js
CHANGED
|
@@ -24,7 +24,8 @@ import {
|
|
|
24
24
|
activate,
|
|
25
25
|
deactivate,
|
|
26
26
|
phrase,
|
|
27
|
-
nearby
|
|
27
|
+
nearby,
|
|
28
|
+
receive
|
|
28
29
|
} from '../lib/operators.js'
|
|
29
30
|
|
|
30
31
|
// what a UI reaches by name: these operators, never close or a handle's privates
|
|
@@ -41,7 +42,8 @@ const VERBS = new Map(
|
|
|
41
42
|
activate,
|
|
42
43
|
deactivate,
|
|
43
44
|
phrase,
|
|
44
|
-
nearby
|
|
45
|
+
nearby,
|
|
46
|
+
receive
|
|
45
47
|
})
|
|
46
48
|
)
|
|
47
49
|
|
|
@@ -24,6 +24,10 @@ export declare const defs: {
|
|
|
24
24
|
type: string;
|
|
25
25
|
kind: string;
|
|
26
26
|
};
|
|
27
|
+
device: {
|
|
28
|
+
type: string;
|
|
29
|
+
kind: string;
|
|
30
|
+
};
|
|
27
31
|
keypair: {
|
|
28
32
|
type: string;
|
|
29
33
|
kind: string;
|
|
@@ -47,6 +51,9 @@ export declare const defs: {
|
|
|
47
51
|
serving: {
|
|
48
52
|
type: string;
|
|
49
53
|
};
|
|
54
|
+
topics: {
|
|
55
|
+
type: string;
|
|
56
|
+
};
|
|
50
57
|
};
|
|
51
58
|
};
|
|
52
59
|
export type RefInfo = import('../lib/spec.js').RefInfo;
|
package/types/build/schemas.d.ts
CHANGED
|
@@ -5,7 +5,7 @@ export declare const main: {
|
|
|
5
5
|
writer: {
|
|
6
6
|
master: import("@cero-base/core").Prim;
|
|
7
7
|
writer: import("@cero-base/core").Prim;
|
|
8
|
-
|
|
8
|
+
proof: import("@cero-base/core").Prim;
|
|
9
9
|
isIndexer: import("@cero-base/core").Prim;
|
|
10
10
|
ts: import("@cero-base/core").Prim;
|
|
11
11
|
memberId: import("@cero-base/core").Prim;
|
|
@@ -32,6 +32,8 @@ export declare const main: {
|
|
|
32
32
|
createdAt: import("@cero-base/core").Prim;
|
|
33
33
|
updatedAt: import("@cero-base/core").Prim;
|
|
34
34
|
index: import("@cero-base/core").Prim;
|
|
35
|
+
key: import("@cero-base/core").Prim;
|
|
36
|
+
proof: import("@cero-base/core").Prim;
|
|
35
37
|
};
|
|
36
38
|
invite: {
|
|
37
39
|
id: import("@cero-base/core").Prim;
|
|
@@ -51,6 +53,7 @@ export declare const main: {
|
|
|
51
53
|
createdAt: import("@cero-base/core").Prim;
|
|
52
54
|
updatedAt: import("@cero-base/core").Prim;
|
|
53
55
|
index: import("@cero-base/core").Prim;
|
|
56
|
+
epochs: import("@cero-base/core").Prim;
|
|
54
57
|
};
|
|
55
58
|
file: {
|
|
56
59
|
id: import("@cero-base/core").Prim;
|
|
@@ -75,6 +78,7 @@ export declare const main: {
|
|
|
75
78
|
accept: {
|
|
76
79
|
id: import("@cero-base/core").Prim;
|
|
77
80
|
role: import("@cero-base/core").Prim;
|
|
81
|
+
proof: import("@cero-base/core").Prim;
|
|
78
82
|
};
|
|
79
83
|
request: {
|
|
80
84
|
id: import("@cero-base/core").Prim;
|
|
@@ -86,6 +90,7 @@ export declare const main: {
|
|
|
86
90
|
admitted: import("@cero-base/core").Prim;
|
|
87
91
|
expires: import("@cero-base/core").Prim;
|
|
88
92
|
role: import("@cero-base/core").Prim;
|
|
93
|
+
key: import("@cero-base/core").Prim;
|
|
89
94
|
};
|
|
90
95
|
removal: {
|
|
91
96
|
id: import("@cero-base/core").Prim;
|
|
@@ -125,11 +130,24 @@ export declare const main: {
|
|
|
125
130
|
id: import("@cero-base/core").Prim;
|
|
126
131
|
reason: import("@cero-base/core").Prim;
|
|
127
132
|
};
|
|
133
|
+
topic: {
|
|
134
|
+
id: import("@cero-base/core").Prim;
|
|
135
|
+
handle: import("@cero-base/core").Prim;
|
|
136
|
+
type: import("@cero-base/core").Prim;
|
|
137
|
+
name: import("@cero-base/core").Prim;
|
|
138
|
+
};
|
|
128
139
|
};
|
|
129
140
|
export declare const local: {
|
|
130
141
|
master: {
|
|
131
142
|
seed: import("@cero-base/core").Prim;
|
|
132
143
|
};
|
|
144
|
+
device: {
|
|
145
|
+
publicKey: import("@cero-base/core").Prim;
|
|
146
|
+
secretKey: import("@cero-base/core").Prim;
|
|
147
|
+
proof: import("@cero-base/core").Prim;
|
|
148
|
+
identity: import("@cero-base/core").Prim;
|
|
149
|
+
encryptionKey: import("@cero-base/core").Prim;
|
|
150
|
+
};
|
|
133
151
|
keypair: {
|
|
134
152
|
publicKey: import("@cero-base/core").Prim;
|
|
135
153
|
secretKey: import("@cero-base/core").Prim;
|
|
@@ -154,6 +172,8 @@ export declare const local: {
|
|
|
154
172
|
key: import("@cero-base/core").Prim;
|
|
155
173
|
encryptionKey: import("@cero-base/core").Prim;
|
|
156
174
|
epochs: import("@cero-base/core").Prim;
|
|
175
|
+
device: import("@cero-base/core").Prim;
|
|
176
|
+
proof: import("@cero-base/core").Prim;
|
|
157
177
|
};
|
|
158
178
|
mail: {
|
|
159
179
|
id: import("@cero-base/core").Prim;
|
|
@@ -164,6 +184,13 @@ export declare const local: {
|
|
|
164
184
|
environment: {
|
|
165
185
|
channel: import("@cero-base/core").Prim;
|
|
166
186
|
};
|
|
187
|
+
subscription: {
|
|
188
|
+
id: import("@cero-base/core").Prim;
|
|
189
|
+
handle: import("@cero-base/core").Prim;
|
|
190
|
+
type: import("@cero-base/core").Prim;
|
|
191
|
+
key: import("@cero-base/core").Prim;
|
|
192
|
+
name: import("@cero-base/core").Prim;
|
|
193
|
+
};
|
|
167
194
|
};
|
|
168
195
|
export declare const rpc: {
|
|
169
196
|
'req-empty': {
|