@cero-base/cero 2.5.0 → 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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cero-base/cero",
3
- "version": "2.5.0",
3
+ "version": "2.6.0",
4
4
  "description": "The ideal p2p API — everything is a handle, handles contain refs, refs contain rows.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -113,7 +113,7 @@
113
113
  "test:node": "find test -name '*.test.js' | sort | xargs -P4 -n1 brittle-node"
114
114
  },
115
115
  "dependencies": {
116
- "@cero-base/core": "^2.5.0",
116
+ "@cero-base/core": "^2.6.0",
117
117
  "b4a": "^1.9.0",
118
118
  "bare-abort-controller": "^1.1.2",
119
119
  "bare-crypto": "^1.15.4",
@@ -185,6 +185,7 @@ function register(name, node, ctx) {
185
185
  ctx.types.push({ name, compact: false, fields: internal.fields(node.fields) })
186
186
  ctx.dispatches.push({ name, requestType: fqn })
187
187
  ctx.meta.refs[name] = { kind: 'action', path: [name], schema: fqn }
188
+ if (node.push) ctx.meta.refs[name].push = true
188
189
  return
189
190
  }
190
191
  if (node.kind === 'single') {
@@ -196,6 +197,7 @@ function register(name, node, ctx) {
196
197
  { kind: 'single', path: [name], schema: fqn },
197
198
  node.fields
198
199
  )
200
+ if (node.push) ctx.meta.refs[name].push = true
199
201
  return
200
202
  }
201
203
  if (node.kind === 'collection') {
@@ -220,6 +222,7 @@ function register(name, node, ctx) {
220
222
  node.fields
221
223
  )
222
224
  if (node.own) refEntry.own = true
225
+ if (node.push) refEntry.push = true
223
226
  ctx.meta.refs[name] = refEntry
224
227
  if (node.indexes) {
225
228
  for (const [idx, fields] of Object.entries(node.indexes)) {
@@ -14,6 +14,7 @@ export const defs = {
14
14
  },
15
15
  local: {
16
16
  master: { type: 'master', kind: 'single' },
17
+ device: { type: 'device', kind: 'single' },
17
18
  keypair: { type: 'keypair', kind: 'single' },
18
19
  'handle-keypairs': { type: 'handle-keypair' },
19
20
  joins: { type: 'join' },
@@ -10,7 +10,8 @@ export const main = {
10
10
  writer: {
11
11
  master: required(bytes),
12
12
  writer: required(bytes),
13
- sig: required(bytes),
13
+ // the device's proof over the admission, chained to `master`
14
+ proof: required(bytes),
14
15
  isIndexer: bool,
15
16
  ts: int,
16
17
  // the paired add-member decides the rank in the same transaction; `role` here is unread
@@ -37,7 +38,11 @@ export const main = {
37
38
  isMobile: bool,
38
39
  createdAt: int,
39
40
  updatedAt: int,
40
- index: uint
41
+ index: uint,
42
+ // the device key its admission proved: rotation seals to it
43
+ key: bytes,
44
+ // the chain to the identity, when a device of the member linked it here
45
+ proof: bytes
41
46
  },
42
47
  invite: {
43
48
  id: required(string),
@@ -57,7 +62,9 @@ export const main = {
57
62
  name: string,
58
63
  createdAt: int,
59
64
  updatedAt: int,
60
- index: uint
65
+ index: uint,
66
+ // its rotation epochs, for a device of the identity opening it later
67
+ epochs: bytes
61
68
  },
62
69
  file: {
63
70
  id: required(string),
@@ -83,7 +90,9 @@ export const main = {
83
90
  },
84
91
  accept: {
85
92
  id: required(string),
86
- role: string
93
+ role: string,
94
+ // the accepter's own device attests the joiner's: a device of the member, not a member
95
+ proof: bytes
87
96
  },
88
97
  // a join from its arrival until the joiner has its keys: waiting for a member on a confirm
89
98
  // invite, then admitted and owed its reply. `id` is the joiner's writer
@@ -97,7 +106,9 @@ export const main = {
97
106
  admitted: bool,
98
107
  expires: int,
99
108
  // what the join asks for, the invite's role; once admitted, the role granted
100
- role: string
109
+ role: string,
110
+ // the device key the join's proof ends at
111
+ key: bytes
101
112
  },
102
113
  // a removed member comes back only through an invite minted after `index`
103
114
  removal: {
@@ -159,6 +170,14 @@ export const local = {
159
170
  master: {
160
171
  seed: required(bytes)
161
172
  },
173
+ // this device's key and its proof, with the identity it chains to and the root encryption key
174
+ device: {
175
+ publicKey: required(bytes),
176
+ secretKey: required(bytes),
177
+ proof: required(bytes),
178
+ identity: required(bytes),
179
+ encryptionKey: required(bytes)
180
+ },
162
181
  keypair: {
163
182
  publicKey: required(bytes),
164
183
  secretKey: required(bytes),
@@ -187,7 +206,10 @@ export const local = {
187
206
  // the reply, once it landed: the join then opens the handle without joining again
188
207
  key: bytes,
189
208
  encryptionKey: bytes,
190
- epochs: bytes
209
+ epochs: bytes,
210
+ // the root's join: this device's secret key, bare until the reply brings its proof
211
+ device: bytes,
212
+ proof: bytes
191
213
  },
192
214
  // mail the device's mailbox keeps: received until handled, sent until read. `mirrors` are
193
215
  // 32-byte keys back to back
@@ -1,5 +1,6 @@
1
1
  import AbortController from 'bare-abort-controller'
2
2
  import b4a from 'b4a'
3
+ import c from 'compact-encoding'
3
4
  import { discoveryKey } from 'hypercore-crypto'
4
5
  import ReadyResource from 'ready-resource'
5
6
  import safetyCatch from 'safety-catch'
@@ -8,9 +9,9 @@ import z32 from 'z32'
8
9
 
9
10
  import { Identity } from '@cero-base/core/identity'
10
11
  import { Database } from '@cero-base/core/database'
11
- import { blobEpochKey } from '@cero-base/core/database/encryption'
12
+ import { blobEpochKey, epochEntries } from '@cero-base/core/database/encryption'
12
13
  import { Pairing } from '@cero-base/core/pairing'
13
- import { receive } from '@cero-base/core/push'
14
+ import { verify } from '@cero-base/core/push'
14
15
  import { Invite } from '@cero-base/core/invite'
15
16
  import { Mailbox } from '@cero-base/core/mailbox'
16
17
  import hid from 'hypercore-id-encoding'
@@ -267,14 +268,14 @@ export class Handle extends ReadyResource {
267
268
  await this.store.ready()
268
269
  // a fresh device takes writes only once provisioned, and an operator waits for the open
269
270
  if (this._boot) await this.store.bootstrap(this._boot)
270
- if (this.parent) {
271
- this._pair = new Pairing({ mailbox: this.mailbox, db: this.store })
272
- await this._pair.ready()
273
- }
271
+ this._pair = new Pairing({ mailbox: this.mailbox, db: this.store })
272
+ await this._pair.ready()
274
273
  this.root._coreKeys.set(b4a.toHex(this.store.key), this.store.encryptionKey)
275
274
  if (!this.parent) {
276
275
  await this.fileServer.listen()
277
276
  await this.mailbox.ready()
277
+ const prune = this.store.onUpdate('devices', () => this._pruneAll().catch(this._onerror))
278
+ this.once('close', prune)
278
279
  if (this._bluetooth) {
279
280
  const off = this.store.onUpdate('profile', () => this._tell().catch(this._onerror))
280
281
  this.once('close', off)
@@ -361,20 +362,28 @@ export class Handle extends ReadyResource {
361
362
 
362
363
  // the verbs in lib/operators.js land here
363
364
 
365
+ // the root's invite is for a device of yours: one, confirmed by hand, carrying the identity the
366
+ // device checks its chain against
364
367
  /** @private */
365
- async _invite(opts) {
366
- return this._pairing().invite(opts)
368
+ async _invite(opts = {}) {
369
+ if (this.parent) return this._pair.invite(opts)
370
+ const { ttl = '2h' } = opts
371
+ return this._pair.invite({ role: 'owner', confirm: true, ttl, data: this.identity.publicKey })
367
372
  }
368
373
 
369
374
  /** @private */
370
375
  async _revoke(invite) {
371
- return this._pairing().revoke(invite)
376
+ return this._pair.revoke(invite)
372
377
  }
373
378
 
379
+ // accepting on the root links the device: this one attests its key
374
380
  /** @private */
375
381
  async _answer(id, { accept, role, reason }) {
376
- const pairing = this._pairing()
377
- return accept ? pairing.accept(id, { role }) : pairing.deny(id, reason)
382
+ if (!accept) return this._pair.deny(id, reason)
383
+ if (this.parent) return this._pair.accept(id, { role })
384
+ const { data: row } = await this.store.get('requests', id)
385
+ if (!row) throw CeroError.UNKNOWN('request', id)
386
+ return this._pair.accept(id, { proof: this.identity.link(row.key) })
378
387
  }
379
388
 
380
389
  /** @private */
@@ -398,12 +407,6 @@ export class Handle extends ReadyResource {
398
407
  })
399
408
  }
400
409
 
401
- /** @private */
402
- _pairing() {
403
- if (!this._pair) throw CeroError.INVALID('the root has no invites, open a handle first')
404
- return this._pair
405
- }
406
-
407
410
  /** @private */
408
411
  async _leave() {
409
412
  if (!this.parent) throw CeroError.INVALID('the root cannot be left')
@@ -576,8 +579,8 @@ export class Handle extends ReadyResource {
576
579
  if (this._sus.suspended) throw CeroError.INVALID('receive: the app is suspended')
577
580
  const { data: rows } = await this.local.store.get('topics')
578
581
  const handles = rows.map(({ handle, key, type, name }) => ({ id: handle, key, type, name }))
579
- const hit = await receive(this.store.store.storage, payload, handles)
580
- return hit && { id: hit.id, type: hit.type, name: hit.name, newer: hit.newer }
582
+ const hit = await verify(this.store.store.storage, payload, handles)
583
+ return hit && { id: hit.id, type: hit.type, name: hit.name, newer: hit.newer, ref: hit.ref }
581
584
  }
582
585
 
583
586
  /** @private */
@@ -734,7 +737,7 @@ export class Handle extends ReadyResource {
734
737
  await tx.call('add-writer', {
735
738
  master: this.identity.publicKey,
736
739
  writer: writerKey,
737
- sig: this.identity.sign(admission(child.store.key, writerKey, child.store.writerKey)),
740
+ proof: this.identity.sign(admission(child.store.key, writerKey, child.store.writerKey)),
738
741
  ts
739
742
  })
740
743
  await tx.call('add-member', {
@@ -880,6 +883,7 @@ export class Handle extends ReadyResource {
880
883
  type,
881
884
  key: child.store.key,
882
885
  encryptionKey: child.store.encryptionKey,
886
+ epochs: c.encode(epochEntries, child.store.keyring.all()),
883
887
  name: null,
884
888
  createdAt: ts,
885
889
  updatedAt: ts
@@ -961,6 +965,7 @@ export class Handle extends ReadyResource {
961
965
  namespace: `${NS}/handle/${type}/${id}`,
962
966
  key: data.key,
963
967
  encryptionKey: data.encryptionKey,
968
+ epochs: data.epochs ? c.decode(epochEntries, data.epochs) : undefined,
964
969
  keyPair: /** @type {KeyPair} */ (writer)
965
970
  })
966
971
  try {
@@ -1010,9 +1015,59 @@ export class Handle extends ReadyResource {
1010
1015
  this._pending.delete(child)
1011
1016
  this.children.add(child)
1012
1017
  this._serve(child)
1018
+ this._carry(child)
1019
+ this._prune(child).catch(this._onerror)
1013
1020
  this.emit('handle', child, info)
1014
1021
  }
1015
1022
 
1023
+ // a device removed from the root loses its seats in every handle: its chain is static, so the
1024
+ // handles are told by whichever device of the identity has them open
1025
+ /** @private */
1026
+ async _prune(child) {
1027
+ const { data: mine } = await this.store.get('devices')
1028
+ const kept = new Set(mine.filter((d) => d.key).map((d) => b4a.toHex(d.key)))
1029
+ const { data: rows } = await child.store.get('devices')
1030
+ for (const row of rows) {
1031
+ if (row.memberId !== this.identity.id || !row.key || kept.has(b4a.toHex(row.key))) continue
1032
+ if (child.closing || child.closed) return
1033
+ await child.store.del('devices', row.id)
1034
+ }
1035
+ }
1036
+
1037
+ /** @private */
1038
+ async _pruneAll() {
1039
+ for (const child of this.children) await this._prune(child)
1040
+ }
1041
+
1042
+ // a handle's epochs ride in its root row, which only the identity's devices read: one that
1043
+ // opens the handle later reads history with them, since envelopes in the log address a device
1044
+ /** @private */
1045
+ _carry(child) {
1046
+ const save = async () => {
1047
+ const epochs = c.encode(epochEntries, child.store.keyring.all())
1048
+ const { data: row } = await this.store.get('handles', child.id)
1049
+ if (!row || b4a.equals(row.epochs || b4a.alloc(0), epochs)) return
1050
+ await this.store.set('handles', { id: row.id, epochs })
1051
+ }
1052
+ // read when the row changes, and when an announcement applies: it is learned only after that
1053
+ const read = async () => {
1054
+ const { data: row } = await this.store.get('handles', child.id)
1055
+ if (row?.epochs) await child.store.learn(c.decode(epochEntries, row.epochs))
1056
+ }
1057
+ const touches = (name) => (touched) => touched.has('*') || touched.has(name)
1058
+ const onepoch = () => save().catch(this._onerror)
1059
+ const onroot = (touched) => touches('handles')(touched) && read().catch(this._onerror)
1060
+ const onchild = (touched) => touches('epochs')(touched) && read().catch(this._onerror)
1061
+ child.store.on('epoch', onepoch)
1062
+ child.store.on('update', onchild)
1063
+ this.store.on('update', onroot)
1064
+ child.once('close', () => {
1065
+ child.store.off('epoch', onepoch)
1066
+ child.store.off('update', onchild)
1067
+ this.store.off('update', onroot)
1068
+ })
1069
+ }
1070
+
1016
1071
  // before(me.room.notes, fn): on every handle open now and every one opened later
1017
1072
  /** @private */
1018
1073
  _hookType(ref, attach, opts) {
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
- const { identity, fresh, seed } = await resolveIdentity(opts, local, done)
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 = !done && !opts.phrase && (fresh || device?.setup === 'create')
95
- const recovering = !done && !creating
96
- const setup = done ? null : creating ? 'create' : 'recover'
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 (seed) await local.store.set('master', { seed })
106
- const timeout = opts.recoveryTimeout || TIMEOUT
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: { publicKey: identity.publicKey, secretKey: identity.secretKey }, manifest }
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) : undefined
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
- : { name: opts.name || null, isMobile: opts.isMobile === true, recovering, timeout }
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
- // `seed` is the one to store: supplied or minted, null when already stored
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 stored = (await local.store.get('master')).data?.seed
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 && provided && !b4a.equals(provided, stored)) {
240
- throw CeroError.INVALID('dir holds another identity: switch with cero.restore')
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
- const identity = await Identity.create({ seed: provided || stored || null, words: opts.words })
243
- return { identity, fresh: !provided && !stored, seed: stored && !provided ? null : identity.seed }
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
  }
@@ -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
- return Identity.verify(
238
- hid.decode(info.id),
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
  }
@@ -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]
@@ -485,12 +491,12 @@ export async function deactivate(ctx) {
485
491
  }
486
492
 
487
493
  /**
488
- * A push the platform delivered, as bytes: the handle it is about, verified against this device's
489
- * own data, or `null` for a forged one or one about no handle here.
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.
490
496
  *
491
497
  * @param {Context} me
492
498
  * @param {Uint8Array} payload
493
- * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean } | null>}
499
+ * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean, ref: string | null } | null>}
494
500
  */
495
501
  export async function receive(me, payload) {
496
502
  if (me.parent) throw CeroError.INVALID("receive is the app's, on me")
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 master seed).
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 master seed exists on disk.
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('master')
32
- return !!data?.seed
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]
@@ -1,11 +1,11 @@
1
1
  import b4a from 'b4a'
2
2
 
3
3
  /**
4
- * `@react-native-firebase/messaging` as a push backend: pass `messaging()`. Pushes to the app in
4
+ * `@react-native-firebase/messaging` as the messaging service `connect` takes for push: pass `messaging()`. Pushes to the app in
5
5
  * front; the push worklet answers the ones the OS delivers while it is not.
6
6
  *
7
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').Backend}
8
+ * @returns {import('../rpc/push.js').Messaging}
9
9
  */
10
10
  export function firebase(messaging) {
11
11
  const payload = (message) => message?.data?.payload && b4a.from(message.data.payload, 'base64')
package/src/push/index.js CHANGED
@@ -3,7 +3,8 @@ import Corestore from 'corestore'
3
3
  import b4a from 'b4a'
4
4
  import safetyCatch from 'safety-catch'
5
5
 
6
- import { receive as verify } from '@cero-base/core/push'
6
+ import { verify } from '@cero-base/core/push'
7
+ import { CeroError } from '@cero-base/core/errors'
7
8
 
8
9
  import { Local } from '../local/index.js'
9
10
 
@@ -16,7 +17,7 @@ import { Local } from '../local/index.js'
16
17
  * @param {import('../lib/spec.js').Spec} spec
17
18
  * @param {Uint8Array} payload
18
19
  * @param {{ storageKey?: Uint8Array }} [opts] The key `cero()` encrypts the local store with, if any.
19
- * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean } | null>}
20
+ * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean, ref: string | null } | null>}
20
21
  */
21
22
  export async function receive(dir, spec, payload, { storageKey } = {}) {
22
23
  const storage = new HypercoreStorage(`${dir}/main`, { readOnly: true })
@@ -30,7 +31,7 @@ export async function receive(dir, spec, payload, { storageKey } = {}) {
30
31
  const { data: rows } = await local.store.get('topics')
31
32
  const handles = rows.map(({ handle, key, type, name }) => ({ id: handle, key, type, name }))
32
33
  const hit = await verify(storage, payload, handles)
33
- return hit && { id: hit.id, type: hit.type, name: hit.name, newer: hit.newer }
34
+ return hit && { id: hit.id, type: hit.type, name: hit.name, newer: hit.newer, ref: hit.ref }
34
35
  } catch (err) {
35
36
  safetyCatch(err)
36
37
  return null
@@ -42,26 +43,29 @@ export async function receive(dir, spec, payload, { storageKey } = {}) {
42
43
  }
43
44
 
44
45
  /**
45
- * The bare-kit push entry: on each push the OS hands this worklet, verify it and answer with the
46
- * notification to show, or nothing. The request carries `storage`, `payload` (base64) and, when
47
- * the app encrypts its local store, `storageKey` (base64).
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).
48
50
  *
49
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.
50
53
  * @returns {void}
51
54
  */
52
- export function push(spec) {
55
+ export function push(spec, show) {
56
+ if (typeof show !== 'function') throw CeroError.INVALID('push: show(push) says what to show')
53
57
  globalThis.BareKit.on('push', async (json, reply) => {
54
- let hit = null
58
+ let shown = null
55
59
  try {
56
60
  const { storage, storageKey, payload } = JSON.parse(json)
57
- hit = await receive(storage, spec, b4a.from(payload, 'base64'), {
61
+ const hit = await receive(storage, spec, b4a.from(payload, 'base64'), {
58
62
  storageKey: storageKey ? b4a.from(storageKey, 'base64') : undefined
59
63
  })
64
+ if (hit?.newer) shown = await show(hit)
60
65
  } catch {
61
66
  // the OS waits for an answer: whatever went wrong, no notification
62
- hit = null
67
+ shown = null
63
68
  }
64
- const shown = hit?.newer ? { title: hit.name || hit.type, body: 'New activity' } : null
65
- reply(null, shown && JSON.stringify(shown))
69
+ reply(null, shown ? JSON.stringify(shown) : null)
66
70
  })
67
71
  }
package/src/rpc/client.js CHANGED
@@ -465,12 +465,12 @@ export class Client extends RPCClient {
465
465
  /**
466
466
  * @param {import('streamx').Duplex} ipc Framed IPC stream (must be writable).
467
467
  * @param {Spec} spec Compiled cero spec (schema + rpc + handles).
468
- * @param {{ onerror?: (err: Error) => void }} [opts] Where the worker's background errors go; the console without one.
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.
469
469
  */
470
470
  constructor(ipc, spec, { onerror, push } = {}) {
471
471
  super(ipc, spec)
472
472
  /** @private */
473
- this._push = push?.backend || null
473
+ this._push = push || null
474
474
  if (spec.local?.schema && !spec.local.codec) bindCodec(spec.local)
475
475
  Object.assign(this, operators)
476
476
  /** @private */
@@ -614,7 +614,7 @@ class Handle {
614
614
  *
615
615
  * @param {import('streamx').Duplex} ipc
616
616
  * @param {Spec} spec
617
- * @param {{ onerror?: (err: Error) => void }} [opts]
617
+ * @param {{ onerror?: (err: Error) => void, push?: import('./push.js').Messaging }} [opts]
618
618
  * @returns {Promise<Client>}
619
619
  */
620
620
  export async function connect(ipc, spec, opts) {
@@ -629,7 +629,7 @@ export async function connect(ipc, spec, opts) {
629
629
  *
630
630
  * @param {import('streamx').Duplex} ipc Framed IPC duplex stream.
631
631
  * @param {Spec} spec Built cero spec.
632
- * @param {{ onerror?: (err: Error) => void }} [opts]
632
+ * @param {{ onerror?: (err: Error) => void, push?: import('./push.js').Messaging }} [opts]
633
633
  * @returns {Promise<Context>}
634
634
  */
635
635
  function start(ipc, spec, opts) {
package/src/rpc/push.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { watch, get, open, activate, receive } from '../lib/operators.js'
2
2
 
3
3
  /**
4
- * @typedef {object} Backend The platform's push service, as `connect` takes it.
4
+ * @typedef {object} Messaging The platform's messaging service, as `connect` takes it for push.
5
5
  * @property {(topic: string) => Promise<void>} subscribe
6
6
  * @property {(topic: string) => Promise<void>} unsubscribe
7
7
  * @property {(event: 'push', fn: (payload: Uint8Array) => void) => (() => void) | void} on
@@ -12,10 +12,10 @@ import { watch, get, open, activate, receive } from '../lib/operators.js'
12
12
  * leaves; and act on a push: the handle it is about ranks first on the swarm.
13
13
  *
14
14
  * @param {import('./client.js').Client} me
15
- * @param {Backend} backend
15
+ * @param {Messaging} messaging
16
16
  * @returns {() => void}
17
17
  */
18
- export function follow(me, backend) {
18
+ export function follow(me, messaging) {
19
19
  const topics = new Set()
20
20
  const stream = watch(me.topics)
21
21
  let closed = false
@@ -26,7 +26,7 @@ export function follow(me, backend) {
26
26
  for (const topic of wanted) {
27
27
  if (topics.has(topic)) continue
28
28
  try {
29
- await backend.subscribe(topic)
29
+ await messaging.subscribe(topic)
30
30
  topics.add(topic)
31
31
  } catch (err) {
32
32
  me._onerror(err)
@@ -35,12 +35,12 @@ export function follow(me, backend) {
35
35
  for (const topic of topics) {
36
36
  if (wanted.has(topic)) continue
37
37
  topics.delete(topic)
38
- await backend.unsubscribe(topic).catch(me._onerror)
38
+ await messaging.unsubscribe(topic).catch(me._onerror)
39
39
  }
40
40
  }
41
41
  }
42
42
  sync().catch((err) => closed || me._onerror(err))
43
- const off = backend.on('push', (payload) => wake(me, payload).catch(me._onerror))
43
+ const off = messaging.on('push', (payload) => wake(me, payload).catch(me._onerror))
44
44
  return () => {
45
45
  closed = true
46
46
  stream.destroy()
@@ -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;
@@ -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
- sig: import("@cero-base/core").Prim;
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;
@@ -136,6 +141,13 @@ export declare const local: {
136
141
  master: {
137
142
  seed: import("@cero-base/core").Prim;
138
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
+ };
139
151
  keypair: {
140
152
  publicKey: import("@cero-base/core").Prim;
141
153
  secretKey: import("@cero-base/core").Prim;
@@ -160,6 +172,8 @@ export declare const local: {
160
172
  key: import("@cero-base/core").Prim;
161
173
  encryptionKey: import("@cero-base/core").Prim;
162
174
  epochs: import("@cero-base/core").Prim;
175
+ device: import("@cero-base/core").Prim;
176
+ proof: import("@cero-base/core").Prim;
163
177
  };
164
178
  mail: {
165
179
  id: import("@cero-base/core").Prim;
@@ -54,6 +54,7 @@ export declare const cero: {
54
54
  type: string;
55
55
  name: string | null;
56
56
  newer: boolean;
57
+ ref: string | null;
57
58
  } | null>;
58
59
  phrase(me: operators.Context): Promise<string>;
59
60
  nearby(ctx: operators.Context, on: boolean, opts?: {
@@ -70,12 +71,17 @@ export declare const cero: {
70
71
  fixed64: import("@cero-base/core").Prim;
71
72
  file: import("@cero-base/core").Prim;
72
73
  required: (marker: import("@cero-base/core").Prim) => import("@cero-base/core").Prim;
73
- single(fields: Record<string, import("@cero-base/core").Prim>): import("@cero-base/core").TypeDef;
74
+ single(fields: Record<string, import("@cero-base/core").Prim>, opts?: {
75
+ push?: boolean;
76
+ }): import("@cero-base/core").TypeDef;
74
77
  collection(fields: Record<string, import("@cero-base/core").Prim>, opts?: {
75
78
  indexes?: Record<string, string[]>;
76
79
  own?: boolean;
80
+ push?: boolean;
81
+ }): import("@cero-base/core").TypeDef;
82
+ action(fields: Record<string, import("@cero-base/core").Prim>, opts?: {
83
+ push?: boolean;
77
84
  }): import("@cero-base/core").TypeDef;
78
- action(fields: Record<string, import("@cero-base/core").Prim>): import("@cero-base/core").TypeDef;
79
85
  extend(fields: Record<string, import("@cero-base/core").Prim>): {
80
86
  kind: 'extend';
81
87
  fields: Record<string, import("@cero-base/core").Prim>;
@@ -280,8 +280,6 @@ export declare class Handle extends ReadyResource {
280
280
  /** @private */
281
281
  private _tx;
282
282
  /** @private */
283
- private _pairing;
284
- /** @private */
285
283
  private _leave;
286
284
  /** @private */
287
285
  private _suspend;
@@ -416,6 +414,12 @@ export declare class Handle extends ReadyResource {
416
414
  /** @private */
417
415
  private _adopt;
418
416
  /** @private */
417
+ private _prune;
418
+ /** @private */
419
+ private _pruneAll;
420
+ /** @private */
421
+ private _carry;
422
+ /** @private */
419
423
  private _hookType;
420
424
  /** @private */
421
425
  private _serve;
package/types/index.d.ts CHANGED
@@ -13,6 +13,14 @@ export type CeroOpts = {
13
13
  * The identity's BIP-39 phrase, as `cero.phrase(me)` gives it: on a new `dir` it recovers that identity.
14
14
  */
15
15
  phrase?: string;
16
+ /**
17
+ * 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.
18
+ */
19
+ invite?: string;
20
+ /**
21
+ * With `invite`: called with the request's id as it is sent, the same id `me.requests` shows on the accepting device.
22
+ */
23
+ onrequest?: (id: string) => void;
16
24
  /**
17
25
  * Mnemonic length when generating a fresh identity.
18
26
  */
@@ -86,6 +94,8 @@ export type CeroOpts = {
86
94
  /**
87
95
  * @typedef {object} CeroOpts
88
96
  * @property {string} [phrase] The identity's BIP-39 phrase, as `cero.phrase(me)` gives it: on a new `dir` it recovers that identity.
97
+ * @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.
98
+ * @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.
89
99
  * @property {12 | 24} [words] Mnemonic length when generating a fresh identity.
90
100
  * @property {string | null} [name] Friendly device name persisted on the identity claim.
91
101
  * @property {boolean} [isMobile] Marks this device as mobile.
@@ -50,6 +50,12 @@ export declare function call(ref: Ref, d?: Row): Promise<void>;
50
50
  * opens; register in an extension's `setup` to see every op the root applies too. The imported
51
51
  * operators throw inside a hook; use the ones on `ctx`. Not available over RPC.
52
52
  *
53
+ * On `members`, removing someone or changing her rank is the rank's call by default: the writer
54
+ * outranks whom she acts on, and `ctx.ranked` says whether she does. A rule there may return
55
+ * `'grant'` to allow what rank alone refuses (a bare `true` grants nothing), or `false` to refuse
56
+ * what it allows, and only a writer's grant counts. It is decided before anything moves. The
57
+ * last owner is never removed nor demoted.
58
+ *
53
59
  * @param {Ref} ref
54
60
  * @param {(ctx: HookContext) => unknown} fn
55
61
  * @param {{ signal?: AbortSignal }} [opts]
@@ -224,18 +230,19 @@ export declare function activate(ctx: Context): Promise<void>;
224
230
  */
225
231
  export declare function deactivate(ctx: Context): Promise<void>;
226
232
  /**
227
- * A push the platform delivered, as bytes: the handle it is about, verified against this device's
228
- * own data, or `null` for a forged one or one about no handle here.
233
+ * A push the platform delivered, as bytes: the handle it is about and the ref the write was on,
234
+ * verified against this device's own data, or `null` for a forged one or one about no handle here.
229
235
  *
230
236
  * @param {Context} me
231
237
  * @param {Uint8Array} payload
232
- * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean } | null>}
238
+ * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean, ref: string | null } | null>}
233
239
  */
234
240
  export declare function receive(me: Context, payload: Uint8Array): Promise<{
235
241
  id: string;
236
242
  type: string;
237
243
  name: string | null;
238
244
  newer: boolean;
245
+ ref: string | null;
239
246
  } | null>;
240
247
  /**
241
248
  * Reveal the recovery phrase.
@@ -1,9 +1,9 @@
1
1
  /**
2
2
  * Quickly check whether the on-disk directory at `dir` already holds an initialised cero
3
- * identity (i.e. a stored master seed).
3
+ * identity (i.e. a stored device key with its proof).
4
4
  *
5
5
  * @param {string} dir Cero data directory.
6
6
  * @param {import('./spec.js').Spec} spec Built spec, the value passed to `cero(dir, spec)`.
7
- * @returns {Promise<boolean>} `true` if a master seed exists on disk.
7
+ * @returns {Promise<boolean>} `true` if a device of an identity exists on disk.
8
8
  */
9
9
  export declare function peek(dir: string, spec: import('./spec.js').Spec): Promise<boolean>;
@@ -31,6 +31,10 @@ export type RefInfo = {
31
31
  */
32
32
  files?: string[];
33
33
  verb?: string;
34
+ /**
35
+ * Whether a write to this ref pushes a notification.
36
+ */
37
+ push?: boolean;
34
38
  };
35
39
  export type SpecMeta = {
36
40
  ns?: string;
@@ -70,6 +74,7 @@ export type Row = import('@cero-base/core/database').Row;
70
74
  * @property {Record<string, string>} [required] The required fields and their types.
71
75
  * @property {string[]} [files] The fields holding file ids.
72
76
  * @property {string} [verb]
77
+ * @property {boolean} [push] Whether a write to this ref pushes a notification.
73
78
  *
74
79
  * @typedef {object} SpecMeta
75
80
  * @property {string} [ns]
@@ -1,12 +1,12 @@
1
1
  /**
2
- * `@react-native-firebase/messaging` as a push backend: pass `messaging()`. Pushes to the app in
2
+ * `@react-native-firebase/messaging` as the messaging service `connect` takes for push: pass `messaging()`. Pushes to the app in
3
3
  * front; the push worklet answers the ones the OS delivers while it is not.
4
4
  *
5
5
  * @param {{ subscribeToTopic: (topic: string) => Promise<void>, unsubscribeFromTopic: (topic: string) => Promise<void>, onMessage: (fn: (message: object) => void) => () => void }} messaging
6
- * @returns {import('../rpc/push.js').Backend}
6
+ * @returns {import('../rpc/push.js').Messaging}
7
7
  */
8
8
  export declare function firebase(messaging: {
9
9
  subscribeToTopic: (topic: string) => Promise<void>;
10
10
  unsubscribeFromTopic: (topic: string) => Promise<void>;
11
11
  onMessage: (fn: (message: object) => void) => () => void;
12
- }): import('../rpc/push.js').Backend;
12
+ }): import('../rpc/push.js').Messaging;
@@ -7,7 +7,7 @@
7
7
  * @param {import('../lib/spec.js').Spec} spec
8
8
  * @param {Uint8Array} payload
9
9
  * @param {{ storageKey?: Uint8Array }} [opts] The key `cero()` encrypts the local store with, if any.
10
- * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean } | null>}
10
+ * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean, ref: string | null } | null>}
11
11
  */
12
12
  export declare function receive(dir: string, spec: import('../lib/spec.js').Spec, payload: Uint8Array, { storageKey }?: {
13
13
  storageKey?: Uint8Array;
@@ -16,13 +16,28 @@ export declare function receive(dir: string, spec: import('../lib/spec.js').Spec
16
16
  type: string;
17
17
  name: string | null;
18
18
  newer: boolean;
19
+ ref: string | null;
19
20
  } | null>;
20
21
  /**
21
- * The bare-kit push entry: on each push the OS hands this worklet, verify it and answer with the
22
- * notification to show, or nothing. The request carries `storage`, `payload` (base64) and, when
23
- * the app encrypts its local store, `storageKey` (base64).
22
+ * The bare-kit push entry: on each push the OS hands this worklet, verify it and, for one about
23
+ * new data on a handle this device holds, answer with what `show` returns: the notification,
24
+ * `{ title, body }`, or nothing. The request carries `storage`, `payload` (base64) and, when the
25
+ * app encrypts its local store, `storageKey` (base64).
24
26
  *
25
27
  * @param {import('../lib/spec.js').Spec} spec
28
+ * @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.
26
29
  * @returns {void}
27
30
  */
28
- export declare function push(spec: import('../lib/spec.js').Spec): void;
31
+ export declare function push(spec: import('../lib/spec.js').Spec, show: (push: {
32
+ id: string;
33
+ type: string;
34
+ name: string | null;
35
+ newer: boolean;
36
+ ref: string | null;
37
+ }) => {
38
+ title: string;
39
+ body: string;
40
+ } | null | undefined | Promise<{
41
+ title: string;
42
+ body: string;
43
+ } | null | undefined>): void;
@@ -46,6 +46,7 @@ declare const remote: {
46
46
  type: string;
47
47
  name: string | null;
48
48
  newer: boolean;
49
+ ref: string | null;
49
50
  } | null>;
50
51
  phrase(me: verbs.Context): Promise<string>;
51
52
  nearby(ctx: verbs.Context, on: boolean, opts?: {
@@ -122,10 +123,11 @@ export declare class Client extends RPCClient {
122
123
  /**
123
124
  * @param {import('streamx').Duplex} ipc Framed IPC stream (must be writable).
124
125
  * @param {Spec} spec Compiled cero spec (schema + rpc + handles).
125
- * @param {{ onerror?: (err: Error) => void }} [opts] Where the worker's background errors go; the console without one.
126
+ * @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.
126
127
  */
127
128
  constructor(ipc: import('streamx').Duplex, spec: Spec, { onerror, push }?: {
128
129
  onerror?: (err: Error) => void;
130
+ push?: import('./push.js').Messaging;
129
131
  });
130
132
  /** @private */
131
133
  private _pumpErrors;
@@ -191,11 +193,12 @@ declare class Handle {
191
193
  *
192
194
  * @param {import('streamx').Duplex} ipc
193
195
  * @param {Spec} spec
194
- * @param {{ onerror?: (err: Error) => void }} [opts]
196
+ * @param {{ onerror?: (err: Error) => void, push?: import('./push.js').Messaging }} [opts]
195
197
  * @returns {Promise<Client>}
196
198
  */
197
199
  export declare function connect(ipc: import('streamx').Duplex, spec: Spec, opts?: {
198
200
  onerror?: (err: Error) => void;
201
+ push?: import('./push.js').Messaging;
199
202
  }): Promise<Client>;
200
203
  /**
201
204
  * Symmetric client entry. Mirrors the main `cero`, but `cero(ipc, spec)` connects to a
@@ -203,11 +206,12 @@ export declare function connect(ipc: import('streamx').Duplex, spec: Spec, opts?
203
206
  *
204
207
  * @param {import('streamx').Duplex} ipc Framed IPC duplex stream.
205
208
  * @param {Spec} spec Built cero spec.
206
- * @param {{ onerror?: (err: Error) => void }} [opts]
209
+ * @param {{ onerror?: (err: Error) => void, push?: import('./push.js').Messaging }} [opts]
207
210
  * @returns {Promise<Context>}
208
211
  */
209
212
  declare function start(ipc: import('streamx').Duplex, spec: Spec, opts?: {
210
213
  onerror?: (err: Error) => void;
214
+ push?: import('./push.js').Messaging;
211
215
  }): Promise<Context>;
212
216
  /** @type {typeof start & typeof remote & { connect: typeof connect, restore: typeof restore, t: typeof t, schema: typeof schema }} */
213
217
  export declare const cero: typeof start & typeof remote & {
@@ -1,10 +1,10 @@
1
- export type Backend = {
1
+ export type Messaging = {
2
2
  subscribe: (topic: string) => Promise<void>;
3
3
  unsubscribe: (topic: string) => Promise<void>;
4
4
  on: (event: 'push', fn: (payload: Uint8Array) => void) => (() => void) | void;
5
5
  };
6
6
  /**
7
- * @typedef {object} Backend The platform's push service, as `connect` takes it.
7
+ * @typedef {object} Messaging The platform's messaging service, as `connect` takes it for push.
8
8
  * @property {(topic: string) => Promise<void>} subscribe
9
9
  * @property {(topic: string) => Promise<void>} unsubscribe
10
10
  * @property {(event: 'push', fn: (payload: Uint8Array) => void) => (() => void) | void} on
@@ -14,7 +14,7 @@ export type Backend = {
14
14
  * leaves; and act on a push: the handle it is about ranks first on the swarm.
15
15
  *
16
16
  * @param {import('./client.js').Client} me
17
- * @param {Backend} backend
17
+ * @param {Messaging} messaging
18
18
  * @returns {() => void}
19
19
  */
20
- export declare function follow(me: import('./client.js').Client, backend: Backend): () => void;
20
+ export declare function follow(me: import('./client.js').Client, messaging: Messaging): () => void;