@cero-base/core 2.7.0 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cero-base/core",
3
- "version": "2.7.0",
3
+ "version": "2.9.0",
4
4
  "description": "cero p2p primitives — identity, storage, network, database, blobs, rpc, pairing.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -152,26 +152,26 @@
152
152
  },
153
153
  "dependencies": {
154
154
  "@hyperswarm/secret-stream": "^6.9.2",
155
- "autobee": "2.12.1",
155
+ "autobee": "2.13.0",
156
156
  "b4a": "^1.9.0",
157
157
  "bare-crypto": "^1.15.4",
158
158
  "bare-fs": "^4.8.4",
159
159
  "bare-path": "^3.1.2",
160
160
  "bip39-mnemonic": "^2.5.0",
161
- "blind-peering": "^2.12.0",
161
+ "blind-peering": "^2.12.2",
162
162
  "blind-push": "^1.0.2",
163
163
  "compact-encoding": "^3.5.2",
164
164
  "corestore": "^7.16.1",
165
165
  "framed-stream": "^1.0.1",
166
166
  "hrpc": "^4.3.1",
167
167
  "hyperblobs": "^2.13.0",
168
- "hypercore": "^11.39.3",
168
+ "hypercore": "^11.39.6",
169
169
  "hypercore-blob-server": "^1.15.1",
170
170
  "hypercore-crypto": "^3.7.0",
171
171
  "hypercore-id-encoding": "^1.3.0",
172
- "hypercore-storage": "^3.3.1",
173
- "hyperdb": "^6.11.0",
174
- "hyperdht": "^6.34.1",
172
+ "hypercore-storage": "^3.4.0",
173
+ "hyperdb": "^6.11.1",
174
+ "hyperdht": "^6.35.0",
175
175
  "hyperdispatch": "^1.6.0",
176
176
  "hyperschema": "^1.26.2",
177
177
  "hyperswarm": "^4.17.2",
@@ -36,6 +36,10 @@ import { makeChanges } from './changes.js'
36
36
  import { makeDispatcher, BESPOKE } from './dispatch.js'
37
37
  import { keyPair } from '../mailbox/inbox.js'
38
38
 
39
+ // autobee remaps an older store once a recovery peer, a mirror, serves it; unset, it closes the store
40
+ const recovery = []
41
+ Hypercore.setRecoveryPeers(recovery)
42
+
39
43
  /**
40
44
  * @typedef {object} DatabaseOpts
41
45
  * @property {import('corestore')} store Corestore (or compatible) used to materialize the autobee.
@@ -99,6 +103,9 @@ export class Database extends ReadyResource {
99
103
  this.store = opts.store
100
104
  this.identity = opts.identity
101
105
  this.network = opts.network || null
106
+ for (const key of this.network?.mirrors || []) {
107
+ if (!recovery.some((k) => b4a.equals(k, key))) recovery.push(key)
108
+ }
102
109
  this.spec = opts.spec
103
110
  this.meta = opts.spec.meta || { ns: NAMESPACE, refs: {} }
104
111
  this.ns = this.meta.ns || NAMESPACE
@@ -107,6 +114,7 @@ export class Database extends ReadyResource {
107
114
  /** @type {number | null} */
108
115
  this.behind = null
109
116
  this.namespace = opts.namespace || NAMESPACE
117
+ this._writable = false
110
118
  this.encryptionKey = opts.encryptionKey
111
119
  this.keyring = new Keyring()
112
120
  if (opts.epochs) for (const e of opts.epochs) this.keyring.add(e.stamp, e.entropy, e.epoch)
@@ -186,7 +194,7 @@ export class Database extends ReadyResource {
186
194
 
187
195
  /** @returns {boolean} whether the bee accepts local writes */
188
196
  get writable() {
189
- return this.bee?.writable === true
197
+ return this._writable
190
198
  }
191
199
 
192
200
  /** @returns {number} number of ops in the local writer */
@@ -228,9 +236,13 @@ export class Database extends ReadyResource {
228
236
 
229
237
  // REMOVE-capable devices re-key when the epoch drifts from the member set
230
238
  this.on('update', () => this.rotation.heal())
231
- this.bee.on('writable', () => this.emit('writable'))
239
+ this._writable = this.bee.writable
240
+ this.bee.on('writable', () => this._onwritable())
232
241
  // falling edge: apps freeze the UI the moment access ends
233
- this.bee.on('unwritable', () => this.emit('unwritable'))
242
+ this.bee.on('unwritable', () => {
243
+ this._writable = false
244
+ this.emit('unwritable')
245
+ })
234
246
  // without a listener autobee escalates apply/view errors to a process crash
235
247
  this.bee.on('error', this._onerror)
236
248
 
@@ -417,6 +429,9 @@ export class Database extends ReadyResource {
417
429
  * @returns {Promise<void>}
418
430
  */
419
431
  async write(ops) {
432
+ // behind, a set merges from a view missing the newer writes and every device takes the stale
433
+ // row: no writes until the update, but leaving, which touches nothing else
434
+ if (this.behind !== null && !leaving(ops, this.identity.id)) throw CeroError.BEHIND(this.behind)
420
435
  if (this.txQueue) {
421
436
  for (const op of ops) this.txQueue.push(op)
422
437
  return
@@ -637,12 +652,11 @@ export class Database extends ReadyResource {
637
652
  */
638
653
  async whenWritable({ timeout = 30000 } = {}) {
639
654
  this.guard()
640
- const { bee } = this
641
- if (bee.writable) return
655
+ if (this.writable) return
642
656
  return new Promise((resolve, reject) => {
643
657
  const done = (err) => {
644
658
  clearTimeout(timer)
645
- bee.off('writable', done)
659
+ this.off('writable', done)
646
660
  this.off('close', onclose)
647
661
  if (err) reject(err)
648
662
  else resolve()
@@ -650,11 +664,25 @@ export class Database extends ReadyResource {
650
664
  const onclose = () => done(CeroError.CLOSED('Database'))
651
665
  const timer =
652
666
  timeout > 0 ? setTimeout(() => done(CeroError.TIMEOUT('whenWritable')), timeout) : null
653
- bee.once('writable', done)
667
+ this.once('writable', done)
654
668
  this.once('close', onclose)
655
669
  })
656
670
  }
657
671
 
672
+ // the bee flips writable inside the apply that admits this device, before that apply's view
673
+ // flush lands its row: writable here means the row is there to read
674
+ /** @private */
675
+ async _onwritable() {
676
+ try {
677
+ await this.bee.updated()
678
+ } catch {
679
+ return
680
+ }
681
+ if (this._writable || !this.bee.writable || this.closing || this.closed) return
682
+ this._writable = true
683
+ this.emit('writable')
684
+ }
685
+
658
686
  /**
659
687
  * Learn epochs handed over after the open, as a root carries them for a handle. One is kept
660
688
  * once its announcement applied here and the secret meets the commitment it carries: hand them
@@ -763,14 +791,22 @@ export class Database extends ReadyResource {
763
791
  await bee.update()
764
792
  }
765
793
 
766
- // ops skipped as too new apply once this version caught up: wipe the boot record and reboot
794
+ // ops skipped as too new apply once this version caught up, and a view whose definition grew
795
+ // since it was built (an index added by a rebuild) fills from the log: wipe the boot record and
796
+ // reboot
767
797
  /** @private */
768
798
  async _replay() {
769
- const behind = await this.bee.local.getUserData('cero/behind')
799
+ const local = this.bee.local
800
+ const behind = await local.getUserData('cero/behind')
770
801
  this.behind = behind ? c.decode(c.uint, behind) : null
771
- if (this.behind === null || this.behind > this.version) return false
772
- await this.bee.local.setUserData('autobee/head', null)
773
- await this.bee.local.setUserData('cero/behind', null)
802
+ const caught = this.behind !== null && this.behind <= this.version
803
+ const built = await local.getUserData('cero/view')
804
+ const { db } = this.spec.database.versions
805
+ const grown = !!built && c.decode(c.uint, built) < db
806
+ if (!built || grown) await local.setUserData('cero/view', c.encode(c.uint, db))
807
+ if (!caught && !grown) return false
808
+ await local.setUserData('autobee/head', null)
809
+ await local.setUserData('cero/behind', null)
774
810
  await this.bee.close()
775
811
  this.behind = null
776
812
  return true
@@ -204,7 +204,8 @@ export class Rotation {
204
204
  /** @private */
205
205
  async _audit() {
206
206
  const db = this.db
207
- if (db.closing || db.closed || !db.writable || this.current) return
207
+ // behind, the membership this device sees is stale: the devices that read everything re-key
208
+ if (db.closing || db.closed || !db.writable || this.current || db.behind !== null) return
208
209
  const { data: device } = await db.get('devices', hid.encode(db.writerKey))
209
210
  const me = device?.memberId ? (await db.get('members', device.memberId)).data : null
210
211
  if (!can(me?.role, REMOVE)) return
package/src/lib/errors.js CHANGED
@@ -102,6 +102,14 @@ export class CeroError extends Error {
102
102
  static NOT_WRITABLE(resource) {
103
103
  return new CeroError('NOT_WRITABLE', `${resource} is not writable`)
104
104
  }
105
+ /**
106
+ * This device skipped writes from a newer app version: it reads, but writes wait for the update.
107
+ *
108
+ * @param {number} version
109
+ */
110
+ static BEHIND(version) {
111
+ return new CeroError('BEHIND', `behind app version ${version}: update to write`)
112
+ }
105
113
  /**
106
114
  * Async operation exceeded its deadline.
107
115
  *
package/src/lib/utils.js CHANGED
@@ -122,10 +122,12 @@ const fold = (s) =>
122
122
 
123
123
  // every term must be a substring of a searched field
124
124
  /** @param {Record<string, unknown>} row @param {string} term @param {string[]} [fields] @returns {boolean} */
125
+ const IDS = new Set(['id', 'memberId'])
126
+
125
127
  export function searchHit(row, term, fields) {
126
128
  const terms = String(term).split(/\s+/).map(fold).filter(Boolean)
127
- // memberId is a random z32, it would produce spurious hits
128
- const keys = fields && fields.length ? fields : Object.keys(row).filter((k) => k !== 'memberId')
129
+ // ids are random z32: any term can occur in one
130
+ const keys = fields && fields.length ? fields : Object.keys(row).filter((k) => !IDS.has(k))
129
131
  const hay = keys.map((k) => (typeof row[k] === 'string' ? fold(row[k]) : '')).join(' ')
130
132
  return terms.every((t) => hay.includes(t))
131
133
  }
@@ -3,6 +3,8 @@ import safetyCatch from 'safety-catch'
3
3
  import crypto from 'hypercore-crypto'
4
4
  import b4a from 'b4a'
5
5
 
6
+ import { CeroError } from '../lib/errors.js'
7
+
6
8
  const NS = b4a.from('cero/mailbox')
7
9
  const READ_TIMEOUT = 30000
8
10
 
@@ -16,17 +18,32 @@ export function keyPair(secret) {
16
18
  return crypto.encryptionKeyPair(crypto.hash([NS, secret]))
17
19
  }
18
20
 
21
+ /**
22
+ * Erase the core a message travelled in. Corestore leaves a core that still has a session open,
23
+ * and that is an error here, not silence.
24
+ *
25
+ * @param {import('corestore')} store
26
+ * @param {Uint8Array} key
27
+ * @returns {Promise<void>}
28
+ */
29
+ export async function erase(store, key) {
30
+ const [gone] = await store.purge(key)
31
+ if (!gone) throw CeroError.CONFLICT(`mailbox: ${b4a.toHex(key)} is still open, not erased`)
32
+ }
33
+
19
34
  /**
20
35
  * Receives at the address a secret owns, direct from the sender or from a mirror. A message
21
36
  * that does not open is dropped; one that opens is kept in `box` until `onmessage` resolves.
37
+ * A core the inbox fetched is erased once dropped, or once handled with `keep` false; one this
38
+ * device held already is left alone.
22
39
  */
23
40
  export class Inbox extends ReadyResource {
24
41
  /**
25
42
  * @param {import('../network/index.js').Network} network
26
43
  * @param {Uint8Array} secret
27
- * @param {{ box: import('./index.js').Box, onmessage: (message: Uint8Array) => unknown, onerror: (err: Error) => void }} opts
44
+ * @param {{ box: import('./index.js').Box, onmessage: (message: Uint8Array) => unknown, onerror: (err: Error) => void, keep?: boolean }} opts
28
45
  */
29
- constructor(network, secret, { box, onmessage, onerror }) {
46
+ constructor(network, secret, { box, onmessage, onerror, keep = true }) {
30
47
  super()
31
48
  this.network = network
32
49
  this.keyPair = keyPair(secret)
@@ -34,6 +51,7 @@ export class Inbox extends ReadyResource {
34
51
  this.box = box
35
52
  this.onmessage = onmessage
36
53
  this.onerror = onerror
54
+ this.keep = keep
37
55
  /** @private */
38
56
  this._seen = new Set()
39
57
  /** @private */
@@ -77,25 +95,32 @@ export class Inbox extends ReadyResource {
77
95
 
78
96
  /** @private */
79
97
  async _read(id, key) {
80
- const core = this.network.store.get({ key })
98
+ const { store } = this.network
99
+ // a core this device already holds is not the inbox's to erase, whatever is announced here
100
+ const fetched = !(await store.storage.hasCore(crypto.discoveryKey(key)))
101
+ const core = store.get({ key })
81
102
  let message
82
103
  try {
83
104
  message = crypto.decrypt(await core.get(0, { timeout: READ_TIMEOUT }), this.keyPair)
84
105
  } finally {
85
106
  await core.close()
86
107
  }
87
- if (!message) return
88
- const mail = { id, address: this.address, message }
108
+ if (!message) {
109
+ if (fetched) await erase(store, key)
110
+ return
111
+ }
112
+ const mail = { id, address: this.address, message, fetched }
89
113
  await this.box.put(mail)
90
114
  this._handle(mail)
91
115
  }
92
116
 
93
117
  // dropped once handled; one that throws stays for the next time this address is received
94
118
  /** @private */
95
- async _handle({ id, message }) {
119
+ async _handle({ id, message, fetched }) {
96
120
  try {
97
121
  await this.onmessage(message)
98
122
  await this.box.del(id)
123
+ if (!this.keep && fetched) await erase(this.network.store, b4a.from(id, 'hex'))
99
124
  } catch (err) {
100
125
  this.onerror(err)
101
126
  }
@@ -3,16 +3,19 @@ import safetyCatch from 'safety-catch'
3
3
  import crypto from 'hypercore-crypto'
4
4
  import b4a from 'b4a'
5
5
 
6
- import { Inbox, keyPair } from './inbox.js'
6
+ import { Inbox, keyPair, erase } from './inbox.js'
7
7
  import { Post } from './post.js'
8
8
  import { CeroError } from '../lib/errors.js'
9
9
 
10
10
  /**
11
11
  * @typedef {object} Mail
12
12
  * @property {string} id Unique per message, hex.
13
+ * @property {string} [name] The core it travels in, so a restart sends it on the same core.
13
14
  * @property {Uint8Array} address Where it goes, or where it arrived.
14
15
  * @property {Uint8Array} message
15
16
  * @property {Uint8Array[]} [mirrors] Where a sent message waits for an owner who is offline.
17
+ * @property {boolean} [keep] False erases the sender's copy once someone read it.
18
+ * @property {boolean} [fetched] The inbox fetched the core it arrived in, so it may erase it.
16
19
  *
17
20
  * @typedef {object} Box Where mail is kept; memory unless given a persistent one.
18
21
  * @property {() => Promise<Mail[]>} list
@@ -81,13 +84,15 @@ export class Mailbox extends ReadyResource {
81
84
  *
82
85
  * @param {Uint8Array} secret
83
86
  * @param {(message: Uint8Array) => unknown} onmessage
87
+ * @param {{ keep?: boolean }} [opts] False erases each message from this device once handled.
84
88
  * @returns {{ close: () => Promise<void> }}
85
89
  */
86
- receive(secret, onmessage) {
90
+ receive(secret, onmessage, { keep = true } = {}) {
87
91
  const inbox = new Inbox(this.network, secret, {
88
92
  box: this.inbox,
89
93
  onmessage,
90
- onerror: this.onerror
94
+ onerror: this.onerror,
95
+ keep
91
96
  })
92
97
  this._track(inbox)
93
98
  inbox.ready().catch(this.onerror)
@@ -100,21 +105,24 @@ export class Mailbox extends ReadyResource {
100
105
  *
101
106
  * @param {Uint8Array} address
102
107
  * @param {Uint8Array} message
103
- * @param {{ mirrors?: Uint8Array[] }} [opts] Where it waits for an owner who is offline; the network's by default.
108
+ * @param {{ mirrors?: Uint8Array[], keep?: boolean }} [opts] `mirrors`: where it waits for an owner who is offline, the network's by default. `keep`: false erases it from this device once someone read it.
104
109
  * @returns {Promise<void>}
105
110
  */
106
- async send(address, message, { mirrors = this.network.mirrors } = {}) {
111
+ async send(address, message, { mirrors = this.network.mirrors, keep = true } = {}) {
107
112
  if (!this.opened) await this.ready()
108
- const mail = { id: b4a.toHex(crypto.randomBytes(16)), address, message, mirrors }
113
+ const name = b4a.toHex(crypto.randomBytes(32))
114
+ const mail = { id: b4a.toHex(crypto.randomBytes(16)), name, address, message, mirrors, keep }
109
115
  await this.outbox.put(mail)
110
116
  this._deliver(mail)
111
117
  }
112
118
 
113
119
  /** @private */
114
- _deliver({ id, address, message, mirrors }) {
115
- const post = new Post(this.network, address, message, { mirrors })
120
+ _deliver({ id, name, address, message, mirrors, keep = true }) {
121
+ const post = new Post(this.network, address, message, { mirrors, name })
116
122
  this._track(post)
117
- deliver(post, () => this.outbox.del(id)).catch(safetyCatch)
123
+ deliver(post, () => this.outbox.del(id))
124
+ .then(() => keep || erase(this.network.store, post.key).catch(this.onerror))
125
+ .catch(safetyCatch)
118
126
  }
119
127
 
120
128
  /** @private */
@@ -7,21 +7,23 @@ import b4a from 'b4a'
7
7
  * One sealed message on its way to an address: written to a fresh core, announced to peers
8
8
  * receiving at the address, and deposited on `mirrors` for an owner who is offline.
9
9
  * `delivered` resolves on the first read, by the owner or by a mirror holding it for them.
10
- * Given a `core` instead, it announces that core as it is.
10
+ * Given a `core` instead, it announces that core as it is; given a `name`, the core is the
11
+ * store's core of that name, and a message it already holds is not written twice.
11
12
  */
12
13
  export class Post extends ReadyResource {
13
14
  /**
14
15
  * @param {import('../network/index.js').Network} network
15
16
  * @param {Uint8Array} address
16
17
  * @param {Uint8Array | null} message
17
- * @param {{ mirrors?: Uint8Array[], core?: import('hypercore') }} [opts]
18
+ * @param {{ mirrors?: Uint8Array[], core?: import('hypercore'), name?: string }} [opts]
18
19
  */
19
- constructor(network, address, message, { mirrors = [], core = null } = {}) {
20
+ constructor(network, address, message, { mirrors = [], core = null, name } = {}) {
20
21
  super()
21
22
  this.network = network
22
23
  this.address = address
23
24
  this.message = message
24
25
  this.mirrors = mirrors
26
+ this.name = name || b4a.toHex(crypto.randomBytes(32))
25
27
  /** @type {Promise<void>} */
26
28
  this.delivered = new Promise((resolve) => {
27
29
  /** @private */
@@ -38,11 +40,11 @@ export class Post extends ReadyResource {
38
40
  /** @private */
39
41
  async _open() {
40
42
  const { network, address } = this
41
- const core = this._core || network.store.get({ name: b4a.toHex(crypto.randomBytes(32)) })
43
+ const core = this._core || network.store.get({ name: this.name })
42
44
  this._core = core
43
45
  await core.ready()
44
46
  core.once('upload', () => this._ondelivered())
45
- if (this.message) await core.append(crypto.encrypt(this.message, address))
47
+ if (this.message && core.length === 0) await core.append(crypto.encrypt(this.message, address))
46
48
 
47
49
  const wakeup = [{ key: core.key, length: core.length }]
48
50
  const session = network.wakeup.session(address, {
@@ -59,6 +61,11 @@ export class Post extends ReadyResource {
59
61
  }
60
62
  }
61
63
 
64
+ /** The key of the core it travels in, once opened. */
65
+ get key() {
66
+ return this._core?.key ?? null
67
+ }
68
+
62
69
  /** @private */
63
70
  async _close() {
64
71
  this._session?.destroy()
@@ -362,9 +362,12 @@ export class Network extends ReadyResource {
362
362
  }
363
363
 
364
364
  // data, not packets: a peer that acked our opener and froze has answered nothing
365
+ // silent since we got it: a direct connection carries its handshake on the stream, so the count
366
+ // starts above zero
365
367
  function dropIfSilent(conn) {
368
+ const seen = conn.rawStream.bytesReceived
366
369
  const timer = setTimeout(() => {
367
- if (conn.rawStream.bytesReceived === 0) conn.destroy()
370
+ if (conn.rawStream.bytesReceived === seen) conn.destroy()
368
371
  }, SILENT_TIMEOUT)
369
372
  timer.unref()
370
373
  conn.once('close', () => clearTimeout(timer))
@@ -101,6 +101,7 @@ export class Invite {
101
101
  static create({ ttl = 0, key, address, link = null, data = null }) {
102
102
  if (key?.byteLength !== 32) throw CeroError.INVALID('key must be a 32-byte buffer')
103
103
  if (address?.byteLength !== 32) throw CeroError.INVALID('address must be a 32-byte buffer')
104
+ if (!sealable(address)) throw CeroError.INVALID('address cannot be sealed to')
104
105
  const expires = ttl ? Date.now() + toMs(ttl) : 0
105
106
  if (data !== null && !b4a.isBuffer(data)) throw CeroError.INVALID('data must be a buffer')
106
107
  return new Invite({
@@ -128,10 +129,24 @@ export class Invite {
128
129
  throw CeroError.INVALID_INVITE('not an invite')
129
130
  }
130
131
  if (fields.version !== VERSION) throw CeroError.INVALID_INVITE('unknown invite version')
132
+ if (!sealable(fields.address)) throw CeroError.INVALID_INVITE('address cannot be sealed to')
131
133
  return new Invite({ ...fields, _str: str })
132
134
  }
133
135
  }
134
136
 
137
+ // a join is sealed to the address: a point nothing seals to (all zeros, a low-order one) would
138
+ // fail every join as a network error
139
+ function sealable(address) {
140
+ try {
141
+ crypto.encrypt(EMPTY, address)
142
+ return true
143
+ } catch {
144
+ return false
145
+ }
146
+ }
147
+
148
+ const EMPTY = b4a.alloc(0)
149
+
135
150
  // ms, or a duration like '12h' or '2d'
136
151
  function toMs(ttl) {
137
152
  const value = typeof ttl === 'string' ? ms(ttl) : ttl
package/src/push/index.js CHANGED
@@ -1,10 +1,19 @@
1
1
  import { decode, readNotification } from 'blind-push'
2
2
  import crypto from 'hypercore-crypto'
3
3
  import b4a from 'b4a'
4
+ import autobeeEncryption from 'autobee/lib/encryption.js'
5
+ import autobeeEncoding from 'autobee/lib/encoding.js'
6
+
7
+ import { Keyring } from '../database/encryption.js'
8
+ import { unwrap } from '../database/envelope.js'
9
+
10
+ const { AutobeeEncryption, WriterEncryption } = autobeeEncryption
11
+ const { decodeOplog } = autobeeEncoding
4
12
 
5
13
  /**
6
14
  * @typedef {{ id: string, key: Uint8Array }} Handle A handle this device holds: its id and its database key.
7
- * @typedef {Handle & { length: number, newer: boolean, ref: string | null }} Hit The handle a push is about, the length it proves, whether this device is behind it, and the ref the write was on.
15
+ * @typedef {{ index: number, value: Uint8Array, writer: Uint8Array }} Block The block a push carries when it fits: its index, its bytes as the writer's core holds them, and the writer's key.
16
+ * @typedef {Handle & { length: number, newer: boolean, ref: string | null, block: Block | null }} Hit The handle a push is about, the length it proves, whether this device is behind it, the ref the write was on, and the block when it rode along.
8
17
  */
9
18
 
10
19
  /**
@@ -33,5 +42,54 @@ export async function verify(storage, payload, handles) {
33
42
  }
34
43
  if (!read) return null
35
44
  const ref = read.extra?.length ? b4a.toString(read.extra) : null
36
- return { ...handle, length: read.result.length, newer: read.result.newer, ref }
45
+ const { block, key: writer } = read.result
46
+ return {
47
+ ...handle,
48
+ length: read.result.length,
49
+ newer: read.result.newer,
50
+ ref,
51
+ block: block?.value ? { index: block.index, value: block.value, writer } : null
52
+ }
53
+ }
54
+
55
+ /**
56
+ * The op a push's block holds, for a device with the handle's keys: decrypted as the writer's
57
+ * core would, under the epoch the block names, and stripped of its envelope. Null when the push
58
+ * carried no block, the writer is not stored here, or the epoch is not among `epochs`.
59
+ *
60
+ * @param {import('hypercore-storage')} storage The same storage `verify` read.
61
+ * @param {Hit} hit
62
+ * @param {{ encryptionKey: Uint8Array, epochs?: Array<{ epoch: number, stamp: number, entropy: Uint8Array }> }} keys The handle's encryption key and the rotation epochs it has learned.
63
+ * @returns {Promise<Uint8Array | null>}
64
+ */
65
+ export async function decrypt(storage, hit, { encryptionKey, epochs = [] }) {
66
+ if (!hit.block) return null
67
+ const core = await storage.resumeCore(crypto.discoveryKey(hit.block.writer))
68
+ if (!core) return null
69
+ const rx = core.read()
70
+ const auth = rx.getAuth()
71
+ rx.tryFlush()
72
+ const manifest = (await auth)?.manifest
73
+ if (!manifest) return null
74
+ const keyring = new Keyring()
75
+ for (const e of epochs) keyring.add(e.stamp, e.entropy, e.epoch)
76
+ const auto = {
77
+ key: hit.key,
78
+ encryptionKey,
79
+ getEntropy: (id) => {
80
+ const entropy = keyring.entropy(id)
81
+ if (!entropy) throw new Error(`unknown epoch ${id}`)
82
+ return entropy
83
+ }
84
+ }
85
+ const value = b4a.from(hit.block.value)
86
+ try {
87
+ await new WriterEncryption(auto).decrypt(hit.block.index, value, {
88
+ key: hit.block.writer,
89
+ manifest
90
+ })
91
+ return unwrap(decodeOplog(value.subarray(AutobeeEncryption.PADDING)).value)?.body ?? null
92
+ } catch {
93
+ return null
94
+ }
37
95
  }
@@ -234,6 +234,7 @@ export declare class Database extends ReadyResource {
234
234
  /** @type {number | null} */
235
235
  behind: number | null;
236
236
  namespace: string;
237
+ _writable: boolean;
237
238
  encryptionKey: Uint8Array<ArrayBufferLike>;
238
239
  keyring: Keyring;
239
240
  /** @private */
@@ -467,6 +468,8 @@ export declare class Database extends ReadyResource {
467
468
  whenWritable({ timeout }?: {
468
469
  timeout?: number;
469
470
  }): Promise<void>;
471
+ /** @private */
472
+ private _onwritable;
470
473
  /**
471
474
  * Learn epochs handed over after the open, as a root carries them for a handle. One is kept
472
475
  * once its announcement applied here and the secret meets the commitment it carries: hand them
@@ -73,6 +73,12 @@ export declare class CeroError extends Error {
73
73
  * @param {string} resource
74
74
  */
75
75
  static NOT_WRITABLE(resource: string): CeroError;
76
+ /**
77
+ * This device skipped writes from a newer app version: it reads, but writes wait for the update.
78
+ *
79
+ * @param {number} version
80
+ */
81
+ static BEHIND(version: number): CeroError;
76
82
  /**
77
83
  * Async operation exceeded its deadline.
78
84
  *
@@ -31,8 +31,7 @@ export declare function subscribe<T>({ get, watch }: {
31
31
  get: () => Promise<T> | T;
32
32
  watch: (fn: () => void) => (() => void) | void;
33
33
  }): import('streamx').Readable<T>;
34
- /** @param {Record<string, unknown>} row @param {string} term @param {string[]} [fields] @returns {boolean} */
35
- export declare function searchHit(row: Record<string, unknown>, term: string, fields?: string[]): boolean;
34
+ export declare function searchHit(row: any, term: any, fields: any): boolean;
36
35
  /**
37
36
  * The in-memory query grammar over rows: equality on any non-reserved field,
38
37
  * id ranges, `search`, then `reverse` and `limit`.
@@ -9,9 +9,20 @@ export declare function keyPair(secret: Uint8Array): {
9
9
  publicKey: Uint8Array;
10
10
  secretKey: Uint8Array;
11
11
  };
12
+ /**
13
+ * Erase the core a message travelled in. Corestore leaves a core that still has a session open,
14
+ * and that is an error here, not silence.
15
+ *
16
+ * @param {import('corestore')} store
17
+ * @param {Uint8Array} key
18
+ * @returns {Promise<void>}
19
+ */
20
+ export declare function erase(store: import('corestore'), key: Uint8Array): Promise<void>;
12
21
  /**
13
22
  * Receives at the address a secret owns, direct from the sender or from a mirror. A message
14
23
  * that does not open is dropped; one that opens is kept in `box` until `onmessage` resolves.
24
+ * A core the inbox fetched is erased once dropped, or once handled with `keep` false; one this
25
+ * device held already is left alone.
15
26
  */
16
27
  export declare class Inbox extends ReadyResource {
17
28
  network: import("../index.js").Network;
@@ -23,6 +34,7 @@ export declare class Inbox extends ReadyResource {
23
34
  box: import("./index.js").Box;
24
35
  onmessage: (message: Uint8Array) => unknown;
25
36
  onerror: (err: Error) => void;
37
+ keep: boolean;
26
38
  /** @private */
27
39
  _seen;
28
40
  /** @private */
@@ -32,12 +44,13 @@ export declare class Inbox extends ReadyResource {
32
44
  /**
33
45
  * @param {import('../network/index.js').Network} network
34
46
  * @param {Uint8Array} secret
35
- * @param {{ box: import('./index.js').Box, onmessage: (message: Uint8Array) => unknown, onerror: (err: Error) => void }} opts
47
+ * @param {{ box: import('./index.js').Box, onmessage: (message: Uint8Array) => unknown, onerror: (err: Error) => void, keep?: boolean }} opts
36
48
  */
37
- constructor(network: import('../network/index.js').Network, secret: Uint8Array, { box, onmessage, onerror }: {
49
+ constructor(network: import('../network/index.js').Network, secret: Uint8Array, { box, onmessage, onerror, keep }: {
38
50
  box: import('./index.js').Box;
39
51
  onmessage: (message: Uint8Array) => unknown;
40
52
  onerror: (err: Error) => void;
53
+ keep?: boolean;
41
54
  });
42
55
  /** @private */
43
56
  private _open;
@@ -4,6 +4,10 @@ export type Mail = {
4
4
  * Unique per message, hex.
5
5
  */
6
6
  id: string;
7
+ /**
8
+ * The core it travels in, so a restart sends it on the same core.
9
+ */
10
+ name?: string;
7
11
  /**
8
12
  * Where it goes, or where it arrived.
9
13
  */
@@ -13,6 +17,14 @@ export type Mail = {
13
17
  * Where a sent message waits for an owner who is offline.
14
18
  */
15
19
  mirrors?: Uint8Array[];
20
+ /**
21
+ * False erases the sender's copy once someone read it.
22
+ */
23
+ keep?: boolean;
24
+ /**
25
+ * The inbox fetched the core it arrived in, so it may erase it.
26
+ */
27
+ fetched?: boolean;
16
28
  };
17
29
  export type Box = {
18
30
  list: () => Promise<Mail[]>;
@@ -36,9 +48,12 @@ export type MailboxOpts = {
36
48
  /**
37
49
  * @typedef {object} Mail
38
50
  * @property {string} id Unique per message, hex.
51
+ * @property {string} [name] The core it travels in, so a restart sends it on the same core.
39
52
  * @property {Uint8Array} address Where it goes, or where it arrived.
40
53
  * @property {Uint8Array} message
41
54
  * @property {Uint8Array[]} [mirrors] Where a sent message waits for an owner who is offline.
55
+ * @property {boolean} [keep] False erases the sender's copy once someone read it.
56
+ * @property {boolean} [fetched] The inbox fetched the core it arrived in, so it may erase it.
42
57
  *
43
58
  * @typedef {object} Box Where mail is kept; memory unless given a persistent one.
44
59
  * @property {() => Promise<Mail[]>} list
@@ -87,9 +102,12 @@ export declare class Mailbox extends ReadyResource {
87
102
  *
88
103
  * @param {Uint8Array} secret
89
104
  * @param {(message: Uint8Array) => unknown} onmessage
105
+ * @param {{ keep?: boolean }} [opts] False erases each message from this device once handled.
90
106
  * @returns {{ close: () => Promise<void> }}
91
107
  */
92
- receive(secret: Uint8Array, onmessage: (message: Uint8Array) => unknown): {
108
+ receive(secret: Uint8Array, onmessage: (message: Uint8Array) => unknown, { keep }?: {
109
+ keep?: boolean;
110
+ }): {
93
111
  close: () => Promise<void>;
94
112
  };
95
113
  /**
@@ -98,11 +116,12 @@ export declare class Mailbox extends ReadyResource {
98
116
  *
99
117
  * @param {Uint8Array} address
100
118
  * @param {Uint8Array} message
101
- * @param {{ mirrors?: Uint8Array[] }} [opts] Where it waits for an owner who is offline; the network's by default.
119
+ * @param {{ mirrors?: Uint8Array[], keep?: boolean }} [opts] `mirrors`: where it waits for an owner who is offline, the network's by default. `keep`: false erases it from this device once someone read it.
102
120
  * @returns {Promise<void>}
103
121
  */
104
- send(address: Uint8Array, message: Uint8Array, { mirrors }?: {
122
+ send(address: Uint8Array, message: Uint8Array, { mirrors, keep }?: {
105
123
  mirrors?: Uint8Array[];
124
+ keep?: boolean;
106
125
  }): Promise<void>;
107
126
  /** @private */
108
127
  private _deliver;
@@ -3,13 +3,15 @@ import ReadyResource from 'ready-resource';
3
3
  * One sealed message on its way to an address: written to a fresh core, announced to peers
4
4
  * receiving at the address, and deposited on `mirrors` for an owner who is offline.
5
5
  * `delivered` resolves on the first read, by the owner or by a mirror holding it for them.
6
- * Given a `core` instead, it announces that core as it is.
6
+ * Given a `core` instead, it announces that core as it is; given a `name`, the core is the
7
+ * store's core of that name, and a message it already holds is not written twice.
7
8
  */
8
9
  export declare class Post extends ReadyResource {
9
10
  network: import("../index.js").Network;
10
11
  address: Uint8Array<ArrayBufferLike>;
11
12
  message: Uint8Array<ArrayBufferLike>;
12
13
  mirrors: Uint8Array<ArrayBufferLike>[];
14
+ name: string;
13
15
  /** @type {Promise<void>} */
14
16
  delivered: Promise<void>;
15
17
  /** @private */
@@ -24,14 +26,17 @@ export declare class Post extends ReadyResource {
24
26
  * @param {import('../network/index.js').Network} network
25
27
  * @param {Uint8Array} address
26
28
  * @param {Uint8Array | null} message
27
- * @param {{ mirrors?: Uint8Array[], core?: import('hypercore') }} [opts]
29
+ * @param {{ mirrors?: Uint8Array[], core?: import('hypercore'), name?: string }} [opts]
28
30
  */
29
- constructor(network: import('../network/index.js').Network, address: Uint8Array, message: Uint8Array | null, { mirrors, core }?: {
31
+ constructor(network: import('../network/index.js').Network, address: Uint8Array, message: Uint8Array | null, { mirrors, core, name }?: {
30
32
  mirrors?: Uint8Array[];
31
33
  core?: import('hypercore');
34
+ name?: string;
32
35
  });
33
36
  /** @private */
34
37
  private _open;
38
+ /** The key of the core it travels in, once opened. */
39
+ get key(): any;
35
40
  /** @private */
36
41
  private _close;
37
42
  }
@@ -2,14 +2,21 @@ export type Handle = {
2
2
  id: string;
3
3
  key: Uint8Array;
4
4
  };
5
+ export type Block = {
6
+ index: number;
7
+ value: Uint8Array;
8
+ writer: Uint8Array;
9
+ };
5
10
  export type Hit = Handle & {
6
11
  length: number;
7
12
  newer: boolean;
8
13
  ref: string | null;
14
+ block: Block | null;
9
15
  };
10
16
  /**
11
17
  * @typedef {{ id: string, key: Uint8Array }} Handle A handle this device holds: its id and its database key.
12
- * @typedef {Handle & { length: number, newer: boolean, ref: string | null }} Hit The handle a push is about, the length it proves, whether this device is behind it, and the ref the write was on.
18
+ * @typedef {{ index: number, value: Uint8Array, writer: Uint8Array }} Block The block a push carries when it fits: its index, its bytes as the writer's core holds them, and the writer's key.
19
+ * @typedef {Handle & { length: number, newer: boolean, ref: string | null, block: Block | null }} Hit The handle a push is about, the length it proves, whether this device is behind it, the ref the write was on, and the block when it rode along.
13
20
  */
14
21
  /**
15
22
  * Verify a push payload against this device's storage: the one the gateway sent, decoded from the
@@ -21,3 +28,21 @@ export type Hit = Handle & {
21
28
  * @returns {Promise<Hit | null>}
22
29
  */
23
30
  export declare function verify(storage: import('hypercore-storage'), payload: Uint8Array, handles: Handle[]): Promise<Hit | null>;
31
+ /**
32
+ * The op a push's block holds, for a device with the handle's keys: decrypted as the writer's
33
+ * core would, under the epoch the block names, and stripped of its envelope. Null when the push
34
+ * carried no block, the writer is not stored here, or the epoch is not among `epochs`.
35
+ *
36
+ * @param {import('hypercore-storage')} storage The same storage `verify` read.
37
+ * @param {Hit} hit
38
+ * @param {{ encryptionKey: Uint8Array, epochs?: Array<{ epoch: number, stamp: number, entropy: Uint8Array }> }} keys The handle's encryption key and the rotation epochs it has learned.
39
+ * @returns {Promise<Uint8Array | null>}
40
+ */
41
+ export declare function decrypt(storage: import('hypercore-storage'), hit: Hit, { encryptionKey, epochs }: {
42
+ encryptionKey: Uint8Array;
43
+ epochs?: Array<{
44
+ epoch: number;
45
+ stamp: number;
46
+ entropy: Uint8Array;
47
+ }>;
48
+ }): Promise<Uint8Array | null>;