@cero-base/core 3.0.1 → 3.2.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": "3.0.1",
3
+ "version": "3.2.0",
4
4
  "description": "cero p2p primitives — identity, storage, network, database, blobs, rpc, pairing.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -152,20 +152,20 @@
152
152
  },
153
153
  "dependencies": {
154
154
  "@hyperswarm/secret-stream": "^6.9.2",
155
- "autobee": "2.13.4",
155
+ "autobee": "2.13.6",
156
156
  "b4a": "^1.9.0",
157
157
  "bare-crypto": "^1.15.4",
158
158
  "bare-fs": "^4.8.4",
159
- "bare-path": "^3.1.2",
159
+ "bare-path": "^3.1.3",
160
160
  "bip39-mnemonic": "^2.5.0",
161
161
  "blind-peering": "^2.14.0",
162
162
  "blind-push": "^1.2.1",
163
- "compact-encoding": "^3.6.0",
163
+ "compact-encoding": "^3.7.0",
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.40.3",
168
+ "hypercore": "^11.40.4",
169
169
  "hypercore-blob-server": "^1.15.1",
170
170
  "hypercore-crypto": "^3.7.0",
171
171
  "hypercore-id-encoding": "^1.3.0",
@@ -177,7 +177,7 @@
177
177
  "hyperswarm": "^4.17.2",
178
178
  "keet-identity-key": "^3.2.0",
179
179
  "ms": "^2.1.3",
180
- "protomux-wakeup": "^2.9.0",
180
+ "protomux-wakeup": "^2.9.1",
181
181
  "ready-resource": "^1.2.0",
182
182
  "safety-catch": "^1.0.3",
183
183
  "sodium-universal": "^5.0.1",
@@ -188,11 +188,11 @@
188
188
  "@hyperswarm/testnet": "^3.1.4",
189
189
  "bare-abort-controller": "^1.1.2",
190
190
  "bare-events": "^2.9.2",
191
- "bare-fetch": "^3.4.1",
191
+ "bare-fetch": "^3.5.0",
192
192
  "bare-process": "^4.5.1",
193
193
  "bare-subprocess": "^6.2.2",
194
- "bare-url": "^2.5.6",
195
- "blind-peer": "^3.18.1",
194
+ "bare-url": "^2.5.7",
195
+ "blind-peer": "^3.18.2",
196
196
  "blind-push-gateway": "^1.0.0",
197
197
  "brittle": "^4.5.0",
198
198
  "protomux": "^3.13.1",
@@ -17,6 +17,8 @@ import {
17
17
  REFUSALS,
18
18
  SPENT,
19
19
  ASKS,
20
+ PASSES,
21
+ MAX_PASS,
20
22
  OWNER,
21
23
  INVITE,
22
24
  REMOVE,
@@ -75,7 +77,8 @@ const REQUESTS = {
75
77
  deny: 'deny',
76
78
  'rotate-key': 'epoch',
77
79
  revoke: 'revoke',
78
- 'ask-key': 'owed'
80
+ 'ask-key': 'owed',
81
+ 'add-pass': 'pass'
79
82
  }
80
83
 
81
84
  // the device keys a request stands on: its own, and those of the chain its join proved or a link
@@ -186,6 +189,7 @@ export function makeDispatcher({
186
189
  const refusals = `@${ns}/${REFUSALS}`
187
190
  const spent = `@${ns}/${SPENT}`
188
191
  const asks = `@${ns}/${ASKS}`
192
+ const passes = `@${ns}/${PASSES}`
189
193
  const getMember = (view, id) => view.get(`@${ns}/members`, { id })
190
194
  const getDevice = (view, id) => view.get(`@${ns}/devices`, { id })
191
195
 
@@ -989,16 +993,41 @@ export function makeDispatcher({
989
993
  await ctx.view.delete(asks, op)
990
994
  })
991
995
 
996
+ // a pass waits in a room both are in for the member it is sealed to: left by a member who
997
+ // writes, under her name, never over another, and taken out by either of them or by one who may
998
+ // remove
999
+ add('add-pass', async (op, ctx) => {
1000
+ await requireWrite(ctx)
1001
+ if (!(op.pass.byteLength <= MAX_PASS)) throw CeroError.REFUSED('pass')
1002
+ if (await ctx.view.get(passes, { id: op.id })) throw CeroError.REFUSED('pass')
1003
+ ctx.touched?.push(PASSES)
1004
+ await ctx.view.insert(passes, { ...op, by: await getSignerMember(ctx.view, ctx.key) })
1005
+ })
1006
+ add('del-pass', async (op, ctx) => {
1007
+ const row = await ctx.view.get(passes, { id: op.id })
1008
+ if (!row) return
1009
+ const { memberId, role } = await author(ctx)
1010
+ if (!memberId || (memberId !== row.to && memberId !== row.by && !can(role, REMOVE))) {
1011
+ throw CeroError.REFUSED('pass')
1012
+ }
1013
+ ctx.touched?.push(PASSES)
1014
+ await ctx.view.delete(passes, { id: op.id })
1015
+ })
1016
+
992
1017
  // any WRITE member mints an invite, its rank capped at admission; an existing row is never
993
1018
  // overwritten, and altering or revoking one needs REMOVE
994
1019
  const invites = `@${ns}/invites`
995
1020
  const requests = `@${ns}/requests`
996
1021
  // an invite grants at most its minter's rank, or the join it admits would grant more
997
1022
  const capped = (r, record) => grants(r, record.role)
1023
+ // a rotation is sealed to the keys an invite names: only a seat names any, the kind a removal spends first
1024
+ const named = ({ keys, to, secret, confirm, reuse }) =>
1025
+ !keys?.byteLength || (to && secret && !confirm && !reuse && keys.byteLength <= MAX_PASS)
998
1026
  add('add-invite', async (op, ctx) => {
999
1027
  await requireWrite(ctx)
1000
1028
  if (await ctx.view.get(invites, { id: op.id })) throw CeroError.REFUSED('invite')
1001
1029
  if (!capped(await getSignerRole(ctx.view, ctx.key), op)) throw CeroError.REFUSED('invite')
1030
+ if (!named(op)) throw CeroError.REFUSED('invite')
1002
1031
  await save(ctx, 'put', 'invites', op)
1003
1032
  })
1004
1033
  add('set-invite', async (op, ctx) => {
@@ -1006,10 +1035,11 @@ export function makeDispatcher({
1006
1035
  const existing = await ctx.view.get(invites, { id: op.id })
1007
1036
  if (!existing) return
1008
1037
  const next = { ...existing, ...op }
1009
- if (!can(r, REMOVE) || !capped(r, next)) throw CeroError.REFUSED('invite')
1038
+ if (!can(r, REMOVE) || !capped(r, next) || !named(next)) throw CeroError.REFUSED('invite')
1010
1039
  await save(ctx, 'set', 'invites', next)
1011
1040
  })
1012
- // a live invite is revoked; a spent one, deleted again, is forgotten
1041
+ // a live invite is revoked; a spent one, deleted again once it ran out, is forgotten. Before, a
1042
+ // second revoke, which two devices write as readily as one, keeps it: whoever holds it hears why
1013
1043
  add('del-invite', async (op, ctx) => {
1014
1044
  const r = await getSignerRole(ctx.view, ctx.key)
1015
1045
  const existing = await ctx.view.get(invites, { id: op.id })
@@ -1017,8 +1047,10 @@ export function makeDispatcher({
1017
1047
  if (!can(r, REMOVE) || !capped(r, existing)) throw CeroError.REFUSED('invite')
1018
1048
  return spend(ctx, existing, 'revoked')
1019
1049
  }
1020
- if (!(await ctx.view.get(spent, { id: op.id }))) return
1050
+ const record = await ctx.view.get(spent, { id: op.id })
1051
+ if (!record) return
1021
1052
  if (!can(r, REMOVE)) throw CeroError.REFUSED('invite')
1053
+ if (!record.expires || !(record.expires <= (ctx.ts || 0))) return
1022
1054
  await ctx.view.delete(spent, { id: op.id })
1023
1055
  })
1024
1056
  // its joins still waiting for a member are turned away with it, and the promises made under it
@@ -1029,6 +1061,8 @@ export function makeDispatcher({
1029
1061
  await drop(ctx, 'invites', invite.id)
1030
1062
  const { secret, confirm } = invite
1031
1063
  await ctx.view.insert(spent, { id: invite.id, reason, expires, secret, confirm })
1064
+ // one made to a member went to her with the keys: unused, she holds them and no seat
1065
+ if (invite.to && reason !== 'spent') await owe(ctx.view)
1032
1066
  const kept = async (request) => {
1033
1067
  if (!request.admitted) return false
1034
1068
  if (!request.promised || reason === 'spent') return true
@@ -1201,6 +1235,11 @@ export function makeDispatcher({
1201
1235
  const last = await recorded(ctx.view)
1202
1236
  return refuse(ctx, { ...turned, identity: last ? join.identity : null }, 'removed', last)
1203
1237
  }
1238
+ // one made to a member lets in her devices alone
1239
+ if (invite.to && invite.to !== memberId) {
1240
+ const turned = { id, reply: join.reply, expires: invite.expires || 0, invite: invite.id }
1241
+ return refuse(ctx, { ...turned, identity: join.identity }, 'denied', true)
1242
+ }
1204
1243
  await ctx.view.delete(refusals, { id })
1205
1244
  const gone = known ? null : await ctx.view.get(removals, { id: leftId(memberId) })
1206
1245
  const older = gone && (invite.index ?? 0) <= gone.index
@@ -98,8 +98,10 @@ export function seal(devices, secret) {
98
98
  * @returns {Generator<Uint8Array, void, unknown>}
99
99
  */
100
100
  export function* opened(identity, id, wrapped) {
101
+ // one sealed before this device had a writer is addressed by its device key
102
+ const device = hid.encode(identity.device.publicKey)
101
103
  for (const w of c.decode(wraps, wrapped)) {
102
- if (w.id !== id) continue
104
+ if (w.id !== id && w.id !== device) continue
103
105
  const secret = identity.unseal(w.box)
104
106
  if (secret) yield secret
105
107
  }
@@ -134,6 +134,8 @@ export class Database extends ReadyResource {
134
134
  /** @private */
135
135
  this._landed = false
136
136
  /** @private */
137
+ this._hooked = 0 // update hooks run: a view move none follows is announced on its own
138
+ /** @private */
137
139
  this._rebuilding = null
138
140
  /** @private */
139
141
  this._writes = new Set()
@@ -305,6 +307,15 @@ export class Database extends ReadyResource {
305
307
  this.bee.on('warning', this._onerror)
306
308
  const bee = this.bee
307
309
  this.bee.on('move-to', () => this._onmove(bee))
310
+ // autobee's update hook follows the view's moves as it applies, not those of a boot, a remap or
311
+ // an interrupted run: one no hook follows changes rows all the same, and anyone waiting hears it
312
+ bee.view.watch(() => {
313
+ const hooked = this._hooked
314
+ Promise.resolve().then(() => {
315
+ if (this._hooked !== hooked || this.bee !== bee || this.closing) return
316
+ this.emit('update', new Set(['*']))
317
+ })
318
+ })
308
319
 
309
320
  // with no mirror to hold the database, every member holds it: any member serves a joiner, offline
310
321
  if (this.network && !this.network.mirrors.length) {
@@ -1228,6 +1239,7 @@ export class Database extends ReadyResource {
1228
1239
  // One that landed ranks its database all the same, changed or not: its ops have to reach the others
1229
1240
  /** @private */
1230
1241
  async _update(db) {
1242
+ this._hooked++
1231
1243
  await db.update()
1232
1244
  this._track(await this.dispatcher.version(db))
1233
1245
  const touched = this._touched
@@ -1541,7 +1553,9 @@ export class Database extends ReadyResource {
1541
1553
  key,
1542
1554
  dbKey: this.key,
1543
1555
  seed: crypto.hash([key, value]),
1544
- stamp
1556
+ stamp,
1557
+ // the time the append will carry, at least: what reads it decides as apply will
1558
+ ts: Math.max(Date.now(), this.bee.system.timestamp || 0)
1545
1559
  })
1546
1560
  wrapped.push(wrap(stamp, value))
1547
1561
  }
@@ -353,6 +353,12 @@ export class Rotation {
353
353
  const { data: requests } = await this.db.get('requests')
354
354
  const promised = []
355
355
  for (const row of requests) if (await this._stands(row)) promised.push(row)
356
+ // a seat handed its member the keys before any device of hers asked: sealed to them until she comes
357
+ const { data: invites } = await this.db.get('invites')
358
+ for (const { keys, expires } of invites) {
359
+ if (expires > 0 && Date.now() > expires) continue
360
+ for (const key of keysOf(keys)) promised.push({ id: hid.encode(key), key })
361
+ }
356
362
  return promised
357
363
  }
358
364
 
@@ -490,7 +496,8 @@ export class Rotation {
490
496
  const { data: members } = await this.db.get('members')
491
497
  const standing = new Set(members.map((m) => m.id))
492
498
  const { data: devices } = await this.db.get('devices')
493
- return devices.some((d) => d.key && standing.has(d.memberId) && !named.has(d.id))
499
+ const unnamed = (d) => !named.has(d.id) && !named.has(hid.encode(d.key))
500
+ return devices.some((d) => d.key && standing.has(d.memberId) && unnamed(d))
494
501
  }
495
502
  }
496
503
 
@@ -63,3 +63,7 @@ export const REFUSALS = 'refusals'
63
63
  export const SPENT = 'spent'
64
64
  // devices that asked for the keys they lack, until each closes its own
65
65
  export const ASKS = 'owed'
66
+ // invites into other rooms, sealed to a member's devices, until one of them takes its own
67
+ export const PASSES = 'seats'
68
+ // what a room keeps of one
69
+ export const MAX_PASS = 64 * 1024
@@ -1,12 +1,12 @@
1
1
  // This file is autogenerated by the hyperschema compiler
2
- // Schema Version: 3
2
+ // Schema Version: 4
3
3
  /* eslint-disable camelcase */
4
4
  /* eslint-disable quotes */
5
5
  /* eslint-disable space-before-function-paren */
6
6
 
7
7
  import { c } from 'hyperschema/runtime'
8
8
 
9
- const VERSION = 3
9
+ const VERSION = 4
10
10
 
11
11
  // eslint-disable-next-line no-unused-vars
12
12
  let version = VERSION
@@ -315,6 +315,47 @@ const encoding8 = {
315
315
  }
316
316
  }
317
317
 
318
+ // @cero/pass.epochs
319
+ const encoding9_3 = encoding4_4
320
+
321
+ // @cero/pass
322
+ const encoding9 = {
323
+ preencode(state, m) {
324
+ c.string.preencode(state, m.invite)
325
+ c.fixed32.preencode(state, m.key)
326
+ c.fixed32.preencode(state, m.encryptionKey)
327
+ state.end++ // max flag is 2 so always one byte
328
+
329
+ if (version >= 4 && m.epochs) encoding9_3.preencode(state, m.epochs)
330
+ if (version >= 4 && m.data) c.buffer.preencode(state, m.data)
331
+ },
332
+ encode(state, m) {
333
+ const flags = ((version >= 4 && m.epochs) ? 1 : 0) | ((version >= 4 && m.data) ? 2 : 0)
334
+
335
+ c.string.encode(state, m.invite)
336
+ c.fixed32.encode(state, m.key)
337
+ c.fixed32.encode(state, m.encryptionKey)
338
+ c.uint.encode(state, flags)
339
+
340
+ if (version >= 4 && m.epochs) encoding9_3.encode(state, m.epochs)
341
+ if (version >= 4 && m.data) c.buffer.encode(state, m.data)
342
+ },
343
+ decode(state) {
344
+ const r0 = c.string.decode(state)
345
+ const r1 = c.fixed32.decode(state)
346
+ const r2 = c.fixed32.decode(state)
347
+ const flags = c.uint.decode(state)
348
+
349
+ return {
350
+ invite: r0,
351
+ key: r1,
352
+ encryptionKey: r2,
353
+ epochs: (version >= 4 && (flags & 1) !== 0) ? encoding9_3.decode(state) : null,
354
+ data: (version >= 4 && (flags & 2) !== 0) ? c.buffer.decode(state) : null
355
+ }
356
+ }
357
+ }
358
+
318
359
  function setVersion(v) {
319
360
  version = v
320
361
  }
@@ -356,6 +397,8 @@ function getEncoding(name) {
356
397
  return encoding7
357
398
  case '@cero/blob-id':
358
399
  return encoding8
400
+ case '@cero/pass':
401
+ return encoding9
359
402
  default:
360
403
  throw new Error('Encoder not found ' + name)
361
404
  }
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": 3,
2
+ "version": 4,
3
3
  "schema": [
4
4
  {
5
5
  "name": "link",
@@ -292,6 +292,45 @@
292
292
  "version": 1
293
293
  }
294
294
  ]
295
+ },
296
+ {
297
+ "name": "pass",
298
+ "namespace": "cero",
299
+ "compact": false,
300
+ "flagsPosition": 3,
301
+ "fields": [
302
+ {
303
+ "name": "invite",
304
+ "required": true,
305
+ "type": "string",
306
+ "version": 4
307
+ },
308
+ {
309
+ "name": "key",
310
+ "required": true,
311
+ "type": "fixed32",
312
+ "version": 4
313
+ },
314
+ {
315
+ "name": "encryptionKey",
316
+ "required": true,
317
+ "type": "fixed32",
318
+ "version": 4
319
+ },
320
+ {
321
+ "name": "epochs",
322
+ "required": false,
323
+ "array": true,
324
+ "type": "@cero/epoch",
325
+ "version": 4
326
+ },
327
+ {
328
+ "name": "data",
329
+ "required": false,
330
+ "type": "buffer",
331
+ "version": 4
332
+ }
333
+ ]
295
334
  }
296
335
  ]
297
336
  }
@@ -25,6 +25,8 @@ import { CeroError } from '../lib/errors.js'
25
25
  import { can, grants, isRank, isOptions, joining, INVITE, REMOVE } from '../lib/utils.js'
26
26
  import { NAMESPACE, MEMBER, REFUSALS, SPENT, ASKS } from '../lib/constants.js'
27
27
 
28
+ export { Pass } from './pass.js'
29
+
28
30
  const Join = getEncoding('@cero/join')
29
31
  // what a sync follows in the log
30
32
  const WATCHED = ['*', 'invites', 'requests', 'members', 'devices', ASKS]
@@ -43,6 +45,8 @@ const MAX_DELAY = 2 ** 31 - 1
43
45
  * @property {boolean} [reuse] Admit more than one joiner. Otherwise spent by the first.
44
46
  * @property {boolean} [confirm] Its joins wait for a member to accept them, as requests.
45
47
  * @property {Uint8Array | null} [data] The app's payload in the invite, readable before joining: `Invite.parse(invite).data`.
48
+ * @property {string | null} [to] The id of the one member it is made for: nobody else joins with it. Single-use, never `confirm`.
49
+ * @property {Uint8Array[]} [keys] The device keys of the member it is made `to`, handed the room's keys with it: a rotation before she comes is sealed to them.
46
50
  *
47
51
  * @typedef {object} AcceptOpts
48
52
  * @property {string} [role] Role granted: the invite's by default, at most the invite's.
@@ -144,8 +148,16 @@ export class Pairing extends ReadyResource {
144
148
  async invite(opts = {}) {
145
149
  if (!isOptions(opts)) throw CeroError.INVALID('invite options are an object')
146
150
  const { role = MEMBER, ttl = 0, reuse = false, confirm = false, data = null } = opts
151
+ const to = opts.to == null ? null : memberId(opts.to)
152
+ if (to && (reuse || confirm)) {
153
+ throw CeroError.INVALID("an invite made 'to' a member is single-use and waits for no accept")
154
+ }
147
155
  if (this.closing || this.closed) throw CeroError.CLOSED('Pairing')
148
156
  if (!this.opened) await this.ready()
157
+ // the encoder drops a field the built spec lacks: the invite would let anyone in
158
+ if (to && !('to' in (this.db.meta.since?.types[`@${this.db.ns}/invite`] ?? {}))) {
159
+ throw CeroError.UNSUPPORTED("'to' in 'invites'")
160
+ }
149
161
  // an invite is a capability: capped at our own rank, or apply would drop the mismatch silently
150
162
  await this._checkGrant(role)
151
163
  // a rank above member is handed out once
@@ -163,7 +175,10 @@ export class Pairing extends ReadyResource {
163
175
  confirm,
164
176
  expires: invite.expires,
165
177
  createdAt: Date.now(),
166
- secret
178
+ secret,
179
+ to,
180
+ // only an invite with an address of its own is spent by a removal before its rotation is sealed
181
+ keys: to && secret && opts.keys && (await this._has('keys')) ? b4a.concat(opts.keys) : null
167
182
  }
168
183
  invite.stamp = await this.db.write([['add-invite', row]])
169
184
  if (secret || invite.stamp > this.db.start) invite.version = STAMPED
@@ -176,9 +191,15 @@ export class Pairing extends ReadyResource {
176
191
  // field, or the database's version has not reached it, and the invite carries the room's address
177
192
  /** @private */
178
193
  async _secret() {
179
- const since = this.db.meta.since?.types[`@${this.db.ns}/invite`]?.secret
180
- const version = await this.db.dispatcher.version(this.db.view)
181
- return since <= version ? crypto.randomBytes(32) : null
194
+ return (await this._has('secret')) ? crypto.randomBytes(32) : null
195
+ }
196
+
197
+ // a field of an invite's row the built spec has and the database's version has reached: a write
198
+ // carrying one it has not is refused
199
+ /** @private */
200
+ async _has(field) {
201
+ const since = this.db.meta.since?.types[`@${this.db.ns}/invite`]?.[field]
202
+ return since <= (await this.db.dispatcher.version(this.db.view))
182
203
  }
183
204
 
184
205
  /**
@@ -285,7 +306,8 @@ export class Pairing extends ReadyResource {
285
306
  const secrets = new Map([...invites, ...spent].map((row) => [row.id, row.secret]))
286
307
  await this._answer(owed, refused, role, secrets)
287
308
  await this._deliver(await this._list(ASKS))
288
- const live = invites.some((row) => !expired(row))
309
+ // one made for a member owes no answer: her device joins with the keys it was handed
310
+ const live = invites.some((row) => !row.to && !expired(row))
289
311
  this.serving = inviter && (live || owed.length > 0 || refused.length > 0)
290
312
  this.emit('serving', this.serving)
291
313
  }
@@ -530,20 +552,9 @@ export class Pairing extends ReadyResource {
530
552
  keep = async () => {}
531
553
  } = {}
532
554
  ) {
533
- if (!mailbox) throw CeroError.REQUIRED('mailbox')
534
- if (typeof identity?.sign !== 'function') throw CeroError.REQUIRED('identity')
535
- if (!spec?.dispatch) throw CeroError.REQUIRED('spec')
536
- if (writer?.publicKey?.byteLength !== 32 || writer.secretKey?.byteLength !== 64) {
537
- throw CeroError.INVALID('writer must be a keypair')
538
- }
539
- const parsed = Invite.parse(invite)
540
- if (parsed.expired) throw CeroError.EXPIRED()
555
+ const { parsed, stamp } = joinable(mailbox, invite, { identity, spec, writer })
541
556
  // an invite with its own address proves its answers: one without a valid tag is nobody's
542
557
  const mine = parsed.own ? Mailbox.keyPair(writer.secretKey) : null
543
- // an invite with no stamp was minted before invites carried one: at the start
544
- const { version = 1, start = 1 } = spec.meta || {}
545
- const stamp = parsed.stamp || start
546
- if (stamp > version) throw CeroError.BEHIND(stamp)
547
558
  if (mailbox.closing || mailbox.closed) throw CeroError.CLOSED('join')
548
559
  if (!mailbox.opened) await mailbox.ready()
549
560
 
@@ -587,11 +598,7 @@ export class Pairing extends ReadyResource {
587
598
 
588
599
  // in the network's store, which every connection replicates: open the database from it
589
600
  const { network } = mailbox
590
- const { store } = network
591
- const core = store.get({
592
- keyPair: writer,
593
- manifest: { version: store.manifestVersion, signers: [{ publicKey: writer.publicKey }] }
594
- })
601
+ const core = coreOf(network.store, writer)
595
602
  // a reply read no longer than the join waits for it
596
603
  const reads = timeout > 0 ? { timeout: Math.min(timeout, 30000) } : {}
597
604
  const inbox = mailbox.receive(writer.secretKey, onreply, { keep: false, ...reads })
@@ -617,7 +624,7 @@ export class Pairing extends ReadyResource {
617
624
  const left = parsed.expires - Date.now()
618
625
  // Node's setTimeout overflows past ~24.8 days: a longer ttl expires at the next resume
619
626
  const expiry = parsed.expires && left < MAX_DELAY ? setTimeout(expire, left) : null
620
- write(core, spec, stamp, parsed, identity, writer)
627
+ written(core, spec, stamp, parsed, identity, writer)
621
628
  .then(() => post.ready())
622
629
  .catch((err) => fail(CeroError.NETWORK_ERROR(err.message)))
623
630
  try {
@@ -631,6 +638,28 @@ export class Pairing extends ReadyResource {
631
638
  }
632
639
  }
633
640
 
641
+ /**
642
+ * Write the join into the writer's own core and stop there: nothing is announced and no reply
643
+ * is waited for. A device that holds the database's keys opens it with this writer and applies
644
+ * its own join; `Pairing.join` with the same writer goes on from it and writes nothing more.
645
+ *
646
+ * @param {Mailbox} mailbox
647
+ * @param {string} invite
648
+ * @param {{ identity: JoinOpts['identity'], spec: JoinOpts['spec'], writer: KeyPair }} opts
649
+ * @returns {Promise<void>}
650
+ */
651
+ static async write(mailbox, invite, { identity, spec, writer } = {}) {
652
+ const { parsed, stamp } = joinable(mailbox, invite, { identity, spec, writer })
653
+ if (mailbox.closing || mailbox.closed) throw CeroError.CLOSED('join')
654
+ if (!mailbox.opened) await mailbox.ready()
655
+ const core = coreOf(mailbox.network.store, writer)
656
+ try {
657
+ await written(core, spec, stamp, parsed, identity, writer)
658
+ } finally {
659
+ await core.close()
660
+ }
661
+ }
662
+
634
663
  /**
635
664
  * Take back a join that waits for a member: the writer's own core says so after its join, and
636
665
  * the database drops the request unless a member let it in first. Announced as the join was.
@@ -713,6 +742,44 @@ export function sealJoin(invite, identity, writer, reply) {
713
742
  // the cancel being appended, by writer: two at once on one writer append it once
714
743
  const cancels = new Map()
715
744
 
745
+ // the join being written, by writer: two at once on one writer write it once
746
+ const writing = new Map()
747
+
748
+ // what a join is made with, checked before anything is written: its invite, and the stamp it takes
749
+ function joinable(mailbox, invite, { identity, spec, writer }) {
750
+ if (!mailbox) throw CeroError.REQUIRED('mailbox')
751
+ if (typeof identity?.sign !== 'function') throw CeroError.REQUIRED('identity')
752
+ if (!spec?.dispatch) throw CeroError.REQUIRED('spec')
753
+ if (writer?.publicKey?.byteLength !== 32 || writer.secretKey?.byteLength !== 64) {
754
+ throw CeroError.INVALID('writer must be a keypair')
755
+ }
756
+ const parsed = Invite.parse(invite)
757
+ if (parsed.expired) throw CeroError.EXPIRED()
758
+ // an invite with no stamp was minted before invites carried one: at the start
759
+ const { version = 1, start = 1 } = spec.meta || {}
760
+ const stamp = parsed.stamp || start
761
+ if (stamp > version) throw CeroError.BEHIND(stamp)
762
+ return { parsed, stamp }
763
+ }
764
+
765
+ // a writer's core in the network's store, which every connection replicates
766
+ function coreOf(store, writer) {
767
+ return store.get({
768
+ keyPair: writer,
769
+ manifest: { version: store.manifestVersion, signers: [{ publicKey: writer.publicKey }] }
770
+ })
771
+ }
772
+
773
+ function written(core, spec, stamp, invite, identity, writer) {
774
+ const id = b4a.toHex(writer.publicKey)
775
+ const run = () => write(core, spec, stamp, invite, identity, writer)
776
+ const last = (writing.get(id) ?? Promise.resolve()).then(run, run)
777
+ writing.set(id, last)
778
+ const done = () => writing.get(id) === last && writing.delete(id)
779
+ last.then(done, done)
780
+ return last
781
+ }
782
+
716
783
  async function retract(core, op) {
717
784
  const at = await core.getUserData('cero/cancel')
718
785
  if (at && c.decode(c.uint, at) === core.length) return
@@ -768,3 +835,12 @@ function getInviteId(invite) {
768
835
  return null
769
836
  }
770
837
  }
838
+
839
+ // a member's id as its row has it, from any form of the identity's key
840
+ function memberId(to) {
841
+ try {
842
+ return hid.normalize(to)
843
+ } catch {
844
+ throw CeroError.INVALID("'to' is a member's id")
845
+ }
846
+ }
@@ -0,0 +1,103 @@
1
+ import b4a from 'b4a'
2
+ import c from 'compact-encoding'
3
+ import hid from 'hypercore-id-encoding'
4
+
5
+ import { Invite, STAMPED } from './invite.js'
6
+ import { Identity } from '../identity/index.js'
7
+ import { wraps, opened } from '../database/encryption.js'
8
+ import { getEncoding } from '../lib/spec/index.js'
9
+ import { CeroError } from '../lib/errors.js'
10
+ import { MAX_PASS } from '../lib/constants.js'
11
+
12
+ const Encoding = getEncoding('@cero/pass')
13
+
14
+ /**
15
+ * @typedef {object} PassFields
16
+ * @property {string} invite An invite into the database.
17
+ * @property {Uint8Array} key The database's key, the one its invite opens.
18
+ * @property {Uint8Array} encryptionKey The database's encryption key.
19
+ * @property {Array<{ epoch: number, stamp: number, entropy: Uint8Array }>} [epochs] Its rotation epochs.
20
+ * @property {Uint8Array | null} [data] The sealer's own bytes, read only by a device that opens the pass.
21
+ */
22
+
23
+ /**
24
+ * An invite into a database with the keys that read it, sealed to devices: one that opens its box
25
+ * joins with the keys in hand and waits for no answer. Unsigned, so whoever opens one holds what
26
+ * it carries to the database's own log.
27
+ */
28
+ export const Pass = { seal, open, fits }
29
+
30
+ /**
31
+ * One box per device, under its device key. A key nothing can be sealed to gets none.
32
+ *
33
+ * @param {Array<{ key: Uint8Array }>} devices
34
+ * @param {PassFields} fields
35
+ * @returns {Uint8Array}
36
+ */
37
+ function seal(devices, fields) {
38
+ if (!Array.isArray(devices) || devices.some((d) => d?.key?.byteLength !== 32)) {
39
+ throw CeroError.INVALID('devices are rows with a 32-byte key')
40
+ }
41
+ const message = wire(() => c.encode(Encoding, checked(fields)))
42
+ const boxes = []
43
+ for (const { key } of devices) {
44
+ try {
45
+ boxes.push({ id: hid.encode(key), box: Identity.seal(key, message) })
46
+ } catch {
47
+ // not a point on the curve: no device holds its secret
48
+ }
49
+ }
50
+ return c.encode(wraps, boxes)
51
+ }
52
+
53
+ /**
54
+ * What a pass carries, read from this device's own box.
55
+ *
56
+ * @param {import('../identity/index.js').Identity} identity
57
+ * @param {Uint8Array} pass
58
+ * @returns {PassFields | null} Null when no box is this device's.
59
+ */
60
+ function open(identity, pass) {
61
+ return wire(() => {
62
+ for (const message of opened(identity, identity.device.id, pass)) {
63
+ const fields = checked(c.decode(Encoding, message))
64
+ return { ...fields, epochs: fields.epochs || [] }
65
+ }
66
+ return null
67
+ })
68
+ }
69
+
70
+ /**
71
+ * Whether a pass to `devices` with these keys stays within what a room keeps of one, whatever
72
+ * invite with no data it carries: known before the invite is minted.
73
+ *
74
+ * @param {Array<{ key: Uint8Array }>} devices
75
+ * @param {Omit<PassFields, 'invite'>} fields
76
+ * @returns {boolean}
77
+ */
78
+ function fits(devices, fields) {
79
+ const { key } = fields
80
+ const widest = Number.MAX_SAFE_INTEGER
81
+ const address = Identity.randomKeyPair().publicKey
82
+ const link = { key, length: widest }
83
+ const at = { version: STAMPED, expires: widest, stamp: widest, own: true }
84
+ const invite = new Invite({ ...at, key, address, seed: key, link }).toString()
85
+ return seal(devices, { ...fields, invite }).byteLength <= MAX_PASS
86
+ }
87
+
88
+ // the invite opens the database the keys are for
89
+ function checked(fields) {
90
+ if (!b4a.equals(Invite.parse(fields?.invite).key, fields.key)) {
91
+ throw new Error('its invite is for another database')
92
+ }
93
+ return fields
94
+ }
95
+
96
+ // what does not encode, or decode, is no pass
97
+ function wire(fn) {
98
+ try {
99
+ return fn()
100
+ } catch (err) {
101
+ throw CeroError.INVALID(`not a pass: ${err.message}`)
102
+ }
103
+ }
@@ -264,6 +264,8 @@ export declare class Database extends ReadyResource {
264
264
  /** @private */
265
265
  _landed;
266
266
  /** @private */
267
+ _hooked;
268
+ /** @private */
267
269
  _rebuilding;
268
270
  /** @private */
269
271
  _writes;
@@ -37,3 +37,5 @@ export declare const REMOVALS = "removals";
37
37
  export declare const REFUSALS = "refusals";
38
38
  export declare const SPENT = "spent";
39
39
  export declare const ASKS = "owed";
40
+ export declare const PASSES = "seats";
41
+ export declare const MAX_PASS: number;
@@ -1,6 +1,7 @@
1
1
  import ReadyResource from 'ready-resource';
2
2
  import { Invite } from './invite.js';
3
3
  import { Mailbox } from '../mailbox/index.js';
4
+ export { Pass } from './pass.js';
4
5
  export type KeyPair = {
5
6
  publicKey: Uint8Array;
6
7
  secretKey: Uint8Array;
@@ -36,6 +37,14 @@ export type InviteOpts = {
36
37
  * The app's payload in the invite, readable before joining: `Invite.parse(invite).data`.
37
38
  */
38
39
  data?: Uint8Array | null;
40
+ /**
41
+ * The id of the one member it is made for: nobody else joins with it. Single-use, never `confirm`.
42
+ */
43
+ to?: string | null;
44
+ /**
45
+ * The device keys of the member it is made `to`, handed the room's keys with it: a rotation before she comes is sealed to them.
46
+ */
47
+ keys?: Uint8Array[];
39
48
  };
40
49
  export type AcceptOpts = {
41
50
  /**
@@ -113,6 +122,8 @@ export type JoinResult = {
113
122
  * @property {boolean} [reuse] Admit more than one joiner. Otherwise spent by the first.
114
123
  * @property {boolean} [confirm] Its joins wait for a member to accept them, as requests.
115
124
  * @property {Uint8Array | null} [data] The app's payload in the invite, readable before joining: `Invite.parse(invite).data`.
125
+ * @property {string | null} [to] The id of the one member it is made for: nobody else joins with it. Single-use, never `confirm`.
126
+ * @property {Uint8Array[]} [keys] The device keys of the member it is made `to`, handed the room's keys with it: a rotation before she comes is sealed to them.
116
127
  *
117
128
  * @typedef {object} AcceptOpts
118
129
  * @property {string} [role] Role granted: the invite's by default, at most the invite's.
@@ -184,6 +195,8 @@ export declare class Pairing extends ReadyResource {
184
195
  invite(opts?: InviteOpts): Promise<string>;
185
196
  /** @private */
186
197
  private _secret;
198
+ /** @private */
199
+ private _has;
187
200
  /**
188
201
  * Revoke an invite, for every member. Needs the remove permission.
189
202
  *
@@ -248,6 +261,21 @@ export declare class Pairing extends ReadyResource {
248
261
  * @returns {Promise<JoinResult>}
249
262
  */
250
263
  static join(mailbox: Mailbox, invite: string, { identity, spec, writer, timeout, signal, keep }?: JoinOpts): Promise<JoinResult>;
264
+ /**
265
+ * Write the join into the writer's own core and stop there: nothing is announced and no reply
266
+ * is waited for. A device that holds the database's keys opens it with this writer and applies
267
+ * its own join; `Pairing.join` with the same writer goes on from it and writes nothing more.
268
+ *
269
+ * @param {Mailbox} mailbox
270
+ * @param {string} invite
271
+ * @param {{ identity: JoinOpts['identity'], spec: JoinOpts['spec'], writer: KeyPair }} opts
272
+ * @returns {Promise<void>}
273
+ */
274
+ static write(mailbox: Mailbox, invite: string, { identity, spec, writer }?: {
275
+ identity: JoinOpts['identity'];
276
+ spec: JoinOpts['spec'];
277
+ writer: KeyPair;
278
+ }): Promise<void>;
251
279
  /**
252
280
  * Take back a join that waits for a member: the writer's own core says so after its join, and
253
281
  * the database drops the request unless a member let it in first. Announced as the join was.
@@ -0,0 +1,74 @@
1
+ export type PassFields = {
2
+ /**
3
+ * An invite into the database.
4
+ */
5
+ invite: string;
6
+ /**
7
+ * The database's key, the one its invite opens.
8
+ */
9
+ key: Uint8Array;
10
+ /**
11
+ * The database's encryption key.
12
+ */
13
+ encryptionKey: Uint8Array;
14
+ /**
15
+ * Its rotation epochs.
16
+ */
17
+ epochs?: Array<{
18
+ epoch: number;
19
+ stamp: number;
20
+ entropy: Uint8Array;
21
+ }>;
22
+ /**
23
+ * The sealer's own bytes, read only by a device that opens the pass.
24
+ */
25
+ data?: Uint8Array | null;
26
+ };
27
+ /**
28
+ * @typedef {object} PassFields
29
+ * @property {string} invite An invite into the database.
30
+ * @property {Uint8Array} key The database's key, the one its invite opens.
31
+ * @property {Uint8Array} encryptionKey The database's encryption key.
32
+ * @property {Array<{ epoch: number, stamp: number, entropy: Uint8Array }>} [epochs] Its rotation epochs.
33
+ * @property {Uint8Array | null} [data] The sealer's own bytes, read only by a device that opens the pass.
34
+ */
35
+ /**
36
+ * An invite into a database with the keys that read it, sealed to devices: one that opens its box
37
+ * joins with the keys in hand and waits for no answer. Unsigned, so whoever opens one holds what
38
+ * it carries to the database's own log.
39
+ */
40
+ export declare const Pass: {
41
+ seal: typeof seal;
42
+ open: typeof open;
43
+ fits: typeof fits;
44
+ };
45
+ /**
46
+ * One box per device, under its device key. A key nothing can be sealed to gets none.
47
+ *
48
+ * @param {Array<{ key: Uint8Array }>} devices
49
+ * @param {PassFields} fields
50
+ * @returns {Uint8Array}
51
+ */
52
+ declare function seal(devices: Array<{
53
+ key: Uint8Array;
54
+ }>, fields: PassFields): Uint8Array;
55
+ /**
56
+ * What a pass carries, read from this device's own box.
57
+ *
58
+ * @param {import('../identity/index.js').Identity} identity
59
+ * @param {Uint8Array} pass
60
+ * @returns {PassFields | null} Null when no box is this device's.
61
+ */
62
+ declare function open(identity: import('../identity/index.js').Identity, pass: Uint8Array): PassFields | null;
63
+ /**
64
+ * Whether a pass to `devices` with these keys stays within what a room keeps of one, whatever
65
+ * invite with no data it carries: known before the invite is minted.
66
+ *
67
+ * @param {Array<{ key: Uint8Array }>} devices
68
+ * @param {Omit<PassFields, 'invite'>} fields
69
+ * @returns {boolean}
70
+ */
71
+ declare function fits(devices: Array<{
72
+ key: Uint8Array;
73
+ }>, fields: Omit<PassFields, 'invite'>): boolean;
74
+ export {};