@cero-base/core 2.3.4 → 2.4.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.
@@ -14,18 +14,16 @@ export const ADMIN = 'admin'
14
14
  export const MEMBER = 'member'
15
15
  export const READER = 'reader'
16
16
 
17
- export const READ = 'read'
18
17
  export const WRITE = 'write'
19
- export const DELETE = 'delete'
20
18
  export const INVITE = 'invite'
21
19
  export const REMOVE = 'remove'
22
20
  export const ASSIGN = 'assign'
23
21
 
24
22
  export const ROLE_PERMS = {
25
23
  [OWNER]: ['*'],
26
- [ADMIN]: [READ, WRITE, DELETE, INVITE, REMOVE, ASSIGN],
27
- [MEMBER]: [READ, WRITE, INVITE],
28
- [READER]: [READ]
24
+ [ADMIN]: [WRITE, INVITE, REMOVE, ASSIGN],
25
+ [MEMBER]: [WRITE, INVITE],
26
+ [READER]: []
29
27
  }
30
28
 
31
29
  export const RANK = { [OWNER]: 3, [ADMIN]: 2, [MEMBER]: 1, [READER]: 0 }
package/src/lib/utils.js CHANGED
@@ -1,15 +1,16 @@
1
1
  import b4a from 'b4a'
2
2
  import { Readable } from 'streamx'
3
3
 
4
- import { ROLE_PERMS, RANK, QUERY_RESERVED } from './constants.js'
4
+ import { ROLE_PERMS, RANK, QUERY_RESERVED, WRITE, INVITE, ASSIGN, REMOVE } from './constants.js'
5
5
  import { CeroError } from './errors.js'
6
6
 
7
7
  // can() callers need the capability names, and constants.js is not public
8
8
  export { WRITE, INVITE, ASSIGN, REMOVE } from './constants.js'
9
9
 
10
- // binding the db key makes an admission unreplayable across rooms
10
+ const PERMS = new Set([WRITE, INVITE, ASSIGN, REMOVE])
11
+
12
+ // binding the db key makes an admission unreplayable across databases
11
13
  const ADD_WRITER_TAG = b4a.from('cero/add-writer')
12
- const CLAIM_WRITER_TAG = b4a.from('cero/claim-writer')
13
14
  const JOIN_TAG = b4a.from('cero/join')
14
15
 
15
16
  // fields the write path stamps itself, always allowed
@@ -20,12 +21,7 @@ export function admission(dbKey, writer, appender) {
20
21
  return b4a.concat([ADD_WRITER_TAG, dbKey, writer, appender])
21
22
  }
22
23
 
23
- /** @type {(dbKey: Uint8Array, writer: Uint8Array) => Uint8Array} */
24
- export function ownership(dbKey, writer) {
25
- return b4a.concat([CLAIM_WRITER_TAG, dbKey, writer])
26
- }
27
-
28
- // what a joiner's identity signs: this room, this invite, this writer, where the keys go
24
+ // what a joiner's identity signs: this database, this invite, this writer, where the keys go
29
25
  /** @type {(dbKey: Uint8Array, invite: Uint8Array, writer: Uint8Array, reply: Uint8Array) => Uint8Array} */
30
26
  export function joining(dbKey, invite, writer, reply) {
31
27
  return b4a.concat([JOIN_TAG, dbKey, invite, writer, reply])
@@ -39,6 +35,9 @@ export function joining(dbKey, invite, writer, reply) {
39
35
  * @returns {boolean}
40
36
  */
41
37
  export function can(role, perm) {
38
+ if (!PERMS.has(perm)) {
39
+ throw CeroError.INVALID(`'${perm}' is not a permission: write, invite, assign or remove`)
40
+ }
42
41
  const perms = ROLE_PERMS[role]
43
42
  return !!perms && (perms.includes('*') || perms.includes(perm))
44
43
  }
@@ -34,7 +34,7 @@ import { CeroError } from '../lib/errors.js'
34
34
  */
35
35
  export class Mailbox extends ReadyResource {
36
36
  /**
37
- * @param {import('../network/index.js').Network} network Needs a store: messages travel as cores in it.
37
+ * @param {import('../network/index.js').Network} network Messages travel as cores in its store.
38
38
  * @param {MailboxOpts} [opts]
39
39
  */
40
40
  constructor(
@@ -42,7 +42,7 @@ export class Mailbox extends ReadyResource {
42
42
  { inbox = memory(), outbox = memory(), onerror = (err) => console.error(err) } = {}
43
43
  ) {
44
44
  super()
45
- if (!network?.store) throw CeroError.REQUIRED('store')
45
+ if (!network) throw CeroError.REQUIRED('network')
46
46
  this.network = network
47
47
  this.inbox = inbox
48
48
  this.outbox = outbox
@@ -1,7 +1,6 @@
1
1
  import NoiseSecretStream from '@hyperswarm/secret-stream'
2
2
  import Autobee from 'autobee'
3
3
  import BlindPeering from 'blind-peering'
4
- import Protomux from 'protomux'
5
4
  import ProtomuxWakeup from 'protomux-wakeup'
6
5
  import ReadyResource from 'ready-resource'
7
6
  import safetyCatch from 'safety-catch'
@@ -10,7 +9,6 @@ import { hash } from 'hypercore-crypto'
10
9
  import HyperDHT from 'hyperdht'
11
10
  import Hyperswarm from 'hyperswarm'
12
11
  import b4a from 'b4a'
13
- import c from 'compact-encoding'
14
12
 
15
13
  import { ACTIVE, PASSIVE } from '../lib/constants.js'
16
14
  import { CeroError } from '../lib/errors.js'
@@ -34,20 +32,18 @@ export function channelTopic(topic, channel) {
34
32
  * @property {Uint8Array[]} [relayThrough] Relay public keys to tunnel through.
35
33
  * @property {number[]} [backoffs] Reconnect backoff tiers in ms; the default escalates to ~10min, far too slow for local nets.
36
34
  * @property {string} [channel] Optional network-isolation label; only same-channel peers meet.
37
- * @property {import('corestore')} [store] Corestore; required for mirrors (blind peers replicate its cores).
38
- * @property {Array<string | Uint8Array>} [mirrors] Blind-peer public keys; each attached room/blob core is mirrored through them for offline sync.
35
+ * @property {import('corestore')} store Corestore; every connection replicates it, so every core it holds rides every peer.
36
+ * @property {Array<string | Uint8Array>} [mirrors] Blind-peer public keys; each attached database/blob core is mirrored through them for offline sync.
39
37
  * @property {(err: Error) => void} [onerror] Background-task error handler.
40
38
  * @property {{ active?: number, announced?: number, idle?: number }} [presence] Swarm budget for attached databases: how many search, how many only announce, and the idle ms before the rest leave.
41
- *
42
- * @typedef {{ replicate: (stream: import('@hyperswarm/secret-stream')) => unknown }} Replicable
43
39
  */
44
40
 
45
41
  /**
46
- * Hyperswarm peer-discovery + replication multiplexer. Wraps a swarm and a
47
- * shared wakeup channel, replicating any attached resource onto every peer.
42
+ * Hyperswarm peer discovery plus a shared wakeup channel. Every connection, swarm or injected,
43
+ * replicates the store.
48
44
  */
49
45
  export class Network extends ReadyResource {
50
- /** @param {NetworkOpts} [opts] */
46
+ /** @param {NetworkOpts} opts */
51
47
  constructor({
52
48
  identity,
53
49
  bootstrap,
@@ -61,14 +57,15 @@ export class Network extends ReadyResource {
61
57
  onerror = (err) => console.error(err)
62
58
  } = {}) {
63
59
  super()
60
+ if (!store) throw CeroError.REQUIRED('store')
64
61
  this.identity = identity || null
65
62
  this.bootstrap = bootstrap || null
66
63
  this.firewall = firewall || null
67
64
  this.relayThrough = relayThrough || null
68
65
  this.backoffs = backoffs || null
69
66
  this.channel = channel || null
70
- /** @type {import('corestore') | null} */
71
- this.store = store || null
67
+ /** @type {import('corestore')} */
68
+ this.store = store
72
69
  /** @type {Uint8Array[]} */
73
70
  this.mirrors = (mirrors || []).map((k) => (typeof k === 'string' ? decodeKey(k) : k))
74
71
 
@@ -78,14 +75,6 @@ export class Network extends ReadyResource {
78
75
  this.wakeup = new ProtomuxWakeup()
79
76
  this.presence = new Presence(this, presence)
80
77
 
81
- this.info = null
82
- /** @private */
83
- this._peerInfo = new Map()
84
- /** @private */
85
- this._infoSenders = new Set()
86
-
87
- /** @private */
88
- this._replicateables = new Set()
89
78
  /** @private */
90
79
  this._discoveries = new Set()
91
80
  /** @private */
@@ -149,17 +138,10 @@ export class Network extends ReadyResource {
149
138
  }
150
139
  dropIfSilent(stream)
151
140
  stream.on('close', () => this._lose(stream.remotePublicKey))
152
- this.wakeup.addStream(stream)
153
- for (const r of this._replicateables) replicateInto(r, stream)
154
- this.emit('connection', stream, info)
141
+ this._add(stream, info)
155
142
  })
156
143
 
157
- if (this.store) {
158
- // mailbox cores live in the store: every connection replicates it, so a listener can fetch them
159
- const store = this.store
160
- this._replicateables.add({ store, replicate: (stream) => store.replicate(stream) })
161
- if (this.mirrors.length) this.peering()
162
- }
144
+ if (this.mirrors.length) this.peering()
163
145
  }
164
146
 
165
147
  /** @private */
@@ -233,13 +215,17 @@ export class Network extends ReadyResource {
233
215
  conn.on('close', () => this._injected.delete(conn))
234
216
  conn.on('error', safetyCatch) // a dropped radio link must not crash the host
235
217
 
236
- this.wakeup.addStream(conn)
237
- this._attachInfo(conn)
238
- for (const r of this._replicateables) replicateInto(r, conn)
239
- this.emit('connection', conn, { injected: true })
218
+ this._add(conn, { injected: true })
240
219
  return conn
241
220
  }
242
221
 
222
+ /** @private */
223
+ _add(conn, info) {
224
+ this.wakeup.addStream(conn)
225
+ this.store.replicate(conn)
226
+ this.emit('connection', conn, info)
227
+ }
228
+
243
229
  /**
244
230
  * The blind-peering client, built on first use: a mailbox post names mirrors this network
245
231
  * may not have been given.
@@ -248,7 +234,6 @@ export class Network extends ReadyResource {
248
234
  */
249
235
  peering() {
250
236
  if (this.closing || this.closed) throw CeroError.CLOSED('Network')
251
- if (!this.store) throw CeroError.REQUIRED('store')
252
237
  if (!this._blindPeering) {
253
238
  this._blindPeering = new BlindPeering(this.swarm.dht, this.store, {
254
239
  blindPeers: this.mirrors.map((key) => ({ key })),
@@ -259,28 +244,6 @@ export class Network extends ReadyResource {
259
244
  return this._blindPeering
260
245
  }
261
246
 
262
- /**
263
- * Declare this peer's self-reported info ({ name, ... }) to the peers of injected streams.
264
- *
265
- * @param {object | null} info
266
- */
267
- setInfo(info) {
268
- this.info = info || null
269
- if (!this.info) return
270
- for (const send of this._infoSenders) send()
271
- }
272
-
273
- /**
274
- * Info a connected peer declared about itself, or null.
275
- *
276
- * @param {Uint8Array | string} key Peer public key (bytes or hex).
277
- * @returns {object | null}
278
- */
279
- getInfo(key) {
280
- const hex = typeof key === 'string' ? key : b4a.toHex(key)
281
- return this._peerInfo.get(hex) ?? null
282
- }
283
-
284
247
  /**
285
248
  * Wait for pending DHT announces and lookups to settle, bounded by timeout.
286
249
  *
@@ -343,21 +306,27 @@ export class Network extends ReadyResource {
343
306
  }
344
307
 
345
308
  /**
346
- * Register a replicable resource (hypercore, autobee, hyperdb).
347
- * It is replicated on every current and future swarm connection.
309
+ * Whether `store` replicates on this network's connections: the network's store or a session of it.
348
310
  *
349
- * @param {Replicable} core
311
+ * @param {import('corestore')} store
312
+ * @returns {boolean}
313
+ */
314
+ replicates(store) {
315
+ return (store.root || store) === (this.store.root || this.store)
316
+ }
317
+
318
+ /**
319
+ * Keep a core or an autobee on the mirrors, so it stays reachable while its writers are
320
+ * offline. It rides the connections already, from the store; a mirror drops it once it closes.
321
+ *
322
+ * @param {import('hypercore') | import('autobee')} core
350
323
  * @returns {void}
351
324
  */
352
325
  attach(core) {
353
326
  if (!core) throw CeroError.REQUIRED('core')
354
- this._replicateables.add(core)
355
- for (const stream of this.connections) replicateInto(core, stream)
356
- // mirror the core so it stays available while its writers are offline
357
- if (this._blindPeering) {
358
- if (Autobee.isAutobee(core)) core.ready().then(() => this._mirror(core), this._onerror)
359
- else this._blindPeering.addCoreBackground(core)
360
- }
327
+ if (!this._blindPeering) return
328
+ if (Autobee.isAutobee(core)) core.ready().then(() => this._mirror(core), this._onerror)
329
+ else this._blindPeering.addCoreBackground(core)
361
330
  }
362
331
 
363
332
  /** @private */
@@ -367,7 +336,7 @@ export class Network extends ReadyResource {
367
336
  peering.addAutobaseBackground(bee)
368
337
  // the bootstrap core leaves the writer set after the local swap, but joiners boot from it
369
338
  peering.addCoreBackground(bee.bootstrap, { referrer: bee.key })
370
- // autobee links views only through a trusted head, which a fresh room's first nodes lack
339
+ // autobee links views only through a trusted head, which a fresh database's first nodes lack
371
340
  const views = bee.views().map((v) => this.store.get({ key: v.key }))
372
341
  for (const view of views) peering.addCoreBackground(view, { referrer: bee.key })
373
342
  bee.once('close', () => {
@@ -375,32 +344,6 @@ export class Network extends ReadyResource {
375
344
  })
376
345
  }
377
346
 
378
- /**
379
- * Unregister a previously attached resource. New connections will no
380
- * longer replicate it (existing replication streams continue).
381
- *
382
- * @param {Replicable} core
383
- * @returns {void}
384
- */
385
- detach(core) {
386
- if (!core) throw CeroError.REQUIRED('core')
387
- this._replicateables.delete(core)
388
- }
389
-
390
- /**
391
- * Replicate a one-off resource onto every current swarm connection
392
- * without registering it as a long-lived attachment.
393
- *
394
- * @param {Replicable} target
395
- * @returns {void}
396
- */
397
- replicate(target) {
398
- if (!target || typeof target.replicate !== 'function') {
399
- throw CeroError.INVALID('target must be an object with a replicate(stream) method')
400
- }
401
- for (const stream of this.connections) replicateInto(target, stream)
402
- }
403
-
404
347
  // hyperswarm stops redialing a peer after a few failed tries and looks it up again only every 10 min
405
348
  /** @private */
406
349
  _lose(key) {
@@ -423,34 +366,6 @@ export class Network extends ReadyResource {
423
366
  }, RELOOKUPS[i])
424
367
  this._relookup.unref()
425
368
  }
426
-
427
- // injected streams only: bytes on a fresh swarm connection trip hyperswarm's duplicate guard
428
- /** @private */
429
- _attachInfo(conn) {
430
- const mux = Protomux.from(conn)
431
- let message = null
432
- const send = () => {
433
- if (!message) {
434
- const channel = mux.createChannel({ protocol: 'cero/info' })
435
- if (channel === null) return
436
- message = channel.addMessage({
437
- encoding: c.json,
438
- onmessage: (info) => {
439
- if (!info || typeof info !== 'object') return
440
- const hex = b4a.toHex(conn.remotePublicKey)
441
- this._peerInfo.set(hex, info)
442
- this.emit('peer-info', hex, info)
443
- }
444
- })
445
- channel.open()
446
- }
447
- if (this.info) message.send(this.info)
448
- }
449
- mux.pair({ protocol: 'cero/info' }, send)
450
- this._infoSenders.add(send)
451
- conn.on('close', () => this._infoSenders.delete(send))
452
- if (this.info) send()
453
- }
454
369
  }
455
370
 
456
371
  function dropIfSilent(conn) {
@@ -461,24 +376,6 @@ function dropIfSilent(conn) {
461
376
  conn.once('close', () => clearTimeout(timer))
462
377
  }
463
378
 
464
- // corestore replication is store-wide: replicate each root once per connection
465
- const replicatedRoots = new WeakMap()
466
-
467
- function replicateInto(core, stream) {
468
- const root = core.store ? core.store.root || core.store : null
469
- if (root) {
470
- let seen = replicatedRoots.get(stream)
471
- if (!seen) replicatedRoots.set(stream, (seen = new WeakSet()))
472
- if (seen.has(root)) return
473
- seen.add(root)
474
- }
475
- try {
476
- core.replicate(stream)
477
- } catch (err) {
478
- safetyCatch(err)
479
- }
480
- }
481
-
482
379
  function isTopic(x) {
483
380
  return b4a.isBuffer(x) && x.length === 32
484
381
  }
@@ -102,7 +102,7 @@ export class Presence {
102
102
  this.entries.clear()
103
103
  }
104
104
 
105
- // up at once, down after idle: a room at the edge of the budget must not churn the DHT
105
+ // up at once, down after idle: a database at the edge of the budget must not churn the DHT
106
106
  /** @private */
107
107
  _want(e, mode) {
108
108
  const current = e.discovery ? e.discovery.mode : null
@@ -7,7 +7,7 @@ import hid from 'hypercore-id-encoding'
7
7
  import Autobee from 'autobee'
8
8
 
9
9
  import { Invite } from './invite.js'
10
- import { Request, Response, STATUS_ACCEPTED, STATUS_DENIED } from './request.js'
10
+ import { Response, STATUS_ACCEPTED, STATUS_DENIED } from './response.js'
11
11
  import { Mailbox } from '../mailbox/index.js'
12
12
  import { Post } from '../mailbox/post.js'
13
13
  import { wrap } from '../database/envelope.js'
@@ -33,12 +33,16 @@ const MAX_DELAY = 2 ** 31 - 1
33
33
  * @property {boolean} [confirm] Its joins wait for a member to accept them, as requests.
34
34
  * @property {Uint8Array | null} [data] The app's payload in the invite, readable before joining: `Invite.parse(invite).data`.
35
35
  *
36
+ * @typedef {object} AcceptOpts
37
+ * @property {string} [role] Role granted: the invite's by default, at most the invite's.
38
+ *
36
39
  * @typedef {object} JoinOpts
37
40
  * @property {import('../identity/index.js').Identity} identity Who joins: the member they become, and who signs the join.
38
41
  * @property {{ dispatch: { encode: Function }, meta?: { ns?: string, version?: number } }} spec The database's spec: the join is one of its ops.
39
42
  * @property {KeyPair} [writer] Their writer keypair in the database, a fresh one by default. The join is its first block and its secret key owns the reply address: pass the same one to resume a join after a restart.
40
43
  * @property {number} [timeout] Deadline for the reply, in ms; `0` waits until the invite expires, or for good. Defaults to 30000.
41
44
  * @property {AbortSignal} [signal] Stops the join, rejecting it with `CLOSED`, as closing the mailbox does.
45
+ * @property {(answer: JoinResult | Error) => Promise<unknown>} [keep] Saves the answer, the keys or the `DENIED`, before the join settles: the reply stays in the mailbox until it resolves, so a join resumed with the same writer after a crash gets it again.
42
46
  *
43
47
  * @typedef {object} JoinResult
44
48
  * @property {Uint8Array} key
@@ -54,7 +58,7 @@ const MAX_DELAY = 2 ** 31 - 1
54
58
  * that may invite offers them while online, and the first one read settles it for all. A join
55
59
  * turned away with an invite the database knows, spent, revoked or older than the joiner's
56
60
  * removal, is answered the same way with `DENIED` and the reason. A `confirm` invite's joins wait
57
- * as requests until a member accepts or denies them; `'request'` fires for each new one.
61
+ * as rows of `requests` until a member accepts or denies one by its id.
58
62
  * `Pairing.join` is the other side: write the join, wait for the reply.
59
63
  */
60
64
  export class Pairing extends ReadyResource {
@@ -66,13 +70,9 @@ export class Pairing extends ReadyResource {
66
70
 
67
71
  this.mailbox = mailbox
68
72
  this.db = db
69
- /** @type {Set<Request>} requests not answered yet: whoever attaches after one fired goes through these first */
70
- this.pending = new Set()
71
73
  /** Whether this device answers the database's joins: it may invite, and invites or joiners owed an answer exist. */
72
74
  this.serving = false
73
75
 
74
- /** @private */
75
- this._requests = new Map() // writer id → Request
76
76
  /** @private */
77
77
  this._replies = new Map() // writer id → the Post offering its keys
78
78
  /** @private */
@@ -157,20 +157,49 @@ export class Pairing extends ReadyResource {
157
157
  }
158
158
 
159
159
  /**
160
- * A join waiting on a `confirm` invite, by its id in the `requests` collection.
160
+ * Admit a join waiting on a `confirm` invite, by its id in `requests`. Every device of an
161
+ * inviter then replies with the keys.
162
+ *
163
+ * @param {string} id
164
+ * @param {AcceptOpts} [opts]
165
+ * @returns {Promise<void>}
166
+ */
167
+ async accept(id, { role } = {}) {
168
+ const invite = await this._waiting(id)
169
+ // apply has no clock: it would admit past the expiry
170
+ if (expired(invite)) throw CeroError.EXPIRED()
171
+ role = role || invite.role
172
+ if (!isRank(role)) {
173
+ throw CeroError.INVALID(`role '${role}' is not a rank (owner, admin, member, reader)`)
174
+ }
175
+ if (!grants(invite.role, role)) {
176
+ throw CeroError.INVALID(`role '${role}' exceeds the invite role '${invite.role}'`)
177
+ }
178
+ await this.db.call('accept', { id, role })
179
+ }
180
+
181
+ /**
182
+ * Refuse a join waiting on a `confirm` invite, by its id in `requests`, with an optional reason.
161
183
  *
162
184
  * @param {string} id
163
- * @returns {Promise<Request>}
185
+ * @param {string} [reason]
186
+ * @returns {Promise<void>}
164
187
  */
165
- async request(id) {
166
- // the row can be read before this device has caught up with it
167
- if (!this._requests.has(id)) await this._sync()
168
- const request = this._requests.get(id)
169
- if (!request) throw CeroError.UNKNOWN('request', id)
170
- return request
188
+ async deny(id, reason = '') {
189
+ await this._waiting(id)
190
+ await this.db.call('deny', { id, reason })
171
191
  }
172
192
 
173
- // follow the log: the invites that ran out, the joins waiting for a member, the answers owed
193
+ // the invite of a join nobody has answered yet
194
+ /** @private */
195
+ async _waiting(id) {
196
+ const { data: row } = await this.db.get('requests', id)
197
+ const invite = row && !row.admitted && (await this.db.get('invites', row.invite)).data
198
+ if (!invite) throw CeroError.UNKNOWN('request', id)
199
+ return invite
200
+ }
201
+
202
+ // follow the log: the invites that ran out, the answers owed
174
203
  /** @private */
175
204
  async _sync() {
176
205
  const me = await this._me()
@@ -191,7 +220,6 @@ export class Pairing extends ReadyResource {
191
220
  const inviter = can(role, INVITE)
192
221
  const owed = inviter ? requests.filter((row) => row.admitted) : []
193
222
  const refused = inviter ? refusals : []
194
- this._pending(inviter ? requests.filter((row) => !row.admitted) : [], invites)
195
223
  await this._answer(owed, refused, role)
196
224
  const live = invites.some((row) => !expired(row))
197
225
  this.serving = inviter && (live || owed.length > 0 || refused.length > 0)
@@ -211,25 +239,6 @@ export class Pairing extends ReadyResource {
211
239
  )
212
240
  }
213
241
 
214
- /** @private */
215
- _pending(rows, invites) {
216
- const live = new Set(rows.map((row) => row.id))
217
- // settled elsewhere: accepted or denied by another member, or its invite revoked
218
- for (const [id, request] of this._requests) {
219
- if (live.has(id)) continue
220
- this._requests.delete(id)
221
- this.pending.delete(request)
222
- }
223
- for (const row of rows) {
224
- const invite = invites.find((i) => i.id === row.invite)
225
- if (!invite || this._requests.has(row.id)) continue
226
- const request = new Request({ pairing: this, invite, row })
227
- this._requests.set(row.id, request)
228
- this.pending.add(request)
229
- this.emit('request', request)
230
- }
231
- }
232
-
233
242
  // an admitted joiner is offered its keys, and a refused one the reason, by every inviter device
234
243
  // online, until one is read. Past the invite's expiry the joiner has given up: a member who can
235
244
  // remove drops an admitted one instead, and a refused one is forgotten
@@ -330,7 +339,14 @@ export class Pairing extends ReadyResource {
330
339
  static async join(
331
340
  mailbox,
332
341
  invite,
333
- { identity, spec, writer = crypto.keyPair(), timeout = 30000, signal = null } = {}
342
+ {
343
+ identity,
344
+ spec,
345
+ writer = crypto.keyPair(),
346
+ timeout = 30000,
347
+ signal = null,
348
+ keep = async () => {}
349
+ } = {}
334
350
  ) {
335
351
  if (!mailbox) throw CeroError.REQUIRED('mailbox')
336
352
  if (typeof identity?.sign !== 'function') throw CeroError.REQUIRED('identity')
@@ -348,12 +364,17 @@ export class Pairing extends ReadyResource {
348
364
  resolve = res
349
365
  fail = rej
350
366
  })
351
- const onreply = (message) => {
367
+ const settle = async (answer, done) => {
368
+ await keep(answer)
369
+ done(answer)
370
+ }
371
+ const onreply = async (message) => {
352
372
  const response = decode(Response, message)
353
- if (response?.status === STATUS_DENIED) fail(CeroError.DENIED(response.reason || null))
354
- else if (response?.key && b4a.equals(response.key, parsed.key)) {
373
+ if (response?.status === STATUS_DENIED) {
374
+ await settle(CeroError.DENIED(response.reason || null), fail)
375
+ } else if (response?.key && b4a.equals(response.key, parsed.key)) {
355
376
  const { key, encryptionKey, epochs } = response
356
- resolve({ key, encryptionKey, epochs: epochs || [], writer })
377
+ await settle({ key, encryptionKey, epochs: epochs || [], writer }, resolve)
357
378
  }
358
379
  }
359
380
 
@@ -0,0 +1,8 @@
1
+ import { getEncoding } from '../lib/spec/index.js'
2
+
3
+ export const STATUS_ACCEPTED = 0
4
+ export const STATUS_DENIED = 1
5
+
6
+ // an accept and a deny both ride this response
7
+ /** @type {import('compact-encoding').Encoder<{ status: number, reason?: string, key?: Uint8Array | null, encryptionKey?: Uint8Array | null, epochs?: Array<{ epoch: number, stamp: number, entropy: Uint8Array }> | null }>} */
8
+ export const Response = getEncoding('@cero/confirm')
@@ -127,6 +127,7 @@ export class Storage extends ReadyResource {
127
127
  async put(name, row) {
128
128
  this._guard()
129
129
  const ref = this._ref(name)
130
+ if (ref.kind === SINGLE) throw CeroError.INVALID(`${name} is a single: write it with set`)
130
131
  checkFields(name, this.refs[name], row)
131
132
  const was = row.id == null ? null : await this._read(ref, row.id)
132
133
  const stored = stamp({ ...row, id: row.id ?? genId() }, was?.createdAt)
@@ -149,8 +150,10 @@ export class Storage extends ReadyResource {
149
150
  checkFields(name, this.refs[name], row)
150
151
  const existing = await this._read(ref, row?.id)
151
152
  if (!upsert && !existing) return null
153
+ // a single is one record with no fields of Cero's
154
+ const merged = { ...existing, ...row }
152
155
  /** @type {Row} */
153
- const stored = stamp({ ...existing, ...row }, existing?.createdAt)
156
+ const stored = ref.kind === SINGLE ? merged : stamp(merged, existing?.createdAt)
154
157
  checkRequired(name, this.refs[name], stored)
155
158
  if (ref.kind === COLLECTION && !stored.id) stored.id = genId()
156
159
  await this._write(ref, stored)
@@ -6,11 +6,7 @@ export type BlobsOpts = {
6
6
  */
7
7
  store: object;
8
8
  /**
9
- * Identity supplying the default encryption key.
10
- */
11
- identity?: import('../identity/index.js').Identity;
12
- /**
13
- * Optional network used to announce + replicate the core.
9
+ * Optional network on this store: the core rides its connections and mirrors.
14
10
  */
15
11
  network?: import('../network/index.js').Network;
16
12
  /**
@@ -18,9 +14,9 @@ export type BlobsOpts = {
18
14
  */
19
15
  key?: Uint8Array;
20
16
  /**
21
- * Explicit encryption key, overrides `identity.encryptionKey`.
17
+ * Encrypts the core.
22
18
  */
23
- encryptionKey?: Uint8Array;
19
+ encryptionKey: Uint8Array;
24
20
  /**
25
21
  * Core name in the store when no `key` is given; `blobs` by default.
26
22
  */
@@ -30,10 +26,9 @@ export type RawBlobId = import('./codec.js').RawBlobId;
30
26
  /**
31
27
  * @typedef {object} BlobsOpts
32
28
  * @property {object} store Corestore (or compatible) used to host the blob core.
33
- * @property {import('../identity/index.js').Identity} [identity] Identity supplying the default encryption key.
34
- * @property {import('../network/index.js').Network} [network] Optional network used to announce + replicate the core.
29
+ * @property {import('../network/index.js').Network} [network] Optional network on this store: the core rides its connections and mirrors.
35
30
  * @property {Uint8Array} [key] Pre-existing blob core key — joins an existing blob feed.
36
- * @property {Uint8Array} [encryptionKey] Explicit encryption key, overrides `identity.encryptionKey`.
31
+ * @property {Uint8Array} encryptionKey Encrypts the core.
37
32
  * @property {string} [name] Core name in the store when no `key` is given; `blobs` by default.
38
33
  *
39
34
  * @typedef {import('./codec.js').RawBlobId} RawBlobId
@@ -41,7 +36,6 @@ export type RawBlobId = import('./codec.js').RawBlobId;
41
36
  /** Thin wrapper over a single Hyperblobs core; deals only in raw blobIds. */
42
37
  export declare class Blobs extends ReadyResource {
43
38
  store: object;
44
- identity: import("../index.js").Identity;
45
39
  network: import("../index.js").Network;
46
40
  encryptionKey: Uint8Array<ArrayBufferLike>;
47
41
  name: string;
@@ -51,10 +45,8 @@ export declare class Blobs extends ReadyResource {
51
45
  core: import('hypercore') | null;
52
46
  /** @type {import('hyperblobs') | null} */
53
47
  hyperblobs: import('hyperblobs') | null;
54
- /** @private */
55
- _discovery;
56
48
  /** @param {BlobsOpts} [opts] */
57
- constructor({ store, identity, network, key, encryptionKey, name }?: BlobsOpts);
49
+ constructor({ store, network, key, encryptionKey, name }?: BlobsOpts);
58
50
  /**
59
51
  * Canonical z32 id of the underlying core (null until ready).
60
52
  *