@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
@@ -5,7 +5,7 @@ import hid from 'hypercore-id-encoding'
5
5
 
6
6
  import { REMOVE } from '../lib/constants.js'
7
7
  import { can } from '../lib/utils.js'
8
- import { wraps, epochEntries } from './encryption.js'
8
+ import { wraps, epochEntries, seal, opened } from './encryption.js'
9
9
  import { Identity } from '../identity/index.js'
10
10
  import { CeroError } from '../lib/errors.js'
11
11
 
@@ -18,7 +18,11 @@ export class Rotation {
18
18
  constructor(db) {
19
19
  this.db = db
20
20
  this.current = null
21
+ /** @private */
22
+ this._queue = Promise.resolve()
23
+ /** @private */
21
24
  this._timer = null
25
+ /** @private */
22
26
  this._healedFor = null
23
27
  }
24
28
 
@@ -27,9 +31,16 @@ export class Rotation {
27
31
  this._timer = null
28
32
  }
29
33
 
30
- /** @returns {Promise<{ epoch: number }>} */
34
+ /**
35
+ * One at a time: a rotation asked for during another runs after it, sealed to the members as
36
+ * they stand then.
37
+ *
38
+ * @returns {Promise<{ epoch: number }>}
39
+ */
31
40
  rotate() {
32
- return this._rotate(false)
41
+ const run = this._queue.catch(() => {}).then(() => this._rotate(false))
42
+ this._queue = run
43
+ return run
33
44
  }
34
45
 
35
46
  /**
@@ -82,11 +93,11 @@ export class Rotation {
82
93
  }, 500)
83
94
  }
84
95
 
96
+ /** @private */
85
97
  async _rotate(retried) {
86
98
  const db = this.db
87
99
  db.guard()
88
100
  if (!db.writable) throw CeroError.NOT_WRITABLE('Database')
89
- if (this.current) throw CeroError.INVALID('a rotation is already in progress')
90
101
  // manifest v1 blocks carry no key id, rotating there is a silent downgrade
91
102
  if (db.bee.local.manifest?.version < 2) {
92
103
  throw CeroError.INVALID('rotation requires manifest v2 cores')
@@ -96,7 +107,7 @@ export class Rotation {
96
107
  const stamp = this._mint()
97
108
  this.current = { entropy, stamp, epoch: 0 }
98
109
  try {
99
- const wrapped = this._seal(await this._members(), entropy)
110
+ const wrapped = seal(await this._members(), entropy)
100
111
  const epoch = await this._announce(stamp, entropy, wrapped)
101
112
  if (!epoch) {
102
113
  // a stamp collision (~2^-32, or an adversarial pre-claim) is not a refusal
@@ -115,6 +126,7 @@ export class Rotation {
115
126
  }
116
127
  }
117
128
 
129
+ /** @private */
118
130
  async _members() {
119
131
  const { data: members } = await this.db.get('members')
120
132
  if (!Array.isArray(members) || members.length === 0) {
@@ -123,20 +135,8 @@ export class Rotation {
123
135
  return members
124
136
  }
125
137
 
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
130
- try {
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
138
  // resolves the sequence apply assigned, 0 if it never applied
139
+ /** @private */
140
140
  async _announce(stamp, entropy, wrapped) {
141
141
  const { bee } = this.db
142
142
  const from = bee.local.length
@@ -158,6 +158,7 @@ export class Rotation {
158
158
  }
159
159
 
160
160
  // a fresh nonzero stamp no known epoch uses
161
+ /** @private */
161
162
  _mint() {
162
163
  for (;;) {
163
164
  const stamp = b4a.readUInt32LE(Identity.randomBytes(4), 0)
@@ -165,21 +166,21 @@ export class Rotation {
165
166
  }
166
167
  }
167
168
 
169
+ /** @private */
168
170
  async _taken(stamp) {
169
171
  return (await this._epochs()).some((r) => r.stamp === stamp)
170
172
  }
171
173
 
174
+ /** @private */
172
175
  _epochs() {
173
176
  return this.db.view.find(`@${this.db.ns}/epochs`, {}).toArray()
174
177
  }
175
178
 
176
179
  // every envelope addressed to us is tried, a bad one must not lock us out
180
+ /** @private */
177
181
  _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
182
+ for (const entropy of opened(this.db.identity, row.wrapped)) {
183
+ if (entropy.byteLength !== 32) continue
183
184
  // a secret failing the row's commitment means the rotator sealed different ones
184
185
  if (row.commit && b4a.equals(crypto.hash(entropy), row.commit)) return entropy
185
186
  this.db._onerror(CeroError.INVALID(`epoch ${row.epoch} envelope fails its commitment`))
@@ -188,39 +189,51 @@ export class Rotation {
188
189
  }
189
190
 
190
191
  // known epoch secrets to local userData (device-only, never replicates)
192
+ /** @private */
191
193
  _save() {
192
194
  const entries = c.encode(epochEntries, this.db.keyring.all())
193
195
  return this.db.bee.local.setUserData('cero/epochs', entries)
194
196
  }
195
197
 
196
198
  // 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
199
+ // when the current epoch's recipients drift from the member list, or when its envelope
200
+ // for them does not open: a rotator must not seal anyone who could heal it out
201
+ /** @private */
198
202
  async _audit() {
199
203
  const db = this.db
200
- if (db.closing || db.closed || !db.writable || this.current || !db.keyring.current) return
204
+ if (db.closing || db.closed || !db.writable || this.current) return
201
205
  const { data: device } = await db.get('devices', hid.encode(db.writerKey))
202
206
  const me = device?.memberId ? (await db.get('members', device.memberId)).data : null
203
207
  if (!can(me?.role, REMOVE)) return
204
208
 
205
209
  const rows = await this._epochs()
206
- if (!rows.length) return
210
+ // a room still on its creation key re-keys at its first removal
211
+ if (!rows.length) {
212
+ if (await db.view.findOne(`@${db.ns}/removals`, {})) await this._heal('first removal')
213
+ return
214
+ }
207
215
  const top = rows.reduce((a, b) => (b.epoch > a.epoch ? b : a))
208
216
  const recipients = new Set(c.decode(wraps, top.wrapped).map((w) => w.id))
209
217
  const { data: members } = await db.get('members')
210
218
  const ids = new Set(members.map((m) => m.id))
211
- if (recipients.size === ids.size && [...recipients].every((id) => ids.has(id))) {
219
+ const sealedOut = !db.keyring.entropy(top.stamp)
220
+ if (!sealedOut && recipients.size === ids.size && [...recipients].every((id) => ids.has(id))) {
212
221
  this._healedFor = null
213
222
  return
214
223
  }
215
- // one attempt per (epoch, membership) state, a failing rotate must not loop
216
- const state = `${top.stamp}:${[...ids].sort().join(',')}`
224
+ await this._heal(`${top.stamp}:${[...ids].sort().join(',')}`)
225
+ }
226
+
227
+ // one attempt per (epoch, membership) state, a failing rotate must not loop
228
+ /** @private */
229
+ async _heal(state) {
217
230
  if (this._healedFor === state) return
218
231
  this._healedFor = state
219
232
  await this.rotate()
220
233
  }
221
234
  }
222
235
 
223
- // the epoch stamp autobee-encryption writes into every block header
236
+ // the epoch stamp autobee's encryption writes into every block header
224
237
  function stampOf(raw) {
225
238
  return b4a.readUInt32LE(raw, 4)
226
239
  }
@@ -111,67 +111,42 @@ export class Identity {
111
111
  * @returns {string}
112
112
  */
113
113
  toPhrase() {
114
- return bip39.entropyToMnemonic(this.seed)
114
+ return Identity.toPhrase(this.seed)
115
115
  }
116
116
 
117
117
  /**
118
- * Build an identity from 16- or 32-byte entropy.
118
+ * An identity from its seed, 16 or 32 bytes; a fresh one without.
119
119
  *
120
- * @param {Uint8Array} seed
120
+ * @param {{ seed?: Uint8Array | null, words?: 12 | 24 }} [opts] `words` sizes a fresh one.
121
121
  * @returns {Promise<Identity>}
122
122
  */
123
- static async fromSeed(seed) {
124
- if (!Identity.isSeed(seed)) throw CeroError.INVALID('seed must be a 16- or 32-byte buffer')
125
- const mnemonic = bip39.entropyToMnemonic(seed)
126
- const id = await IdentityKey.from({ mnemonic })
123
+ static async create({ seed = null, words = 12 } = {}) {
124
+ seed ??= randomSeed(words)
125
+ if (!b4a.isBuffer(seed) || (seed.byteLength !== 16 && seed.byteLength !== 32)) {
126
+ throw CeroError.INVALID('seed must be 16 or 32 bytes')
127
+ }
128
+ const id = await IdentityKey.from({ mnemonic: bip39.entropyToMnemonic(seed) })
127
129
  const { publicKey, secretKey } = id.identityKeyPair
128
130
  const encryptionKey = id.keyChain.getSymmetricKey([...DERIVE_PATH, 'encryption'])
129
131
  return new Identity({ publicKey, secretKey, encryptionKey, seed })
130
132
  }
131
133
 
132
134
  /**
133
- * Build an identity from a BIP-39 mnemonic.
134
- *
135
- * @param {string} phrase
136
- * @returns {Promise<Identity>}
137
- */
138
- static async fromPhrase(phrase) {
139
- if (!Identity.isPhrase(phrase)) throw CeroError.INVALID('phrase must be a valid BIP39 mnemonic')
140
- return Identity.fromSeed(bip39.mnemonicToEntropy(phrase))
141
- }
142
-
143
- /**
144
- * Generate a fresh identity from CSPRNG entropy.
145
- *
146
- * @param {{ words?: 12 | 24 }} [opts]
147
- * @returns {Promise<Identity>}
148
- */
149
- static async generate({ words = 12 } = {}) {
150
- return Identity.fromSeed(Identity.randomSeed(words))
151
- }
152
-
153
- /**
154
- * Generate a random BIP-39 mnemonic.
155
- *
156
- * @param {12 | 24} [words]
157
- * @returns {string}
158
- */
159
- static genPhrase(words = 12) {
160
- return bip39.entropyToMnemonic(Identity.randomSeed(words))
161
- }
162
-
163
- /**
164
- * Phrase → seed entropy.
135
+ * The seed a BIP-39 phrase writes out.
165
136
  *
166
137
  * @param {string} phrase
167
138
  * @returns {Uint8Array}
168
139
  */
169
140
  static toSeed(phrase) {
170
- return bip39.mnemonicToEntropy(phrase)
141
+ try {
142
+ return bip39.mnemonicToEntropy(phrase)
143
+ } catch {
144
+ throw CeroError.INVALID('phrase must be a BIP-39 mnemonic')
145
+ }
171
146
  }
172
147
 
173
148
  /**
174
- * Seed entropy → phrase.
149
+ * A seed written out as a BIP-39 phrase.
175
150
  *
176
151
  * @param {Uint8Array} seed
177
152
  * @returns {string}
@@ -180,33 +155,6 @@ export class Identity {
180
155
  return bip39.entropyToMnemonic(seed)
181
156
  }
182
157
 
183
- /**
184
- * Validate that a value is a 16- or 32-byte buffer.
185
- *
186
- * @param {any} x
187
- * @returns {x is Uint8Array}
188
- */
189
- static isSeed(x) {
190
- if (!b4a.isBuffer(x)) return false
191
- return x.length === 16 || x.length === 32
192
- }
193
-
194
- /**
195
- * Validate that a string is a BIP-39 mnemonic.
196
- *
197
- * @param {unknown} x
198
- * @returns {x is string}
199
- */
200
- static isPhrase(x) {
201
- if (typeof x !== 'string') return false
202
- try {
203
- bip39.mnemonicToEntropy(x)
204
- return true
205
- } catch {
206
- return false
207
- }
208
- }
209
-
210
158
  /**
211
159
  * Verify a signature against an arbitrary public key.
212
160
  *
@@ -258,17 +206,11 @@ export class Identity {
258
206
  sodium.randombytes_buf(buf)
259
207
  return buf
260
208
  }
209
+ }
261
210
 
262
- /**
263
- * Fresh seed entropy sized for the chosen mnemonic length.
264
- *
265
- * @param {12 | 24} [words]
266
- * @returns {Uint8Array}
267
- */
268
- static randomSeed(words = 12) {
269
- if (words !== 12 && words !== 24) throw CeroError.INVALID('words must be 12 or 24')
270
- return Identity.randomBytes((words / 3) * 4)
271
- }
211
+ function randomSeed(words) {
212
+ if (words !== 12 && words !== 24) throw CeroError.INVALID('words must be 12 or 24')
213
+ return Identity.randomBytes((words / 3) * 4)
272
214
  }
273
215
 
274
216
  function topicOf(publicKey) {
package/src/index.js CHANGED
@@ -11,28 +11,21 @@ export * from './identity/index.js'
11
11
  // colliding typedef names from storage and pairing are re-exported under aliases
12
12
  export { Storage } from './storage/index.js'
13
13
  /**
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.
14
+ * The database exports its `Ref` already, so storage's typedefs come under storage names; rows
15
+ * and results are the database's.
17
16
  *
18
17
  * @typedef {import('./storage/index.js').Ref} StorageRef
19
- * @typedef {import('./storage/index.js').SingleResult} StorageSingleResult
20
- * @typedef {import('./storage/index.js').ListResult} StorageListResult
21
18
  * @typedef {import('./storage/index.js').StorageOpts} StorageOpts
22
- * @typedef {import('./storage/index.js').StoredRow} StoredRow
23
- * @typedef {import('./storage/index.js').GetByIdResult} GetByIdResult
24
19
  */
25
20
  export * from './network/index.js'
26
21
  export * from './database/index.js'
27
22
  export * from './blobs/index.js'
28
23
  export * from './rpc/index.js'
24
+ export * from './mailbox/index.js'
29
25
  export * from './pairing/index.js'
30
26
  export { Invite } from './pairing/invite.js'
31
27
  /**
32
- * `CreateInviteOpts` is a typedef (not a runtime export); re-export it as a type alias.
33
- * @typedef {import('./pairing/invite.js').CreateInviteOpts} MintInviteOpts
34
28
  * @typedef {import('./pairing/invite.js').InviteFields} InviteFields
35
- * @typedef {import('./pairing/invite.js').ParseInviteOpts} ParseInviteOpts
36
29
  */
37
30
  export * from './lib/schema.js'
38
31
  export * from './lib/utils.js'
@@ -49,3 +49,5 @@ export const QUERY_RESERVED = new Set([
49
49
  export const COUNTERS = 'counters'
50
50
  // rotation announcements
51
51
  export const EPOCHS = 'epochs'
52
+ // removed members, with the last invite minted before their removal
53
+ export const REMOVALS = 'removals'
package/src/lib/errors.js CHANGED
@@ -23,7 +23,7 @@ export class CeroError extends Error {
23
23
  /**
24
24
  * Type-guard for `err instanceof CeroError` that survives realm boundaries.
25
25
  *
26
- * @param {any} err
26
+ * @param {unknown} err
27
27
  * @returns {err is CeroError}
28
28
  */
29
29
  static isCeroError(err) {
@@ -107,8 +107,8 @@ export class CeroError extends Error {
107
107
  *
108
108
  * @param {string} what
109
109
  */
110
- static TIMED_OUT(what) {
111
- return new CeroError('TIMED_OUT', `${what} timed out`)
110
+ static TIMEOUT(what) {
111
+ return new CeroError('TIMEOUT', `${what} timed out`)
112
112
  }
113
113
  /**
114
114
  * Feature is not yet implemented.
@@ -155,14 +155,6 @@ export class CeroError extends Error {
155
155
  static REFUSED(rule, msg = `refused by ${rule}`) {
156
156
  return new CeroError('REFUSED', msg, { rule })
157
157
  }
158
- /**
159
- * Pairing handshake did not complete in time.
160
- *
161
- * @param {string} [msg]
162
- */
163
- static TIMEOUT(msg = 'pairing timed out') {
164
- return new CeroError('TIMEOUT', msg)
165
- }
166
158
  /**
167
159
  * Underlying swarm/transport failure.
168
160
  *