@cero-base/core 2.11.0 → 3.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 (39) hide show
  1. package/package.json +8 -8
  2. package/src/blobs/codec.js +25 -0
  3. package/src/blobs/index.js +5 -2
  4. package/src/blobs/server.js +2 -2
  5. package/src/database/dispatch.js +805 -208
  6. package/src/database/encryption.js +25 -21
  7. package/src/database/index.js +747 -124
  8. package/src/database/rotation.js +333 -38
  9. package/src/lib/constants.js +10 -0
  10. package/src/lib/errors.js +8 -0
  11. package/src/lib/schema.js +12 -2
  12. package/src/lib/spec/index.js +10 -5
  13. package/src/lib/spec/schema.json +13 -1
  14. package/src/lib/utils.js +24 -3
  15. package/src/mailbox/inbox.js +368 -41
  16. package/src/mailbox/index.js +75 -20
  17. package/src/mailbox/post.js +13 -8
  18. package/src/network/index.js +12 -5
  19. package/src/pairing/index.js +347 -57
  20. package/src/pairing/invite.js +36 -12
  21. package/src/pairing/response.js +78 -0
  22. package/src/push/index.js +20 -2
  23. package/types/blobs/codec.d.ts +13 -0
  24. package/types/blobs/index.d.ts +2 -0
  25. package/types/database/dispatch.d.ts +52 -7
  26. package/types/database/encryption.d.ts +13 -5
  27. package/types/database/index.d.ts +199 -19
  28. package/types/database/rotation.d.ts +85 -2
  29. package/types/lib/constants.d.ts +4 -0
  30. package/types/lib/errors.d.ts +6 -0
  31. package/types/lib/schema.d.ts +11 -0
  32. package/types/lib/utils.d.ts +2 -0
  33. package/types/mailbox/inbox.d.ts +78 -10
  34. package/types/mailbox/index.d.ts +42 -16
  35. package/types/mailbox/post.d.ts +7 -5
  36. package/types/pairing/index.d.ts +53 -8
  37. package/types/pairing/invite.d.ts +27 -8
  38. package/types/pairing/response.d.ts +50 -0
  39. package/types/push/index.d.ts +12 -2
@@ -3,7 +3,7 @@ import safetyCatch from 'safety-catch'
3
3
  import crypto from 'hypercore-crypto'
4
4
  import b4a from 'b4a'
5
5
 
6
- import { Inbox, keyPair, erase } from './inbox.js'
6
+ import { Inbox, keyPair, erase, aged } from './inbox.js'
7
7
  import { Post } from './post.js'
8
8
  import { CeroError } from '../lib/errors.js'
9
9
 
@@ -12,28 +12,31 @@ import { CeroError } from '../lib/errors.js'
12
12
  * @property {string} id Unique per message, hex.
13
13
  * @property {string} [name] The core it travels in, so a restart sends it on the same core.
14
14
  * @property {Uint8Array} address Where it goes, or where it arrived.
15
- * @property {Uint8Array} message
15
+ * @property {Uint8Array} message Sent: as `sealed` says. Received: empty, it stays in its core.
16
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.
17
+ * @property {boolean} [keep] False erases the sender's copy once a device or a mirror stored it.
18
+ * @property {boolean} [fetched] The inbox fetched the core it arrived in, so it may erase it; on a handled row, it still has to.
19
+ * @property {number} [handled] When it was handled: the id is remembered for a while.
20
+ * @property {boolean} [sealed] Sent: `message` is sealed to the address, not in the clear.
19
21
  *
20
22
  * @typedef {object} Box Where mail is kept; memory unless given a persistent one.
21
23
  * @property {() => Promise<Mail[]>} list
24
+ * @property {(id: string) => Promise<Mail | null>} get The one row under an id, null when there is none.
22
25
  * @property {(mail: Mail) => Promise<unknown>} put
23
26
  * @property {(id: string) => Promise<unknown>} del
24
27
  *
25
28
  * @typedef {object} MailboxOpts
26
29
  * @property {Box} [inbox] Keeps a received message until it was handled.
27
- * @property {Box} [outbox] Keeps a sent message until someone read it.
30
+ * @property {Box} [outbox] Keeps a sent message until a device or a mirror stored it.
28
31
  * @property {(err: Error) => void} [onerror] Called when a message fails to be handled or sent.
29
32
  */
30
33
 
31
34
  /**
32
35
  * A device's mailbox. It receives at the addresses it holds the secret of, and sends to any
33
- * address. Both ends keep their mail until it is done with: the outbox until someone read it,
34
- * the inbox until it was handled. Give it persistent boxes and that survives a restart: it
35
- * sends again what was not read and hands over again what was not handled, so a message may
36
- * arrive twice, never not at all.
36
+ * address. Both ends keep their mail until it is done with: the outbox until a device or a
37
+ * mirror stored it, the inbox until it was handled. Give it persistent boxes and that survives a
38
+ * restart: it sends again what was not stored and hands over again what was not handled, so a
39
+ * message may arrive twice, never not at all.
37
40
  */
38
41
  export class Mailbox extends ReadyResource {
39
42
  /**
@@ -46,6 +49,7 @@ export class Mailbox extends ReadyResource {
46
49
  ) {
47
50
  super()
48
51
  if (!network) throw CeroError.REQUIRED('network')
52
+ if (typeof inbox.get !== 'function') throw CeroError.INVALID('inbox box has no get(id)')
49
53
  this.network = network
50
54
  this.inbox = inbox
51
55
  this.outbox = outbox
@@ -78,6 +82,12 @@ export class Mailbox extends ReadyResource {
78
82
  /** @private */
79
83
  async _open() {
80
84
  await this.network.ready()
85
+ // at any address, one received at again or not: handled rows that aged go, and a core its
86
+ // inbox had to leave as it closed is erased
87
+ for (const mail of await this.inbox.list()) {
88
+ if (aged(mail)) await this.inbox.del(mail.id)
89
+ else if (mail.handled && mail.fetched) await this._owed(mail)
90
+ }
81
91
  for (const mail of await this.outbox.list()) this._deliver(mail)
82
92
  }
83
93
 
@@ -91,32 +101,51 @@ export class Mailbox extends ReadyResource {
91
101
  /**
92
102
  * Receive the messages sent to the address `secret` owns, until the returned inbox closes.
93
103
  * A message stays in the inbox until `onmessage` resolves; one it did not finish is handed
94
- * over again the next time this address is received.
104
+ * over again the next time this address is received. One it resolves `false` on was not for
105
+ * this address: it is erased as one that does not open. A message that was being read when the
106
+ * app was killed or its inbox closed is handed over at the next start and stays on the device,
107
+ * whatever `keep` says or `onmessage` resolves.
95
108
  *
96
109
  * @param {Uint8Array} secret
97
110
  * @param {(message: Uint8Array) => unknown} onmessage
98
- * @param {{ keep?: boolean }} [opts] False erases each message from this device once handled.
111
+ * @param {{ keep?: boolean, timeout?: number }} [opts] `keep`: false erases each message from this device once handled. `timeout`: ms a message has to arrive once announced, and again to be handled, 30 s by default.
99
112
  * @returns {{ close: () => Promise<void> }}
100
113
  */
101
- receive(secret, onmessage, { keep = true } = {}) {
114
+ receive(secret, onmessage, { keep = true, timeout } = {}) {
115
+ const address = keyPair(secret).publicKey
116
+ // an inbox still closing at this address may yet leave a row: this one opens once it has, and finds it
117
+ const after = [...this._resources]
118
+ .filter((r) => r instanceof Inbox && r.closing && b4a.equals(r.address, address))
119
+ .map((r) => r.closing)
120
+ const siblings = () =>
121
+ [...this._resources].filter(
122
+ (r) => r instanceof Inbox && r !== inbox && b4a.equals(r.address, address)
123
+ )
102
124
  const inbox = new Inbox(this.network, secret, {
103
125
  box: this.inbox,
104
126
  onmessage,
105
127
  onerror: this.onerror,
106
- keep
128
+ keep,
129
+ timeout,
130
+ after,
131
+ siblings
107
132
  })
108
133
  this._track(inbox)
134
+ // a read it leaves unsettled as it closes goes to the inboxes still open at its address
135
+ inbox.once('close', () => {
136
+ for (const left of siblings()) left.inherit().catch(this.onerror)
137
+ })
109
138
  inbox.ready().catch(this.onerror)
110
139
  return inbox
111
140
  }
112
141
 
113
142
  /**
114
143
  * Send a message to an address. Resolves once the outbox keeps it; it is delivered in the
115
- * background, and dropped from the outbox once someone read it.
144
+ * background, and dropped from the outbox once the owner or a mirror stored it.
116
145
  *
117
146
  * @param {Uint8Array} address
118
147
  * @param {Uint8Array} message
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.
148
+ * @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 a device or a mirror stored it.
120
149
  * @returns {Promise<void>}
121
150
  */
122
151
  async send(address, message, { mirrors = this.network.mirrors, keep = true } = {}) {
@@ -124,7 +153,15 @@ export class Mailbox extends ReadyResource {
124
153
  if (this.closing) throw CeroError.CLOSED('Mailbox')
125
154
  if (!this.opened) await this.ready()
126
155
  const name = b4a.toHex(crypto.randomBytes(32))
127
- const mail = { id: b4a.toHex(crypto.randomBytes(16)), name, address, message, mirrors, keep }
156
+ const mail = {
157
+ id: b4a.toHex(crypto.randomBytes(16)),
158
+ name,
159
+ address,
160
+ message: crypto.encrypt(message, address),
161
+ mirrors,
162
+ keep,
163
+ sealed: true
164
+ }
128
165
  try {
129
166
  await this.outbox.put(mail)
130
167
  } catch (err) {
@@ -136,14 +173,31 @@ export class Mailbox extends ReadyResource {
136
173
  }
137
174
 
138
175
  /** @private */
139
- _deliver({ id, name, address, message, mirrors, keep = true }) {
140
- const post = new Post(this.network, address, message, { mirrors, name })
176
+ _deliver({ id, name, address, message, mirrors, keep = true, sealed = false }) {
177
+ const post = new Post(this.network, address, message, { mirrors, name, sealed })
141
178
  this._track(post)
142
179
  deliver(post, () => this.outbox.del(id))
143
- .then(() => keep || erase(this.network.store, post.key).catch(this.onerror))
180
+ .then(() => keep || this._erase(post.key).catch(this.onerror))
144
181
  .catch(safetyCatch)
145
182
  }
146
183
 
184
+ /** @private */
185
+ _erase(key) {
186
+ return erase(this.network.store, key, () => !this.closing)
187
+ }
188
+
189
+ // an erase its inbox had to leave, done once and then no longer owed
190
+ /** @private */
191
+ async _owed({ id, address, handled }) {
192
+ try {
193
+ if (await this._erase(b4a.from(id, 'hex'))) {
194
+ await this.inbox.put({ id, address, message: b4a.alloc(0), handled })
195
+ }
196
+ } catch (err) {
197
+ this.onerror(err)
198
+ }
199
+ }
200
+
147
201
  /** @private */
148
202
  _track(resource) {
149
203
  this._resources.add(resource)
@@ -151,7 +205,7 @@ export class Mailbox extends ReadyResource {
151
205
  }
152
206
  }
153
207
 
154
- // wait until a post is read once, then close it
208
+ // wait until a post is stored once, then close it
155
209
  async function deliver(post, ondelivered) {
156
210
  try {
157
211
  await post.ready()
@@ -167,6 +221,7 @@ function memory() {
167
221
  const kept = new Map()
168
222
  return {
169
223
  list: async () => [...kept.values()],
224
+ get: async (id) => kept.get(id) ?? null,
170
225
  put: async (mail) => kept.set(mail.id, mail),
171
226
  del: async (id) => kept.delete(id)
172
227
  }
@@ -6,22 +6,23 @@ import b4a from 'b4a'
6
6
  /**
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
- * `delivered` resolves on the first read, by the owner or by a mirror holding it for them.
9
+ * `delivered` resolves once it is stored, by the owner or by a mirror holding it for them.
10
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
+ * store's core of that name, and a message it already holds is not written twice. `sealed` says
12
+ * the message is sealed to the address already.
12
13
  */
13
14
  export class Post extends ReadyResource {
14
15
  /**
15
16
  * @param {import('../network/index.js').Network} network
16
17
  * @param {Uint8Array} address
17
18
  * @param {Uint8Array | null} message
18
- * @param {{ mirrors?: Uint8Array[], core?: import('hypercore'), name?: string }} [opts]
19
+ * @param {{ mirrors?: Uint8Array[], core?: import('hypercore'), name?: string, sealed?: boolean }} [opts]
19
20
  */
20
- constructor(network, address, message, { mirrors = [], core = null, name } = {}) {
21
+ constructor(network, address, message, { mirrors = [], core = null, name, sealed = false } = {}) {
21
22
  super()
22
23
  this.network = network
23
24
  this.address = address
24
- this.message = message
25
+ this.message = message && !sealed ? crypto.encrypt(message, address) : message
25
26
  this.mirrors = mirrors
26
27
  this.name = name || b4a.toHex(crypto.randomBytes(32))
27
28
  /** @type {Promise<void>} */
@@ -43,13 +44,17 @@ export class Post extends ReadyResource {
43
44
  const core = this._core || network.store.get({ name: this.name })
44
45
  this._core = core
45
46
  await core.ready()
46
- core.once('upload', () => this._ondelivered())
47
- if (this.message && core.length === 0) await core.append(crypto.encrypt(this.message, address))
47
+ if (this.message && core.length === 0) await core.append(this.message)
48
+ // a peer, the owner or a mirror, says it holds every block only once they are on its disk
49
+ const held = () => core.remoteContiguousLength >= core.length && this._ondelivered()
50
+ core.on('remote-contiguous-length', held)
51
+ held()
48
52
 
49
53
  const wakeup = [{ key: core.key, length: core.length }]
50
54
  const session = network.wakeup.session(address, {
51
55
  discoveryKey: crypto.discoveryKey(address),
52
- onpeeractive: (peer) => session.announce(peer, wakeup)
56
+ onpeeractive: (peer) => session.announce(peer, wakeup),
57
+ onlookup: (req, peer) => session.announce(peer, wakeup)
53
58
  })
54
59
  this._session = session
55
60
  // a topic this network already joined has active peers that will not fire onpeeractive again
@@ -167,10 +167,7 @@ export class Network extends ReadyResource {
167
167
  this._swarm = null
168
168
  if (swarm) {
169
169
  // force destroy still awaits a server.close round-trip; cap it
170
- await Promise.race([
171
- swarm.destroy({ force: true }).catch(safetyCatch),
172
- new Promise((r) => setTimeout(r, 750))
173
- ])
170
+ await capped(swarm.destroy({ force: true }).catch(safetyCatch), 750)
174
171
  }
175
172
 
176
173
  if (this._blindPeering) {
@@ -262,7 +259,7 @@ export class Network extends ReadyResource {
262
259
  */
263
260
  async flush({ timeout = 500 } = {}) {
264
261
  if (!this._swarm) return
265
- await Promise.race([this._swarm.flush(), new Promise((r) => setTimeout(r, timeout))])
262
+ await capped(this._swarm.flush(), timeout)
266
263
  }
267
264
 
268
265
  /**
@@ -391,6 +388,16 @@ function dropIfSilent(conn) {
391
388
  conn.once('close', () => clearTimeout(timer))
392
389
  }
393
390
 
391
+ // the timer goes once the race settles, or it keeps a closed process alive
392
+ async function capped(promise, ms) {
393
+ let timer = null
394
+ try {
395
+ await Promise.race([promise, new Promise((resolve) => (timer = setTimeout(resolve, ms)))])
396
+ } finally {
397
+ clearTimeout(timer)
398
+ }
399
+ }
400
+
394
401
  function isTopic(x) {
395
402
  return b4a.isBuffer(x) && x.length === 32
396
403
  }