@cero-base/core 2.3.3 → 2.4.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/README.md CHANGED
@@ -22,24 +22,24 @@ Each primitive but `Identity` is a `ReadyResource`: construct it, `await x.ready
22
22
 
23
23
  ## Exports
24
24
 
25
- | Subpath | What it gives you |
26
- | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
27
- | `@cero-base/core` | Every subpath below in one import, but `/database/encryption` and `/blobs/server` |
28
- | `@cero-base/core/identity` | `Identity`: a keypair from a seed; signs, verifies, seals, names a swarm topic |
29
- | `@cero-base/core/network` | `Network`: Hyperswarm plus wakeup, with managed discovery sessions; `channelTopic` |
30
- | `@cero-base/core/database` | `Database`: multi-writer, permissions checked at apply, hooks, key rotation |
31
- | `@cero-base/core/database/encryption` | `Keyring`, `EpochAutobee`, `blobEpochKey`, `loadEpochs`, `seal`, `opened`, `wraps`, `epochEntries`: the key epochs a `Database` rotates through |
32
- | `@cero-base/core/mailbox` | `Mailbox`: messages to an address, delivered directly or held by a mirror |
33
- | `@cero-base/core/pairing` | `Pairing`: invites into a database, joins admitted at apply; `sealJoin` |
34
- | `@cero-base/core/invite` | `Invite`: parse an invite string, read its `data` before joining |
35
- | `@cero-base/core/storage` | `Storage`: local tables on Hyperbee or RocksDB, for device-only data |
36
- | `@cero-base/core/blobs` | `Blobs`: bytes in a Hyperblobs core, addressed by position, encrypted; `encodeId`, `decodeId` |
37
- | `@cero-base/core/blobs/codec` | `encodeId`, `decodeId`: a core key, blob id and type as one string |
38
- | `@cero-base/core/blobs/server` | `FileServer`: a file id served at a local url |
39
- | `@cero-base/core/rpc` | `RPCServer`, `RPCClient`, `bindCodec`: a typed channel over any duplex stream |
40
- | `@cero-base/core/schema` | `t`, `schema`: the field types and the wrapper a build takes |
41
- | `@cero-base/core/utils` | `WRITE`, `INVITE`, `ASSIGN`, `REMOVE`, `can`, `grants`, `outranks`, `isRank`, `filter`, `searchHit`, `onAbort`, `subscribe`, `admission`, `ownership`, `joining`, `checkFields`, `checkRequired`, `stamp` |
42
- | `@cero-base/core/errors` | `CeroError` |
25
+ | Subpath | What it gives you |
26
+ | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
27
+ | `@cero-base/core` | Every subpath below in one import, but `/database/encryption` and `/blobs/server` |
28
+ | `@cero-base/core/identity` | `Identity`: a keypair from a seed; signs, verifies, seals, names a swarm topic |
29
+ | `@cero-base/core/network` | `Network`: Hyperswarm plus wakeup, with managed discovery sessions; `channelTopic` |
30
+ | `@cero-base/core/database` | `Database`: multi-writer, permissions checked at apply, hooks, key rotation |
31
+ | `@cero-base/core/database/encryption` | `Keyring`, `EpochAutobee`, `blobEpochKey`, `loadEpochs`, `seal`, `opened`, `wraps`, `epochEntries`: the key epochs a `Database` rotates through |
32
+ | `@cero-base/core/mailbox` | `Mailbox`: messages to an address, delivered directly or held by a mirror |
33
+ | `@cero-base/core/pairing` | `Pairing`: invites into a database, joins admitted at apply; `sealJoin` |
34
+ | `@cero-base/core/invite` | `Invite`: parse an invite string, read its `data` before joining |
35
+ | `@cero-base/core/storage` | `Storage`: local tables on Hyperbee or RocksDB, for device-only data |
36
+ | `@cero-base/core/blobs` | `Blobs`: bytes in a Hyperblobs core, addressed by position, encrypted; `encodeId`, `decodeId` |
37
+ | `@cero-base/core/blobs/codec` | `encodeId`, `decodeId`: a core key, blob id and type as one string |
38
+ | `@cero-base/core/blobs/server` | `FileServer`: a file id served at a local url |
39
+ | `@cero-base/core/rpc` | `RPCServer`, `RPCClient`, `bindCodec`: a typed channel over any duplex stream |
40
+ | `@cero-base/core/schema` | `t`, `schema`: the field types and the wrapper a build takes |
41
+ | `@cero-base/core/utils` | `WRITE`, `INVITE`, `ASSIGN`, `REMOVE`, `can`, `grants`, `outranks`, `isRank`, `filter`, `searchHit`, `onAbort`, `subscribe`, `admission`, `joining`, `checkFields`, `checkRequired`, `stamp` |
42
+ | `@cero-base/core/errors` | `CeroError` |
43
43
 
44
44
  Runs on Node and Bare, with TypeScript declarations.
45
45
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cero-base/core",
3
- "version": "2.3.3",
3
+ "version": "2.4.0",
4
4
  "description": "cero p2p primitives — identity, storage, network, database, blobs, rpc, pairing.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -148,19 +148,19 @@
148
148
  },
149
149
  "dependencies": {
150
150
  "@hyperswarm/secret-stream": "^6.9.2",
151
- "autobee": "2.12.0",
151
+ "autobee": "2.12.1",
152
152
  "b4a": "^1.9.0",
153
- "bare-crypto": "^1.15.3",
153
+ "bare-crypto": "^1.15.4",
154
154
  "bare-fs": "^4.8.2",
155
155
  "bare-path": "^3.1.2",
156
156
  "bip39-mnemonic": "^2.5.0",
157
157
  "blind-peering": "^2.9.5",
158
158
  "compact-encoding": "^3.5.2",
159
- "corestore": "^7.12.6",
159
+ "corestore": "^7.13.0",
160
160
  "framed-stream": "^1.0.1",
161
161
  "hrpc": "^4.3.1",
162
162
  "hyperblobs": "^2.12.1",
163
- "hypercore": "^11.37.0",
163
+ "hypercore": "^11.37.1",
164
164
  "hypercore-blob-server": "^1.15.0",
165
165
  "hypercore-crypto": "^3.7.0",
166
166
  "hypercore-id-encoding": "^1.3.0",
@@ -172,7 +172,6 @@
172
172
  "hyperswarm": "^4.17.2",
173
173
  "keet-identity-key": "^3.2.0",
174
174
  "ms": "^2.1.3",
175
- "protomux": "^3.12.1",
176
175
  "protomux-wakeup": "^2.9.0",
177
176
  "ready-resource": "^1.2.0",
178
177
  "safety-catch": "^1.0.3",
@@ -188,8 +187,9 @@
188
187
  "bare-process": "^4.5.1",
189
188
  "bare-subprocess": "^6.2.0",
190
189
  "bare-url": "^2.5.4",
191
- "blind-peer": "^3.15.0",
190
+ "blind-peer": "^3.15.1",
192
191
  "brittle": "^4.2.0",
192
+ "protomux": "^3.12.1",
193
193
  "typescript": "^7.0.2",
194
194
  "which-runtime": "^1.4.0"
195
195
  },
@@ -12,10 +12,9 @@ const NS = `${NAMESPACE}/blobs`
12
12
  /**
13
13
  * @typedef {object} BlobsOpts
14
14
  * @property {object} store Corestore (or compatible) used to host the blob core.
15
- * @property {import('../identity/index.js').Identity} [identity] Identity supplying the default encryption key.
16
- * @property {import('../network/index.js').Network} [network] Optional network used to announce + replicate the core.
15
+ * @property {import('../network/index.js').Network} [network] Optional network on this store: the core rides its connections and mirrors.
17
16
  * @property {Uint8Array} [key] Pre-existing blob core key — joins an existing blob feed.
18
- * @property {Uint8Array} [encryptionKey] Explicit encryption key, overrides `identity.encryptionKey`.
17
+ * @property {Uint8Array} encryptionKey Encrypts the core.
19
18
  * @property {string} [name] Core name in the store when no `key` is given; `blobs` by default.
20
19
  *
21
20
  * @typedef {import('./codec.js').RawBlobId} RawBlobId
@@ -24,15 +23,18 @@ const NS = `${NAMESPACE}/blobs`
24
23
  /** Thin wrapper over a single Hyperblobs core; deals only in raw blobIds. */
25
24
  export class Blobs extends ReadyResource {
26
25
  /** @param {BlobsOpts} [opts] */
27
- constructor({ store, identity, network, key, encryptionKey, name } = {}) {
26
+ constructor({ store, network, key, encryptionKey, name } = {}) {
28
27
  super()
29
28
  if (!store) throw CeroError.REQUIRED('store')
30
- if (!identity && !encryptionKey) throw CeroError.REQUIRED('identity or encryptionKey')
29
+ if (!encryptionKey) throw CeroError.REQUIRED('encryptionKey')
30
+ // a network replicates its own store only: a core in another would never leave the device
31
+ if (network && !network.replicates(store)) {
32
+ throw CeroError.INVALID("store must be the network's store or a session of it")
33
+ }
31
34
 
32
35
  this.store = store
33
- this.identity = identity || null
34
36
  this.network = network || null
35
- this.encryptionKey = encryptionKey || (identity && identity.encryptionKey) || null
37
+ this.encryptionKey = encryptionKey
36
38
  this.name = name || 'blobs'
37
39
 
38
40
  /** @private */
@@ -41,8 +43,6 @@ export class Blobs extends ReadyResource {
41
43
  this.core = null
42
44
  /** @type {import('hyperblobs') | null} */
43
45
  this.hyperblobs = null
44
- /** @private */
45
- this._discovery = null
46
46
  }
47
47
 
48
48
  /**
@@ -88,16 +88,12 @@ export class Blobs extends ReadyResource {
88
88
  this.hyperblobs = new Hyperblobs(this.core)
89
89
  await this.hyperblobs.ready()
90
90
 
91
- if (this.network) {
92
- this.network.attach(this.core)
93
- this._discovery = this.network.join(this.core.discoveryKey)
94
- }
91
+ // files ride the connections the network already has, and mirrors through attach
92
+ if (this.network) this.network.attach(this.core)
95
93
  }
96
94
 
97
95
  /** @private */
98
96
  async _close() {
99
- if (this._discovery) await this._discovery.destroy()
100
- if (this.network && this.core) this.network.detach(this.core)
101
97
  if (this.hyperblobs) await this.hyperblobs.close()
102
98
  if (this.core) await this.core.close()
103
99
  }
@@ -24,7 +24,6 @@ import {
24
24
  grants,
25
25
  outranks,
26
26
  admission,
27
- ownership,
28
27
  joining,
29
28
  checkFields,
30
29
  checkRequired,
@@ -319,18 +318,6 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
319
318
  await drop(ctx, 'devices', hid.encode(op.writer))
320
319
  })
321
320
 
322
- add('claim-writer', async (op, ctx) => {
323
- if (!isKey(op.identity) || !isKey(op.writer) || !isSig(op.sig)) return
324
- if (!Identity.verify(op.identity, ownership(ctx.dbKey, op.writer), op.sig)) return
325
- // from any other core a claim is inapplicable, not refused: it must not abort that writer's batch
326
- if (!b4a.equals(ctx.key, op.writer)) return
327
- const memberId = hid.encode(op.identity)
328
- if (!can(await getRole(ctx.view, op.identity), WRITE)) throw CeroError.REFUSED('write')
329
- if (await boundElsewhere(ctx.view, op.writer, memberId)) throw CeroError.REFUSED('member')
330
- await ctx.host.addWriter(op.writer, { isIndexer: true })
331
- await seat(ctx, op.writer, memberId, op.ts || 0)
332
- })
333
-
334
321
  // the genesis batch names the creator; everyone after comes in through a signed join
335
322
  add('add-member', async (op, ctx) => {
336
323
  if (!isKey(op.key)) return
@@ -380,7 +367,7 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
380
367
  const r = await getSignerRole(ctx.view, ctx.key)
381
368
  if (!can(r, REMOVE) || !outranks(r, existing.role)) throw CeroError.REFUSED('remove')
382
369
  } else if (existing.role === OWNER && (await orphans(ctx.view, op.id))) {
383
- throw CeroError.INVALID('the last owner cannot leave: hand the room to another owner first')
370
+ throw CeroError.INVALID('the last owner cannot leave: make another member an owner first')
384
371
  }
385
372
  if (existing.key) await ctx.host.removeWriter(existing.key)
386
373
  // every device of the member goes with them, and any keys they were still owed
@@ -398,7 +385,7 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
398
385
 
399
386
  add('rotate-key', async (op, ctx) => {
400
387
  if (!op.wrapped?.byteLength) return
401
- // the commitment lets every member verify the sealed secret, so a rotator cannot split the room
388
+ // the commitment lets every member verify the sealed secret, so a rotator cannot split the database
402
389
  if (op.commit?.byteLength !== 32) return
403
390
  // the stamp is picked before any block is written, so epochs reorder freely; uniqueness is enforced here
404
391
  if (!Number.isInteger(op.stamp) || op.stamp <= 0 || op.stamp > 0xffffffff) return
@@ -440,7 +427,7 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
440
427
  })
441
428
 
442
429
  // a device row is the writer→role mapping, so memberId never comes off the wire; a core no
443
- // member owns writes none, or any stranger's optimistic node would plant a device in the room
430
+ // member owns writes none, or any stranger's optimistic node would plant a device in the database
444
431
  const bind = async (ctx) => {
445
432
  const { memberId } = await author(ctx)
446
433
  if (!memberId) throw CeroError.REFUSED('member')
@@ -571,7 +558,7 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
571
558
  const id = hid.encode(ctx.key)
572
559
  const invite = await ctx.view.get(invites, { id: b4a.toHex(join.invite) })
573
560
  if (!invite) {
574
- // an invite the room never held could be anyone's: nobody answers it
561
+ // an invite the database never held could be anyone's: nobody answers it
575
562
  const record = await ctx.view.get(spent, { id: b4a.toHex(join.invite) })
576
563
  if (!record) return
577
564
  return refuse(ctx, { id, reply: join.reply, expires: record.expires }, record.reason)
@@ -610,6 +597,14 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
610
597
  const { identity, reply, createdAt: ts = 0 } = waiting
611
598
  await admit(ctx, { invite, identity, writer: hid.decode(op.id), reply, role, ts })
612
599
  })
600
+ // answered through the log like every refusal; a deny that lost the race to an accept is nothing
601
+ add('deny', async (op, ctx) => {
602
+ const waiting = await ctx.view.get(requests, { id: op.id })
603
+ if (!waiting || waiting.admitted) return
604
+ if (!can(await getSignerRole(ctx.view, ctx.key), INVITE)) throw CeroError.REFUSED('invite')
605
+ await drop(ctx, 'requests', op.id)
606
+ await refuse(ctx, waiting, op.reason || '')
607
+ })
613
608
  // only a join writes a request
614
609
  const joinsOnly = async () => {
615
610
  throw CeroError.REFUSED('request')
@@ -140,8 +140,10 @@ export class Keyring {
140
140
  this.current = 0
141
141
  /** highest adopted apply-order sequence (0 = base era) */
142
142
  this.seq = 0
143
- /** bumped on every add/remove — cheap change detection for retries */
143
+ /** bumped on every add/remove — cheap change detection */
144
144
  this.version = 0
145
+ /** @type {(() => void) | null} called when an epoch is learned or dropped */
146
+ this.onchange = null
145
147
  }
146
148
 
147
149
  /** @returns {Array<{ epoch: number, stamp: number, entropy: Uint8Array }>} ascending by seq */
@@ -171,6 +173,7 @@ export class Keyring {
171
173
  this.current = stamp
172
174
  }
173
175
  this.version++
176
+ this.onchange?.()
174
177
  }
175
178
 
176
179
  /**
@@ -198,6 +201,7 @@ export class Keyring {
198
201
  }
199
202
  }
200
203
  this.version++
204
+ this.onchange?.()
201
205
  }
202
206
  }
203
207
 
@@ -216,14 +220,14 @@ export class EpochAutobee extends Autobee {
216
220
  super(store, key, handlers)
217
221
  /** @type {Keyring | null} */
218
222
  this.keyring = handlers.keyring || null
223
+ // a block from an unknown epoch parks what read it until the keyring learns something
224
+ if (this.keyring) this.keyring.onchange = () => this._scheduleEpochWake()
219
225
  /** @private */
220
226
  this._epochStalled = new Set()
221
227
  /** @private */
222
- this._epochRetry = null
228
+ this._epochParked = false
223
229
  /** @private */
224
- this._epochRetryDelay = 1000
225
- /** @private */
226
- this._epochRetrySeen = 0
230
+ this._epochWake = null
227
231
  }
228
232
 
229
233
  /** @returns {number} the key id new blocks are written with */
@@ -231,35 +235,25 @@ export class EpochAutobee extends Autobee {
231
235
  return this.keyring ? this.keyring.current : 0
232
236
  }
233
237
 
234
- // a block from an epoch not learned yet: the writer freezes over the throw, and the retry
235
- // wakes it once the announcement lands
238
+ // a block from an epoch not learned yet: the writer freezes over the throw, and the keyring
239
+ // learning an epoch wakes it
236
240
  /** @param {number} id @param {{ key?: Uint8Array }} [ctx] @returns {Promise<Uint8Array>} */
237
241
  async getEntropy(id, ctx) {
238
242
  const entropy = this.keyring && this.keyring.entropy(id)
239
243
  if (entropy) return entropy
240
- if (ctx?.key) {
241
- this._epochStalled.add(b4a.toHex(ctx.key))
242
- this._scheduleEpochRetry()
243
- }
244
+ if (ctx?.key) this._epochStalled.add(b4a.toHex(ctx.key))
244
245
  throw CeroError.UNKNOWN_EPOCH(id)
245
246
  }
246
247
 
247
- /** @private */
248
- async _close() {
249
- if (this._epochRetry) clearTimeout(this._epochRetry)
250
- this._epochRetry = null
251
- return super._close()
252
- }
253
-
254
- // an UNKNOWN_EPOCH from the drain parks the pass; the retry wakes the stalled cores once the
255
- // announcement lands. Forward the arguments: the local drain passes { local: true }
248
+ // an UNKNOWN_EPOCH from the drain parks the pass until the keyring learns an epoch. Forward
249
+ // the arguments: the local drain passes { local: true }
256
250
  /** @private */
257
251
  async _bumpPendingWriters(...args) {
258
252
  try {
259
253
  return await super._bumpPendingWriters(...args)
260
254
  } catch (err) {
261
255
  if (err?.code !== 'UNKNOWN_EPOCH') throw err
262
- this._scheduleEpochRetry()
256
+ this._epochParked = true
263
257
  return false
264
258
  }
265
259
  }
@@ -271,30 +265,28 @@ export class EpochAutobee extends Autobee {
271
265
  return await super._applyWakeupHints()
272
266
  } catch (err) {
273
267
  if (err?.code !== 'UNKNOWN_EPOCH') throw err
274
- this._scheduleEpochRetry()
268
+ this._epochParked = true
275
269
  return []
276
270
  }
277
271
  }
278
272
 
279
- // a stalled core produces no wake-up of its own, only wakeup() re-adds it; exponential backoff
273
+ // a stalled core produces no wake-up of its own, only wakeup() re-adds it. The keyring learns
274
+ // inside a drain pass, which may itself have frozen a writer: let that pass finish and detach it,
275
+ // then wake what stalled
280
276
  /** @private */
281
- _scheduleEpochRetry() {
282
- if (this._epochRetry || this.closing) return
283
- const version = this.keyring ? this.keyring.version : 0
284
- if (version !== this._epochRetrySeen) {
285
- this._epochRetrySeen = version
286
- this._epochRetryDelay = 1000
287
- }
288
- this._epochRetry = setTimeout(() => {
289
- this._epochRetry = null
277
+ _scheduleEpochWake() {
278
+ if (this._epochWake || this.closing) return
279
+ if (!this._epochParked && !this._epochStalled.size) return
280
+ this._epochWake = setTimeout(async () => {
281
+ await this.update().catch(noop)
282
+ this._epochWake = null
290
283
  if (this.closing) return
291
- for (const hex of this._epochStalled) {
292
- this.wakeup({ key: b4a.from(hex, 'hex'), length: 0 }).catch(noop)
293
- }
284
+ const stalled = [...this._epochStalled]
294
285
  this._epochStalled.clear()
286
+ this._epochParked = false
287
+ for (const hex of stalled) this.wakeup({ key: b4a.from(hex, 'hex'), length: 0 }).catch(noop)
295
288
  this.update().catch(noop)
296
- }, this._epochRetryDelay)
297
- this._epochRetryDelay = Math.min(this._epochRetryDelay * 2, 60000)
289
+ }, 0)
298
290
  }
299
291
  }
300
292
 
@@ -16,15 +16,19 @@ export function wrap(version, body) {
16
16
  }
17
17
 
18
18
  /**
19
- * Split an op into contract version and payload. Ops written before the
20
- * envelope existed carry no sentinel and read as version 0.
19
+ * Split an op into contract version and payload, or `null` for bytes with no envelope or a cut one.
21
20
  *
22
21
  * @param {Uint8Array} buf
23
- * @returns {{ version: number, body: Uint8Array }}
22
+ * @returns {{ version: number, body: Uint8Array } | null}
24
23
  */
25
24
  export function unwrap(buf) {
26
- if (buf.byteLength === 0 || buf[0] !== SENTINEL) return { version: 0, body: buf }
25
+ if (buf.byteLength === 0 || buf[0] !== SENTINEL) return null
27
26
  const state = { buffer: buf, start: 1, end: buf.byteLength }
28
- const version = c.uint.decode(state)
29
- return { version, body: buf.subarray(state.start) }
27
+ try {
28
+ const version = c.uint.decode(state)
29
+ return { version, body: buf.subarray(state.start) }
30
+ } catch {
31
+ // any writer can append bytes: a version cut short must not throw inside apply
32
+ return null
33
+ }
30
34
  }