@cero-base/cero 2.5.0 → 2.7.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.7.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.7.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'
@@ -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)) {
@@ -270,9 +273,10 @@ function emitMain(dir, ns, { types, collections, dispatches, indexes = [] }, { r
270
273
 
271
274
  const s = Hyperschema.from(schemaDir)
272
275
  const sns = s.namespace(ns)
273
- for (const desc of internal.types('main', extend)) sns.register(desc)
274
- for (const desc of types) sns.register(desc)
275
- 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))
276
280
  Hyperschema.toDisk(s, schemaDir, { esm: true })
277
281
 
278
282
  const db = HyperdbBuilder.from(schemaDir, dbDir)
@@ -302,8 +306,9 @@ function emitLocal(dir, ns, { types, collections, indexes = [] }) {
302
306
 
303
307
  const s = Hyperschema.from(schemaDir)
304
308
  const sns = s.namespace(ns)
305
- for (const desc of internal.types('local')) sns.register(desc)
306
- 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))
307
312
  Hyperschema.toDisk(s, schemaDir, { esm: true })
308
313
 
309
314
  const db = HyperdbBuilder.from(schemaDir, dbDir)
@@ -314,6 +319,25 @@ function emitLocal(dir, ns, { types, collections, indexes = [] }) {
314
319
  HyperdbBuilder.toDisk(db, dbDir, { esm: true })
315
320
  }
316
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
+
317
341
  const IMPORTS = {
318
342
  database: (n) => `import ${n}Database from './handles/${n}/db/index.js'`,
319
343
  dispatch: (n) => `import * as ${n}Dispatch from './handles/${n}/dispatch/index.js'`,
@@ -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' },
@@ -193,7 +194,8 @@ const COMMANDS = [
193
194
  ['close-handle', 'req-handle', 'res-ok'],
194
195
  // not a verb: it ends the handle on both sides
195
196
  ['leave', 'req-handle', 'res-ok'],
196
- ['verb', 'req-verb', 'res-data']
197
+ ['verb', 'req-verb', 'res-data'],
198
+ ['link', 'req-link', 'res-link', true]
197
199
  ]
198
200
 
199
201
  /**
@@ -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
@@ -217,6 +239,9 @@ export const rpc = {
217
239
  'req-restore': {
218
240
  phrase: required(string)
219
241
  },
242
+ 'req-link': {
243
+ invite: required(string)
244
+ },
220
245
  'req-row': {
221
246
  handle: required(string),
222
247
  ref: required(string),
@@ -291,6 +316,15 @@ export const rpc = {
291
316
  fileToken: string,
292
317
  deviceName: string
293
318
  },
319
+ // a link's frames: the request's id as it is sent, then the identity once linked
320
+ 'res-link': {
321
+ request: string,
322
+ id: string,
323
+ deviceId: string,
324
+ deviceName: string,
325
+ fileBase: string,
326
+ fileToken: string
327
+ },
294
328
  'res-ok': {
295
329
  ok: bool
296
330
  },
@@ -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
@@ -901,6 +905,8 @@ export class Handle extends ReadyResource {
901
905
  /** @private */
902
906
  async _carryOn() {
903
907
  for (const { id, invite, type } of (await this.local.store.get('joins')).data) {
908
+ // the root's own device link row has no handle type: the launch resumes that one
909
+ if (!this.spec.handles?.[type]) continue
904
910
  if (await this._joined(type, Invite.parse(invite).discoveryKey)) {
905
911
  await this.local.store.del('joins', id)
906
912
  continue
@@ -961,6 +967,7 @@ export class Handle extends ReadyResource {
961
967
  namespace: `${NS}/handle/${type}/${id}`,
962
968
  key: data.key,
963
969
  encryptionKey: data.encryptionKey,
970
+ epochs: data.epochs ? c.decode(epochEntries, data.epochs) : undefined,
964
971
  keyPair: /** @type {KeyPair} */ (writer)
965
972
  })
966
973
  try {
@@ -1010,9 +1017,59 @@ export class Handle extends ReadyResource {
1010
1017
  this._pending.delete(child)
1011
1018
  this.children.add(child)
1012
1019
  this._serve(child)
1020
+ this._carry(child)
1021
+ this._prune(child).catch(this._onerror)
1013
1022
  this.emit('handle', child, info)
1014
1023
  }
1015
1024
 
1025
+ // a device removed from the root loses its seats in every handle: its chain is static, so the
1026
+ // handles are told by whichever device of the identity has them open
1027
+ /** @private */
1028
+ async _prune(child) {
1029
+ const { data: mine } = await this.store.get('devices')
1030
+ const kept = new Set(mine.filter((d) => d.key).map((d) => b4a.toHex(d.key)))
1031
+ const { data: rows } = await child.store.get('devices')
1032
+ for (const row of rows) {
1033
+ if (row.memberId !== this.identity.id || !row.key || kept.has(b4a.toHex(row.key))) continue
1034
+ if (child.closing || child.closed) return
1035
+ await child.store.del('devices', row.id)
1036
+ }
1037
+ }
1038
+
1039
+ /** @private */
1040
+ async _pruneAll() {
1041
+ for (const child of this.children) await this._prune(child)
1042
+ }
1043
+
1044
+ // a handle's epochs ride in its root row, which only the identity's devices read: one that
1045
+ // opens the handle later reads history with them, since envelopes in the log address a device
1046
+ /** @private */
1047
+ _carry(child) {
1048
+ const save = async () => {
1049
+ const epochs = c.encode(epochEntries, child.store.keyring.all())
1050
+ const { data: row } = await this.store.get('handles', child.id)
1051
+ if (!row || b4a.equals(row.epochs || b4a.alloc(0), epochs)) return
1052
+ await this.store.set('handles', { id: row.id, epochs })
1053
+ }
1054
+ // read when the row changes, and when an announcement applies: it is learned only after that
1055
+ const read = async () => {
1056
+ const { data: row } = await this.store.get('handles', child.id)
1057
+ if (row?.epochs) await child.store.learn(c.decode(epochEntries, row.epochs))
1058
+ }
1059
+ const touches = (name) => (touched) => touched.has('*') || touched.has(name)
1060
+ const onepoch = () => save().catch(this._onerror)
1061
+ const onroot = (touched) => touches('handles')(touched) && read().catch(this._onerror)
1062
+ const onchild = (touched) => touches('epochs')(touched) && read().catch(this._onerror)
1063
+ child.store.on('epoch', onepoch)
1064
+ child.store.on('update', onchild)
1065
+ this.store.on('update', onroot)
1066
+ child.once('close', () => {
1067
+ child.store.off('epoch', onepoch)
1068
+ child.store.off('update', onchild)
1069
+ this.store.off('update', onroot)
1070
+ })
1071
+ }
1072
+
1016
1073
  // before(me.room.notes, fn): on every handle open now and every one opened later
1017
1074
  /** @private */
1018
1075
  _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,18 @@ 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
+ const resolved = linking ? null : await resolveIdentity(opts, local, done)
93
106
  // 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'
107
+ const creating =
108
+ !done && !linking && !opts.phrase && (resolved.fresh || device?.setup === 'create')
109
+ const recovering = !done && !linking && !creating
110
+ const setup = done ? null : linking ? 'link' : creating ? 'create' : 'recover'
97
111
  const keyPair =
98
112
  done || device?.setup === setup
99
113
  ? { publicKey: device.publicKey, secretKey: device.secretKey }
@@ -102,8 +116,11 @@ async function start(dir, spec, opts = {}) {
102
116
  if (!done && device?.setup !== setup) {
103
117
  await local.store.set('keypair', { ...keyPair, setup })
104
118
  }
105
- if (seed) await local.store.set('master', { seed })
106
- const timeout = opts.recoveryTimeout || TIMEOUT
119
+ if (resolved?.minted) {
120
+ await local.store.set('master', { seed: resolved.identity.seed })
121
+ await local.store.set('device', pack(resolved.identity))
122
+ }
123
+ const timeout = opts.recoveryTimeout ?? TIMEOUT
107
124
 
108
125
  // a storage remembers its channel; reopening under another would silently rejoin the global network
109
126
  const stored = (await local.store.get('environment')).data?.channel ?? null
@@ -122,6 +139,12 @@ async function start(dir, spec, opts = {}) {
122
139
  onerror
123
140
  })
124
141
  await network.ready()
142
+ // the link first: who this device is comes with the reply
143
+ const linked = linking
144
+ ? await ask(local, network, spec, { ...opts, writer: keyPair, timeout }, pending)
145
+ : null
146
+ const identity = linked ? linked.identity : resolved.identity
147
+ const fresh = resolved?.fresh === true
125
148
  // the radio before the pointer read: a phrase recovers from a device in range, no internet
126
149
  bluetooth = new Bluetooth(network, { ...bt, identity, keyPair })
127
150
  await bluetooth.ready()
@@ -133,13 +156,13 @@ async function start(dir, spec, opts = {}) {
133
156
  const manifest = pointerManifest(store, identity)
134
157
  const pointer = store.get(
135
158
  creating
136
- ? { keyPair: { publicKey: identity.publicKey, secretKey: identity.secretKey }, manifest }
159
+ ? { keyPair: await Identity.keyPair(identity.seed), manifest }
137
160
  : { key: Hypercore.key(manifest) }
138
161
  )
139
162
  await pointer.ready()
140
163
  network.attach(pointer)
141
164
 
142
- const key = recovering ? await readPointer(pointer, timeout) : undefined
165
+ const key = recovering ? await readPointer(pointer, timeout) : linked?.key
143
166
 
144
167
  me = new Handle({
145
168
  storage,
@@ -153,10 +176,16 @@ async function start(dir, spec, opts = {}) {
153
176
  dir,
154
177
  key,
155
178
  keyPair,
179
+ epochs: linked?.epochs,
156
180
  bluetooth,
157
181
  bootstrap: done
158
182
  ? null
159
- : { name: opts.name || null, isMobile: opts.isMobile === true, recovering, timeout }
183
+ : {
184
+ name: opts.name || null,
185
+ isMobile: opts.isMobile === true,
186
+ recovering: recovering || linking,
187
+ timeout
188
+ }
160
189
  })
161
190
  // an extension's hooks see every op the root applies; what else it calls waits for the open
162
191
  const setups = Promise.all(me.extensions.map(async (ext) => ext.setup?.(me)))
@@ -168,6 +197,10 @@ async function start(dir, spec, opts = {}) {
168
197
  if (creating && pointer.length === 0) {
169
198
  await pointer.append(c.encode(c.fixed32, me.store.key))
170
199
  }
200
+ if (linked) {
201
+ await local.store.set('device', pack(identity))
202
+ await local.store.del('joins', linked.id)
203
+ }
171
204
  await local.store.set('keypair', { setup: null })
172
205
  }
173
206
 
@@ -215,9 +248,31 @@ export async function restore(me, phrase) {
215
248
  return start(dir, spec, { ...opts, phrase })
216
249
  }
217
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
+
218
273
  // the facade: cero.put and import { put } are the same function
219
- /** @type {typeof start & typeof verbs & { t: typeof t, schema: typeof schema, peek: typeof peek, restore: typeof restore }} */
220
- 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 })
221
276
 
222
277
  function pointerManifest(store, identity) {
223
278
  return { version: store.manifestVersion, signers: [{ publicKey: identity.publicKey }] }
@@ -231,14 +286,88 @@ async function readPointer(pointer, timeout) {
231
286
  }
232
287
  }
233
288
 
234
- // `seed` is the one to store: supplied or minted, null when already stored
289
+ // the identity as this device holds it: stored, or minted now from the phrase or afresh
235
290
  async function resolveIdentity(opts, local, done) {
236
291
  const provided = opts.phrase ? Identity.toSeed(opts.phrase) : null
237
- const stored = (await local.store.get('master')).data?.seed
292
+ const seed = (await local.store.get('master')).data?.seed ?? null
293
+ const row = (await local.store.get('device')).data
294
+ if (seed && !row) throw CeroError.INVALID('this storage predates device keys: recreate it')
295
+ const same =
296
+ row && provided ? b4a.equals((await Identity.keyPair(provided)).publicKey, row.identity) : true
238
297
  // 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')
298
+ if (done && !same) throw CeroError.INVALID('dir holds another identity: switch with cero.restore')
299
+ // a phrase given to an unfinished setup takes over from the identity it minted
300
+ if (row && same) return { identity: unpack(row, seed), fresh: false, minted: false }
301
+ const identity = await Identity.create({ seed: provided, words: opts.words })
302
+ return { identity, fresh: !provided, minted: true }
303
+ }
304
+
305
+ // the root's own join in the joins rows
306
+ const LINK = 'root'
307
+
308
+ async function pendingLink(local) {
309
+ const { data: rows } = await local.store.get('joins')
310
+ return rows.find((row) => row.type === LINK) ?? null
311
+ }
312
+
313
+ // the root's join: this device, bare, knocks with the invite and waits for a device of the identity
314
+ // to let it in. What it learns is kept in its joins row, so a killed launch resumes it
315
+ async function ask(local, network, spec, { invite, writer, onrequest, timeout }, pending) {
316
+ const parsed = Invite.parse(invite ?? pending.invite)
317
+ if (parsed.data?.byteLength !== 32) throw CeroError.INVALID_INVITE('not a device invite')
318
+ const secret = pending?.device ?? Identity.randomKeyPair().secretKey
319
+ const device = { publicKey: secret.subarray(32), secretKey: secret }
320
+ const row = {
321
+ ...pending,
322
+ id: b4a.toHex(parsed.discoveryKey),
323
+ type: LINK,
324
+ invite: invite ?? pending.invite,
325
+ publicKey: writer.publicKey,
326
+ secretKey: writer.secretKey,
327
+ device: secret
328
+ }
329
+ await local.store.put('joins', row)
330
+ let reply = row.key
331
+ ? { ...row, epochs: row.epochs ? c.decode(epochEntries, row.epochs) : [] }
332
+ : null
333
+ if (!reply) {
334
+ const { store } = network
335
+ const inbox = box(local.store, 'inbox')
336
+ const outbox = box(local.store, 'outbox')
337
+ const mailbox = new Mailbox(network, { inbox, outbox })
338
+ await mailbox.ready()
339
+ try {
340
+ const signers = [{ publicKey: writer.publicKey }]
341
+ onrequest?.(hid.encode(Hypercore.key({ version: store.manifestVersion, signers })))
342
+ // the reply is kept before the join settles, a denial forgets the join
343
+ const keep = async (answer) => {
344
+ if (answer instanceof Error) return local.store.del('joins', row.id)
345
+ const { key, encryptionKey, epochs, proof } = answer
346
+ const kept = { ...row, key, encryptionKey, epochs: c.encode(epochEntries, epochs), proof }
347
+ await local.store.put('joins', kept)
348
+ }
349
+ const identity = await Identity.bare(device)
350
+ reply = await Pairing.join(mailbox, row.invite, { identity, spec, writer, timeout, keep })
351
+ } finally {
352
+ await mailbox.close()
353
+ }
241
354
  }
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 }
355
+ // the chain the accepting device wrote ends at this device, under the identity the invite named
356
+ const chained = Identity.verify(reply.proof, null, parsed.data)
357
+ if (!chained || !b4a.equals(chained.device, device.publicKey)) {
358
+ throw CeroError.INVALID('the reply does not link this device to the identity of the invite')
359
+ }
360
+ const { encryptionKey, proof } = reply
361
+ const identity = Identity.from({ publicKey: parsed.data, encryptionKey, device, proof })
362
+ return { identity, key: reply.key, epochs: reply.epochs, id: row.id }
363
+ }
364
+
365
+ function pack({ device, proof, publicKey, encryptionKey }) {
366
+ const { publicKey: key, secretKey } = device
367
+ return { publicKey: key, secretKey, proof, identity: publicKey, encryptionKey }
368
+ }
369
+
370
+ function unpack({ publicKey, secretKey, proof, identity, encryptionKey }, seed) {
371
+ const device = { publicKey, secretKey }
372
+ return Identity.from({ publicKey: identity, encryptionKey, device, proof, seed })
244
373
  }