@cero-base/core 1.18.1 → 1.19.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 (46) hide show
  1. package/README.md +5 -6
  2. package/package.json +9 -9
  3. package/src/blobs/index.js +2 -2
  4. package/src/database/changes.js +37 -59
  5. package/src/database/dispatch.js +31 -45
  6. package/src/database/index.js +395 -343
  7. package/src/database/rotation.js +201 -189
  8. package/src/identity/index.js +3 -3
  9. package/src/lib/utils.js +50 -18
  10. package/src/pairing/candidate.js +125 -0
  11. package/src/pairing/index.js +6 -223
  12. package/src/pairing/request.js +102 -0
  13. package/src/storage/index.js +11 -18
  14. package/types/blobs/codec.d.ts +8 -8
  15. package/types/blobs/index.d.ts +34 -33
  16. package/types/blobs/server.d.ts +8 -8
  17. package/types/database/changes.d.ts +5 -7
  18. package/types/database/dispatch.d.ts +30 -23
  19. package/types/database/encryption.d.ts +14 -10
  20. package/types/database/envelope.d.ts +2 -2
  21. package/types/database/index.d.ts +173 -181
  22. package/types/database/rotation.d.ts +53 -30
  23. package/types/identity/index.d.ts +81 -81
  24. package/types/index.d.ts +37 -51
  25. package/types/lib/constants.d.ts +34 -38
  26. package/types/lib/errors.d.ts +10 -10
  27. package/types/lib/schema.d.ts +47 -37
  28. package/types/lib/spec/index.d.ts +29 -55
  29. package/types/lib/utils.d.ts +27 -17
  30. package/types/network/discovery.d.ts +7 -7
  31. package/types/network/index.d.ts +50 -48
  32. package/types/pairing/candidate.d.ts +37 -0
  33. package/types/pairing/index.d.ts +87 -139
  34. package/types/pairing/invite.d.ts +88 -88
  35. package/types/pairing/request.d.ts +135 -0
  36. package/types/rpc/client.d.ts +2 -2
  37. package/types/rpc/index.d.ts +33 -33
  38. package/types/rpc/peer.d.ts +9 -7
  39. package/types/rpc/server.d.ts +2 -2
  40. package/types/storage/index.d.ts +70 -68
  41. package/src/database/bootstrap.js +0 -133
  42. package/src/database/hooks.js +0 -112
  43. package/src/database/membership.js +0 -67
  44. package/types/database/bootstrap.d.ts +0 -20
  45. package/types/database/hooks.d.ts +0 -8
  46. package/types/database/membership.d.ts +0 -7
@@ -1,228 +1,240 @@
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 {
12
+ /**
13
+ * Epoch key rotation for a database: mint a secret, seal it to every member,
14
+ * announce it through the log, and on every peer learn the secrets addressed
15
+ * to it. A debounced audit re-keys when the current epoch's recipients drift
16
+ * from the member set.
17
+ */
18
+ export class Rotation {
19
+ /** @param {import('./index.js').Database} db */
20
+ constructor(db) {
21
+ this.db = db
22
+ this.current = null
23
+ this._timer = null
24
+ this._healedFor = null
25
+ }
26
+
27
+ close() {
28
+ clearTimeout(this._timer)
29
+ this._timer = null
30
+ }
31
+
32
+ /** @returns {Promise<{ epoch: number }>} */
33
+ rotate() {
34
+ return this._rotate(false)
35
+ }
36
+
37
+ async _rotate(retried) {
38
+ const db = this.db
39
+ db.guard()
40
+ if (!db.writable) throw CeroError.NOT_WRITABLE('Database')
41
+ if (this.current) throw CeroError.INVALID('a rotation is already in progress')
42
+ // manifest v1 blocks carry no key id, rotating there is a silent downgrade
43
+ if (db.bee.local.manifest?.version < 2) {
44
+ throw CeroError.INVALID('rotation requires manifest v2 cores')
45
+ }
46
+ // claimed synchronously, no await may separate the check from the claim. The
47
+ // keyring learns the secret only after the announcement flushed: blocks are
48
+ // encrypted at drain time, so advancing it now seals the announcement to itself
24
49
  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)
50
+ const stamp = this._mint()
51
+ this.current = { entropy, stamp, epoch: 0 }
52
+ try {
53
+ const wrapped = this._seal(await this._members(), entropy)
54
+ const epoch = await this._announce(stamp, entropy, wrapped)
55
+ if (!epoch) {
56
+ // a stamp collision (~2^-32, or an adversarial pre-claim) is not a refusal
57
+ if (!retried && (await this._taken(stamp))) {
58
+ this.current = null
59
+ return this._rotate(true)
60
+ }
61
+ // permission is refused before the append, so the dry-run missed something
62
+ throw CeroError.INVALID('rotation was not applied')
33
63
  }
34
- // permission is refused before the append, so the dry-run missed something
35
- throw CeroError.INVALID('rotation was not applied')
64
+ db.keyring.add(stamp, entropy, epoch)
65
+ await this._save()
66
+ return { epoch }
67
+ } finally {
68
+ this.current = null
36
69
  }
37
- db.keyring.add(stamp, entropy, epoch)
38
- await saveEpochs(db)
39
- return { epoch }
40
- } finally {
41
- db._rotation = null
42
70
  }
43
- }
44
71
 
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')
72
+ async _members() {
73
+ const { data: members } = await this.db.get('members')
74
+ if (!Array.isArray(members) || members.length === 0) {
75
+ throw CeroError.INVALID('cannot rotate a database with no members')
76
+ }
77
+ return members
49
78
  }
50
- return members
51
- }
52
79
 
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}`)
80
+ // one sealed copy of the secret per member, addressed by member id
81
+ _seal(members, entropy) {
82
+ return members.map((m) => {
83
+ let key
84
+ try {
85
+ key = hid.decode(m.id)
86
+ } catch {
87
+ throw CeroError.INVALID(`member id is not an identity key: ${m.id}`)
88
+ }
89
+ return { id: m.id, box: Identity.seal(key, entropy) }
90
+ })
91
+ }
92
+
93
+ // append the announcement under the current epoch and wait for its apply;
94
+ // resolves the sequence apply assigned, 0 if it never applied
95
+ async _announce(stamp, entropy, wrapped) {
96
+ const { bee } = this.db
97
+ const from = bee.local.length
98
+ await this.db.call('rotate-key', {
99
+ epoch: 0, // sequence assigned deterministically at apply time
100
+ stamp,
101
+ wrapped: c.encode(wraps, wrapped),
102
+ createdAt: Date.now(),
103
+ commit: crypto.hash(entropy)
104
+ })
105
+ await bee.update()
106
+ // a block appended during a rotation must not carry the stamp it announces
107
+ for (let i = from; i < bee.local.length; i++) {
108
+ if (stampOf(await bee.local.get(i, { raw: true })) === stamp) {
109
+ throw CeroError.INVALID('announcement encrypted under its own epoch — aborting rotation')
110
+ }
61
111
  }
62
- return { id: m.id, box: Identity.seal(key, entropy) }
63
- })
64
- }
112
+ return this.current.epoch
113
+ }
65
114
 
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')
115
+ // a fresh nonzero stamp no known epoch uses
116
+ _mint() {
117
+ for (;;) {
118
+ const stamp = b4a.readUInt32LE(Identity.randomBytes(4), 0)
119
+ if (stamp !== 0 && !this.db.keyring.entropy(stamp)) return stamp
88
120
  }
89
121
  }
90
- return db._rotation.epoch
91
- }
92
122
 
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
- }
123
+ async _taken(stamp) {
124
+ return (await this._epochs()).some((r) => r.stamp === stamp)
125
+ }
97
126
 
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
127
+ _epochs() {
128
+ return this.db.view.find(`@${this.db.ns}/epochs`, {}).toArray()
104
129
  }
105
- }
106
130
 
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
132
- }
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)
131
+ /**
132
+ * An applied rotation announcement: open our envelope, learn the secret,
133
+ * persist it. Removed members have no envelope and stop here, every block
134
+ * after the announcement is noise to them. Our own in-flight rotation is left
135
+ * to `rotate()`, which adds the secret once the announcement flushed.
136
+ *
137
+ * @param {{ epoch: number, stamp: number, wrapped: Uint8Array, commit: Uint8Array }} row
138
+ */
139
+ async learn(row) {
140
+ const { keyring } = this.db
141
+ const known = keyring.entropy(row.stamp)
142
+ const entropy = known || this._unseal(row)
143
+ if (known) {
144
+ keyring.add(row.stamp, known, row.epoch) // re-applied, the sequence may be news
145
+ } else if (this.current && entropy && b4a.equals(entropy, this.current.entropy)) {
146
+ this.current.epoch = row.epoch
147
+ } else if (entropy) {
148
+ keyring.add(row.stamp, entropy, row.epoch)
137
149
  try {
138
- await saveEpochs(db)
150
+ await this._save()
139
151
  } catch (err) {
140
152
  // an epoch we cannot reload after a restart must not be used for writes
141
- db.keyring.remove(row.stamp)
142
- db._onerror(err)
153
+ keyring.remove(row.stamp)
154
+ this.db._onerror(err)
143
155
  }
144
156
  }
145
- break
157
+ this.heal()
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
+ // our envelope's secret, or null. A bad envelope ahead of a good one must not
161
+ // lock us out, so every one addressed to us is tried
162
+ _unseal(row) {
163
+ const { identity } = this.db
164
+ for (const w of c.decode(wraps, row.wrapped)) {
165
+ if (w.id !== identity.id) continue
166
+ const entropy = identity.unseal(w.box)
167
+ if (entropy?.byteLength !== 32) continue
168
+ // a secret failing the row's commitment means the rotator sealed different ones
169
+ if (row.commit && b4a.equals(crypto.hash(entropy), row.commit)) return entropy
170
+ this.db._onerror(CeroError.INVALID(`epoch ${row.epoch} envelope fails its commitment`))
161
171
  }
162
- } catch {
163
- // pre-rotation spec, or rows past our newest epoch, which hydrate via apply
172
+ return null
164
173
  }
165
- }
166
174
 
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
- }
175
+ /**
176
+ * Safety net after boot: an epoch applied but never saved, e.g. a crash
177
+ * between a rotation's append and its save, is learned from the epochs
178
+ * collection.
179
+ */
180
+ async hydrate() {
181
+ try {
182
+ for (const row of await this._epochs()) {
183
+ if (!this.db.keyring.entropy(row.stamp)) await this.learn(row)
184
+ }
185
+ } catch {
186
+ // pre-rotation spec, or rows past our newest epoch, which hydrate via apply
187
+ }
188
+ }
171
189
 
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
- }
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
+ }
180
195
 
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()
196
+ /** Debounced audit, run after every update. */
197
+ heal() {
198
+ const db = this.db
199
+ if (this._timer || db.closing || db.closed) return
200
+ this._timer = setTimeout(() => {
201
+ this._timer = null
202
+ this._audit().catch(db._onerror)
203
+ }, 500)
204
+ }
205
+
206
+ // Convergence rotation: a rotation seals for the rotator's possibly stale
207
+ // view of the members, so after linearization the current epoch may include
208
+ // a since-removed member (who still holds the key) or miss a since-added one
209
+ // (who is locked out). Every REMOVE-capable writable device compares the
210
+ // current epoch's recipients with the members and re-keys on mismatch. Only
211
+ // databases that rotated at least once are audited, rotation stays opt-in
212
+ async _audit() {
213
+ const db = this.db
214
+ if (db.closing || db.closed || !db.writable || this.current || !db.keyring.current) return
215
+ const { data: device } = await db.get('devices', hid.encode(db.writerKey))
216
+ const me = device?.memberId ? (await db.get('members', device.memberId)).data : null
217
+ if (!can(me?.role, REMOVE)) return
218
+
219
+ const rows = await this._epochs()
220
+ if (!rows.length) return
221
+ const top = rows.reduce((a, b) => (b.epoch > a.epoch ? b : a))
222
+ const recipients = new Set(c.decode(wraps, top.wrapped).map((w) => w.id))
223
+ const { data: members } = await db.get('members')
224
+ const ids = new Set(members.map((m) => m.id))
225
+ if (recipients.size === ids.size && [...recipients].every((id) => ids.has(id))) {
226
+ this._healedFor = null
227
+ return
228
+ }
229
+ // one attempt per (epoch, membership) state, a failing rotate must not loop
230
+ const state = `${top.stamp}:${[...ids].sort().join(',')}`
231
+ if (this._healedFor === state) return
232
+ this._healedFor = state
233
+ await this.rotate()
234
+ }
213
235
  }
214
236
 
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)
237
+ // the epoch stamp autobee-encryption writes into every block header
238
+ function stampOf(raw) {
239
+ return b4a.readUInt32LE(raw, 4)
228
240
  }
@@ -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
 
@@ -26,7 +26,7 @@ export class Identity {
26
26
  *
27
27
  * @type {string}
28
28
  */
29
- this.id = toId(keys.publicKey)
29
+ this.id = hid.encode(keys.publicKey)
30
30
  /** @type {Uint8Array} */
31
31
  this.publicKey = keys.publicKey
32
32
  /** @type {Uint8Array} */
@@ -248,7 +248,7 @@ export class Identity {
248
248
  const publicKey = b4a.alloc(sodium.crypto_sign_PUBLICKEYBYTES)
249
249
  const secretKey = b4a.alloc(sodium.crypto_sign_SECRETKEYBYTES)
250
250
  sodium.crypto_sign_keypair(publicKey, secretKey)
251
- return { publicKey, secretKey, id: toId(publicKey) }
251
+ return { publicKey, secretKey, id: hid.encode(publicKey) }
252
252
  }
253
253
 
254
254
  /**
package/src/lib/utils.js CHANGED
@@ -2,9 +2,8 @@ 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
8
  // the capability names travel with can(): a caller cannot ask `can(role, REMOVE)`
10
9
  // without them, and constants.js is not a public subpath
@@ -19,20 +18,6 @@ export function genId() {
19
18
  return z32.encode(crypto.randomBytes(16))
20
19
  }
21
20
 
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
21
  // Domain-separated payloads for writer-admission signatures. Binding the db
37
22
  // key makes an admission unreplayable across rooms; the tag pins the format.
38
23
  // v2 — pre-1.2 signatures (writer‖appender / bare writer) no longer verify.
@@ -40,12 +25,12 @@ const ADD_WRITER_TAG = b4a.from('cero/add-writer/v2')
40
25
  const CLAIM_WRITER_TAG = b4a.from('cero/claim-writer/v2')
41
26
 
42
27
  /** @type {(dbKey: Uint8Array, writer: Uint8Array, appender: Uint8Array) => Uint8Array} */
43
- export function addWriterPayload(dbKey, writer, appender) {
28
+ export function admission(dbKey, writer, appender) {
44
29
  return b4a.concat([ADD_WRITER_TAG, dbKey, writer, appender])
45
30
  }
46
31
 
47
32
  /** @type {(dbKey: Uint8Array, writer: Uint8Array) => Uint8Array} */
48
- export function claimWriterPayload(dbKey, writer) {
33
+ export function ownership(dbKey, writer) {
49
34
  return b4a.concat([CLAIM_WRITER_TAG, dbKey, writer])
50
35
  }
51
36
 
@@ -152,3 +137,50 @@ export function searchHit(row, term, fields) {
152
137
  const hay = keys.map((k) => (typeof row[k] === 'string' ? fold(row[k]) : '')).join(' ')
153
138
  return terms.every((t) => hay.includes(t))
154
139
  }
140
+
141
+ /**
142
+ * The in-memory query grammar over rows: equality on any non-reserved field,
143
+ * id ranges, `search`, then `reverse` and `limit`.
144
+ *
145
+ * @param {any[]} rows
146
+ * @param {Record<string, any>} [query]
147
+ * @returns {any[]}
148
+ */
149
+ export function filter(rows, query) {
150
+ if (!query) return rows
151
+ let out = rows
152
+ for (const key of Object.keys(query)) {
153
+ if (QUERY_RESERVED.has(key)) continue
154
+ out = out.filter((r) => valueEq(r[key], query[key]))
155
+ }
156
+ if (query.gt !== undefined) out = out.filter((r) => r.id > query.gt)
157
+ if (query.gte !== undefined) out = out.filter((r) => r.id >= query.gte)
158
+ if (query.lt !== undefined) out = out.filter((r) => r.id < query.lt)
159
+ if (query.lte !== undefined) out = out.filter((r) => r.id <= query.lte)
160
+ if (query.search) out = out.filter((r) => searchHit(r, query.search, query.fields))
161
+ if (query.reverse) out = [...out].reverse()
162
+ if (query.limit !== undefined) out = out.slice(0, query.limit)
163
+ return out
164
+ }
165
+
166
+ function valueEq(a, b) {
167
+ if (a instanceof Uint8Array && b instanceof Uint8Array) return b4a.equals(a, b)
168
+ return a === b
169
+ }
170
+
171
+ /**
172
+ * Run `cb` when `signal` aborts — or immediately if it already has. No-op
173
+ * without a signal. The listener removes itself on fire. Returns a disposer that
174
+ * detaches the listener early, so a manual unsubscribe doesn't leave it lingering
175
+ * on a long-lived signal.
176
+ *
177
+ * @param {AbortSignal | undefined} signal
178
+ * @param {() => void} cb
179
+ * @returns {(() => void) | undefined}
180
+ */
181
+ export function onAbort(signal, cb) {
182
+ if (!signal) return
183
+ if (signal.aborted) return void cb()
184
+ signal.addEventListener('abort', cb, { once: true })
185
+ return () => signal.removeEventListener('abort', cb)
186
+ }