@cero-base/cero 2.6.0 → 2.8.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.6.0",
3
+ "version": "2.8.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,
@@ -103,7 +103,7 @@
103
103
  }
104
104
  },
105
105
  "scripts": {
106
- "build:test": "rm -rf test/fixtures/spec && node test/fixtures/build.js",
106
+ "build:test": "rm -rf test/fixtures/spec && node test/fixtures/build.js && node test/fixtures/compat.js",
107
107
  "build:types": "rm -rf types && tsc -p .",
108
108
  "pretest": "npm run build:test",
109
109
  "prepublishOnly": "npm run build:types",
@@ -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.6.0",
116
+ "@cero-base/core": "^2.8.0",
117
117
  "b4a": "^1.9.0",
118
118
  "bare-abort-controller": "^1.1.2",
119
119
  "bare-crypto": "^1.15.4",
@@ -1,5 +1,5 @@
1
1
  import { join, resolve } from 'path'
2
- import { promises as fs } from 'fs'
2
+ import { promises as fs, existsSync, readFileSync } from 'fs'
3
3
  import { pathToFileURL } from 'url'
4
4
 
5
5
  import b4a from 'b4a'
@@ -239,12 +239,12 @@ function register(name, node, ctx) {
239
239
  }
240
240
 
241
241
  // one contract for the app, kept in contract.json: it rises once per build that changes what is
242
- // stored, at the root or in any handle type, never for RPC alone. A spec without one starts from
243
- // its builders' versions, so a shipped app's number never goes down
242
+ // stored, at the root or in any handle type, or what a write means to Cero, never for RPC alone.
243
+ // A spec without one starts from its builders' versions, so a shipped app's number never goes down
244
244
  async function contract(specDir, dirs) {
245
245
  const file = join(specDir, 'contract.json')
246
246
  const shapes = await Promise.all(dirs.map((dir) => shapeOf(join(specDir, dir))))
247
- const json = JSON.stringify(shapes.map((s) => s.stored))
247
+ const json = JSON.stringify([internal.contract.version, ...shapes.map((s) => s.stored)])
248
248
  const shape = b4a.toString(crypto.hash(b4a.from(json)), 'hex')
249
249
  const kept = await fs.readFile(file, 'utf-8').then(JSON.parse, () => null)
250
250
  const version = kept
@@ -273,9 +273,10 @@ function emitMain(dir, ns, { types, collections, dispatches, indexes = [] }, { r
273
273
 
274
274
  const s = Hyperschema.from(schemaDir)
275
275
  const sns = s.namespace(ns)
276
- for (const desc of internal.types('main', extend)) sns.register(desc)
277
- for (const desc of types) sns.register(desc)
278
- if (rpc) for (const desc of internal.types('rpc')) sns.register(desc)
276
+ const keep = slots(schemaDir, ns)
277
+ for (const desc of internal.types('main', extend)) sns.register(keep(desc))
278
+ for (const desc of types) sns.register(keep(desc))
279
+ if (rpc) for (const desc of internal.types('rpc')) sns.register(keep(desc))
279
280
  Hyperschema.toDisk(s, schemaDir, { esm: true })
280
281
 
281
282
  const db = HyperdbBuilder.from(schemaDir, dbDir)
@@ -305,8 +306,9 @@ function emitLocal(dir, ns, { types, collections, indexes = [] }) {
305
306
 
306
307
  const s = Hyperschema.from(schemaDir)
307
308
  const sns = s.namespace(ns)
308
- for (const desc of internal.types('local')) sns.register(desc)
309
- for (const desc of types) sns.register(desc)
309
+ const keep = slots(schemaDir, ns)
310
+ for (const desc of internal.types('local')) sns.register(keep(desc))
311
+ for (const desc of types) sns.register(keep(desc))
310
312
  Hyperschema.toDisk(s, schemaDir, { esm: true })
311
313
 
312
314
  const db = HyperdbBuilder.from(schemaDir, dbDir)
@@ -317,6 +319,25 @@ function emitLocal(dir, ns, { types, collections, indexes = [] }) {
317
319
  HyperdbBuilder.toDisk(db, dbDir, { esm: true })
318
320
  }
319
321
 
322
+ // a field keeps the slot the built spec gave it, whichever schema declares it: hyperschema stores
323
+ // a row by position, and a type's fields are cero's, then its extensions', then the app's, so one
324
+ // more of cero's would take an extension's slot. A field the spec lacks goes after the ones it has
325
+ function slots(schemaDir, ns) {
326
+ const file = join(schemaDir, 'schema.json')
327
+ const built = existsSync(file) ? JSON.parse(readFileSync(file, 'utf-8')).schema : []
328
+ const had = new Map(
329
+ built
330
+ .filter((x) => x.namespace === ns && x.fields)
331
+ .map((x) => [x.name, x.fields.map((f) => f.name)])
332
+ )
333
+ return (desc) => {
334
+ const names = had.get(desc.name)
335
+ if (!names || !desc.fields) return desc
336
+ const at = (f) => (names.includes(f.name) ? names.indexOf(f.name) : names.length)
337
+ return { ...desc, fields: desc.fields.toSorted((a, b) => at(a) - at(b)) }
338
+ }
339
+ }
340
+
320
341
  const IMPORTS = {
321
342
  database: (n) => `import ${n}Database from './handles/${n}/db/index.js'`,
322
343
  dispatch: (n) => `import * as ${n}Dispatch from './handles/${n}/dispatch/index.js'`,
@@ -3,6 +3,8 @@ import { COUNTERS, EPOCHS, REMOVALS, REFUSALS, SPENT } from '../lib/constants.js
3
3
  import * as schemas from './schemas.js'
4
4
 
5
5
  // internal refs by scope; kind defaults to collection
6
+ export const { contract } = schemas
7
+
6
8
  export const defs = {
7
9
  main: {
8
10
  members: { type: 'member' },
@@ -194,7 +196,8 @@ const COMMANDS = [
194
196
  ['close-handle', 'req-handle', 'res-ok'],
195
197
  // not a verb: it ends the handle on both sides
196
198
  ['leave', 'req-handle', 'res-ok'],
197
- ['verb', 'req-verb', 'res-data']
199
+ ['verb', 'req-verb', 'res-data'],
200
+ ['link', 'req-link', 'res-link', true]
198
201
  ]
199
202
 
200
203
  /**
@@ -222,16 +222,23 @@ export const local = {
222
222
  environment: {
223
223
  channel: required(string)
224
224
  },
225
- // the handles rows a cold push process can read without the root: topic → handle and its key
225
+ // the handles rows a cold push process can read without the root: topic → handle, its keys and
226
+ // the epochs it learned, so a push's block opens there too
226
227
  subscription: {
227
228
  id: required(string),
228
229
  handle: required(string),
229
230
  type: required(string),
230
231
  key: required(bytes),
231
- name: string
232
+ name: string,
233
+ encryptionKey: bytes,
234
+ epochs: bytes
232
235
  }
233
236
  }
234
237
 
238
+ // what a write means to apply. A release that changes it without changing what is stored bumps
239
+ // this, so an app's next build raises its contract and devices on the old release skip the new writes
240
+ export const contract = { version: 1 }
241
+
235
242
  export const rpc = {
236
243
  'req-empty': {
237
244
  ok: bool
@@ -239,6 +246,9 @@ export const rpc = {
239
246
  'req-restore': {
240
247
  phrase: required(string)
241
248
  },
249
+ 'req-link': {
250
+ invite: required(string)
251
+ },
242
252
  'req-row': {
243
253
  handle: required(string),
244
254
  ref: required(string),
@@ -313,6 +323,15 @@ export const rpc = {
313
323
  fileToken: string,
314
324
  deviceName: string
315
325
  },
326
+ // a link's frames: the request's id as it is sent, then the identity once linked
327
+ 'res-link': {
328
+ request: string,
329
+ id: string,
330
+ deviceId: string,
331
+ deviceName: string,
332
+ fileBase: string,
333
+ fileToken: string
334
+ },
316
335
  'res-ok': {
317
336
  ok: bool
318
337
  },
@@ -11,7 +11,7 @@ import { Identity } from '@cero-base/core/identity'
11
11
  import { Database } from '@cero-base/core/database'
12
12
  import { blobEpochKey, epochEntries } from '@cero-base/core/database/encryption'
13
13
  import { Pairing } from '@cero-base/core/pairing'
14
- import { verify } from '@cero-base/core/push'
14
+ import { read } from '../push/index.js'
15
15
  import { Invite } from '@cero-base/core/invite'
16
16
  import { Mailbox } from '@cero-base/core/mailbox'
17
17
  import hid from 'hypercore-id-encoding'
@@ -366,7 +366,12 @@ export class Handle extends ReadyResource {
366
366
  // device checks its chain against
367
367
  /** @private */
368
368
  async _invite(opts = {}) {
369
- if (this.parent) return this._pair.invite(opts)
369
+ if (this.parent) {
370
+ const invite = await this._pair.invite(opts)
371
+ // a close right after the invite must not drop the row that reopens this handle at boot
372
+ await this._saved
373
+ return invite
374
+ }
370
375
  const { ttl = '2h' } = opts
371
376
  return this._pair.invite({ role: 'owner', confirm: true, ttl, data: this.identity.publicKey })
372
377
  }
@@ -566,7 +571,15 @@ export class Handle extends ReadyResource {
566
571
  if (!wanted.has(row.id)) await this.local.store.del('topics', row.id)
567
572
  }
568
573
  for (const [id, h] of wanted) {
569
- const row = { id, handle: h.id, type: h.type, key: h.key, name: h.name ?? null }
574
+ const row = {
575
+ id,
576
+ handle: h.id,
577
+ type: h.type,
578
+ key: h.key,
579
+ name: h.name ?? null,
580
+ encryptionKey: h.encryptionKey ?? null,
581
+ epochs: h.epochs && c.decode(epochEntries, h.epochs).length ? h.epochs : null
582
+ }
570
583
  if (same(have.get(id), row)) continue
571
584
  await this.local.store.put('topics', row)
572
585
  }
@@ -578,9 +591,7 @@ export class Handle extends ReadyResource {
578
591
  // a suspended storage answers no read: the cold entry serves a push while the app sleeps
579
592
  if (this._sus.suspended) throw CeroError.INVALID('receive: the app is suspended')
580
593
  const { data: rows } = await this.local.store.get('topics')
581
- const handles = rows.map(({ handle, key, type, name }) => ({ id: handle, key, type, name }))
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 }
594
+ return read(this.store.store.storage, this.spec, payload, rows)
584
595
  }
585
596
 
586
597
  /** @private */
@@ -905,6 +916,8 @@ export class Handle extends ReadyResource {
905
916
  /** @private */
906
917
  async _carryOn() {
907
918
  for (const { id, invite, type } of (await this.local.store.get('joins')).data) {
919
+ // the root's own device link row has no handle type: the launch resumes that one
920
+ if (!this.spec.handles?.[type]) continue
908
921
  if (await this._joined(type, Invite.parse(invite).discoveryKey)) {
909
922
  await this.local.store.del('joins', id)
910
923
  continue
@@ -1102,8 +1115,12 @@ export class Handle extends ReadyResource {
1102
1115
  if (!serving) return this.local.store.del('serving', child.id)
1103
1116
  await this.local.store.put('serving', { id: child.id, type: child.type })
1104
1117
  }
1105
- child._pair.on('serving', () => save().catch(this._onerror))
1106
- save().catch(this._onerror)
1118
+ // one at a time, so an invite can wait for its row
1119
+ const queue = () => {
1120
+ child._saved = (child._saved || Promise.resolve()).then(save).catch(this._onerror)
1121
+ }
1122
+ child._pair.on('serving', queue)
1123
+ queue()
1107
1124
  }
1108
1125
 
1109
1126
  /** @private */
@@ -1188,10 +1205,16 @@ function same(row, next) {
1188
1205
  row.handle === next.handle &&
1189
1206
  row.type === next.type &&
1190
1207
  (row.name ?? null) === next.name &&
1191
- b4a.equals(row.key, next.key)
1208
+ b4a.equals(row.key, next.key) &&
1209
+ sameBytes(row.encryptionKey, next.encryptionKey) &&
1210
+ sameBytes(row.epochs, next.epochs)
1192
1211
  )
1193
1212
  }
1194
1213
 
1214
+ function sameBytes(a, b) {
1215
+ return a && b ? b4a.equals(a, b) : (a ?? null) === (b ?? null)
1216
+ }
1217
+
1195
1218
  // run every teardown step, then surface the first failure: a bug must not leak the storage lock
1196
1219
  async function settle(steps) {
1197
1220
  let failed = null
package/src/index.js CHANGED
@@ -102,9 +102,6 @@ async function start(dir, spec, opts = {}) {
102
102
  // a device invite, this launch's or the one a killed launch was waiting on
103
103
  const pending = done || opts.phrase ? null : await pendingLink(local)
104
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
105
  const resolved = linking ? null : await resolveIdentity(opts, local, done)
109
106
  // cero creates only an identity it minted, in this launch or in the killed one it resumes
110
107
  const creating =
@@ -144,7 +141,7 @@ async function start(dir, spec, opts = {}) {
144
141
  await network.ready()
145
142
  // the link first: who this device is comes with the reply
146
143
  const linked = linking
147
- ? await link(local, network, spec, { ...opts, writer: keyPair, timeout }, pending)
144
+ ? await ask(local, network, spec, { ...opts, writer: keyPair, timeout }, pending)
148
145
  : null
149
146
  const identity = linked ? linked.identity : resolved.identity
150
147
  const fresh = resolved?.fresh === true
@@ -251,9 +248,31 @@ export async function restore(me, phrase) {
251
248
  return start(dir, spec, { ...opts, phrase })
252
249
  }
253
250
 
251
+ /**
252
+ * Link this device to the identity behind a device invite: closes `me`, deletes `dir/main` and
253
+ * opens the directory with `invite`, as a new device of that identity, with no phrase on it.
254
+ *
255
+ * @param {Context} me The root to replace.
256
+ * @param {string} invite A device invite, as `cero.invite(me)` gives it on a device of that identity.
257
+ * @param {{ onrequest?: (id: string) => void }} [opts] `onrequest`: the request's id as it is sent, the one the accepting device sees in `me.requests`.
258
+ * @returns {Promise<Handle>} The linked root handle.
259
+ */
260
+ export async function link(me, invite, { onrequest } = {}) {
261
+ if (!me?._dir) throw CeroError.INVALID('me must be a cero instance')
262
+ if (!invite) throw CeroError.REQUIRED('invite')
263
+
264
+ const { _dir: dir, spec, _opts: opts } = me
265
+
266
+ await me.close()
267
+ await fs.promises.rm(`${dir}/main`, { recursive: true, force: true })
268
+
269
+ // the other device is in someone's other hand: the wait is the invite's lifetime, deny ends it
270
+ return start(dir, spec, { ...opts, phrase: undefined, invite, onrequest, recoveryTimeout: 0 })
271
+ }
272
+
254
273
  // the facade: cero.put and import { put } are the same function
255
- /** @type {typeof start & typeof verbs & { t: typeof t, schema: typeof schema, peek: typeof peek, restore: typeof restore }} */
256
- export const cero = Object.assign(start, verbs, { t, schema, peek, restore })
274
+ /** @type {typeof start & typeof verbs & { t: typeof t, schema: typeof schema, peek: typeof peek, restore: typeof restore, link: typeof link }} */
275
+ export const cero = Object.assign(start, verbs, { t, schema, peek, restore, link })
257
276
 
258
277
  function pointerManifest(store, identity) {
259
278
  return { version: store.manifestVersion, signers: [{ publicKey: identity.publicKey }] }
@@ -293,7 +312,7 @@ async function pendingLink(local) {
293
312
 
294
313
  // the root's join: this device, bare, knocks with the invite and waits for a device of the identity
295
314
  // 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) {
315
+ async function ask(local, network, spec, { invite, writer, onrequest, timeout }, pending) {
297
316
  const parsed = Invite.parse(invite ?? pending.invite)
298
317
  if (parsed.data?.byteLength !== 32) throw CeroError.INVALID_INVITE('not a device invite')
299
318
  const secret = pending?.device ?? Identity.randomKeyPair().secretKey
@@ -496,7 +496,7 @@ export async function deactivate(ctx) {
496
496
  *
497
497
  * @param {Context} me
498
498
  * @param {Uint8Array} payload
499
- * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean, ref: string | null } | null>}
499
+ * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean, ref: string | null, row: object | null } | null>}
500
500
  */
501
501
  export async function receive(me, payload) {
502
502
  if (me.parent) throw CeroError.INVALID("receive is the app's, on me")
package/src/push/index.js CHANGED
@@ -3,11 +3,47 @@ import Corestore from 'corestore'
3
3
  import b4a from 'b4a'
4
4
  import safetyCatch from 'safety-catch'
5
5
 
6
- import { verify } from '@cero-base/core/push'
6
+ import c from 'compact-encoding'
7
+ import { verify, decrypt } from '@cero-base/core/push'
7
8
  import { CeroError } from '@cero-base/core/errors'
9
+ import { epochEntries } from '@cero-base/core/database/encryption'
8
10
 
9
11
  import { Local } from '../local/index.js'
10
12
 
13
+ /**
14
+ * A push verified against the handles the topics rows name, with the row it wrote when the block
15
+ * rode along and this device holds the handle's keys.
16
+ *
17
+ * @param {import('hypercore-storage')} storage
18
+ * @param {import('../lib/spec.js').Spec} spec
19
+ * @param {Uint8Array} payload
20
+ * @param {Array<{ id: string, handle: string, type: string, key: Uint8Array, name: string | null, encryptionKey?: Uint8Array | null, epochs?: Uint8Array | null }>} rows The root's `topics` rows.
21
+ * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean, ref: string | null, row: object | null } | null>}
22
+ */
23
+ export async function read(storage, spec, payload, rows) {
24
+ const handles = rows.map(({ handle, key, type, name }) => ({ id: handle, key, type, name }))
25
+ const hit = await verify(storage, payload, handles)
26
+ if (!hit) return null
27
+ const keys = rows.find((r) => r.handle === hit.id)
28
+ const row = await rowOf(storage, spec, hit, keys)
29
+ return { id: hit.id, type: hit.type, name: hit.name, newer: hit.newer, ref: hit.ref, row }
30
+ }
31
+
32
+ // the row a push's block holds: null when none rode along, or it does not decode with what we hold
33
+ async function rowOf(storage, spec, hit, { encryptionKey, epochs }) {
34
+ if (!hit.block || !encryptionKey) return null
35
+ try {
36
+ const body = await decrypt(storage, hit, {
37
+ encryptionKey,
38
+ epochs: epochs ? c.decode(epochEntries, epochs) : []
39
+ })
40
+ return body ? (spec.handles[hit.type].dispatch.decode(body).value ?? null) : null
41
+ } catch (err) {
42
+ safetyCatch(err)
43
+ return null
44
+ }
45
+ }
46
+
11
47
  /**
12
48
  * A push the platform delivered while the app is dead, verified from its storage opened
13
49
  * read-only. `null` while the live app holds the storage, which shows the activity itself, and
@@ -17,7 +53,7 @@ import { Local } from '../local/index.js'
17
53
  * @param {import('../lib/spec.js').Spec} spec
18
54
  * @param {Uint8Array} payload
19
55
  * @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>}
56
+ * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean, ref: string | null, row: object | null } | null>}
21
57
  */
22
58
  export async function receive(dir, spec, payload, { storageKey } = {}) {
23
59
  const storage = new HypercoreStorage(`${dir}/main`, { readOnly: true })
@@ -29,9 +65,7 @@ export async function receive(dir, spec, payload, { storageKey } = {}) {
29
65
  local = new Local(null, spec, { store, storageKey })
30
66
  await local.ready()
31
67
  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 }
68
+ return await read(storage, spec, payload, rows)
35
69
  } catch (err) {
36
70
  safetyCatch(err)
37
71
  return null
@@ -44,16 +78,16 @@ export async function receive(dir, spec, payload, { storageKey } = {}) {
44
78
 
45
79
  /**
46
80
  * 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
81
+ * new data on a handle this device holds, answer with what the show handler returns: the
82
+ * notification, `{ title, body }`, or nothing. The request carries `storage`, `payload` (base64) and, when the
49
83
  * app encrypts its local store, `storageKey` (base64).
50
84
  *
51
85
  * @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.
86
+ * @param {(push: { id: string, type: string, name: string | null, newer: boolean, ref: string | null, row: object | null }) => { title: string, body: string } | null | undefined | Promise<{ title: string, body: string } | null | undefined>} show The show handler: what to show for a verified push, as `cero.receive` would give it to the app.
53
87
  * @returns {void}
54
88
  */
55
89
  export function push(spec, show) {
56
- if (typeof show !== 'function') throw CeroError.INVALID('push: show(push) says what to show')
90
+ if (typeof show !== 'function') throw CeroError.INVALID('push: a show handler says what to show')
57
91
  globalThis.BareKit.on('push', async (json, reply) => {
58
92
  let shown = null
59
93
  try {
package/src/rpc/client.js CHANGED
@@ -424,6 +424,28 @@ export async function restore(me, phrase) {
424
424
  return me
425
425
  }
426
426
 
427
+ /**
428
+ * Link the app to the identity behind a device invite, as `cero.link` does in the worker: the
429
+ * client is then that identity. `onrequest` gets the request's id as it is sent.
430
+ *
431
+ * @param {Client} me
432
+ * @param {string} invite
433
+ * @param {{ onrequest?: (id: string) => void }} [opts]
434
+ * @returns {Promise<Client>}
435
+ */
436
+ export function link(me, invite, { onrequest } = {}) {
437
+ return new Promise((resolve, reject) => {
438
+ const wire = me.rpc.link({ invite })
439
+ wire.on('data', (frame) => {
440
+ if (frame.request) onrequest?.(frame.request)
441
+ else me._identify(frame)
442
+ })
443
+ wire.on('error', reject)
444
+ wire.on('end', () => resolve(me))
445
+ wire.on('close', () => reject(CeroError.INVALID('link: the worker closed the stream')))
446
+ })
447
+ }
448
+
427
449
  /**
428
450
  * Per-device `local`-namespace surface on a Client.
429
451
  */
@@ -636,8 +658,8 @@ function start(ipc, spec, opts) {
636
658
  return /** @type {Promise<Context>} */ (connect(ipc, spec, opts))
637
659
  }
638
660
 
639
- /** @type {typeof start & typeof remote & { connect: typeof connect, restore: typeof restore, t: typeof t, schema: typeof schema }} */
640
- export const cero = Object.assign(start, remote, { connect, restore, t, schema })
661
+ /** @type {typeof start & typeof remote & { connect: typeof connect, restore: typeof restore, link: typeof link, t: typeof t, schema: typeof schema }} */
662
+ export const cero = Object.assign(start, remote, { connect, restore, link, t, schema })
641
663
 
642
664
  // the same shape a local root has
643
665
  function device({ deviceId, deviceName }) {
package/src/rpc/server.js CHANGED
@@ -4,7 +4,7 @@ import safetyCatch from 'safety-catch'
4
4
  import { RPCServer, bindCodec } from '@cero-base/core/rpc'
5
5
  import { CeroError } from '@cero-base/core/errors'
6
6
 
7
- import { cero, restore } from '../index.js'
7
+ import { cero, restore, link } from '../index.js'
8
8
  import {
9
9
  put,
10
10
  set,
@@ -139,6 +139,7 @@ export class Server extends RPCServer {
139
139
  this._wireHandles()
140
140
  this._wireVerbs()
141
141
  this._wireRestore()
142
+ this._wireLink()
142
143
  }
143
144
 
144
145
  /** @private */
@@ -206,6 +207,30 @@ export class Server extends RPCServer {
206
207
  })
207
208
  }
208
209
 
210
+ /**
211
+ * Wire the `link` handler: a stream, the request's id as it is sent, the identity once linked.
212
+ * @private
213
+ */
214
+ _wireLink() {
215
+ this.rpc.onLink((stream) => {
216
+ stream.on('error', safetyCatch)
217
+ const run = async () => {
218
+ if (!this.me) throw CeroError.NOT_READY('Server', 'server')
219
+ this.me = await link(this.me, stream.data.invite, {
220
+ onrequest: (id) => stream.write({ request: id })
221
+ })
222
+ this.handles = new Map([[this.me.id, this.me]])
223
+ stream.write({ request: '', ...this._identity() })
224
+ stream.end()
225
+ }
226
+ run().catch((err) => {
227
+ stream.once('error', () => {})
228
+ stream.writeStream.destroy(err)
229
+ stream.destroy()
230
+ })
231
+ })
232
+ }
233
+
209
234
  /**
210
235
  * Register the row-level RPC handlers (put/set/get/del/watch/call).
211
236
  * @private
@@ -1,3 +1,6 @@
1
+ export declare const contract: {
2
+ version: number;
3
+ };
1
4
  export declare const defs: {
2
5
  main: {
3
6
  members: {
@@ -190,8 +190,13 @@ export declare const local: {
190
190
  type: import("@cero-base/core").Prim;
191
191
  key: import("@cero-base/core").Prim;
192
192
  name: import("@cero-base/core").Prim;
193
+ encryptionKey: import("@cero-base/core").Prim;
194
+ epochs: import("@cero-base/core").Prim;
193
195
  };
194
196
  };
197
+ export declare const contract: {
198
+ version: number;
199
+ };
195
200
  export declare const rpc: {
196
201
  'req-empty': {
197
202
  ok: import("@cero-base/core").Prim;
@@ -199,6 +204,9 @@ export declare const rpc: {
199
204
  'req-restore': {
200
205
  phrase: import("@cero-base/core").Prim;
201
206
  };
207
+ 'req-link': {
208
+ invite: import("@cero-base/core").Prim;
209
+ };
202
210
  'req-row': {
203
211
  handle: import("@cero-base/core").Prim;
204
212
  ref: import("@cero-base/core").Prim;
@@ -274,6 +282,14 @@ export declare const rpc: {
274
282
  fileToken: import("@cero-base/core").Prim;
275
283
  deviceName: import("@cero-base/core").Prim;
276
284
  };
285
+ 'res-link': {
286
+ request: import("@cero-base/core").Prim;
287
+ id: import("@cero-base/core").Prim;
288
+ deviceId: import("@cero-base/core").Prim;
289
+ deviceName: import("@cero-base/core").Prim;
290
+ fileBase: import("@cero-base/core").Prim;
291
+ fileToken: import("@cero-base/core").Prim;
292
+ };
277
293
  'res-ok': {
278
294
  ok: import("@cero-base/core").Prim;
279
295
  };
@@ -55,6 +55,7 @@ export declare const cero: {
55
55
  name: string | null;
56
56
  newer: boolean;
57
57
  ref: string | null;
58
+ row: object | null;
58
59
  } | null>;
59
60
  phrase(me: operators.Context): Promise<string>;
60
61
  nearby(ctx: operators.Context, on: boolean, opts?: {
package/types/index.d.ts CHANGED
@@ -127,10 +127,23 @@ declare function start(dir: string, spec: import('./lib/spec.js').Spec, opts?: C
127
127
  * @returns {Promise<Handle>} Freshly restored root handle.
128
128
  */
129
129
  export declare function restore(me: Context, phrase: string): Promise<Handle>;
130
- /** @type {typeof start & typeof verbs & { t: typeof t, schema: typeof schema, peek: typeof peek, restore: typeof restore }} */
130
+ /**
131
+ * Link this device to the identity behind a device invite: closes `me`, deletes `dir/main` and
132
+ * opens the directory with `invite`, as a new device of that identity, with no phrase on it.
133
+ *
134
+ * @param {Context} me The root to replace.
135
+ * @param {string} invite A device invite, as `cero.invite(me)` gives it on a device of that identity.
136
+ * @param {{ onrequest?: (id: string) => void }} [opts] `onrequest`: the request's id as it is sent, the one the accepting device sees in `me.requests`.
137
+ * @returns {Promise<Handle>} The linked root handle.
138
+ */
139
+ export declare function link(me: Context, invite: string, { onrequest }?: {
140
+ onrequest?: (id: string) => void;
141
+ }): Promise<Handle>;
142
+ /** @type {typeof start & typeof verbs & { t: typeof t, schema: typeof schema, peek: typeof peek, restore: typeof restore, link: typeof link }} */
131
143
  export declare const cero: typeof start & typeof verbs & {
132
144
  t: typeof t;
133
145
  schema: typeof schema;
134
146
  peek: typeof peek;
135
147
  restore: typeof restore;
148
+ link: typeof link;
136
149
  };
@@ -235,7 +235,7 @@ export declare function deactivate(ctx: Context): Promise<void>;
235
235
  *
236
236
  * @param {Context} me
237
237
  * @param {Uint8Array} payload
238
- * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean, ref: string | null } | null>}
238
+ * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean, ref: string | null, row: object | null } | null>}
239
239
  */
240
240
  export declare function receive(me: Context, payload: Uint8Array): Promise<{
241
241
  id: string;
@@ -243,6 +243,7 @@ export declare function receive(me: Context, payload: Uint8Array): Promise<{
243
243
  name: string | null;
244
244
  newer: boolean;
245
245
  ref: string | null;
246
+ row: object | null;
246
247
  } | null>;
247
248
  /**
248
249
  * Reveal the recovery phrase.
@@ -1,3 +1,29 @@
1
+ /**
2
+ * A push verified against the handles the topics rows name, with the row it wrote when the block
3
+ * rode along and this device holds the handle's keys.
4
+ *
5
+ * @param {import('hypercore-storage')} storage
6
+ * @param {import('../lib/spec.js').Spec} spec
7
+ * @param {Uint8Array} payload
8
+ * @param {Array<{ id: string, handle: string, type: string, key: Uint8Array, name: string | null, encryptionKey?: Uint8Array | null, epochs?: Uint8Array | null }>} rows The root's `topics` rows.
9
+ * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean, ref: string | null, row: object | null } | null>}
10
+ */
11
+ export declare function read(storage: import('hypercore-storage'), spec: import('../lib/spec.js').Spec, payload: Uint8Array, rows: Array<{
12
+ id: string;
13
+ handle: string;
14
+ type: string;
15
+ key: Uint8Array;
16
+ name: string | null;
17
+ encryptionKey?: Uint8Array | null;
18
+ epochs?: Uint8Array | null;
19
+ }>): Promise<{
20
+ id: string;
21
+ type: string;
22
+ name: string | null;
23
+ newer: boolean;
24
+ ref: string | null;
25
+ row: object | null;
26
+ } | null>;
1
27
  /**
2
28
  * A push the platform delivered while the app is dead, verified from its storage opened
3
29
  * read-only. `null` while the live app holds the storage, which shows the activity itself, and
@@ -7,7 +33,7 @@
7
33
  * @param {import('../lib/spec.js').Spec} spec
8
34
  * @param {Uint8Array} payload
9
35
  * @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, ref: string | null } | null>}
36
+ * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean, ref: string | null, row: object | null } | null>}
11
37
  */
12
38
  export declare function receive(dir: string, spec: import('../lib/spec.js').Spec, payload: Uint8Array, { storageKey }?: {
13
39
  storageKey?: Uint8Array;
@@ -17,15 +43,16 @@ export declare function receive(dir: string, spec: import('../lib/spec.js').Spec
17
43
  name: string | null;
18
44
  newer: boolean;
19
45
  ref: string | null;
46
+ row: object | null;
20
47
  } | null>;
21
48
  /**
22
49
  * 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
50
+ * new data on a handle this device holds, answer with what the show handler returns: the
51
+ * notification, `{ title, body }`, or nothing. The request carries `storage`, `payload` (base64) and, when the
25
52
  * app encrypts its local store, `storageKey` (base64).
26
53
  *
27
54
  * @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.
55
+ * @param {(push: { id: string, type: string, name: string | null, newer: boolean, ref: string | null, row: object | null }) => { title: string, body: string } | null | undefined | Promise<{ title: string, body: string } | null | undefined>} show The show handler: what to show for a verified push, as `cero.receive` would give it to the app.
29
56
  * @returns {void}
30
57
  */
31
58
  export declare function push(spec: import('../lib/spec.js').Spec, show: (push: {
@@ -34,6 +61,7 @@ export declare function push(spec: import('../lib/spec.js').Spec, show: (push: {
34
61
  name: string | null;
35
62
  newer: boolean;
36
63
  ref: string | null;
64
+ row: object | null;
37
65
  }) => {
38
66
  title: string;
39
67
  body: string;
@@ -47,6 +47,7 @@ declare const remote: {
47
47
  name: string | null;
48
48
  newer: boolean;
49
49
  ref: string | null;
50
+ row: object | null;
50
51
  } | null>;
51
52
  phrase(me: verbs.Context): Promise<string>;
52
53
  nearby(ctx: verbs.Context, on: boolean, opts?: {
@@ -76,6 +77,18 @@ export type Context = (Client | Handle) & Record<string, Ref>;
76
77
  * @returns {Promise<Client>}
77
78
  */
78
79
  export declare function restore(me: Client, phrase: string): Promise<Client>;
80
+ /**
81
+ * Link the app to the identity behind a device invite, as `cero.link` does in the worker: the
82
+ * client is then that identity. `onrequest` gets the request's id as it is sent.
83
+ *
84
+ * @param {Client} me
85
+ * @param {string} invite
86
+ * @param {{ onrequest?: (id: string) => void }} [opts]
87
+ * @returns {Promise<Client>}
88
+ */
89
+ export declare function link(me: Client, invite: string, { onrequest }?: {
90
+ onrequest?: (id: string) => void;
91
+ }): Promise<Client>;
79
92
  /**
80
93
  * Per-device `local`-namespace surface on a Client.
81
94
  */
@@ -213,10 +226,11 @@ declare function start(ipc: import('streamx').Duplex, spec: Spec, opts?: {
213
226
  onerror?: (err: Error) => void;
214
227
  push?: import('./push.js').Messaging;
215
228
  }): Promise<Context>;
216
- /** @type {typeof start & typeof remote & { connect: typeof connect, restore: typeof restore, t: typeof t, schema: typeof schema }} */
229
+ /** @type {typeof start & typeof remote & { connect: typeof connect, restore: typeof restore, link: typeof link, t: typeof t, schema: typeof schema }} */
217
230
  export declare const cero: typeof start & typeof remote & {
218
231
  connect: typeof connect;
219
232
  restore: typeof restore;
233
+ link: typeof link;
220
234
  t: typeof t;
221
235
  schema: typeof schema;
222
236
  };
@@ -131,6 +131,11 @@ export declare class Server extends RPCServer {
131
131
  * @private
132
132
  */
133
133
  private _wireRestore;
134
+ /**
135
+ * Wire the `link` handler: a stream, the request's id as it is sent, the identity once linked.
136
+ * @private
137
+ */
138
+ private _wireLink;
134
139
  /**
135
140
  * Register the row-level RPC handlers (put/set/get/del/watch/call).
136
141
  * @private