@cero-base/core 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 (55) hide show
  1. package/README.md +32 -212
  2. package/package.json +18 -9
  3. package/src/blobs/index.js +9 -0
  4. package/src/blobs/server.js +2 -0
  5. package/src/database/changes.js +1 -1
  6. package/src/database/dispatch.js +341 -209
  7. package/src/database/encryption.js +83 -33
  8. package/src/database/index.js +188 -84
  9. package/src/database/rotation.js +43 -30
  10. package/src/identity/index.js +20 -78
  11. package/src/index.js +3 -10
  12. package/src/lib/constants.js +2 -0
  13. package/src/lib/errors.js +3 -11
  14. package/src/lib/spec/index.js +136 -132
  15. package/src/lib/spec/schema.json +84 -99
  16. package/src/lib/utils.js +57 -3
  17. package/src/mailbox/inbox.js +103 -0
  18. package/src/mailbox/index.js +146 -0
  19. package/src/mailbox/post.js +69 -0
  20. package/src/network/discovery.js +26 -1
  21. package/src/network/index.js +105 -64
  22. package/src/network/presence.js +6 -2
  23. package/src/pairing/index.js +330 -254
  24. package/src/pairing/invite.js +83 -144
  25. package/src/pairing/request.js +54 -56
  26. package/src/rpc/index.js +18 -93
  27. package/src/rpc/peer.js +4 -1
  28. package/src/storage/index.js +78 -39
  29. package/types/blobs/index.d.ts +22 -9
  30. package/types/blobs/server.d.ts +4 -2
  31. package/types/database/changes.d.ts +2 -2
  32. package/types/database/dispatch.d.ts +19 -13
  33. package/types/database/encryption.d.ts +67 -29
  34. package/types/database/index.d.ts +144 -119
  35. package/types/database/rotation.d.ts +32 -13
  36. package/types/identity/index.d.ts +6 -47
  37. package/types/index.d.ts +3 -16
  38. package/types/lib/constants.d.ts +1 -0
  39. package/types/lib/errors.d.ts +3 -9
  40. package/types/lib/spec/index.d.ts +52 -16
  41. package/types/lib/utils.d.ts +40 -8
  42. package/types/mailbox/inbox.d.ts +52 -0
  43. package/types/mailbox/index.d.ts +111 -0
  44. package/types/mailbox/post.d.ts +37 -0
  45. package/types/network/discovery.d.ts +21 -5
  46. package/types/network/index.d.ts +64 -48
  47. package/types/network/presence.d.ts +17 -4
  48. package/types/pairing/index.d.ts +143 -134
  49. package/types/pairing/invite.d.ts +70 -114
  50. package/types/pairing/request.d.ts +58 -98
  51. package/types/rpc/index.d.ts +26 -44
  52. package/types/rpc/peer.d.ts +10 -7
  53. package/types/storage/index.d.ts +64 -54
  54. package/src/pairing/candidate.js +0 -123
  55. package/types/pairing/candidate.d.ts +0 -36
package/README.md CHANGED
@@ -1,228 +1,48 @@
1
1
  # @cero-base/core
2
2
 
3
- The building blocks `cero` is made of. Use them when `cero` is too high-level — when you want just an autobee, just a swarm, or just signed pairing.
3
+ > [!IMPORTANT]
4
+ > This project is experimental. The API is subject to change and may break at any time.
4
5
 
5
- Seven primitives, one subpath each: identity, storage, network, database, blobs, pairing, rpc. `ReadyResource`-shaped where it makes sense (`.ready()` + `.close()`).
6
+ Core is the eight primitives Cero is built from, one of the two Cero Base packages: reach for it to build a tool on one of them. Each is a small wrapper over a [Pear](https://pears.com) module: just invites and pairing, just a mailbox, just a replicated database, just a swarm with wakeup, just a typed channel to a worker. For an app, use Cero, [`@cero-base/cero`](https://www.npmjs.com/package/@cero-base/cero).
6
7
 
7
- ```js
8
- // Barrel import — everything in one place
9
- import {
10
- Identity,
11
- Storage,
12
- Network,
13
- Database,
14
- Blobs,
15
- Pairing,
16
- Invite,
17
- RPCServer,
18
- RPCClient,
19
- t,
20
- schema,
21
- CeroError
22
- } from '@cero-base/core'
23
-
24
- // Or by subpath when you want a smaller graph
25
- import { Identity } from '@cero-base/core/identity'
26
- ```
27
-
28
- Ships with TypeScript declarations (`.d.ts`) generated from JSDoc. Plain JS source — no TS in the tree, no compile step for runtime.
29
-
30
- ## Identity
31
-
32
- A keypair backed by a 12- or 24-word phrase. Signs and verifies. Derives a topic for swarm discovery.
33
-
34
- ```js
35
- import { Identity } from '@cero-base/core/identity'
36
-
37
- const me = await Identity.generate() // fresh random
38
- const me2 = await Identity.fromPhrase('twelve words …') // restore
39
- const sig = me.sign(message)
40
- Identity.verify(me.publicKey, message, sig) // → true / false
41
- me.id // z32-encoded public key
42
- me.topic // 32-byte buffer for swarm.join(...)
43
- me.toPhrase() // back to words
44
- ```
45
-
46
- ## Storage
47
-
48
- Hyperbee or Rocks-backed local table store with a uniform put/set/get/del/watch surface.
49
-
50
- ```js
51
- import { Storage } from '@cero-base/core/storage'
52
-
53
- const s = Storage.bee('./data', { spec: { database, meta } })
54
- await s.ready()
55
- await s.put('drafts', { text: 'hi' })
56
- const { data } = await s.get('drafts', 'some-id')
57
- ```
58
-
59
- ## Network
60
-
61
- Hyperswarm + Wakeup. `join(topic)` returns a managed `Discovery` that auto-closes with the network.
62
-
63
- ```js
64
- import { Network } from '@cero-base/core/network'
65
-
66
- const net = new Network({ bootstrap })
67
- await net.ready()
68
- const discovery = net.join(identity.topic)
69
- await discovery.flush() // bounded peer announce
70
- net.attach(myCore) // start replicating
71
- ```
72
-
73
- ## Database
74
-
75
- Autobee + HyperDB view with dispatch routing, hooks, and writer admission (bootstrap, claim).
76
-
77
- ```js
78
- import { Database } from '@cero-base/core/database'
79
-
80
- const db = new Database({ store, identity, network, spec })
81
- await db.ready()
82
- await db.bootstrap({ name: 'this-device' }) // mint a per-device writer
83
- await db.put('messages', { text: 'hi' }) // memberId stamped automatically
84
- db.before('put', (ctx) => {
85
- /* mutate or veto */
86
- })
87
- ```
88
-
89
- `db.bootstrap(...)` provisions this device. Its writer core was minted when the database opened and this device is its only author, ever. For a **second device** sharing the same identity, use `db.bootstrap({ recovering: true })` — it waits for the other devices' state, admits itself with a master-signed add-writer appended optimistically, then records the device.
90
-
91
- `db.claim()` is an alternative path: a second device claims its existing local writer; the host admits it via `add-writer` once it sees the claim.
92
-
93
- ## Blobs
94
-
95
- Content-addressed Hyperblobs store. `put(bytes)` returns a blob id you hand back to `get` (or `clear` to reclaim space).
96
-
97
- ```js
98
- import { Blobs } from '@cero-base/core/blobs'
99
-
100
- const blobs = new Blobs({ store, identity, network })
101
- await blobs.ready()
102
- const id = await blobs.put(Buffer.from('hello'))
103
- const bytes = await blobs.get(id)
104
- ```
105
-
106
- ## Pairing
107
-
108
- BlindPairing wrapper with signed invites. `createInvite()` mints, `join(invite)` consumes. The host gets a `candidate` event; call `candidate.confirm({ key, encryptionKey })` to admit.
109
-
110
- ```js
111
- import { Pairing } from '@cero-base/core/pairing'
112
-
113
- const pair = new Pairing({ network, identity, topic: myBeeKey })
114
- await pair.ready()
115
-
116
- const invite = await pair.createInvite({ role: 'write' })
117
- // host side:
118
- pair.on('candidate', async (c) => {
119
- await c.confirm({ key: bee.key, encryptionKey: bee.encryptionKey })
120
- })
121
-
122
- // joiner side:
123
- const { key, encryptionKey } = await pair.join(invite, { userData, timeout: 30000 })
124
- ```
125
-
126
- ## RPC
127
-
128
- Framed bare-rpc over any duplex stream. `bindCodec(spec)` attaches encode/decode helpers for hyperschema-typed envelopes.
129
-
130
- ```js
131
- import { RPCServer, RPCClient, bindCodec } from '@cero-base/core/rpc'
132
-
133
- class MyServer extends RPCServer {
134
- async _open() {
135
- await super._open()
136
- this.rpc.onPing(async (m) => `pong:${m}`)
137
- }
138
- }
139
- const server = new MyServer(ipc, spec)
140
- const client = new RPCClient(ipc2, spec)
141
- await server.ready()
142
- await client.ready()
143
- await client.rpc.ping('hi') // → 'pong:hi'
144
- ```
145
-
146
- ## Utils
147
-
148
- ```js
149
- import { genId, subscribe } from '@cero-base/core/utils'
150
-
151
- genId() // short z32 of 16 random bytes (for ids)
8
+ ```sh
9
+ npm install @cero-base/core
152
10
  ```
153
11
 
154
- Keys travel as z32 strings through `hypercore-id-encoding` (`hid.encode(bee.key)` / `hid.decode(id)`).
155
-
156
- `subscribe({ get, watch })` builds a Readable that re-emits the latest `get()` on every `watch(fn)` tick — the primitive `Database.watch` is built on.
157
-
158
- ## Errors
159
-
160
- `CeroError` is what the library itself throws. It's diagnostic — your app should still wrap calls in its own try/catch and decide what's user-facing, retryable, fatal, etc. The codes are stable so you can branch on them safely.
161
-
162
12
  ```js
163
- import { CeroError } from '@cero-base/core/errors'
164
-
165
- try {
166
- await cero.open(me.room, invite)
167
- } catch (e) {
168
- if (!CeroError.isCeroError(e)) throw e
169
- switch (e.code) {
170
- case 'INVALID_INVITE':
171
- return showToast('Bad invite link')
172
- case 'EXPIRED':
173
- return showToast('This invite has expired')
174
- case 'DENIED':
175
- return showToast(`Denied${e.reason ? `: ${e.reason}` : ''}`)
176
- case 'TIMEOUT':
177
- return retry()
178
- default:
179
- return reportError(e)
180
- }
181
- }
13
+ import { Identity, Network, Database } from '@cero-base/core'
182
14
  ```
183
15
 
184
- ### Codes
16
+ Each primitive but `Identity` is a `ReadyResource`: construct it, `await x.ready()`, `await x.close()`.
185
17
 
186
- Generic:
18
+ ## Docs
187
19
 
188
- | Code | Thrown when |
189
- | ------------------ | ------------------------------------------------------------------------------ |
190
- | `REQUIRED` | A constructor or function arg is missing (`store`, `identity`, `spec`, …) |
191
- | `INVALID` | Arg has the wrong shape/type (`publicKey must be a 32-byte buffer`) |
192
- | `CLOSED` | You called a method on a closed `Database`, `Storage`, `Network`, `Pairing`, … |
193
- | `NOT_READY` | You called a method before `await x.ready()` |
194
- | `DESTROYED` | A `Discovery` is destroyed |
195
- | `UNKNOWN` | Asked for a `ref`, `handle`, or other thing that doesn't exist |
196
- | `NOT_WRITABLE` | Tried to write to a `Database` whose local writer isn't admitted yet |
197
- | `TIMED_OUT` | A bounded wait elapsed (`until(...)` etc.) |
198
- | `UNSUPPORTED` | Feature not yet wired (nested handles, …) |
199
- | `CHANNEL_MISMATCH` | Storage stamped with one `channel` reopened under another (or none) |
200
- | `CONFLICT` | The operation raced an existing state (e.g. double init) |
20
+ - [Core primitives](https://github.com/lekinox/cero-base/blob/main/docs/core.md): each primitive with examples, and how Cero puts them together
21
+ - [Errors](https://github.com/lekinox/cero-base/blob/main/docs/errors.md): the stable codes a `CeroError` carries
201
22
 
202
- Pairing-specific:
23
+ ## Exports
203
24
 
204
- | Code | Thrown when | Extra fields |
205
- | ---------------- | ----------------------------------------------------------- | ------------ |
206
- | `INVALID_INVITE` | Invite string is malformed, wrong version, or signature bad | — |
207
- | `EXPIRED` | Invite past its `expiresIn` | — |
208
- | `DENIED` | Host rejected the candidate | `reason` |
209
- | `TIMEOUT` | Pairing didn't complete in time | — |
210
- | `NETWORK_ERROR` | Underlying swarm/blind-pairing failure | — |
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` |
211
43
 
212
- Every factory produces a `CeroError` with `name === 'CeroError'`, `isCeroError === true`, the listed `.code`, and (where applicable) the extra fields above. Pattern-match on `.code`, not on the message.
44
+ Runs on Node and Bare, with TypeScript declarations.
213
45
 
214
- ## Tests
215
-
216
- ```sh
217
- cd packages/core && npm test
218
- ```
219
-
220
- Runs every `test/**/*.test.js` under brittle-node (brittle v4). `npm run build:test` regenerates the test fixture spec.
221
-
222
- ## Types
223
-
224
- ```sh
225
- npm run build:types
226
- ```
46
+ ## License
227
47
 
228
- Emits `.d.ts` from JSDoc into `types/`. Runs automatically on `npm publish` via `prepublishOnly`.
48
+ Apache-2.0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cero-base/core",
3
- "version": "2.2.1",
3
+ "version": "2.3.1",
4
4
  "description": "cero p2p primitives — identity, storage, network, database, blobs, rpc, pairing.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -65,6 +65,10 @@
65
65
  "types": "./types/rpc/index.d.ts",
66
66
  "default": "./src/rpc/index.js"
67
67
  },
68
+ "./mailbox": {
69
+ "types": "./types/mailbox/index.d.ts",
70
+ "default": "./src/mailbox/index.js"
71
+ },
68
72
  "./pairing": {
69
73
  "types": "./types/pairing/index.d.ts",
70
74
  "default": "./src/pairing/index.js"
@@ -125,6 +129,10 @@
125
129
  "process": {
126
130
  "bare": "bare-process",
127
131
  "default": "process"
132
+ },
133
+ "child_process": {
134
+ "bare": "bare-subprocess",
135
+ "default": "child_process"
128
136
  }
129
137
  },
130
138
  "scripts": {
@@ -140,31 +148,31 @@
140
148
  },
141
149
  "dependencies": {
142
150
  "@hyperswarm/secret-stream": "^6.9.2",
143
- "autobee": "2.10.0",
144
- "autobee-encryption": "0.1.4",
151
+ "autobee": "2.11.8",
145
152
  "b4a": "^1.9.0",
146
153
  "bare-crypto": "^1.15.3",
147
154
  "bare-fs": "^4.8.1",
148
155
  "bare-path": "^3.1.2",
149
156
  "bip39-mnemonic": "^2.5.0",
150
- "blind-pairing": "^2.3.1",
151
157
  "blind-peering": "^2.9.5",
152
- "compact-encoding": "^3.5.0",
153
- "corestore": "^7.12.5",
158
+ "compact-encoding": "^3.5.2",
159
+ "corestore": "^7.12.6",
154
160
  "framed-stream": "^1.0.1",
155
161
  "hrpc": "^4.3.1",
156
162
  "hyperblobs": "^2.12.1",
157
- "hypercore": "^11.36.1",
163
+ "hypercore": "^11.37.0",
158
164
  "hypercore-blob-server": "^1.15.0",
159
165
  "hypercore-crypto": "^3.7.0",
160
166
  "hypercore-id-encoding": "^1.3.0",
161
167
  "hypercore-storage": "^3.3.1",
162
168
  "hyperdb": "^6.9.0",
169
+ "hyperdht": "^6.34.0",
163
170
  "hyperdispatch": "^1.6.0",
164
171
  "hyperschema": "^1.26.2",
165
- "hyperswarm": "^4.17.1",
172
+ "hyperswarm": "^4.17.2",
166
173
  "keet-identity-key": "^3.2.0",
167
- "protomux": "^3.12.0",
174
+ "ms": "^2.1.3",
175
+ "protomux": "^3.12.1",
168
176
  "protomux-wakeup": "^2.9.0",
169
177
  "ready-resource": "^1.2.0",
170
178
  "safety-catch": "^1.0.3",
@@ -178,6 +186,7 @@
178
186
  "bare-events": "^2.9.2",
179
187
  "bare-fetch": "^3.4.0",
180
188
  "bare-process": "^4.5.1",
189
+ "bare-subprocess": "^6.2.0",
181
190
  "bare-url": "^2.5.4",
182
191
  "blind-peer": "^3.15.0",
183
192
  "brittle": "^4.2.0",
@@ -16,6 +16,7 @@ const NS = `${NAMESPACE}/blobs`
16
16
  * @property {import('../network/index.js').Network} [network] Optional network used to announce + replicate the core.
17
17
  * @property {Uint8Array} [key] Pre-existing blob core key — joins an existing blob feed.
18
18
  * @property {Uint8Array} [encryptionKey] Explicit encryption key, overrides `identity.encryptionKey`.
19
+ * @property {string} [name] Core name in the store when no `key` is given; `blobs` by default.
19
20
  *
20
21
  * @typedef {import('./codec.js').RawBlobId} RawBlobId
21
22
  */
@@ -34,9 +35,13 @@ export class Blobs extends ReadyResource {
34
35
  this.encryptionKey = encryptionKey || (identity && identity.encryptionKey) || null
35
36
  this.name = name || 'blobs'
36
37
 
38
+ /** @private */
37
39
  this._coreKey = key || null
40
+ /** @type {import('hypercore') | null} */
38
41
  this.core = null
42
+ /** @type {import('hyperblobs') | null} */
39
43
  this.hyperblobs = null
44
+ /** @private */
40
45
  this._discovery = null
41
46
  }
42
47
 
@@ -67,6 +72,7 @@ export class Blobs extends ReadyResource {
67
72
  return this.core ? this.core.discoveryKey : null
68
73
  }
69
74
 
75
+ /** @private */
70
76
  async _open() {
71
77
  await this.store.ready()
72
78
  if (this.network) await this.network.ready()
@@ -88,6 +94,7 @@ export class Blobs extends ReadyResource {
88
94
  }
89
95
  }
90
96
 
97
+ /** @private */
91
98
  async _close() {
92
99
  if (this._discovery) await this._discovery.destroy()
93
100
  if (this.network && this.core) this.network.detach(this.core)
@@ -147,6 +154,7 @@ export class Blobs extends ReadyResource {
147
154
  /**
148
155
  * @param {import('streamx').Readable} input
149
156
  * @returns {Promise<RawBlobId>}
157
+ * @private
150
158
  */
151
159
  async _putStream(input) {
152
160
  const ws = this.hyperblobs.createWriteStream()
@@ -159,6 +167,7 @@ export class Blobs extends ReadyResource {
159
167
  return ws.id
160
168
  }
161
169
 
170
+ /** @private */
162
171
  _guard() {
163
172
  if (this.closed) throw CeroError.CLOSED('Blobs')
164
173
  if (!this.opened) throw CeroError.NOT_READY('Blobs', 'blobs')
@@ -16,11 +16,13 @@ export class FileServer {
16
16
  */
17
17
  constructor({ store, resolve }) {
18
18
  this.resolve = resolve
19
+ /** @type {import('hypercore-blob-server')} */
19
20
  this.server = new BlobServer(store.session(), {
20
21
  resolve: (key, info) => this.resolve(key, info)
21
22
  })
22
23
  }
23
24
 
25
+ /** @returns {number} */
24
26
  get port() {
25
27
  return this.server.port
26
28
  }
@@ -8,7 +8,7 @@ import b4a from 'b4a'
8
8
  * @param {import('./index.js').Database} db
9
9
  * @param {string} name Ref name (scopes the update ticks).
10
10
  * @param {string} col Collection path (`@ns/name`).
11
- * @param {(row: any) => boolean} matches
11
+ * @param {(row: Record<string, unknown>) => boolean} matches
12
12
  * @returns {import('streamx').Readable}
13
13
  */
14
14
  export function makeChanges(db, name, col, matches) {