@cero-base/cero 2.2.1 → 2.3.1

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.
Files changed (42) hide show
  1. package/README.md +24 -16
  2. package/package.json +7 -6
  3. package/src/build/index.js +38 -34
  4. package/src/build/internal.js +96 -11
  5. package/src/build/schemas.js +119 -19
  6. package/src/extensions/handle-sync.js +8 -12
  7. package/src/extensions/index.js +17 -63
  8. package/src/extensions/mirror.js +44 -0
  9. package/src/extensions/profile-sync.js +10 -12
  10. package/src/handle/index.js +499 -374
  11. package/src/handle/join.js +144 -0
  12. package/src/index.js +91 -119
  13. package/src/lib/bluetooth.js +83 -19
  14. package/src/lib/constants.js +1 -0
  15. package/src/lib/operators.js +296 -128
  16. package/src/lib/peek.js +1 -1
  17. package/src/lib/refs.js +7 -7
  18. package/src/lib/spec.js +32 -0
  19. package/src/local/index.js +27 -3
  20. package/src/rpc/client.js +247 -205
  21. package/src/rpc/server.js +186 -133
  22. package/types/build/index.d.ts +3 -8
  23. package/types/build/internal.d.ts +86 -27
  24. package/types/build/schemas.d.ts +91 -12
  25. package/types/extensions/handle-sync.d.ts +4 -12
  26. package/types/extensions/index.d.ts +59 -59
  27. package/types/extensions/mirror.d.ts +13 -0
  28. package/types/extensions/profile-sync.d.ts +4 -13
  29. package/types/handle/index.d.ts +229 -198
  30. package/types/handle/join.d.ts +63 -0
  31. package/types/index.d.ts +36 -53
  32. package/types/lib/bluetooth.d.ts +57 -19
  33. package/types/lib/constants.d.ts +1 -0
  34. package/types/lib/operators.d.ts +166 -81
  35. package/types/lib/peek.d.ts +2 -2
  36. package/types/lib/refs.d.ts +14 -15
  37. package/types/lib/spec.d.ts +87 -0
  38. package/types/local/index.d.ts +19 -9
  39. package/types/rpc/client.d.ts +110 -93
  40. package/types/rpc/server.d.ts +91 -50
  41. package/src/rpc/index.js +0 -8
  42. package/types/rpc/index.d.ts +0 -7
@@ -0,0 +1,144 @@
1
+ import AbortController from 'bare-abort-controller'
2
+ import b4a from 'b4a'
3
+ import c from 'compact-encoding'
4
+ import safetyCatch from 'safety-catch'
5
+
6
+ import { Pairing } from '@cero-base/core/pairing'
7
+ import { Identity } from '@cero-base/core/identity'
8
+ import { CeroError } from '@cero-base/core/errors'
9
+ import { epochEntries } from '@cero-base/core/database/encryption'
10
+
11
+ /**
12
+ * One handle being joined. It joins with the latest invite and waits as long as it takes: the
13
+ * caller's timeout only ends the caller's wait. What it learns is saved as it goes, the writer
14
+ * before the join is written and the keys once the reply lands, so a join resumed after a restart
15
+ * picks up where it stopped. It ends admitted, denied, expired or cancelled; a close only pauses
16
+ * it. How it ends reaches the caller, or `onerror` once nobody waits.
17
+ */
18
+ export class Join {
19
+ /**
20
+ * @param {import('./index.js').Handle} root
21
+ * @param {{ type: string, spec: object, discoveryKey: Uint8Array, onend: () => void }} opts
22
+ */
23
+ constructor(root, { type, spec, discoveryKey, onend }) {
24
+ this.root = root
25
+ this.type = type
26
+ this.spec = spec
27
+ this.id = b4a.toHex(discoveryKey)
28
+ this.invite = null
29
+ this.waiting = 0
30
+ this.cancelled = false
31
+ /** @private */
32
+ this._running = null // aborts the attempt in flight
33
+ /** @private */
34
+ this._row = null
35
+ /** @type {Promise<import('./index.js').Handle>} */
36
+ this.done = new Promise((resolve, reject) => {
37
+ /** @private */
38
+ this._resolve = resolve
39
+ /** @private */
40
+ this._reject = reject
41
+ })
42
+ this.done.catch(safetyCatch)
43
+ /** @private */
44
+ this._onend = onend
45
+ }
46
+
47
+ /**
48
+ * Join with `invite`, taking over from an older attempt: the writer stays, so a reply to the
49
+ * older one still lands.
50
+ *
51
+ * @param {string} invite
52
+ */
53
+ async start(invite) {
54
+ this.invite = invite
55
+ this._running?.abort()
56
+ const running = new AbortController()
57
+ this._running = running
58
+ const nearby = this.root._bluetooth?.announce(invite)
59
+ try {
60
+ const row = await this._save({ invite })
61
+ const writer = { publicKey: row.publicKey, secretKey: row.secretKey }
62
+ const { mailbox, identity } = this.root
63
+ const opts = { identity, spec: this.spec, writer, timeout: 0, signal: running.signal }
64
+ const reply = row.key
65
+ ? unpack(row)
66
+ : await this._keep(await Pairing.join(mailbox, invite, opts))
67
+ this._end(this._resolve, await this.root._enter(this.type, reply))
68
+ await this._forget()
69
+ } catch (err) {
70
+ if (running !== this._running) return
71
+ // a close pauses the join, anything else ends it
72
+ if (err.code !== 'CLOSED' || this.cancelled) await this._forget()
73
+ if (err.code !== 'CLOSED' && !this.waiting) this.root._onerror(err)
74
+ this._end(this._reject, err)
75
+ } finally {
76
+ nearby?.()
77
+ }
78
+ }
79
+
80
+ close() {
81
+ this._running?.abort()
82
+ }
83
+
84
+ // ends it for good: the attempt forgets its row as it unwinds, so no restart resumes it
85
+ async cancel() {
86
+ this.cancelled = true
87
+ this._running?.abort()
88
+ await this.done.catch(safetyCatch)
89
+ }
90
+
91
+ // the first save fixes the writer, later ones add what was learned
92
+ /** @private */
93
+ async _save(fields) {
94
+ const store = this.root.local?.store
95
+ this._row ??= (store && (await store.get('joins', this.id)).data) || Identity.randomKeyPair()
96
+ this._row = { ...this._row, id: this.id, type: this.type, ...fields }
97
+ await store?.put('joins', this._row)
98
+ return this._row
99
+ }
100
+
101
+ // the reply, kept so a restart opens the handle without joining again
102
+ /** @private */
103
+ async _keep(reply) {
104
+ const { key, encryptionKey, epochs } = reply
105
+ await this._save({ key, encryptionKey, epochs: c.encode(epochEntries, epochs) })
106
+ return reply
107
+ }
108
+
109
+ /** @private */
110
+ async _forget() {
111
+ await this.root.local?.store.del('joins', this.id).catch(safetyCatch)
112
+ }
113
+
114
+ /** @private */
115
+ _end(settle, value) {
116
+ this._onend()
117
+ settle(value)
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Wait for a join, but stop waiting after `ms`; the join itself goes on.
123
+ *
124
+ * @param {Promise<import('./index.js').Handle>} done
125
+ * @param {number} ms `0` waits as long as the join takes.
126
+ * @returns {Promise<import('./index.js').Handle>}
127
+ */
128
+ export async function wait(done, ms) {
129
+ if (!ms) return done
130
+ let timer
131
+ const timeout = new Promise((resolve, reject) => {
132
+ timer = setTimeout(() => reject(CeroError.TIMEOUT('join')), ms)
133
+ })
134
+ try {
135
+ return await Promise.race([done, timeout])
136
+ } finally {
137
+ clearTimeout(timer)
138
+ }
139
+ }
140
+
141
+ function unpack({ key, encryptionKey, epochs, publicKey, secretKey }) {
142
+ const writer = { publicKey, secretKey }
143
+ return { key, encryptionKey, epochs: epochs ? c.decode(epochEntries, epochs) : [], writer }
144
+ }
package/src/index.js CHANGED
@@ -12,50 +12,24 @@ import { CeroError } from '@cero-base/core/errors'
12
12
  import { Handle, Ref } from './handle/index.js'
13
13
  import { Local } from './local/index.js'
14
14
  import { Bluetooth } from './lib/bluetooth.js'
15
- import {
16
- put,
17
- set,
18
- get,
19
- del,
20
- watch,
21
- changes,
22
- call,
23
- open,
24
- rotate,
25
- before,
26
- after
27
- } from './lib/operators.js'
15
+ import * as verbs from './lib/operators.js'
28
16
  import { peek } from './lib/peek.js'
29
17
  import { t, schema } from './lib/spec.js'
30
18
  import { FLUSH, TIMEOUT } from './lib/constants.js'
31
- import { bind } from './extensions/index.js'
32
19
 
33
20
  export { Handle, Ref, Local }
34
- export {
35
- put,
36
- set,
37
- get,
38
- del,
39
- watch,
40
- changes,
41
- call,
42
- open,
43
- rotate,
44
- before,
45
- after
46
- } from './lib/operators.js'
21
+ export * from './lib/operators.js'
47
22
  export { peek } from './lib/peek.js'
48
23
  export { t, schema } from './lib/spec.js'
49
24
 
50
25
  /**
51
- * @typedef {import('./handle/index.js').CeroHandle} CeroHandle
26
+ * @typedef {import('./handle/index.js').Context} Context
52
27
  */
53
28
 
54
29
  /**
55
30
  * @typedef {object} CeroOpts
56
- * @property {Identity} [identity] Pre-resolved identity. If absent, derived from `seed`/`phrase` or generated.
57
- * @property {Uint8Array} [seed] 16- or 32-byte seed entropy.
58
- * @property {string} [phrase] BIP-39 mnemonic — alternative to `seed`.
31
+ * @property {Identity} [identity] Pre-resolved identity. If absent, derived from `seed` or generated.
32
+ * @property {Uint8Array} [seed] 16- or 32-byte seed entropy: `toSeed(phrase)` restores from a phrase.
59
33
  * @property {12 | 24} [words] Mnemonic length when generating a fresh identity.
60
34
  * @property {string | null} [name] Friendly device name persisted on the identity claim.
61
35
  * @property {boolean} [isMobile] Marks this device as mobile.
@@ -66,24 +40,22 @@ export { t, schema } from './lib/spec.js'
66
40
  * @property {{ active?: number, announced?: number, idle?: number }} [presence] How many rooms search, how many only announce, and the idle ms before the rest leave the swarm.
67
41
  * @property {Uint8Array} [key] Existing database key to recover into, skipping the pointer lookup.
68
42
  * @property {Uint8Array} [encryptionKey] Pre-existing encryption key.
69
- * @property {Record<string, Function>} [routes] Custom RPC routes for the database dispatcher.
70
- * @property {(err: any) => void} [onerror] Background-task error handler; without one, errors emit 'error' on the root handle.
43
+ * @property {(err: Error) => void} [onerror] Where background errors go; the console without one.
71
44
  * @property {number} [recoveryTimeout] Max wait to find another device and be admitted, in ms. Defaults to 30000.
72
45
  * @property {Uint8Array} [storageKey] 32-byte key encrypting local key material (master seed, device keypairs) at rest. Source it from the OS keychain — cero never stores it.
73
46
  * @property {import('./extensions/index.js').Extension[]} [extensions] The extensions this instance runs, instead of the ones the spec carries. Build with the same list.
74
- * @property {Record<string, any>} [operators] The operators to bind, instead of the ones the spec carries.
75
- * @property {boolean | { autoStart?: boolean, backend?: any, maxOutbound?: number, maxInbound?: number, pipe?: 'l2cap' | 'gatt' }} [bluetooth] `true` enables nearby (Bluetooth) sync via `me.bluetooth` (auto-started). `{ autoStart: false }` creates the facade without starting the radio — the app calls `me.bluetooth.start()`/`stop()` (user toggle). `backend` injects a bare-bluetooth-shaped backend (tests). `maxOutbound`/`maxInbound` cap concurrent outbound links and inbound sessions. `pipe` picks the data pipe — `'l2cap'` (default, faster) or `'gatt'`; both peers must match. Absent backend on an unsupported host → `me.bluetooth.state === 'unsupported'`.
47
+ * @property {boolean | { autoStart?: boolean, backend?: object, maxOutbound?: number, maxInbound?: number, pipe?: 'l2cap' | 'gatt' }} [bluetooth] `true` enables nearby (Bluetooth) sync, the radio on. `{ autoStart: false }` leaves it off until `cero.nearby(me, true)`. `backend` injects a bare-bluetooth-shaped backend (tests). `maxOutbound`/`maxInbound` cap concurrent outbound links and inbound sessions. `pipe` picks the data pipe, `'l2cap'` (default, faster) or `'gatt'`; both peers must match. Without a backend on the host, `me.status` reports `nearby: 'unsupported'`.
76
48
  */
77
49
 
78
50
  /**
79
51
  * Open (or create) a cero handle at `dir`.
80
52
  *
81
53
  * @param {string} dir Data directory.
82
- * @param {any} spec Built spec — output of `cero/build`.
54
+ * @param {import('./lib/spec.js').Spec} spec Built spec, the output of `cero/build`.
83
55
  * @param {CeroOpts} [opts]
84
- * @returns {Promise<CeroHandle>}
56
+ * @returns {Promise<Context>}
85
57
  */
86
- export async function cero(dir, spec, opts = {}) {
58
+ async function start(dir, spec, opts = {}) {
87
59
  if (typeof dir !== 'string' || !dir) throw CeroError.INVALID('dir must be a non-empty string')
88
60
  if (!spec) throw CeroError.REQUIRED('spec')
89
61
 
@@ -92,11 +64,10 @@ export async function cero(dir, spec, opts = {}) {
92
64
  let local = null
93
65
  let network = null
94
66
  let discovery = null
67
+ let bluetooth = null
95
68
  let me = null
96
- // background failures reach the app through opts.onerror or the root's 'error' event, never silence
97
- const onerror =
98
- opts.onerror ||
99
- ((err) => (me?.listenerCount('error') ? me.emit('error', err) : console.error(err)))
69
+ // background failures reach opts.onerror, else the console, never silence
70
+ const onerror = opts.onerror || ((err) => console.error(err))
100
71
  opts = { ...opts, onerror }
101
72
  // any failure during open must close what opened, or the storage lock leaks
102
73
  try {
@@ -116,10 +87,23 @@ export async function cero(dir, spec, opts = {}) {
116
87
  await local.ready()
117
88
  }
118
89
 
119
- const { identity, fresh } = await resolveIdentity(opts, local)
120
- const writer = local ? (await local.store.get('keypair')).data : null
121
- // a supplied identity on a device with no writer recovers; only a cero-minted identity creates
122
- const recovering = !writer && (!!opts.key || !fresh)
90
+ const { identity, fresh, seed } = await resolveIdentity(opts, local)
91
+ const device = local ? (await local.store.get('keypair')).data : null
92
+ const done = !!device && !device.setup
93
+ // cero creates only an identity it minted, in this launch or in the killed one it resumes
94
+ const creating =
95
+ !done && !opts.key && !opts.seed && !opts.identity && (fresh || device?.setup === 'create')
96
+ const recovering = !done && !creating
97
+ const setup = done ? null : creating ? 'create' : 'recover'
98
+ const keyPair =
99
+ done || device?.setup === setup
100
+ ? { publicKey: device.publicKey, secretKey: device.secretKey }
101
+ : Identity.randomKeyPair()
102
+ // the key before the seed: a seed stored without its create would read as one to recover
103
+ if (local && !done && device?.setup !== setup) {
104
+ await local.store.set('keypair', { ...keyPair, setup })
105
+ }
106
+ if (local && seed) await local.store.set('master', { seed })
123
107
  const timeout = opts.recoveryTimeout || TIMEOUT
124
108
 
125
109
  // a storage remembers its channel; reopening under another would silently rejoin the global network
@@ -141,6 +125,21 @@ export async function cero(dir, spec, opts = {}) {
141
125
  onerror
142
126
  })
143
127
  await network.ready()
128
+ // the radio before the pointer read: a phrase recovers from a device in range, no internet
129
+ if (opts.bluetooth) {
130
+ const bt = opts.bluetooth === true ? {} : opts.bluetooth
131
+ bluetooth = new Bluetooth(network, {
132
+ identity,
133
+ keyPair,
134
+ // an omitted backend lazy-loads bare-bluetooth, null disables it
135
+ backend: bt.backend,
136
+ autoStart: bt.autoStart !== false,
137
+ maxOutbound: bt.maxOutbound,
138
+ maxInbound: bt.maxInbound,
139
+ pipe: bt.pipe
140
+ })
141
+ await bluetooth.ready()
142
+ }
144
143
  discovery = network.join(identity.topic)
145
144
  // a fresh identity has no peers yet, flushing the announce would only delay onboarding
146
145
  if (!fresh) await Promise.race([discovery.flush(), new Promise((r) => setTimeout(r, FLUSH))])
@@ -148,7 +147,7 @@ export async function cero(dir, spec, opts = {}) {
148
147
  // the pointer core: identity-signed, written once by the creating device, holds the root key
149
148
  const manifest = pointerManifest(store, identity)
150
149
  const pointer = store.get(
151
- !writer && !recovering
150
+ creating
152
151
  ? { keyPair: { publicKey: identity.publicKey, secretKey: identity.secretKey }, manifest }
153
152
  : { key: Hypercore.key(manifest) }
154
153
  )
@@ -167,61 +166,43 @@ export async function cero(dir, spec, opts = {}) {
167
166
  spec,
168
167
  opts,
169
168
  dir,
170
- routes: opts.routes,
171
169
  key,
172
170
  encryptionKey: opts.encryptionKey,
173
- keyPair: writer ? { publicKey: writer.publicKey, secretKey: writer.secretKey } : undefined,
174
- pair: false
171
+ keyPair,
172
+ bluetooth,
173
+ pair: false,
174
+ bootstrap: done
175
+ ? null
176
+ : { name: opts.name || null, isMobile: opts.isMobile === true, recovering, timeout }
175
177
  })
178
+ // an extension's hooks see every op the root applies; what else it calls waits for the open
179
+ const setups = Promise.all(me.extensions.map(async (ext) => ext.setup?.(me)))
180
+ setups.catch(() => {}) // a failed setup surfaces below, once the root can close
176
181
  await me.ready()
177
182
  me.once('close', () => {
178
183
  network.detach(pointer)
179
184
  pointer.close().catch(safetyCatch)
180
185
  })
181
186
 
182
- if (!writer) {
183
- const result = await me.bootstrap({
184
- name: opts.name || null,
185
- isMobile: opts.isMobile === true,
186
- recovering,
187
- timeout
188
- })
189
- if (local) {
190
- await local.store.set('keypair', {
191
- publicKey: result.writer.publicKey,
192
- secretKey: result.writer.secretKey
193
- })
194
- }
195
- if (!recovering && pointer.length === 0) {
187
+ if (!done) {
188
+ if (creating && pointer.length === 0) {
196
189
  await pointer.append(c.encode(c.fixed32, me.store.key))
197
190
  }
191
+ if (local) await local.store.set('keypair', { setup: null })
198
192
  }
199
193
 
200
- for (const ext of me.extensions) {
201
- const off = await ext.setup?.(me)
194
+ for (const off of await setups) {
202
195
  if (typeof off === 'function') me.once('close', off)
203
196
  }
204
197
 
205
- if (opts.bluetooth) {
206
- const bt = opts.bluetooth === true ? {} : opts.bluetooth
207
- me.bluetooth = new Bluetooth(me, {
208
- // an omitted backend lazy-loads bare-bluetooth, null disables it
209
- backend: bt.backend,
210
- autoStart: bt.autoStart !== false,
211
- maxOutbound: bt.maxOutbound,
212
- maxInbound: bt.maxInbound,
213
- pipe: bt.pipe
214
- })
215
- await me.bluetooth.ready()
216
- }
217
-
218
- bind(me, null, me.operators)
219
198
  return me
220
199
  } catch (err) {
221
- // before the root Handle exists, tear the raw resources down in reverse order
222
- if (me) await me.close().catch(safetyCatch)
200
+ // before the root opens, tear the raw resources down in reverse order
201
+ if (me?.opened) await me.close().catch(safetyCatch)
223
202
  else {
203
+ await me?.store.close().catch(safetyCatch)
224
204
  await discovery?.destroy().catch(safetyCatch)
205
+ await bluetooth?.close().catch(safetyCatch)
225
206
  await network?.close().catch(safetyCatch)
226
207
  await local?.close().catch(safetyCatch)
227
208
  await store?.close().catch(safetyCatch)
@@ -232,48 +213,46 @@ export async function cero(dir, spec, opts = {}) {
232
213
  }
233
214
 
234
215
  /**
235
- * Restore a cero instance from a mnemonic phrase.
216
+ * Restore a cero instance from a seed.
236
217
  *
237
- * @param {Handle} me Existing root handle to restore.
238
- * @param {string} phrase BIP-39 mnemonic phrase.
218
+ * @param {Context} me The root to restore.
219
+ * @param {Uint8Array} seed The identity's seed: `toSeed(phrase)` from a phrase.
239
220
  * @returns {Promise<Handle>} Freshly restored root handle.
240
221
  */
241
- export async function restore(me, phrase) {
222
+ export async function restore(me, seed) {
242
223
  if (!me?._dir) throw CeroError.INVALID('me must be a cero instance')
243
- if (!phrase || typeof phrase !== 'string') throw CeroError.INVALID('phrase must be a string')
224
+ // no seed would mint a fresh identity and wipe this one
225
+ if (!seed) throw CeroError.REQUIRED('seed')
244
226
 
245
- const current = await Identity.fromSeed(Identity.toSeed(phrase))
227
+ const current = await Identity.create({ seed })
246
228
  if (current.id === me.identity.id) return me
247
229
 
248
230
  // everything carries over except the identity, the channel above all
249
231
  const {
250
232
  _dir: dir,
251
233
  spec,
252
- _opts: { seed, identity, key, keyPair, ...opts }
234
+ _opts: { identity, key, keyPair, ...opts }
253
235
  } = me
254
236
 
255
237
  await me.close()
256
238
  await fs.promises.rm(`${dir}/main`, { recursive: true, force: true })
257
239
 
258
- return cero(dir, spec, { ...opts, phrase })
240
+ return start(dir, spec, { ...opts, seed })
241
+ }
242
+
243
+ /**
244
+ * The seed a BIP-39 phrase writes out, for `cero(dir, spec, { seed })` and `restore(me, seed)`.
245
+ *
246
+ * @param {string} phrase
247
+ * @returns {Uint8Array}
248
+ */
249
+ export function toSeed(phrase) {
250
+ return Identity.toSeed(phrase)
259
251
  }
260
252
 
261
253
  // the facade: cero.put and import { put } are the same function
262
- cero.t = t
263
- cero.put = put
264
- cero.set = set
265
- cero.get = get
266
- cero.del = del
267
- cero.watch = watch
268
- cero.changes = changes
269
- cero.call = call
270
- cero.open = open
271
- cero.rotate = rotate
272
- cero.before = before
273
- cero.after = after
274
- cero.peek = peek
275
- cero.restore = restore
276
- cero.schema = schema
254
+ /** @type {typeof start & typeof verbs & { t: typeof t, schema: typeof schema, peek: typeof peek, restore: typeof restore, toSeed: typeof toSeed }} */
255
+ export const cero = Object.assign(start, verbs, { t, schema, peek, restore, toSeed })
277
256
 
278
257
  function pointerManifest(store, identity) {
279
258
  return { version: store.manifestVersion, signers: [{ publicKey: identity.publicKey }] }
@@ -283,23 +262,16 @@ async function readPointer(pointer, timeout) {
283
262
  try {
284
263
  return c.decode(c.fixed32, await pointer.get(0, { timeout }))
285
264
  } catch {
286
- throw CeroError.TIMED_OUT('recovery: finding a device of this identity')
265
+ throw CeroError.TIMEOUT('recovery: finding a device of this identity')
287
266
  }
288
267
  }
289
268
 
269
+ // `seed` is the one to store: supplied or minted, null when already stored
290
270
  async function resolveIdentity(opts, local) {
291
- if (opts.identity) return { identity: opts.identity, fresh: false }
292
-
293
- const provided = opts.seed || (opts.phrase && Identity.toSeed(opts.phrase))
294
- if (provided) {
295
- if (local) await local.store.set('master', { seed: provided })
296
- return { identity: await Identity.fromSeed(provided), fresh: false }
297
- }
298
-
299
- const stored = local && (await local.store.get('master')).data?.seed
300
- if (stored) return { identity: await Identity.fromSeed(stored), fresh: false }
271
+ if (opts.identity) return { identity: opts.identity, fresh: false, seed: null }
301
272
 
302
- const identity = await Identity.generate({ words: opts.words })
303
- if (local) await local.store.set('master', { seed: identity.seed })
304
- return { identity, fresh: true }
273
+ const provided = opts.seed
274
+ const stored = !provided && local && (await local.store.get('master')).data?.seed
275
+ const identity = await Identity.create({ seed: provided || stored || null, words: opts.words })
276
+ return { identity, fresh: !provided && !stored, seed: stored ? null : identity.seed }
305
277
  }
@@ -3,10 +3,14 @@ import BluetoothSwarm from 'ble-swarm'
3
3
  import crypto from 'hypercore-crypto'
4
4
  import safetyCatch from 'safety-catch'
5
5
  import b4a from 'b4a'
6
+ import hid from 'hypercore-id-encoding'
6
7
 
7
- import { Pairing } from '@cero-base/core/pairing'
8
+ import { Identity } from '@cero-base/core/identity'
8
9
  import { Invite } from '@cero-base/core/invite'
9
10
 
11
+ // what a person signs to claim one of its devices: the key that device links with
12
+ const DEVICE = b4a.from('cero/device')
13
+
10
14
  /**
11
15
  * `me.bluetooth` — the app-facing surface for nearby (Bluetooth) sync, a thin facade over
12
16
  * ble-swarm.
@@ -15,29 +19,40 @@ import { Invite } from '@cero-base/core/invite'
15
19
  */
16
20
  export class Bluetooth extends ReadyResource {
17
21
  /**
18
- * @param {object} handle Root cero Handle (network + identity + channel).
19
- * @param {object} [opts]
20
- * @param {any} [opts.backend] Injected bare-bluetooth-shaped backend (tests); omitted → ble-swarm loads its own, null/false → unsupported.
21
- * @param {boolean} [opts.autoStart] Start on handle open (from `cero({ bluetooth: true })`).
22
+ * @param {import('@cero-base/core/network').Network} network Where links go: its channel scopes the mesh.
23
+ * @param {object} opts
24
+ * @param {import('@cero-base/core/identity').Identity} opts.identity Signs this device's key for the peers it links with.
25
+ * @param {import('@cero-base/core/identity').KeyPair} opts.keyPair This device's writer keypair.
26
+ * @param {object | null} [opts.backend] Injected bare-bluetooth-shaped backend (tests); omitted → ble-swarm loads its own, null/false → unsupported.
27
+ * @param {boolean} [opts.autoStart] Start on open (from `cero({ bluetooth: true })`).
22
28
  * @param {number} [opts.maxOutbound] Max concurrent outbound links; gossip covers the rest.
23
29
  * @param {number} [opts.maxInbound] Max concurrent inbound sessions; newcomers past this are refused.
24
30
  * @param {'l2cap' | 'gatt'} [opts.pipe] Data pipe — 'l2cap' (default, faster) or 'gatt'. Both peers must match.
25
31
  */
26
- constructor(handle, { backend, autoStart, maxOutbound, maxInbound, pipe } = {}) {
32
+ constructor(network, { identity, keyPair, backend, autoStart, maxOutbound, maxInbound, pipe }) {
27
33
  super()
28
- this._handle = handle
34
+ /** @private */
35
+ this._network = network
36
+ /** @private */
29
37
  this._autoStart = autoStart === true
30
- /** @type {{ hex: string, count: number, timer: any } | null} active invite rendezvous (single topic — one at a time) */
38
+ /** @type {{ hex: string, count: number, timer: ReturnType<typeof setTimeout> | null } | null} active invite rendezvous (single topic — one at a time) */
31
39
  this._announce = null
40
+ /** @private */
32
41
  this._restorePending = false
33
42
 
34
- const identity = handle.identity
35
43
  // one mesh topic per channel, or a global one when channelless; strangers still sync nothing
36
- this._topic = crypto.hash(b4a.from(handle.network.channel || 'cero-ble'))
44
+ /** @private */
45
+ this._topic = crypto.hash(b4a.from(network.channel || 'cero-ble'))
46
+ /** @private */
47
+ this._id = identity.id
48
+ /** @private */
49
+ this._proof = b4a.toString(identity.sign(b4a.concat([DEVICE, keyPair.publicKey])), 'hex')
50
+ /** @type {import('ble-swarm')} */
37
51
  this.swarm = new BluetoothSwarm({
38
52
  backend,
39
- // the swarm identity, so one person over Wi-Fi and BLE dedupes to one peer
40
- keyPair: { publicKey: identity.publicKey, secretKey: identity.secretKey },
53
+ // this device's writer keypair, kept across launches: a person's devices each have one, so
54
+ // they link to each other, where ble-swarm refuses a remote with its own key
55
+ keyPair,
41
56
  topic: this._topic,
42
57
  tag: 'cero-ble',
43
58
  pipe,
@@ -53,7 +68,7 @@ export class Bluetooth extends ReadyResource {
53
68
  this.emit('update')
54
69
  })
55
70
  this.swarm.on('connection', (conn) => {
56
- this._handle.network.inject(conn)
71
+ network.inject(conn)
57
72
  })
58
73
  }
59
74
 
@@ -62,20 +77,50 @@ export class Bluetooth extends ReadyResource {
62
77
  return this.swarm.state
63
78
  }
64
79
 
65
- /** @returns {Map<string, any>} Live BLE links, keyed by peer public key. */
80
+ /** @returns {Map<string, object>} Live BLE links, keyed by peer public key. */
66
81
  get peers() {
67
82
  return this.swarm.peers
68
83
  }
69
84
 
85
+ /** @private */
70
86
  async _open() {
71
87
  if (this._autoStart) await this.start()
72
88
  }
73
89
 
90
+ /** @private */
74
91
  async _close() {
75
92
  this._clearAnnounce()
76
93
  await this.swarm.destroy()
77
94
  }
78
95
 
96
+ /**
97
+ * What a peer hears when a Bluetooth link opens: whose device this is, signed, with `info`.
98
+ *
99
+ * @param {{ name: string | null, isMobile: boolean }} info
100
+ */
101
+ tell({ name, isMobile }) {
102
+ this._network.setInfo({ id: this._id, proof: this._proof, name, isMobile })
103
+ }
104
+
105
+ /**
106
+ * Who a linked device says it is: its person, who signed the key it links with, its name and
107
+ * whether it is a phone. `null` until it said, or when that signature is not its person's.
108
+ *
109
+ * @param {string} hex A key of `peers`.
110
+ * @returns {{ id: string, name: string | null, isMobile: boolean } | null}
111
+ */
112
+ told(hex) {
113
+ const info = this._network.getInfo(hex)
114
+ if (!signed(info, b4a.from(hex, 'hex'))) return null
115
+ const name = typeof info.name === 'string' ? info.name : null
116
+ return {
117
+ id: info.id,
118
+ device: hid.encode(b4a.from(hex, 'hex')),
119
+ name,
120
+ isMobile: info.isMobile === true
121
+ }
122
+ }
123
+
79
124
  /**
80
125
  * Begin advertising + scanning. Idempotent; no-op when unsupported.
81
126
  *
@@ -109,20 +154,24 @@ export class Bluetooth extends ReadyResource {
109
154
  if (this.state !== 'on' && this.state !== 'waiting' && this.state !== 'starting') {
110
155
  return () => {}
111
156
  }
112
- const topic = Pairing.inviteTopic(invite)
113
- if (!topic) return () => {}
157
+ let parsed
158
+ try {
159
+ parsed = Invite.parse(invite)
160
+ } catch {
161
+ return () => {}
162
+ }
114
163
 
115
- const hex = b4a.toString(topic, 'hex')
164
+ const hex = b4a.toHex(parsed.discoveryKey)
116
165
  if (this._announce && this._announce.hex !== hex) this._stopAnnounce()
117
166
  if (!this._announce) {
118
167
  const entry = { hex, count: 0, timer: null }
119
- const { expires } = Invite.parse(invite)
168
+ const { expires } = parsed
120
169
  if (expires > 0) {
121
170
  entry.timer = setTimeout(() => this._stopAnnounce(), Math.max(0, expires - Date.now()))
122
171
  }
123
172
  this._announce = entry
124
173
  this._restorePending = false
125
- this.swarm.setTopic(topic).catch(safetyCatch)
174
+ this.swarm.setTopic(parsed.discoveryKey).catch(safetyCatch)
126
175
  }
127
176
  const entry = this._announce
128
177
  entry.count++
@@ -153,12 +202,14 @@ export class Bluetooth extends ReadyResource {
153
202
  await this.swarm.resume()
154
203
  }
155
204
 
205
+ /** @private */
156
206
  _stopAnnounce() {
157
207
  this._clearAnnounce()
158
208
  if (this.swarm.peers.size > 0) this._restorePending = true
159
209
  else this.swarm.setTopic(this._topic).catch(safetyCatch)
160
210
  }
161
211
 
212
+ /** @private */
162
213
  _clearAnnounce() {
163
214
  const e = this._announce
164
215
  if (!e) return
@@ -167,3 +218,16 @@ export class Bluetooth extends ReadyResource {
167
218
  this._restorePending = false
168
219
  }
169
220
  }
221
+
222
+ function signed(info, key) {
223
+ if (typeof info?.id !== 'string' || typeof info.proof !== 'string') return false
224
+ try {
225
+ return Identity.verify(
226
+ hid.decode(info.id),
227
+ b4a.concat([DEVICE, key]),
228
+ b4a.from(info.proof, 'hex')
229
+ )
230
+ } catch {
231
+ return false
232
+ }
233
+ }