@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
@@ -1,228 +1,226 @@
1
1
  import c from 'compact-encoding'
2
2
  import crypto from 'hypercore-crypto'
3
3
  import b4a from 'b4a'
4
+ import hid from 'hypercore-id-encoding'
4
5
 
5
6
  import { REMOVE } from '../lib/constants.js'
6
- import { toId, toKey, can } from '../lib/utils.js'
7
+ import { can } from '../lib/utils.js'
7
8
  import { wraps, epochEntries } from './encryption.js'
8
9
  import { Identity } from '../identity/index.js'
9
10
  import { CeroError } from '../lib/errors.js'
10
11
 
11
- export async function rotate(db, retried = false) {
12
- db.guard()
13
- if (!db.writable) throw CeroError.NOT_WRITABLE('Database')
14
- // queued in tx() the epoch is unobservable, and a batched rekey blurs the epoch
15
- if (db.txQueue) throw CeroError.INVALID('rotate() cannot run inside tx()')
16
- if (db._rotation) throw CeroError.INVALID('a rotation is already in progress')
17
- // manifest v1 blocks carry no key id, rotating there is a silent downgrade
18
- if (db.bee.local.manifest?.version < 2) {
19
- throw CeroError.INVALID('rotation requires manifest v2 cores')
20
- }
21
- // claimed synchronously, no await may separate the check from the claim
22
- db._rotation = { entropy: null, stamp: 0, epoch: 0 }
23
- try {
24
- const entropy = Identity.randomBytes(32)
25
- const stamp = randomStamp(db)
26
- const wrapped = sealFor(await members(db), entropy)
27
- const epoch = await announce(db, stamp, entropy, wrapped)
28
- if (!epoch) {
29
- // a stamp collision (~2^-32, or an adversarial pre-claim) is not a refusal
30
- if (!retried && (await stampTaken(db, stamp))) {
31
- db._rotation = null
32
- return db.rotate(true)
33
- }
34
- // permission is refused before the append, so the dry-run missed something
35
- throw CeroError.INVALID('rotation was not applied')
36
- }
37
- db.keyring.add(stamp, entropy, epoch)
38
- await saveEpochs(db)
39
- return { epoch }
40
- } finally {
41
- db._rotation = null
12
+ /**
13
+ * Epoch key rotation for a database: mint a secret, seal it to every member, announce it
14
+ * through the log, and on every peer learn the secrets addressed to it.
15
+ */
16
+ export class Rotation {
17
+ /** @param {import('./index.js').Database} db */
18
+ constructor(db) {
19
+ this.db = db
20
+ this.current = null
21
+ this._timer = null
22
+ this._healedFor = null
42
23
  }
43
- }
44
24
 
45
- async function members(db) {
46
- const { data: members } = await db.get('members')
47
- if (!Array.isArray(members) || members.length === 0) {
48
- throw CeroError.INVALID('cannot rotate a database with no members')
25
+ close() {
26
+ clearTimeout(this._timer)
27
+ this._timer = null
49
28
  }
50
- return members
51
- }
52
29
 
53
- /** One sealed copy of the epoch secret per member, addressed by member id. */
54
- function sealFor(members, entropy) {
55
- return members.map((m) => {
56
- let key
57
- try {
58
- key = toKey(m.id)
59
- } catch {
60
- throw CeroError.INVALID(`member id is not an identity key: ${m.id}`)
30
+ /** @returns {Promise<{ epoch: number }>} */
31
+ rotate() {
32
+ return this._rotate(false)
33
+ }
34
+
35
+ /**
36
+ * An applied rotation announcement: open our envelope, learn the secret, persist it.
37
+ *
38
+ * @param {{ epoch: number, stamp: number, wrapped: Uint8Array, commit: Uint8Array }} row
39
+ */
40
+ async learn(row) {
41
+ const { keyring } = this.db
42
+ const known = keyring.entropy(row.stamp)
43
+ const entropy = known || this._unseal(row)
44
+ if (known) {
45
+ keyring.add(row.stamp, known, row.epoch) // re-applied, the sequence may be news
46
+ } else if (this.current && entropy && b4a.equals(entropy, this.current.entropy)) {
47
+ this.current.epoch = row.epoch
48
+ } else if (entropy) {
49
+ keyring.add(row.stamp, entropy, row.epoch)
50
+ try {
51
+ await this._save()
52
+ } catch (err) {
53
+ // an epoch we cannot reload after a restart must not be used for writes
54
+ keyring.remove(row.stamp)
55
+ this.db._onerror(err)
56
+ }
61
57
  }
62
- return { id: m.id, box: Identity.seal(key, entropy) }
63
- })
64
- }
58
+ this.heal()
59
+ }
65
60
 
66
- // append the announcement under the current epoch and wait for its apply;
67
- // resolves the sequence apply assigned, 0 if it never applied
68
- async function announce(db, stamp, entropy, wrapped) {
69
- // defer our own hydration until the append flushed: the block is encrypted
70
- // at drain time, so advancing the keyring now seals the announcement to itself
71
- db._rotation.entropy = entropy
72
- db._rotation.stamp = stamp
73
- const from = db.bee.local.length
74
- await db.call('rotate-key', {
75
- epoch: 0, // sequence assigned deterministically at apply time
76
- stamp,
77
- wrapped: c.encode(wraps, wrapped),
78
- createdAt: Date.now(),
79
- commit: crypto.hash(entropy)
80
- })
81
- await db.bee.update()
82
- // a block appended during a rotation must not carry the stamp it announces
83
- for (let i = from; i < db.bee.local.length; i++) {
84
- const raw = await db.bee.local.get(i, { raw: true })
85
- const id = c.uint32.decode({ start: 4, end: 8, buffer: raw.subarray(0, 8) })
86
- if (id === stamp) {
87
- throw CeroError.INVALID('announcement encrypted under its own epoch — aborting rotation')
61
+ /**
62
+ * Safety net after boot: an epoch applied but never saved, e.g. a crash between a
63
+ * rotation's append and its save, is learned from the epochs collection.
64
+ */
65
+ async hydrate() {
66
+ try {
67
+ for (const row of await this._epochs()) {
68
+ if (!this.db.keyring.entropy(row.stamp)) await this.learn(row)
69
+ }
70
+ } catch {
71
+ // rows past our newest epoch hydrate via apply
88
72
  }
89
73
  }
90
- return db._rotation.epoch
91
- }
92
74
 
93
- async function stampTaken(db, stamp) {
94
- const rows = await db.view.find(`@${db.ns}/epochs`, {}).toArray()
95
- return rows.some((r) => r.stamp === stamp)
96
- }
75
+ /** Debounced audit, run after every update. */
76
+ heal() {
77
+ const db = this.db
78
+ if (this._timer || db.closing || db.closed) return
79
+ this._timer = setTimeout(() => {
80
+ this._timer = null
81
+ this._audit().catch(db._onerror)
82
+ }, 500)
83
+ }
97
84
 
98
- /** Fresh nonzero uint32 block-header stamp not already used by a known epoch. */
99
- function randomStamp(db) {
100
- for (;;) {
101
- const buf = Identity.randomBytes(4)
102
- const stamp = ((buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3]) >>> 0
103
- if (stamp !== 0 && !db.keyring.entropy(stamp)) return stamp
85
+ async _rotate(retried) {
86
+ const db = this.db
87
+ db.guard()
88
+ if (!db.writable) throw CeroError.NOT_WRITABLE('Database')
89
+ if (this.current) throw CeroError.INVALID('a rotation is already in progress')
90
+ // manifest v1 blocks carry no key id, rotating there is a silent downgrade
91
+ if (db.bee.local.manifest?.version < 2) {
92
+ throw CeroError.INVALID('rotation requires manifest v2 cores')
93
+ }
94
+ // claimed synchronously; the keyring learns the secret only after the announcement flushed
95
+ const entropy = Identity.randomBytes(32)
96
+ const stamp = this._mint()
97
+ this.current = { entropy, stamp, epoch: 0 }
98
+ try {
99
+ const wrapped = this._seal(await this._members(), entropy)
100
+ const epoch = await this._announce(stamp, entropy, wrapped)
101
+ if (!epoch) {
102
+ // a stamp collision (~2^-32, or an adversarial pre-claim) is not a refusal
103
+ if (!retried && (await this._taken(stamp))) {
104
+ this.current = null
105
+ return this._rotate(true)
106
+ }
107
+ // permission is refused before the append, so the dry-run missed something
108
+ throw CeroError.INVALID('rotation was not applied')
109
+ }
110
+ db.keyring.add(stamp, entropy, epoch)
111
+ await this._save()
112
+ return { epoch }
113
+ } finally {
114
+ this.current = null
115
+ }
104
116
  }
105
- }
106
117
 
107
- /**
108
- * Per-peer side of an applied rotation: open our envelope, learn the epoch
109
- * secret, persist it locally. Peers without an envelope (removed members)
110
- * simply stop here — every block after the announcement is noise to them.
111
- * Our own in-flight rotation is deferred to `rotate()` (see above).
112
- *
113
- * @param {import('./index.js').Database} db
114
- * @param {{ epoch: number, wrapped: Uint8Array, createdAt: number }} row
115
- */
116
- export async function onepoch(db, row) {
117
- if (db.keyring.entropy(row.stamp)) {
118
- // idempotent re-apply, but record the sequence if it was unknown
119
- db.keyring.add(row.stamp, db.keyring.entropy(row.stamp), row.epoch)
120
- scheduleHeal(db)
121
- return
122
- }
123
- for (const w of c.decode(wraps, row.wrapped)) {
124
- if (w.id !== db.identity.id) continue
125
- const entropy = db.identity.unseal(w.box)
126
- // keep scanning, a bad envelope ahead of a good one must not lock us out
127
- if (entropy?.byteLength !== 32) continue
128
- // a secret failing the row's commitment means the rotator sealed different ones
129
- if (!row.commit || !b4a.equals(crypto.hash(entropy), row.commit)) {
130
- db._onerror(CeroError.INVALID(`epoch ${row.epoch} envelope fails its commitment`))
131
- continue
118
+ async _members() {
119
+ const { data: members } = await this.db.get('members')
120
+ if (!Array.isArray(members) || members.length === 0) {
121
+ throw CeroError.INVALID('cannot rotate a database with no members')
132
122
  }
133
- if (db._rotation?.entropy && b4a.equals(entropy, db._rotation.entropy)) {
134
- db._rotation.epoch = row.epoch
135
- } else {
136
- db.keyring.add(row.stamp, entropy, row.epoch)
123
+ return members
124
+ }
125
+
126
+ // one sealed copy of the secret per member, addressed by member id
127
+ _seal(members, entropy) {
128
+ return members.map((m) => {
129
+ let key
137
130
  try {
138
- await saveEpochs(db)
139
- } catch (err) {
140
- // an epoch we cannot reload after a restart must not be used for writes
141
- db.keyring.remove(row.stamp)
142
- db._onerror(err)
131
+ key = hid.decode(m.id)
132
+ } catch {
133
+ throw CeroError.INVALID(`member id is not an identity key: ${m.id}`)
134
+ }
135
+ return { id: m.id, box: Identity.seal(key, entropy) }
136
+ })
137
+ }
138
+
139
+ // resolves the sequence apply assigned, 0 if it never applied
140
+ async _announce(stamp, entropy, wrapped) {
141
+ const { bee } = this.db
142
+ const from = bee.local.length
143
+ await this.db.call('rotate-key', {
144
+ epoch: 0, // sequence assigned deterministically at apply time
145
+ stamp,
146
+ wrapped: c.encode(wraps, wrapped),
147
+ createdAt: Date.now(),
148
+ commit: crypto.hash(entropy)
149
+ })
150
+ await bee.update()
151
+ // a block appended during a rotation must not carry the stamp it announces
152
+ for (let i = from; i < bee.local.length; i++) {
153
+ if (stampOf(await bee.local.get(i, { raw: true })) === stamp) {
154
+ throw CeroError.INVALID('announcement encrypted under its own epoch — aborting rotation')
143
155
  }
144
156
  }
145
- break
157
+ return this.current.epoch
146
158
  }
147
- scheduleHeal(db)
148
- }
149
159
 
150
- /**
151
- * Safety net after boot (userData priming happens in EpochAutobee's
152
- * `_bootState`): scan the epochs collection for anything applied but never
153
- * hydrated — e.g. a crash between a rotation's append and its save.
154
- */
155
- export async function hydrateEpochs(db) {
156
- try {
157
- const rows = await db.view.find(`@${db.ns}/epochs`, {}).toArray()
158
- for (const row of rows) {
159
- if (db.keyring.entropy(row.stamp)) continue
160
- await db._onepoch(row)
160
+ // a fresh nonzero stamp no known epoch uses
161
+ _mint() {
162
+ for (;;) {
163
+ const stamp = b4a.readUInt32LE(Identity.randomBytes(4), 0)
164
+ if (stamp !== 0 && !this.db.keyring.entropy(stamp)) return stamp
161
165
  }
162
- } catch {
163
- // pre-rotation spec, or rows past our newest epoch, which hydrate via apply
164
166
  }
165
- }
166
167
 
167
- /** Persist known epoch secrets to local userData (device-only, never replicates). */
168
- function saveEpochs(db) {
169
- return db.bee.local.setUserData('cero/epochs', c.encode(epochEntries, db.keyring.all()))
170
- }
168
+ async _taken(stamp) {
169
+ return (await this._epochs()).some((r) => r.stamp === stamp)
170
+ }
171
171
 
172
- /** Debounced trigger for the epoch/membership consistency check. */
173
- export function scheduleHeal(db) {
174
- if (db._healTimer || db.closing || db.closed) return
175
- db._healTimer = setTimeout(() => {
176
- db._healTimer = null
177
- healEpochs(db).catch(db._onerror)
178
- }, 500)
179
- }
172
+ _epochs() {
173
+ return this.db.view.find(`@${this.db.ns}/epochs`, {}).toArray()
174
+ }
180
175
 
181
- /**
182
- * Convergence rotation: rotations author their envelope set against the
183
- * rotator's possibly-stale local view, so after linearization the current
184
- * epoch may include a since-removed member (who then still holds the
185
- * current key) or miss a since-added one (who is locked out). Every
186
- * REMOVE-capable writable device audits the current epoch's recipients
187
- * against canonical membership and re-keys on mismatch. Only rooms that
188
- * have rotated at least once are audited — rotation stays opt-in.
189
- */
190
- async function healEpochs(db) {
191
- if (db.closing || db.closed || !db.writable || db._rotation) return
192
- if (!db.keyring.current) return
193
- const { data: device } = await db.get('devices', toId(db.writerKey))
194
- const me = device?.memberId ? (await db.get('members', device.memberId)).data : null
195
- if (!can(me?.role, REMOVE)) return
196
-
197
- const rows = await db.view.find(`@${db.ns}/epochs`, {}).toArray()
198
- if (!rows.length) return
199
- const top = rows.reduce((a, b) => (b.epoch > a.epoch ? b : a))
200
- const recipients = new Set(c.decode(wraps, top.wrapped).map((w) => w.id))
201
- const { data: members } = await db.get('members')
202
- const ids = new Set(members.map((m) => m.id))
203
- const clean = recipients.size === ids.size && [...recipients].every((id) => ids.has(id))
204
- if (clean) {
205
- db._healedFor = null
206
- return
207
- }
208
- // one attempt per (epoch, membership) state, a failing rotate must not loop
209
- const state = `${top.stamp}:${[...ids].sort().join(',')}`
210
- if (db._healedFor === state) return
211
- db._healedFor = state
212
- await db.rotate()
176
+ // every envelope addressed to us is tried, a bad one must not lock us out
177
+ _unseal(row) {
178
+ const { identity } = this.db
179
+ for (const w of c.decode(wraps, row.wrapped)) {
180
+ if (w.id !== identity.id) continue
181
+ const entropy = identity.unseal(w.box)
182
+ if (entropy?.byteLength !== 32) continue
183
+ // a secret failing the row's commitment means the rotator sealed different ones
184
+ if (row.commit && b4a.equals(crypto.hash(entropy), row.commit)) return entropy
185
+ this.db._onerror(CeroError.INVALID(`epoch ${row.epoch} envelope fails its commitment`))
186
+ }
187
+ return null
188
+ }
189
+
190
+ // known epoch secrets to local userData (device-only, never replicates)
191
+ _save() {
192
+ const entries = c.encode(epochEntries, this.db.keyring.all())
193
+ return this.db.bee.local.setUserData('cero/epochs', entries)
194
+ }
195
+
196
+ // a rotation seals for the rotator's view of the members; REMOVE-capable devices re-key
197
+ // when the current epoch's recipients drift from the member list
198
+ async _audit() {
199
+ const db = this.db
200
+ if (db.closing || db.closed || !db.writable || this.current || !db.keyring.current) return
201
+ const { data: device } = await db.get('devices', hid.encode(db.writerKey))
202
+ const me = device?.memberId ? (await db.get('members', device.memberId)).data : null
203
+ if (!can(me?.role, REMOVE)) return
204
+
205
+ const rows = await this._epochs()
206
+ if (!rows.length) return
207
+ const top = rows.reduce((a, b) => (b.epoch > a.epoch ? b : a))
208
+ const recipients = new Set(c.decode(wraps, top.wrapped).map((w) => w.id))
209
+ const { data: members } = await db.get('members')
210
+ const ids = new Set(members.map((m) => m.id))
211
+ if (recipients.size === ids.size && [...recipients].every((id) => ids.has(id))) {
212
+ this._healedFor = null
213
+ return
214
+ }
215
+ // one attempt per (epoch, membership) state, a failing rotate must not loop
216
+ const state = `${top.stamp}:${[...ids].sort().join(',')}`
217
+ if (this._healedFor === state) return
218
+ this._healedFor = state
219
+ await this.rotate()
220
+ }
213
221
  }
214
222
 
215
- /**
216
- * Record that the log contains ops from a newer app version than this
217
- * peer understands. Fires `'behind'` once per version so apps can prompt
218
- * an upgrade; the marker survives restarts via local core userData.
219
- *
220
- * @param {import('./index.js').Database} db
221
- * @param {number} version
222
- */
223
- export function onfuture(db, version) {
224
- if (db.behind !== null && version <= db.behind) return
225
- db.behind = version
226
- db.bee.local.setUserData('cero/behind', c.encode(c.uint, version)).catch(db._onerror)
227
- db.emit('behind', version)
223
+ // the epoch stamp autobee-encryption writes into every block header
224
+ function stampOf(raw) {
225
+ return b4a.readUInt32LE(raw, 4)
228
226
  }
@@ -2,9 +2,9 @@ import sodium from 'sodium-universal'
2
2
  import IdentityKey from 'keet-identity-key'
3
3
  import bip39 from 'bip39-mnemonic'
4
4
  import b4a from 'b4a'
5
+ import hid from 'hypercore-id-encoding'
5
6
 
6
7
  import { CeroError } from '../lib/errors.js'
7
- import { toId } from '../lib/utils.js'
8
8
 
9
9
  const DERIVE_PATH = ['SLIP-0021', 'cero', 'v1', 'identity']
10
10
 
@@ -14,9 +14,7 @@ const DERIVE_PATH = ['SLIP-0021', 'cero', 'v1', 'identity']
14
14
  */
15
15
 
16
16
  /**
17
- * Long-lived user identity derived from a BIP-39 seed phrase. Holds the
18
- * sign keypair, a symmetric encryption key and the canonical id/topic used
19
- * by every other resource to identify this user.
17
+ * Long-lived user identity derived from a BIP-39 seed phrase.
20
18
  */
21
19
  export class Identity {
22
20
  /** @param {IdentityFields} keys */
@@ -26,7 +24,7 @@ export class Identity {
26
24
  *
27
25
  * @type {string}
28
26
  */
29
- this.id = toId(keys.publicKey)
27
+ this.id = hid.encode(keys.publicKey)
30
28
  /** @type {Uint8Array} */
31
29
  this.publicKey = keys.publicKey
32
30
  /** @type {Uint8Array} */
@@ -90,9 +88,8 @@ export class Identity {
90
88
  }
91
89
 
92
90
  /**
93
- * Open a sealed box addressed to this identity (any device holding the
94
- * seed-derived keypair can open it). Returns null when the box is not ours
95
- * or is corrupt — callers treat that as "not addressed to me".
91
+ * Open a sealed box addressed to this identity (any device holding the seed-derived
92
+ * keypair can open it).
96
93
  *
97
94
  * @param {Uint8Array} sealed
98
95
  * @returns {Uint8Array | null}
@@ -223,9 +220,8 @@ export class Identity {
223
220
  }
224
221
 
225
222
  /**
226
- * Seal a message to an identity's Ed25519 public key (sealed box over the
227
- * curve25519 conversion). Only the holder of the matching secret key —
228
- * i.e. any of that identity's devices — can open it.
223
+ * Seal a message to an identity's Ed25519 public key (sealed box over the curve25519
224
+ * conversion).
229
225
  *
230
226
  * @param {Uint8Array} publicKey
231
227
  * @param {Uint8Array} message
@@ -248,7 +244,7 @@ export class Identity {
248
244
  const publicKey = b4a.alloc(sodium.crypto_sign_PUBLICKEYBYTES)
249
245
  const secretKey = b4a.alloc(sodium.crypto_sign_SECRETKEYBYTES)
250
246
  sodium.crypto_sign_keypair(publicKey, secretKey)
251
- return { publicKey, secretKey, id: toId(publicKey) }
247
+ return { publicKey, secretKey, id: hid.encode(publicKey) }
252
248
  }
253
249
 
254
250
  /**
package/src/index.js CHANGED
@@ -8,17 +8,13 @@
8
8
  */
9
9
 
10
10
  export * from './identity/index.js'
11
- // `database`, `pairing` and `pairing/invite` declare a few generically-named
12
- // result/option typedefs (`Ref`, `SingleResult`, `ListResult`,
13
- // `CreateInviteOpts`) that also exist on `storage`/`pairing`. Re-export the
14
- // lower-level modules' colliding names under namespaced aliases so the barrel
15
- // stays unambiguous while the canonical (`database`/`pairing`) versions own the
16
- // bare names.
11
+ // colliding typedef names from storage and pairing are re-exported under aliases
17
12
  export { Storage } from './storage/index.js'
18
13
  /**
19
- * `Ref` / `SingleResult` / `ListResult` are JSDoc typedefs (types, not runtime exports), so they
20
- * are re-exported as namespaced type aliases — `export { Ref as StorageRef }` fails at import
21
- * because the module provides no runtime `Ref` export.
14
+ * `Ref` / `SingleResult` / `ListResult` are JSDoc typedefs (types, not runtime exports),
15
+ * so they are re-exported as namespaced type aliases — `export { Ref as StorageRef }`
16
+ * fails at import because the.
17
+ *
22
18
  * @typedef {import('./storage/index.js').Ref} StorageRef
23
19
  * @typedef {import('./storage/index.js').SingleResult} StorageSingleResult
24
20
  * @typedef {import('./storage/index.js').ListResult} StorageListResult
@@ -1,24 +1,19 @@
1
- // Schema kinds
2
1
  export const SINGLE = 'single'
3
2
  export const COLLECTION = 'collection'
4
3
  export const HANDLE = 'handle'
5
4
  export const ACTION = 'action'
6
5
 
7
- // Network topic modes
8
6
  export const ACTIVE = 'active'
9
7
  export const PASSIVE = 'passive'
10
8
 
11
- // Storage backends
12
9
  export const ROCKS = 'rocks'
13
10
  export const BEE = 'bee'
14
11
 
15
- // Roles
16
12
  export const OWNER = 'owner'
17
13
  export const ADMIN = 'admin'
18
14
  export const MEMBER = 'member'
19
15
  export const READER = 'reader'
20
16
 
21
- // Permissions
22
17
  export const READ = 'read'
23
18
  export const WRITE = 'write'
24
19
  export const DELETE = 'delete'
@@ -26,7 +21,6 @@ export const INVITE = 'invite'
26
21
  export const REMOVE = 'remove'
27
22
  export const ASSIGN = 'assign'
28
23
 
29
- // Default role → permissions
30
24
  export const ROLE_PERMS = {
31
25
  [OWNER]: ['*'],
32
26
  [ADMIN]: [READ, WRITE, DELETE, INVITE, REMOVE, ASSIGN],
@@ -34,14 +28,11 @@ export const ROLE_PERMS = {
34
28
  [READER]: [READ]
35
29
  }
36
30
 
37
- // Role ordering (higher = more authority)
38
31
  export const RANK = { [OWNER]: 3, [ADMIN]: 2, [MEMBER]: 1, [READER]: 0 }
39
32
 
40
- // Identity / hypercore namespace
41
33
  export const NAMESPACE = 'cero'
42
34
 
43
- // Query-grammar keys — everything else in a query object is an equality field.
44
- // One set shared by both backends (Database and Storage) so they cannot drift.
35
+ // everything else in a query is an equality field; shared so both backends agree
45
36
  export const QUERY_RESERVED = new Set([
46
37
  'gt',
47
38
  'gte',
@@ -54,7 +45,7 @@ export const QUERY_RESERVED = new Set([
54
45
  'total'
55
46
  ])
56
47
 
57
- // Internal counter collection (assigns monotonic `index` to every row in every collection)
48
+ // monotonic index per collection
58
49
  export const COUNTERS = 'counters'
59
- // Internal key-rotation epoch collection (rotation announcements with sealed envelopes)
50
+ // rotation announcements
60
51
  export const EPOCHS = 'epochs'
package/src/lib/errors.js CHANGED
@@ -1,7 +1,6 @@
1
1
  /**
2
- * Canonical error class. Every instance carries a stable `code` field which
3
- * is also prefixed to the message, so logs stay self-identifying. Static
4
- * factories produce errors with the right code + a sensible message.
2
+ * Canonical error class. Every instance carries a stable `code` field which is also
3
+ * prefixed to the message, so logs stay self-identifying.
5
4
  */
6
5
  export class CeroError extends Error {
7
6
  /**
@@ -56,9 +55,7 @@ export class CeroError extends Error {
56
55
  return new CeroError('CLOSED', `${resource} is closed`)
57
56
  }
58
57
  /**
59
- * A channel-stamped storage was opened under a different channel. Deliberately
60
- * does NOT name the stored channel — that label gates the network, so leaking it
61
- * in an error would hint at a realm the caller isn't on.
58
+ * A channel-stamped storage was opened under a different channel.
62
59
  */
63
60
  static CHANNEL_MISMATCH() {
64
61
  return new CeroError('CHANNEL_MISMATCH', 'storage belongs to a different channel')
@@ -148,10 +145,9 @@ export class CeroError extends Error {
148
145
  return new CeroError('DENIED', msg, { reason })
149
146
  }
150
147
  /**
151
- * An apply-time rule refused the op. Every peer reaches this verdict from the
152
- * same node and the same view, so it aborts the writer's whole batch — which
153
- * is what makes a transaction atomic. Reserve it for deterministic decisions:
154
- * anything that could differ between peers must not abort, or they fork.
148
+ * An apply-time rule refused the op. Every peer reaches this verdict from the same node
149
+ * and the same view, so it aborts the writer's whole batch — which is what makes a
150
+ * transaction atomic.
155
151
  *
156
152
  * @param {string} rule Which rule refused, e.g. 'write' or 'own'.
157
153
  * @param {string} [msg]
package/src/lib/schema.js CHANGED
@@ -46,11 +46,8 @@ export const t = {
46
46
  },
47
47
 
48
48
  /**
49
- * Multi-row table keyed by `id`.
50
- *
51
- * `own` restricts a row to the member who wrote it — anyone may add rows, but
52
- * only the author changes or deletes theirs. Members holding REMOVE can still
53
- * moderate. Without it a writer may edit any row in the collection.
49
+ * Multi-row table keyed by `id`. `own` restricts a row to the member who wrote it — anyone
50
+ * may add rows, but only the author changes or deletes theirs.
54
51
  *
55
52
  * @param {Record<string, Prim>} fields
56
53
  * @param {{ indexes?: Record<string, string[]>, own?: boolean }} [opts]