@cero-base/core 1.18.2 → 2.0.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.
Files changed (57) hide show
  1. package/README.md +5 -6
  2. package/package.json +14 -11
  3. package/src/blobs/index.js +17 -17
  4. package/src/blobs/server.js +0 -2
  5. package/src/database/changes.js +34 -60
  6. package/src/database/dispatch.js +156 -245
  7. package/src/database/encryption.js +22 -52
  8. package/src/database/envelope.js +1 -3
  9. package/src/database/index.js +514 -513
  10. package/src/database/rotation.js +191 -193
  11. package/src/identity/index.js +8 -12
  12. package/src/index.js +5 -9
  13. package/src/lib/constants.js +3 -12
  14. package/src/lib/errors.js +6 -10
  15. package/src/lib/schema.js +2 -5
  16. package/src/lib/utils.js +55 -38
  17. package/src/network/index.js +138 -166
  18. package/src/pairing/candidate.js +123 -0
  19. package/src/pairing/index.js +36 -267
  20. package/src/pairing/invite.js +3 -4
  21. package/src/pairing/request.js +96 -0
  22. package/src/rpc/index.js +4 -14
  23. package/src/rpc/peer.js +3 -7
  24. package/src/storage/index.js +36 -49
  25. package/types/blobs/codec.d.ts +8 -8
  26. package/types/blobs/index.d.ts +38 -37
  27. package/types/blobs/server.d.ts +8 -10
  28. package/types/database/changes.d.ts +3 -8
  29. package/types/database/dispatch.d.ts +28 -25
  30. package/types/database/encryption.d.ts +22 -30
  31. package/types/database/envelope.d.ts +2 -2
  32. package/types/database/index.d.ts +196 -221
  33. package/types/database/rotation.d.ts +47 -30
  34. package/types/identity/index.d.ts +83 -87
  35. package/types/index.d.ts +42 -55
  36. package/types/lib/constants.d.ts +34 -38
  37. package/types/lib/errors.d.ts +16 -20
  38. package/types/lib/schema.d.ts +49 -42
  39. package/types/lib/spec/index.d.ts +29 -55
  40. package/types/lib/utils.d.ts +26 -20
  41. package/types/network/discovery.d.ts +7 -7
  42. package/types/network/index.d.ts +64 -72
  43. package/types/pairing/candidate.d.ts +36 -0
  44. package/types/pairing/index.d.ts +91 -151
  45. package/types/pairing/invite.d.ts +91 -91
  46. package/types/pairing/request.d.ts +133 -0
  47. package/types/rpc/client.d.ts +2 -2
  48. package/types/rpc/index.d.ts +30 -33
  49. package/types/rpc/peer.d.ts +11 -11
  50. package/types/rpc/server.d.ts +2 -2
  51. package/types/storage/index.d.ts +70 -71
  52. package/src/database/bootstrap.js +0 -133
  53. package/src/database/hooks.js +0 -112
  54. package/src/database/membership.js +0 -67
  55. package/types/database/bootstrap.d.ts +0 -20
  56. package/types/database/hooks.d.ts +0 -8
  57. package/types/database/membership.d.ts +0 -7
package/src/lib/utils.js CHANGED
@@ -2,12 +2,10 @@ import crypto from 'crypto'
2
2
  import b4a from 'b4a'
3
3
  import { Readable } from 'streamx'
4
4
  import z32 from 'z32'
5
- import { encode, decode } from 'hypercore-id-encoding'
6
5
 
7
- import { ROLE_PERMS, RANK } from './constants.js'
6
+ import { ROLE_PERMS, RANK, QUERY_RESERVED } from './constants.js'
8
7
 
9
- // the capability names travel with can(): a caller cannot ask `can(role, REMOVE)`
10
- // without them, and constants.js is not a public subpath
8
+ // can() callers need the capability names, and constants.js is not public
11
9
  export { WRITE, INVITE, ASSIGN, REMOVE } from './constants.js'
12
10
 
13
11
  /**
@@ -19,33 +17,17 @@ export function genId() {
19
17
  return z32.encode(crypto.randomBytes(16))
20
18
  }
21
19
 
22
- /**
23
- * z32-encode a 32-byte key into a canonical string id.
24
- *
25
- * @type {(key: Uint8Array) => string}
26
- */
27
- export const toId = encode
28
-
29
- /**
30
- * Decode a canonical string id back into a 32-byte key.
31
- *
32
- * @type {(id: string) => Uint8Array}
33
- */
34
- export const toKey = decode
35
-
36
- // Domain-separated payloads for writer-admission signatures. Binding the db
37
- // key makes an admission unreplayable across rooms; the tag pins the format.
38
- // v2 — pre-1.2 signatures (writer‖appender / bare writer) no longer verify.
20
+ // binding the db key makes an admission unreplayable across rooms
39
21
  const ADD_WRITER_TAG = b4a.from('cero/add-writer/v2')
40
22
  const CLAIM_WRITER_TAG = b4a.from('cero/claim-writer/v2')
41
23
 
42
24
  /** @type {(dbKey: Uint8Array, writer: Uint8Array, appender: Uint8Array) => Uint8Array} */
43
- export function addWriterPayload(dbKey, writer, appender) {
25
+ export function admission(dbKey, writer, appender) {
44
26
  return b4a.concat([ADD_WRITER_TAG, dbKey, writer, appender])
45
27
  }
46
28
 
47
29
  /** @type {(dbKey: Uint8Array, writer: Uint8Array) => Uint8Array} */
48
- export function claimWriterPayload(dbKey, writer) {
30
+ export function ownership(dbKey, writer) {
49
31
  return b4a.concat([CLAIM_WRITER_TAG, dbKey, writer])
50
32
  }
51
33
 
@@ -61,9 +43,7 @@ export function can(role, perm) {
61
43
  return !!perms && (perms.includes('*') || perms.includes(perm))
62
44
  }
63
45
 
64
- // A role that is not one of the four ranks grants nothing and outranks
65
- // nothing, so every gate built on `grants` silently refuses it. Callers that
66
- // accept a role from an app or a peer must reject it loudly instead.
46
+ // an unknown role grants nothing; callers taking a role from an app must check it
67
47
  export function isRank(role) {
68
48
  return RANK[role] != null
69
49
  }
@@ -76,9 +56,8 @@ export function outranks(a, b) {
76
56
  }
77
57
 
78
58
  /**
79
- * Stream-of-snapshots primitive. Couples a `get` (returns the latest value)
80
- * with a `watch` (re-fires on change) and emits the newest snapshot every
81
- * time `watch` ticks.
59
+ * Stream-of-snapshots primitive. Couples a `get` (returns the latest value) with a `watch`
60
+ * (re-fires on change) and emits the newest snapshot every time `watch` ticks.
82
61
  *
83
62
  * @template T
84
63
  * @param {object} args
@@ -102,10 +81,7 @@ export function subscribe({ get, watch }) {
102
81
  stream.push(data)
103
82
  }
104
83
 
105
- // Coalesce: one get() in flight at a time. Ticks that land mid-read mark
106
- // dirty and fold into a single trailing re-read — a write burst costs one
107
- // extra snapshot instead of one concurrent scan per tick, and only the
108
- // latest state is emitted.
84
+ // one get() in flight; ticks mid-read fold into a single trailing re-read
109
85
  let running = false
110
86
  let dirty = false
111
87
  const push = async () => {
@@ -134,7 +110,6 @@ export function subscribe({ get, watch }) {
134
110
  return stream
135
111
  }
136
112
 
137
- // Lowercase, fold diacritics ('jose' → 'José'), drop whitespace.
138
113
  const fold = (s) =>
139
114
  s
140
115
  .normalize('NFD')
@@ -142,13 +117,55 @@ const fold = (s) =>
142
117
  .toLowerCase()
143
118
  .replace(/\s/g, '')
144
119
 
145
- // keet's message-search style: every term must be a substring of `fields` (or
146
- // every string field). 'smith' → 'John Smith', 'jo sm' → both must appear.
120
+ // every term must be a substring of a searched field
147
121
  export function searchHit(row, term, fields) {
148
122
  const terms = String(term).split(/\s+/).map(fold).filter(Boolean)
149
- // default to all fields except memberId — a framework-stamped random z32 whose value would
150
- // otherwise produce spurious, non-deterministic search hits (user-set id/code stay searchable)
123
+ // memberId is a random z32, it would produce spurious hits
151
124
  const keys = fields && fields.length ? fields : Object.keys(row).filter((k) => k !== 'memberId')
152
125
  const hay = keys.map((k) => (typeof row[k] === 'string' ? fold(row[k]) : '')).join(' ')
153
126
  return terms.every((t) => hay.includes(t))
154
127
  }
128
+
129
+ /**
130
+ * The in-memory query grammar over rows: equality on any non-reserved field,
131
+ * id ranges, `search`, then `reverse` and `limit`.
132
+ *
133
+ * @param {any[]} rows
134
+ * @param {Record<string, any>} [query]
135
+ * @returns {any[]}
136
+ */
137
+ export function filter(rows, query) {
138
+ if (!query) return rows
139
+ let out = rows
140
+ for (const key of Object.keys(query)) {
141
+ if (QUERY_RESERVED.has(key)) continue
142
+ out = out.filter((r) => valueEq(r[key], query[key]))
143
+ }
144
+ if (query.gt !== undefined) out = out.filter((r) => r.id > query.gt)
145
+ if (query.gte !== undefined) out = out.filter((r) => r.id >= query.gte)
146
+ if (query.lt !== undefined) out = out.filter((r) => r.id < query.lt)
147
+ if (query.lte !== undefined) out = out.filter((r) => r.id <= query.lte)
148
+ if (query.search) out = out.filter((r) => searchHit(r, query.search, query.fields))
149
+ if (query.reverse) out = [...out].reverse()
150
+ if (query.limit !== undefined) out = out.slice(0, query.limit)
151
+ return out
152
+ }
153
+
154
+ function valueEq(a, b) {
155
+ if (a instanceof Uint8Array && b instanceof Uint8Array) return b4a.equals(a, b)
156
+ return a === b
157
+ }
158
+
159
+ /**
160
+ * Run `cb` when `signal` aborts — or immediately if it already has.
161
+ *
162
+ * @param {AbortSignal | undefined} signal
163
+ * @param {() => void} cb
164
+ * @returns {(() => void) | undefined}
165
+ */
166
+ export function onAbort(signal, cb) {
167
+ if (!signal) return
168
+ if (signal.aborted) return void cb()
169
+ signal.addEventListener('abort', cb, { once: true })
170
+ return () => signal.removeEventListener('abort', cb)
171
+ }
@@ -79,13 +79,108 @@ export class Network extends ReadyResource {
79
79
  return this._swarm
80
80
  }
81
81
 
82
+ /** @returns {Map<string, any>} Known peers keyed by public-key string. */
83
+ get peers() {
84
+ return this.swarm ? this.swarm.peers : new Map()
85
+ }
86
+
87
+ /** @returns {Set<any>} Live connection streams — swarm and injected. */
88
+ get connections() {
89
+ if (!this._injected.size) return this.swarm ? this.swarm.connections : new Set()
90
+ return new Set([...(this.swarm ? this.swarm.connections : []), ...this._injected])
91
+ }
92
+
93
+ /** @returns {boolean} */
94
+ get suspended() {
95
+ return this.swarm?.suspended === true
96
+ }
97
+
98
+ async _open() {
99
+ const opts = {}
100
+ if (this.identity) {
101
+ opts.keyPair = { publicKey: this.identity.publicKey, secretKey: this.identity.secretKey }
102
+ }
103
+ if (this.bootstrap) opts.bootstrap = this.bootstrap
104
+ if (this.firewall) opts.firewall = this.firewall
105
+ if (this.relayThrough) opts.relayThrough = this.relayThrough
106
+ if (this.backoffs) opts.backoffs = this.backoffs
107
+
108
+ const swarm = (this._swarm = new Hyperswarm(opts))
109
+ swarm.on('connection', (stream, info) => {
110
+ if (this.closing || this.closed) {
111
+ stream.destroy()
112
+ return
113
+ }
114
+ this.wakeup.addStream(stream)
115
+ this._attachInfo(stream)
116
+ for (const r of this._replicateables) replicateInto(r, stream)
117
+ this.emit('connection', stream, info)
118
+ })
119
+
120
+ if (this.store && this.mirrors.length) {
121
+ this._blindPeering = new BlindPeering(swarm.dht, this.store, {
122
+ blindPeers: this.mirrors.map((key) => ({ key })),
123
+ wakeup: this.wakeup,
124
+ pick: 2
125
+ })
126
+ }
127
+ }
128
+
129
+ async _close() {
130
+ for (const conn of [...this._injected]) {
131
+ try {
132
+ conn.destroy()
133
+ } catch (err) {
134
+ safetyCatch(err)
135
+ }
136
+ }
137
+ this._injected.clear()
138
+
139
+ // stop discovery now, never await the DHT unannounce round-trips
140
+ for (const d of [...this._discoveries]) d.destroy().catch(safetyCatch)
141
+ this._discoveries.clear()
142
+
143
+ // the swarm dies first with force, so per-topic unannounces become no-ops
144
+ const swarm = this._swarm
145
+ this._swarm = null
146
+ if (swarm) {
147
+ // force destroy still awaits a server.close round-trip; cap it
148
+ await Promise.race([
149
+ swarm.destroy({ force: true }).catch(safetyCatch),
150
+ new Promise((r) => setTimeout(r, 750))
151
+ ])
152
+ }
153
+
154
+ if (this._blindPeering) {
155
+ try {
156
+ await this._blindPeering.close()
157
+ } catch (err) {
158
+ safetyCatch(err)
159
+ }
160
+ this._blindPeering = null
161
+ }
162
+
163
+ if (this._blind) {
164
+ try {
165
+ await (await this._blind).close()
166
+ } catch (err) {
167
+ safetyCatch(err)
168
+ }
169
+ this._blind = null
170
+ }
171
+
172
+ if (this.wakeup) {
173
+ try {
174
+ await this.wakeup.destroy()
175
+ } catch (err) {
176
+ safetyCatch(err)
177
+ }
178
+ }
179
+ }
180
+
82
181
  /**
83
- * Feed an externally-established connection — a Bluetooth L2CAP channel, a
84
- * serial link, an in-process pair, any duplex — into the network. A raw
85
- * duplex is wrapped in NoiseSecretStream (pass `isInitiator`); a stream
86
- * that already IS one is used as-is. From here it gets the exact same
87
- * treatment as a swarm connection: wakeup, replication of every attached
88
- * core, pairing, and the 'connection' event.
182
+ * Feed an externally-established connection — a Bluetooth L2CAP channel, a serial link, an
183
+ * in-process pair, any duplex — into the network.
89
184
  *
90
185
  * @param {any} stream Duplex transport, or a ready NoiseSecretStream.
91
186
  * @param {{ isInitiator?: boolean }} [opts] Which side initiates the noise handshake (raw duplexes only).
@@ -94,9 +189,7 @@ export class Network extends ReadyResource {
94
189
  inject(stream, { isInitiator } = {}) {
95
190
  if (this.closing || this.closed) throw CeroError.CLOSED('Network')
96
191
  if (!stream) throw CeroError.REQUIRED('stream')
97
- // Injected links authenticate with the same long-lived identity as the
98
- // swarm — an ephemeral key per link would defeat duplicate-peer detection
99
- // (two radios between one pair would look like two different peers).
192
+ // the swarm identity, so two radios between one pair dedupe to one peer
100
193
  const keyPair = this.identity
101
194
  ? { publicKey: this.identity.publicKey, secretKey: this.identity.secretKey }
102
195
  : (this.swarm?.keyPair ?? undefined)
@@ -105,10 +198,7 @@ export class Network extends ReadyResource {
105
198
  ? stream
106
199
  : new NoiseSecretStream(isInitiator === true, stream, keyPair ? { keyPair } : undefined)
107
200
 
108
- // blind-pairing picks the lowest-`rtt` unvisited channel to send on; that
109
- // field only exists on real udx sockets. A raw injected duplex has none,
110
- // so `rtt < Infinity` is always false and pairing never sends a request.
111
- // Zero is also the semantically correct RTT for a direct injected link.
201
+ // blind-pairing sends on the lowest-rtt channel; an injected duplex has no rtt, so give it one
112
202
  if (conn.rawStream && conn.rawStream.rtt === undefined) conn.rawStream.rtt = 0
113
203
 
114
204
  this._injected.add(conn)
@@ -123,9 +213,7 @@ export class Network extends ReadyResource {
123
213
  }
124
214
 
125
215
  /**
126
- * Lazily create the network-shared BlindPairing. One instance serves every
127
- * handle's pairing member — per-handle instances each added their own swarm
128
- * and DHT listeners plus a protomux channel per connection.
216
+ * Lazily create the network-shared BlindPairing.
129
217
  *
130
218
  * @returns {Promise<any>}
131
219
  */
@@ -134,9 +222,7 @@ export class Network extends ReadyResource {
134
222
  if (!this._blind) {
135
223
  const blind = new BlindPairing(this.swarm)
136
224
  this._blind = blind.ready().then(() => {
137
- // blind-pairing only watches the swarm — injected connections must
138
- // reach it too, or offline (e.g. Bluetooth) pairing never completes.
139
- // _onconnection is upstream-private; the offline-pairing test pins it.
225
+ // blind-pairing only watches the swarm; injected connections must reach it too
140
226
  this.on('connection', (conn, info) => {
141
227
  if (info?.injected) blind._onconnection(conn)
142
228
  })
@@ -148,11 +234,9 @@ export class Network extends ReadyResource {
148
234
  }
149
235
 
150
236
  /**
151
- * Re-attach pairing channels on injected connections. blind-pairing only
152
- * auto-attaches refs that existed when a connection arrived — swarm peers
153
- * meet again over topic joins, injected links (Bluetooth, pipes) don't, so
154
- * a member/candidate added later must re-run the attach. Idempotent:
155
- * protomux refuses duplicate channels.
237
+ * Re-attach pairing channels on injected connections. blind-pairing only auto-attaches
238
+ * refs that existed when a connection arrived — swarm peers meet again over topic joins,
239
+ * injected links (Bluetooth,.
156
240
  *
157
241
  * @returns {Promise<void>}
158
242
  */
@@ -163,9 +247,7 @@ export class Network extends ReadyResource {
163
247
  }
164
248
 
165
249
  /**
166
- * Declare this peer's self-reported info ({ name, ... }). Sent over an
167
- * encrypted channel on every live and future connection — never on the
168
- * radio advertisement or the DHT.
250
+ * Declare this peer's self-reported info ({ name, ... }).
169
251
  *
170
252
  * @param {object | null} info
171
253
  */
@@ -186,82 +268,6 @@ export class Network extends ReadyResource {
186
268
  return this._peerInfo.get(hex) ?? null
187
269
  }
188
270
 
189
- // The channel stays silent until a side has info to send: bytes on a fresh
190
- // connection make hyperswarm's duplicate-connection guard treat it as the
191
- // stale one and drop it when both peers dialed each other at once.
192
- _attachInfo(conn) {
193
- const mux = Protomux.from(conn)
194
- let message = null
195
- const send = () => {
196
- if (!message) {
197
- const channel = mux.createChannel({ protocol: 'cero/info' })
198
- if (channel === null) return
199
- message = channel.addMessage({
200
- encoding: c.json,
201
- onmessage: (info) => {
202
- if (!info || typeof info !== 'object') return
203
- const hex = b4a.toString(conn.remotePublicKey, 'hex')
204
- this._peerInfo.set(hex, info)
205
- this.emit('peer-info', hex, info)
206
- }
207
- })
208
- channel.open()
209
- }
210
- if (this.info) message.send(this.info)
211
- }
212
- mux.pair({ protocol: 'cero/info' }, send)
213
- this._infoSenders.add(send)
214
- conn.on('close', () => this._infoSenders.delete(send))
215
- if (this.info) send()
216
- }
217
-
218
- /** @returns {Map<string, any>} Known peers keyed by public-key string. */
219
- get peers() {
220
- return this.swarm ? this.swarm.peers : new Map()
221
- }
222
-
223
- /** @returns {Set<any>} Live connection streams — swarm and injected. */
224
- get connections() {
225
- if (!this._injected.size) return this.swarm ? this.swarm.connections : new Set()
226
- return new Set([...(this.swarm ? this.swarm.connections : []), ...this._injected])
227
- }
228
-
229
- /** @returns {boolean} */
230
- get suspended() {
231
- return this.swarm?.suspended === true
232
- }
233
-
234
- async _open() {
235
- const opts = {}
236
- if (this.identity) {
237
- opts.keyPair = { publicKey: this.identity.publicKey, secretKey: this.identity.secretKey }
238
- }
239
- if (this.bootstrap) opts.bootstrap = this.bootstrap
240
- if (this.firewall) opts.firewall = this.firewall
241
- if (this.relayThrough) opts.relayThrough = this.relayThrough
242
- if (this.backoffs) opts.backoffs = this.backoffs
243
-
244
- const swarm = (this._swarm = new Hyperswarm(opts))
245
- swarm.on('connection', (stream, info) => {
246
- if (this.closing || this.closed) {
247
- stream.destroy()
248
- return
249
- }
250
- this.wakeup.addStream(stream)
251
- this._attachInfo(stream)
252
- for (const r of this._replicateables) replicateInto(r, stream)
253
- this.emit('connection', stream, info)
254
- })
255
-
256
- if (this.store && this.mirrors.length) {
257
- this._blindPeering = new BlindPeering(swarm.dht, this.store, {
258
- blindPeers: this.mirrors.map((key) => ({ key })),
259
- wakeup: this.wakeup,
260
- pick: 2
261
- })
262
- }
263
- }
264
-
265
271
  /**
266
272
  * Wait for pending DHT announces and lookups to settle, bounded by timeout.
267
273
  *
@@ -303,63 +309,6 @@ export class Network extends ReadyResource {
303
309
  await this._blindPeering?.resume()
304
310
  }
305
311
 
306
- async _close() {
307
- for (const conn of [...this._injected]) {
308
- try {
309
- conn.destroy()
310
- } catch (err) {
311
- safetyCatch(err)
312
- }
313
- }
314
- this._injected.clear()
315
-
316
- // stop every discovery session NOW (timers die synchronously) but never
317
- // await the DHT unannounce round-trips — the force destroy below skips
318
- // upstream's own clear(), so un-destroyed sessions would leak live timers
319
- for (const d of [...this._discoveries]) d.destroy().catch(safetyCatch)
320
- this._discoveries.clear()
321
-
322
- // the swarm dies FIRST, with force: every polite per-topic DHT unannounce
323
- // (blind-pairing's included) becomes an instant no-op instead of a network
324
- // round-trip — a vanished node ages out of the DHT regardless
325
- const swarm = this._swarm
326
- this._swarm = null
327
- if (swarm) {
328
- // even force destroy awaits a graceful server.close DHT round-trip
329
- // upstream — cap the wait and let the teardown finish in the background
330
- await Promise.race([
331
- swarm.destroy({ force: true }).catch(safetyCatch),
332
- new Promise((r) => setTimeout(r, 750))
333
- ])
334
- }
335
-
336
- if (this._blindPeering) {
337
- try {
338
- await this._blindPeering.close()
339
- } catch (err) {
340
- safetyCatch(err)
341
- }
342
- this._blindPeering = null
343
- }
344
-
345
- if (this._blind) {
346
- try {
347
- await (await this._blind).close()
348
- } catch (err) {
349
- safetyCatch(err)
350
- }
351
- this._blind = null
352
- }
353
-
354
- if (this.wakeup) {
355
- try {
356
- await this.wakeup.destroy()
357
- } catch (err) {
358
- safetyCatch(err)
359
- }
360
- }
361
- }
362
-
363
312
  /**
364
313
  * Announce/lookup on a 32-byte topic and return a Discovery handle.
365
314
  *
@@ -396,8 +345,7 @@ export class Network extends ReadyResource {
396
345
  if (!core) throw CeroError.REQUIRED('core')
397
346
  this._replicateables.add(core)
398
347
  for (const stream of this.connections) replicateInto(core, stream)
399
- // mirror the core so it stays available when its writers are offline —
400
- // autobees announce their whole writer set, plain cores (blobs) just themselves
348
+ // mirror the core so it stays available while its writers are offline
401
349
  if (this._blindPeering) {
402
350
  if (Autobee.isAutobee(core)) {
403
351
  this._blindPeering.addAutobaseBackground(core)
@@ -434,12 +382,36 @@ export class Network extends ReadyResource {
434
382
  }
435
383
  for (const stream of this.connections) replicateInto(target, stream)
436
384
  }
385
+
386
+ // silent until a side has info: bytes on a fresh connection trip hyperswarm's duplicate guard
387
+ _attachInfo(conn) {
388
+ const mux = Protomux.from(conn)
389
+ let message = null
390
+ const send = () => {
391
+ if (!message) {
392
+ const channel = mux.createChannel({ protocol: 'cero/info' })
393
+ if (channel === null) return
394
+ message = channel.addMessage({
395
+ encoding: c.json,
396
+ onmessage: (info) => {
397
+ if (!info || typeof info !== 'object') return
398
+ const hex = b4a.toString(conn.remotePublicKey, 'hex')
399
+ this._peerInfo.set(hex, info)
400
+ this.emit('peer-info', hex, info)
401
+ }
402
+ })
403
+ channel.open()
404
+ }
405
+ if (this.info) message.send(this.info)
406
+ }
407
+ mux.pair({ protocol: 'cero/info' }, send)
408
+ this._infoSenders.add(send)
409
+ conn.on('close', () => this._infoSenders.delete(send))
410
+ if (this.info) send()
411
+ }
437
412
  }
438
413
 
439
- // Corestore replication is store-wide: N attached bees on one store would
440
- // re-attach every core AND add N duplicate StreamTracker records per
441
- // connection. Replicate each root store once per stream; wakeup streams are
442
- // added at the network level, so skipped bees lose nothing.
414
+ // corestore replication is store-wide: replicate each root once per connection
443
415
  const replicatedRoots = new WeakMap()
444
416
 
445
417
  function replicateInto(core, stream) {
@@ -0,0 +1,123 @@
1
+ import safetyCatch from 'safety-catch'
2
+ import c from 'compact-encoding'
3
+
4
+ import { channelTopic } from '../network/index.js'
5
+ import { CeroError } from '../lib/errors.js'
6
+ import { Response, STATUS_DENIED } from './request.js'
7
+
8
+ /**
9
+ * Internal — the joiner side: a candidate's handshake state machine (this *is* the
10
+ * blind-pairing `addCandidate`).
11
+ *
12
+ * @property {any} _candidate blind-pairing addCandidate handle (null until started).
13
+ * @property {ReturnType<typeof setTimeout> | null} _timer Pending timeout, if any.
14
+ * @property {((result: any) => void) | null} _resolve Promise resolver, set in `start`.
15
+ * @property {((err: Error) => void) | null} _reject Promise rejecter, set in `start`.
16
+ * @property {boolean} _settled Whether the handshake has already settled.
17
+ */
18
+ export class Candidate {
19
+ /**
20
+ * @param {import('./index.js').Pairing} pairing
21
+ * @param {import('./invite.js').Invite} invite
22
+ * @param {Uint8Array | null} userData
23
+ * @param {number} timeout
24
+ */
25
+ constructor(pairing, invite, userData, timeout) {
26
+ this.pairing = pairing
27
+ this.invite = invite
28
+ this.userData = userData
29
+ this.timeout = timeout
30
+ this._candidate = null
31
+ this._timer = null
32
+ this._resolve = null
33
+ this._reject = null
34
+ this._settled = false
35
+ }
36
+
37
+ /**
38
+ * Kick off the handshake; returns a promise that settles with the host response.
39
+ *
40
+ * @returns {Promise<import('./index.js').JoinResult>}
41
+ */
42
+ start() {
43
+ this.pairing._candidates.add(this)
44
+
45
+ return new Promise((resolve, reject) => {
46
+ this._resolve = resolve
47
+ this._reject = reject
48
+
49
+ if (this.timeout > 0) {
50
+ this._timer = setTimeout(() => this._fail(CeroError.TIMEOUT()), this.timeout)
51
+ }
52
+
53
+ try {
54
+ this._candidate = this.pairing._blind.addCandidate({
55
+ invite: this.invite.blind,
56
+ userData: this.userData,
57
+ // must hash exactly like the member side — see Pairing._open
58
+ discoveryKey: channelTopic(this.invite.discoveryKey, this.pairing.network.channel),
59
+ onadd: (result) => this._done(result)
60
+ })
61
+ this._candidate.request.on('rejected', (err) => this._fail(fromBlindError(err)))
62
+ this.pairing.network.refreshInjected().catch(this._onerror ?? (() => {}))
63
+ } catch (err) {
64
+ this._fail(err instanceof CeroError ? err : CeroError.NETWORK_ERROR(err.message))
65
+ }
66
+ })
67
+ }
68
+
69
+ _done(result) {
70
+ if (this._settled) return
71
+
72
+ let envelope = null
73
+ try {
74
+ if (result?.data) envelope = c.decode(Response, result.data)
75
+ } catch {}
76
+
77
+ if (envelope && envelope.status === STATUS_DENIED) {
78
+ this._fail(CeroError.DENIED(envelope.reason || null))
79
+ return
80
+ }
81
+
82
+ if (!envelope) {
83
+ this._fail(CeroError.NETWORK_ERROR('malformed pairing response'))
84
+ return
85
+ }
86
+
87
+ this._settled = true
88
+ this.pairing._candidates.delete(this)
89
+ clearTimeout(this._timer)
90
+
91
+ this._resolve({
92
+ key: envelope.key,
93
+ encryptionKey: envelope.encryptionKey,
94
+ additional: envelope.extra
95
+ })
96
+
97
+ this._candidate.close().catch(safetyCatch)
98
+ }
99
+
100
+ _fail(err) {
101
+ if (this._settled) return
102
+ this._settled = true
103
+ this.pairing._candidates.delete(this)
104
+ clearTimeout(this._timer)
105
+ if (this._candidate) this._candidate.close().catch(safetyCatch)
106
+ this._reject(err)
107
+ }
108
+ }
109
+
110
+ function fromBlindError(err) {
111
+ // a code-less rejection is a protocol failure, never a host decision
112
+ if (!err || !err.code) return CeroError.NETWORK_ERROR(err?.message || 'pairing failed')
113
+ switch (err.code) {
114
+ case 'INVITE_EXPIRED':
115
+ return CeroError.EXPIRED(err.message)
116
+ case 'INVITE_USED':
117
+ return CeroError.DENIED('used', err.message)
118
+ case 'PAIRING_REJECTED':
119
+ return CeroError.DENIED(null, err.message)
120
+ default:
121
+ return CeroError.DENIED(err.message)
122
+ }
123
+ }