@cero-base/cero 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/cero",
3
- "version": "3.0.1",
3
+ "version": "3.2.0",
4
4
  "description": "The ideal p2p API — everything is a handle, handles contain refs, refs contain rows.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -113,18 +113,18 @@
113
113
  "test:node": "find test -name '*.test.js' | sort | xargs -P4 -n1 brittle-node"
114
114
  },
115
115
  "dependencies": {
116
- "@cero-base/core": "^3.0.1",
116
+ "@cero-base/core": "^3.2.0",
117
117
  "b4a": "^1.9.0",
118
118
  "bare-abort-controller": "^1.1.2",
119
119
  "bare-crypto": "^1.15.4",
120
120
  "bare-fs": "^4.8.4",
121
- "bare-path": "^3.1.2",
121
+ "bare-path": "^3.1.3",
122
122
  "ble-swarm": "^2.4.0",
123
- "compact-encoding": "^3.6.0",
123
+ "compact-encoding": "^3.7.0",
124
124
  "corestore": "^7.16.1",
125
125
  "fd-lock": "^2.2.0",
126
126
  "hrpc": "^4.3.1",
127
- "hypercore": "^11.40.3",
127
+ "hypercore": "^11.40.4",
128
128
  "hypercore-crypto": "^3.7.0",
129
129
  "hypercore-id-encoding": "^1.3.0",
130
130
  "hypercore-storage": "^3.4.0",
@@ -141,10 +141,10 @@
141
141
  "devDependencies": {
142
142
  "@hyperswarm/testnet": "^3.1.4",
143
143
  "bare-events": "^2.9.2",
144
- "bare-fetch": "^3.4.1",
144
+ "bare-fetch": "^3.5.0",
145
145
  "bare-process": "^4.5.1",
146
- "bare-url": "^2.5.6",
147
- "blind-peer": "^3.18.1",
146
+ "bare-url": "^2.5.7",
147
+ "blind-peer": "^3.18.2",
148
148
  "brittle": "^4.5.0",
149
149
  "typescript": "^7.0.2"
150
150
  },
@@ -1,5 +1,5 @@
1
1
  import { CeroError } from '@cero-base/core/errors'
2
- import { COUNTERS, EPOCHS, REMOVALS, REFUSALS, SPENT, ASKS } from '../lib/constants.js'
2
+ import { COUNTERS, EPOCHS, REMOVALS, REFUSALS, SPENT, ASKS, PASSES } from '../lib/constants.js'
3
3
  import * as schemas from './schemas.js'
4
4
 
5
5
  // internal refs by scope; kind defaults to collection
@@ -175,7 +175,10 @@ export function collections(ns, scope) {
175
175
  // collections cero added once apps shipped: numbered after the app's collections and indexes, so
176
176
  // a new spec gives each of those the id an older release gave it
177
177
  export function added(ns) {
178
- return [{ name: ASKS, schema: `@${ns}/owed`, key: ['id'] }]
178
+ return [
179
+ { name: ASKS, schema: `@${ns}/owed`, key: ['id'] },
180
+ { name: PASSES, schema: `@${ns}/pass`, key: ['id'] }
181
+ ]
179
182
  }
180
183
 
181
184
  /**
@@ -227,7 +230,9 @@ export function appended(ns) {
227
230
  { name: 'revoke', requestType: `@${ns}/revoke` },
228
231
  { name: 'ask-key', requestType: `@${ns}/owed` },
229
232
  { name: 'del-owed', requestType: `@${ns}/del-by-id` },
230
- { name: 'cancel-join', requestType: `@${ns}/del-by-id` }
233
+ { name: 'cancel-join', requestType: `@${ns}/del-by-id` },
234
+ { name: 'add-pass', requestType: `@${ns}/pass` },
235
+ { name: 'del-pass', requestType: `@${ns}/del-by-id` }
231
236
  ]
232
237
  }
233
238
 
@@ -57,7 +57,11 @@ export const main = {
57
57
  confirm: bool,
58
58
  // the secret behind its own address: every device that has the row opens its joins and proves
59
59
  // their answers
60
- secret: bytes
60
+ secret: bytes,
61
+ // the member it was made for: nobody else joins with it
62
+ to: string,
63
+ // her device keys, 32 bytes each, back to back: a rotation before she comes is sealed to them
64
+ keys: bytes
61
65
  },
62
66
  handle: {
63
67
  id: required(string),
@@ -222,6 +226,15 @@ export const main = {
222
226
  removed: bytes,
223
227
  standing: bytes,
224
228
  proof: bytes
229
+ },
230
+ // an invite into another room and that room's keys, sealed to the devices of the member it is
231
+ // `to`, waiting here until one of them takes it. `by` is the member who wrote it
232
+ pass: {
233
+ id: required(string),
234
+ to: required(string),
235
+ by: string,
236
+ pass: required(bytes),
237
+ createdAt: uint
225
238
  }
226
239
  }
227
240
 
@@ -335,7 +348,7 @@ export const local = {
335
348
 
336
349
  // what a write means to apply. A release that changes it without changing what is stored bumps
337
350
  // this, so an app's next build raises its contract and devices on the old release skip the new writes
338
- export const contract = { version: 4 }
351
+ export const contract = { version: 6 }
339
352
 
340
353
  export const rpc = {
341
354
  'req-empty': {
@@ -29,6 +29,9 @@ export async function mirror(from, row, fields, to, id) {
29
29
  changed ||= (was[k] ?? null) !== (row[k] ?? null)
30
30
  } else if (prev && (await get(to.handle.files, prev)).data?.from === file) {
31
31
  out[k] = prev
32
+ } else if (!to.handle.store.writable) {
33
+ // a file takes a seat to add: a reader's row keeps the one it has, and takes the rest
34
+ out[k] = prev
32
35
  } else {
33
36
  const data = await from.handle._bytes(file)
34
37
  const { type } = decodeId(file)
@@ -10,7 +10,7 @@ import z32 from 'z32'
10
10
  import { Identity } from '@cero-base/core/identity'
11
11
  import { Database } from '@cero-base/core/database'
12
12
  import { blobEpochKey, epochEntries } from '@cero-base/core/database/encryption'
13
- import { Pairing } from '@cero-base/core/pairing'
13
+ import { Pairing, Pass } from '@cero-base/core/pairing'
14
14
  import { read } from '../push/index.js'
15
15
  import { Invite } from '@cero-base/core/invite'
16
16
  import { Mailbox } from '@cero-base/core/mailbox'
@@ -22,7 +22,7 @@ import { Blobs } from '@cero-base/core/blobs'
22
22
  import { decodeId, servedType } from '@cero-base/core/blobs/codec'
23
23
  import { FileServer } from '@cero-base/core/blobs/server'
24
24
 
25
- import { KEEP_OPEN, NS, TIMEOUT } from '../lib/constants.js'
25
+ import { KEEP_OPEN, NS, PASSES, REFUSALS, SPENT, TIMEOUT } from '../lib/constants.js'
26
26
 
27
27
  import { Ref } from '../lib/refs.js'
28
28
  import { box } from '../local/index.js'
@@ -138,6 +138,10 @@ export class Handle extends ReadyResource {
138
138
  /** @private */
139
139
  this._taking = parent ? null : new Set() // the requests being taken back, by writer
140
140
  /** @private */
141
+ this._held = parent ? null : new Map() // pass invite → when it is tried again, its join having settled nothing
142
+ /** @private */
143
+ this._retries = parent ? null : new Map() // room open here → the timer that reads its passes again
144
+ /** @private */
141
145
  this._coreKeys = parent ? null : new Map()
142
146
  /** @private */
143
147
  this._offJoins = null
@@ -238,7 +242,7 @@ export class Handle extends ReadyResource {
238
242
  /** @private */
239
243
  this._ac = new AbortController()
240
244
  if (this.closed) this._ac.abort()
241
- else this.once('close', () => this._ac.abort())
245
+ else this._onclose(() => this._ac.abort())
242
246
  }
243
247
  return this._ac.signal
244
248
  }
@@ -250,6 +254,17 @@ export class Handle extends ReadyResource {
250
254
  return h
251
255
  }
252
256
 
257
+ // what is tied to this handle while it is open is undone as it closes, by one listener however many there are
258
+ /** @private */
259
+ _onclose(fn) {
260
+ if (!this._offs) {
261
+ /** @private */
262
+ this._offs = []
263
+ this.once('close', () => this._offs.forEach((off) => off()))
264
+ }
265
+ this._offs.push(fn)
266
+ }
267
+
253
268
  /**
254
269
  * Lazily-built file server for this identity. Root-only — child handles
255
270
  * reach it through `this.root.fileServer`.
@@ -325,10 +340,10 @@ export class Handle extends ReadyResource {
325
340
  this._pruneAll().catch(this._onerror)
326
341
  this._tellClosed()
327
342
  })
328
- this.once('close', prune)
343
+ this._onclose(prune)
329
344
  if (this._bluetooth) {
330
345
  const off = this.store.onUpdate('profile', () => this._tell().catch(this._onerror))
331
- this.once('close', off)
346
+ this._onclose(off)
332
347
  await this._tell()
333
348
  }
334
349
  // the joins on their way, at launch and as their rows move
@@ -340,7 +355,7 @@ export class Handle extends ReadyResource {
340
355
  this._tellClosed()
341
356
  // the handles rows, keyed by push topic, for a cold push process that cannot read the root
342
357
  const off = this.store.onUpdate('handles', () => this._index().catch(this._onerror))
343
- this.once('close', off)
358
+ this._onclose(off)
344
359
  await this._index()
345
360
  }
346
361
  }
@@ -479,6 +494,56 @@ export class Handle extends ReadyResource {
479
494
  return this.store.removed(id)
480
495
  }
481
496
 
497
+ // an invite made to her, sealed with this room's keys to her devices in a room both are in, where
498
+ // they find it. `from` crosses the bridge as its id
499
+ /** @private */
500
+ async _seat(id, { from, role = 'member', ttl } = {}) {
501
+ if (!this.parent) throw CeroError.INVALID('a device is linked, not seated')
502
+ if (typeof from === 'string') {
503
+ const { data: row } = await this.root.store.get('handles', from)
504
+ if (!row) throw CeroError.UNKNOWN('handle', from)
505
+ const shared = await this.root._load(row.type, from)
506
+ try {
507
+ return await this._seat(id, { from: shared, role, ttl })
508
+ } finally {
509
+ await shared.close()
510
+ }
511
+ }
512
+ if (!(from instanceof Handle) || !from.parent) {
513
+ throw CeroError.INVALID('seat takes { from }: a room she is in')
514
+ }
515
+ const { store } = from
516
+ const { data: me } = await store.get('members', this.identity.id)
517
+ if (!can(me?.role, WRITE)) throw CeroError.DENIED(null, `you cannot write in ${from.id}`)
518
+ // a member's devices, which a removal takes with her
519
+ const devices = (await store.get('devices')).data.filter((d) => d.memberId === id && d.key)
520
+ if (!devices.length) throw CeroError.UNKNOWN('member', id)
521
+ // one seat at a time: in, let in and not yet claimed, or seated and not come yet
522
+ if (await promised(this.store, { id, publicKey: hid.decode(id) })) {
523
+ throw CeroError.INVALID(`${id} is in already`)
524
+ }
525
+ const { data: invites } = await this.store.get('invites')
526
+ if (invites.some((i) => i.to === id && !(i.expires && i.expires <= Date.now()))) {
527
+ throw CeroError.INVALID(`${id} has a seat already`)
528
+ }
529
+ // what would keep its pass out of `from` is checked first: an invite minted is live
530
+ const at = Math.min(store.version, await store.dispatcher.version(store.view))
531
+ if ((store.meta.since?.routes[`@${store.ns}/add-pass`] ?? 0) > at) {
532
+ throw CeroError.UNSUPPORTED(`'add-pass' in ${from.id}`)
533
+ }
534
+ const { key, encryptionKey, keyring } = this.store
535
+ const fields = { key, encryptionKey, epochs: keyring.all(), data: b4a.from(this.type) }
536
+ if (!Pass.fits(devices, fields)) {
537
+ throw CeroError.INVALID(
538
+ `this room has too many keys to seal to her ${devices.length} devices`
539
+ )
540
+ }
541
+ const invite = await this._invite({ role, ttl, to: id, keys: devices.map((d) => d.key) })
542
+ const pass = Pass.seal(devices, { ...fields, invite })
543
+ const row = { id: b4a.toHex(Identity.randomBytes(16)), to: id, pass, createdAt: Date.now() }
544
+ await store.call('add-pass', row)
545
+ }
546
+
482
547
  // the same context, its refs writing into one batch; a fn that ignores it would write outside
483
548
  /** @private */
484
549
  async _tx(fn) {
@@ -551,16 +616,28 @@ export class Handle extends ReadyResource {
551
616
  this._departing.set(id, going)
552
617
  }
553
618
 
554
- // a device that applies its own identity's removal writes it on the row, with who removed her
619
+ // a device that applies its own identity's removal writes it on the row, with who removed her; `out`, a seat
620
+ // she holds no more with no removal to read, as a seat of hers that never counted there
555
621
  /** @private */
556
- async _ousted(child) {
557
- const removal = await child.store.removal(this.identity.id)
558
- if (!removal) return
622
+ async _ousted(child, out = false) {
559
623
  const { data: row } = await this.store.get('handles', child.id)
560
624
  // only a seat held is lost: a row asking or joining is a rejoin under way, one ended is over
561
625
  if (!row || !['in', 'leaving'].includes(row.state || 'in')) return
626
+ const lost = out || (await refused(child.store, this.identity))
627
+ const removal = (await child.store.removal(this.identity.id)) ?? (lost ? { by: null } : null)
628
+ if (!removal) return
562
629
  const fields = { by: removal.by, reason: null, encryptionKey: null, epochs: null }
563
630
  await this.store.set('handles', { id: child.id, state: 'removed', ...fields })
631
+ // a seat waiting for the room this one held is taken now
632
+ this._repass()
633
+ }
634
+
635
+ // the passes in every room open here, read again
636
+ /** @private */
637
+ _repass() {
638
+ for (const child of this.children) {
639
+ this._passes(child).catch((err) => this.closing || this._onerror(err))
640
+ }
564
641
  }
565
642
 
566
643
  /**
@@ -1179,11 +1256,21 @@ export class Handle extends ReadyResource {
1179
1256
 
1180
1257
  // one join a handle, whoever waits on it: it goes on until its row says how it ended, and a close only pauses it
1181
1258
  /** @private */
1182
- _start(invite, type) {
1259
+ _start(invite, type, pass = null) {
1183
1260
  const id = hid.encode(Invite.parse(invite).key)
1184
1261
  let join = this._joining.get(id)
1185
1262
  if (!join) {
1186
- join = { id, type, invite: null, writer: null, waiting: 0, end: null, running: null }
1263
+ join = {
1264
+ id,
1265
+ type,
1266
+ invite: null,
1267
+ pass,
1268
+ writer: null,
1269
+ waiting: 0,
1270
+ end: null,
1271
+ running: null,
1272
+ read: false
1273
+ }
1187
1274
  join.done = new Promise((resolve, reject) => {
1188
1275
  join.resolve = resolve
1189
1276
  join.reject = reject
@@ -1191,8 +1278,13 @@ export class Handle extends ReadyResource {
1191
1278
  join.done.catch(safetyCatch)
1192
1279
  this._joining.set(id, join)
1193
1280
  }
1194
- // a join past its reply enters with those keys: a newer invite waits on it
1195
- if (join.invite !== invite && !join.entering) this._run(join, invite)
1281
+ // a join past its reply enters with those keys: a newer invite waits on it, and one waiting
1282
+ // for a reply takes the keys a pass hands it. A pass waits for another pass's join to end
1283
+ const other = join.invite !== invite && !(pass && join.pass && join.invite)
1284
+ if ((other || (pass && !join.pass)) && !join.entering) {
1285
+ join.pass = pass
1286
+ this._run(join, invite)
1287
+ }
1196
1288
  return join
1197
1289
  }
1198
1290
 
@@ -1208,7 +1300,15 @@ export class Handle extends ReadyResource {
1208
1300
  end(value)
1209
1301
  }
1210
1302
  try {
1211
- const id = await this._ask(join.type, invite)
1303
+ const { pass } = join
1304
+ const taken = pass && (await this._take(join, invite, running.signal))
1305
+ // a pass for a room she sits in already: the room is hers as it is, let go like one entered
1306
+ if (taken === false) {
1307
+ const child = await this._load(join.type, join.id)
1308
+ child.close().catch(this._onerror)
1309
+ return settle(join.resolve, child)
1310
+ }
1311
+ const id = pass ? hid.encode(pass.key) : await this._ask(join.type, invite)
1212
1312
  const writer = (join.writer = await this._loadKeyPair(id))
1213
1313
  const { data: row } = await this.store.get('handles', id)
1214
1314
  // the keys are on the row before the reply is let go: a restart opens the handle without joining again
@@ -1218,14 +1318,16 @@ export class Handle extends ReadyResource {
1218
1318
  const spec = pickHandle(this.spec, join.type)
1219
1319
  const { identity, mailbox } = this
1220
1320
  const opts = { identity, spec, writer, keep, timeout: 0, signal: running.signal }
1221
- const reply = row.encryptionKey
1222
- ? { ...row, epochs: row.epochs ? c.decode(epochEntries, row.epochs) : [], writer }
1223
- : await Pairing.join(mailbox, invite, opts)
1321
+ const reply = taken
1322
+ ? { ...pass, writer }
1323
+ : row.encryptionKey
1324
+ ? { ...row, epochs: row.epochs ? c.decode(epochEntries, row.epochs) : [], writer }
1325
+ : await Pairing.join(mailbox, invite, opts)
1224
1326
  // an abort stops no reply already in hand: the newer attempt enters
1225
- if (running !== join.running) return
1327
+ if (running !== join.running) return taken?._end()
1226
1328
  join.entering = true
1227
1329
  await this._stand(id, 'joining', keys(reply))
1228
- const child = await this._enter(join.type, reply, invite)
1330
+ const child = await this._enter(join.type, reply, invite, taken)
1229
1331
  // every waiter takes its own hold once the row reads in: this one is let go, idle until the app opens it
1230
1332
  child.close().catch(this._onerror)
1231
1333
  settle(join.resolve, child)
@@ -1239,11 +1341,134 @@ export class Handle extends ReadyResource {
1239
1341
  if (end.code !== 'CLOSED') {
1240
1342
  await this._over(join.id, end, { invite, writer: join.writer }).catch(report)
1241
1343
  }
1242
- if (err.code !== 'CLOSED' && alone) this._onerror(err)
1344
+ // a pass whose room did not show in time is tried again, nothing on the root
1345
+ if (err.code !== 'CLOSED' && err.code !== 'TIMEOUT' && alone) this._onerror(err)
1243
1346
  settle(join.reject, end)
1244
1347
  }
1245
1348
  }
1246
1349
 
1350
+ // a pass's join: its invite read in the room its keys open, as nobody, before anything is written;
1351
+ // then asked, written and seated by this device's own claim. Null when that takes longer: it goes
1352
+ // on as a plain join
1353
+ /** @private */
1354
+ async _take(join, invite, signal) {
1355
+ const { type, pass } = join
1356
+ const id = hid.encode(pass.key)
1357
+ const spec = pickHandle(this.spec, type)
1358
+ const { key, encryptionKey, epochs } = pass
1359
+ const room = (keyPair) => {
1360
+ const namespace = `${NS}/handle/${type}/${randomNs()}`
1361
+ return this._room({ spec, namespace, key, encryptionKey, epochs, keyPair })
1362
+ }
1363
+ const reader = room(Identity.randomKeyPair())
1364
+ let moot = false
1365
+ try {
1366
+ await reader.ready()
1367
+ const { store } = reader
1368
+ const inviteId = b4a.toHex(Invite.parse(invite).id)
1369
+ const shows = async () =>
1370
+ !!(await store.get('invites', inviteId)).data ||
1371
+ !!(await store.view.get(`@${store.ns}/${SPENT}`, { id: inviteId }))
1372
+ if (!(await until(store, shows, TIMEOUT, signal))) {
1373
+ throw signal.aborted ? CeroError.CLOSED('join') : CeroError.TIMEOUT('join')
1374
+ }
1375
+ // a seat lost, or one that never counted there, ends on the root before she asks again: the
1376
+ // room holds neither her nor a promise to her at a seat made after she was out
1377
+ const seated = await promised(store, this.identity)
1378
+ await this._ousted(reader, !seated)
1379
+ // a room she reads as in under another invite takes nothing now, read again in its turn
1380
+ const { data: row } = await this.store.get('handles', id)
1381
+ moot = seated && !!row && (row.state || 'in') === 'in'
1382
+ } finally {
1383
+ await reader._end().catch(safetyCatch)
1384
+ }
1385
+ if (moot) return false
1386
+ const { data: kept } = await this.local.store.get('handle-keypairs', id)
1387
+ const { publicKey, secretKey } = kept?.invite === invite ? kept : Identity.randomKeyPair()
1388
+ const writer = (join.writer = { publicKey, secretKey })
1389
+ // asked before its join is written: a retry, or the latest ask, finds its writer
1390
+ await this._ask(type, invite, writer)
1391
+ await Pairing.write(this.mailbox, invite, { identity: this.identity, spec, writer })
1392
+ const child = room(writer)
1393
+ try {
1394
+ await child.ready()
1395
+ const { store } = child
1396
+ const err = await store.claim({ timeout: TIMEOUT }).catch((err) => err)
1397
+ if (signal.aborted) throw CeroError.CLOSED('join')
1398
+ if (!err) return child
1399
+ // another device of hers took the invite first: this one sits beside it, on a writer of its own
1400
+ if (err.code === 'DENIED' && (await promised(store, this.identity))) {
1401
+ await this._saveKeyPair(id, Identity.randomKeyPair(), invite)
1402
+ await this._stand(id, 'joining', keys(pass))
1403
+ } else if (err.code !== 'TIMEOUT') {
1404
+ throw err
1405
+ }
1406
+ } catch (err) {
1407
+ await child._end().catch(safetyCatch)
1408
+ throw err
1409
+ }
1410
+ await child._end()
1411
+ return null
1412
+ }
1413
+
1414
+ // the passes for this identity in a room open here, read whenever its seats change, a join of one
1415
+ // ends, a seat of hers ends, and every TIMEOUT while one waits: one join a room at a time, the
1416
+ // newest pass first, and one whose join settled nothing waits TIMEOUT before its next try
1417
+ /** @private */
1418
+ async _passes(from) {
1419
+ const { store } = from
1420
+ const rows = await store.view.find(`@${store.ns}/${PASSES}`, {}).toArray()
1421
+ rows.sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0))
1422
+ let waiting = false
1423
+ for (const row of rows) {
1424
+ if (row.to !== this.identity.id) continue
1425
+ const pass = opens(this.identity, row.pass)
1426
+ const type = pass?.data && b4a.toString(pass.data)
1427
+ if (!type || !this.spec.handles?.[type]) continue
1428
+ if (await this._spent(from, row, pass)) continue
1429
+ waiting = true
1430
+ if ((this._held.get(pass.invite) ?? 0) > Date.now()) continue
1431
+ const join = this._start(pass.invite, type, pass)
1432
+ // another pass's join for the room ends first, and the read after it starts this one
1433
+ if (join.invite !== pass.invite || join.read) continue
1434
+ join.read = true
1435
+ const next = async () => {
1436
+ if (!(await this._spent(from, row, pass))) this._held.set(pass.invite, Date.now() + TIMEOUT)
1437
+ if (!from.closing && !from.closed) await this._passes(from)
1438
+ }
1439
+ join.done.then(next, next).catch((err) => this.closing || this._onerror(err))
1440
+ }
1441
+ if (waiting) this._retry(from)
1442
+ }
1443
+
1444
+ // a pass waiting in a room is read again in TIMEOUT: its room may show late, or its join have
1445
+ // settled nothing
1446
+ /** @private */
1447
+ _retry(from) {
1448
+ if (this._retries.has(from) || from.closing || from.closed) return
1449
+ const timer = setTimeout(() => {
1450
+ this._retries.delete(from)
1451
+ if (from.closing || from.closed) return
1452
+ this._passes(from).catch((err) => this.closing || this._onerror(err))
1453
+ }, TIMEOUT)
1454
+ timer.unref?.()
1455
+ this._retries.set(from, timer)
1456
+ }
1457
+
1458
+ // a pass goes once its join is in or ended, or it ran out. A room in under another invite is a
1459
+ // seat she may have lost since, unheard on a device that keeps it closed
1460
+ /** @private */
1461
+ async _spent(from, row, pass) {
1462
+ const { data: was } = await this.store.get('handles', hid.encode(pass.key))
1463
+ const state = was && (was.state || 'in')
1464
+ const done = was?.invite === pass.invite && (state === 'in' || SWEPT.includes(state))
1465
+ if (!done && !Invite.parse(pass.invite).expired) return false
1466
+ if (from.store.writable && !from.closing && !from.closed) {
1467
+ await from.store.call('del-pass', { id: row.id })
1468
+ }
1469
+ return true
1470
+ }
1471
+
1247
1472
  // ends it for good from any device: its row reads cancelled, so no device and no restart carries it on
1248
1473
  /** @private */
1249
1474
  async _cancel(invite) {
@@ -1271,12 +1496,24 @@ export class Handle extends ReadyResource {
1271
1496
  if (mine && asks && row.writer === ask.id) return
1272
1497
  // a seated row names no writer
1273
1498
  const ended = row && !asks && state !== 'cancelled' && (!row.writer || row.writer === ask.id)
1274
- if (ended && row.invite === ask.invite) return this.local.store.del('asks', ask.id)
1499
+ const same = ended && row.invite === ask.invite
1500
+ // let in on another device, this one's join stops and its writer, which may never have claimed,
1501
+ // goes: the room opens here as on any device of hers
1502
+ const elsewhere =
1503
+ same &&
1504
+ state === 'in' &&
1505
+ !this._loading.has(ask.handle) &&
1506
+ ![...this.children].some((c) => c.id === ask.handle)
1507
+ if (same && !elsewhere) return this.local.store.del('asks', ask.id)
1275
1508
  // only the join that asks with this writer stops: one still choosing its writer may ask anew
1276
1509
  const join = this._joining.get(ask.handle)
1277
1510
  if (join?.writer && b4a.equals(join.writer.publicKey, ask.publicKey)) {
1278
1511
  this._stop(join, CeroError.CANCELLED())
1279
1512
  }
1513
+ if (elsewhere) {
1514
+ await this._forget(ask.handle, ask)
1515
+ return this.local.store.del('asks', ask.id)
1516
+ }
1280
1517
  if (this._taking.has(ask.id)) return
1281
1518
  this._taking.add(ask.id)
1282
1519
  this._takeBack(ask)
@@ -1331,7 +1568,7 @@ export class Handle extends ReadyResource {
1331
1568
 
1332
1569
  // a join's row: `asking` with its invite and no keys. A join that ended under this invite ends the same way again
1333
1570
  /** @private */
1334
- async _ask(type, invite) {
1571
+ async _ask(type, invite, given = null) {
1335
1572
  const { key } = Invite.parse(invite)
1336
1573
  const id = hid.encode(key)
1337
1574
  const { data: row } = await this.store.get('handles', id)
@@ -1346,7 +1583,8 @@ export class Handle extends ReadyResource {
1346
1583
  const mine = !!kept?.invite && (state === 'joining' || latest)
1347
1584
  if (mine && (state === 'joining' || row.invite === invite)) return id
1348
1585
  if (ENDS[state] && row.invite === invite) throw ENDS[state](row.reason)
1349
- const writer = mine ? kept : Identity.randomKeyPair()
1586
+ // a pass's join asks with the writer its join is written with, whatever ask stood before
1587
+ const writer = given || (mine ? kept : Identity.randomKeyPair())
1350
1588
  await this._saveKeyPair(id, writer, invite)
1351
1589
  // a room another device of this identity already has the keys of is joined with them
1352
1590
  if (state === 'joining') return id
@@ -1431,18 +1669,23 @@ export class Handle extends ReadyResource {
1431
1669
  * @returns {Promise<Handle>}
1432
1670
  * @private
1433
1671
  */
1434
- async _enter(type, reply, invite) {
1672
+ async _enter(type, reply, invite, taken = null) {
1435
1673
  const id = hid.encode(reply.key)
1436
- // a room this identity lost its seat in stays open on its old writer: it ends before the new seat opens it
1674
+ // open here on another writer than the seat it enters on, the room is one this identity lost, or
1675
+ // whose seat never counted: it ends before the new seat opens it
1437
1676
  const stale = [...this.children].find((c) => c.id === id && !c.closing)
1438
- const out = stale && (await stale.store.removed(this.identity.id))
1439
- if (out) await stale._end().catch(safetyCatch)
1677
+ const writer = taken ? taken.store.writerKey : reply.writer?.publicKey
1678
+ if (stale && writer && !b4a.equals(stale.store.writerKey, writer)) {
1679
+ await stale._end().catch(safetyCatch)
1680
+ }
1681
+ // a pass's join is already open, seated
1440
1682
  const child = /** @type {Child} */ (
1441
- this._room({
1442
- spec: pickHandle(this.spec, type),
1443
- namespace: `${NS}/handle/${type}/${randomNs()}`,
1444
- ...delivered(reply)
1445
- })
1683
+ taken ||
1684
+ this._room({
1685
+ spec: pickHandle(this.spec, type),
1686
+ namespace: `${NS}/handle/${type}/${randomNs()}`,
1687
+ ...delivered(reply)
1688
+ })
1446
1689
  )
1447
1690
  // its row is listed while it joins: an open by id shares this child, a second on the same core deadlocks
1448
1691
  let publish = null
@@ -1458,12 +1701,18 @@ export class Handle extends ReadyResource {
1458
1701
  // let in by a promise, this device seats itself: its claim writes the member row
1459
1702
  await child.store.claim({ timeout: 0 })
1460
1703
  // admitted once our member row lands; the same apply seats a writer, a reader has no seat
1461
- const member = await admitted(child.store, this.identity.id)
1704
+ const member = await admitted(
1705
+ child.store,
1706
+ this.identity.id,
1707
+ b4a.toHex(Invite.parse(invite).id)
1708
+ )
1462
1709
  if (member.role !== 'reader' && !child.store.writable) {
1463
1710
  await child.store.whenWritable({ timeout: 0 })
1464
1711
  }
1465
1712
 
1466
1713
  await this._saveKeyPair(id, child.store.keyPair, invite)
1714
+ // seated on its own writer: its ask is answered, never read as one let in on another device
1715
+ await this.local.store.del('asks', hid.encode(child.store.keyPair.publicKey))
1467
1716
 
1468
1717
  const ts = Date.now()
1469
1718
  await this.store.call('add-handle', {
@@ -1615,7 +1864,7 @@ export class Handle extends ReadyResource {
1615
1864
  const child = new Handle({ parent: this, ...opts })
1616
1865
  for (const hook of this._typeHooks) hook.apply(child)
1617
1866
  this._pending.add(child)
1618
- child.once('close', () => this._pending.delete(child))
1867
+ child._onclose(() => this._pending.delete(child))
1619
1868
  return child
1620
1869
  }
1621
1870
 
@@ -1649,9 +1898,16 @@ export class Handle extends ReadyResource {
1649
1898
  // it tells a handle nothing before it has a seat there
1650
1899
  const prune = () => this._prune(child).catch(this._onerror)
1651
1900
  child.store.on('writable', prune)
1652
- child.once('close', () => child.store.off('writable', prune))
1901
+ child._onclose(() => child.store.off('writable', prune))
1653
1902
  prune()
1654
1903
  this._seats(child)
1904
+ const take = () => this._passes(child).catch((err) => this.closing || this._onerror(err))
1905
+ child._onclose(child.store.onUpdate(PASSES, take))
1906
+ child._onclose(() => {
1907
+ clearTimeout(this._retries.get(child))
1908
+ this._retries.delete(child)
1909
+ })
1910
+ take()
1655
1911
  // what a listener ties to the handle as it runs is no holder's: it stays through their last close
1656
1912
  child._arriving = true
1657
1913
  try {
@@ -1668,11 +1924,12 @@ export class Handle extends ReadyResource {
1668
1924
  const onchange = (touched) => {
1669
1925
  if (touched.has('*') || touched.has('devices') || touched.has('members')) {
1670
1926
  this._index(child).catch(this._onerror)
1671
- this._ousted(child).catch((err) => this.closing || this._onerror(err))
1672
1927
  }
1928
+ // whatever a batch touched: a reorder takes back a seat it read before
1929
+ this._ousted(child).catch((err) => this.closing || this._onerror(err))
1673
1930
  }
1674
1931
  child.store.on('update', onchange)
1675
- child.once('close', () => child.store.off('update', onchange))
1932
+ child._onclose(() => child.store.off('update', onchange))
1676
1933
  this._index(child).catch(this._onerror)
1677
1934
  }
1678
1935
 
@@ -2001,13 +2258,15 @@ export class Handle extends ReadyResource {
2001
2258
  }
2002
2259
  const touches = (name) => (touched) => touched.has('*') || touched.has(name)
2003
2260
  const onepoch = () => save().catch(this._onerror)
2004
- const onroot = (touched) => touches('handles')(touched) && read().catch(this._onerror)
2005
- const onchild = (touched) => touches('epochs')(touched) && read().catch(this._onerror)
2261
+ // a room that closed under the read says nothing
2262
+ const report = (err) => err.code === 'CLOSED' || this._onerror(err)
2263
+ const onroot = (touched) => touches('handles')(touched) && read().catch(report)
2264
+ const onchild = (touched) => touches('epochs')(touched) && read().catch(report)
2006
2265
  child.store.on('epoch', onepoch)
2007
2266
  child.store.on('update', onchild)
2008
2267
  this.store.on('update', onroot)
2009
2268
  this.store.on('epoch', onepoch)
2010
- child.once('close', () => {
2269
+ child._onclose(() => {
2011
2270
  child.store.off('epoch', onepoch)
2012
2271
  child.store.off('update', onchild)
2013
2272
  this.store.off('update', onroot)
@@ -2025,7 +2284,7 @@ export class Handle extends ReadyResource {
2025
2284
  apply: (child) => {
2026
2285
  if (child.type !== ref.type) return
2027
2286
  offs.set(child, attach(child))
2028
- child.once('close', () => offs.delete(child))
2287
+ child._onclose(() => offs.delete(child))
2029
2288
  }
2030
2289
  }
2031
2290
  this._typeHooks.add(hook)
@@ -2249,7 +2508,59 @@ function listed(rows, query = {}) {
2249
2508
  return { data, total: data.length, size: data.length }
2250
2509
  }
2251
2510
 
2252
- function admitted(db, id) {
2511
+ // whether `check` holds of a room within `ms` as its view updates: false once past, or stopped
2512
+ function until(db, check, ms, signal) {
2513
+ return new Promise((resolve, reject) => {
2514
+ const done = (err, found) => {
2515
+ clearTimeout(timer)
2516
+ db.off('update', test)
2517
+ db.off('close', closed)
2518
+ signal.removeEventListener('abort', stop)
2519
+ if (err) reject(err)
2520
+ else resolve(found)
2521
+ }
2522
+ const test = () => check().then((found) => found && done(null, true), done)
2523
+ const stop = () => done(null, false)
2524
+ const closed = () => done(CeroError.CLOSED('Database'))
2525
+ const timer = setTimeout(stop, ms)
2526
+ db.on('update', test)
2527
+ db.once('close', closed)
2528
+ signal.addEventListener('abort', stop)
2529
+ if (signal.aborted) stop()
2530
+ else test()
2531
+ })
2532
+ }
2533
+
2534
+ // the room turned this device's writer away, under `invite` when one is named
2535
+ async function turned(db, invite = null) {
2536
+ const refusal = await db.view.get(`@${db.ns}/${REFUSALS}`, { id: hid.encode(db.writerKey) })
2537
+ return refusal && (!invite || !refusal.invite || refusal.invite === invite) ? refusal : null
2538
+ }
2539
+
2540
+ // a seat this device took that never counted: no member row, and its writer turned away
2541
+ async function refused(db, identity) {
2542
+ if ((await db.get('members', identity.id)).data) return false
2543
+ return !!(await turned(db))
2544
+ }
2545
+
2546
+ // whether a room let this identity in, by any of its devices
2547
+ async function promised(db, identity) {
2548
+ if ((await db.get('members', identity.id)).data) return true
2549
+ const { data: requests } = await db.get('requests')
2550
+ return requests.some((row) => row.promised && b4a.equals(row.identity, identity.publicKey))
2551
+ }
2552
+
2553
+ // what a pass holds for this device; a malformed one, or none of its boxes, is nothing
2554
+ function opens(identity, pass) {
2555
+ try {
2556
+ return Pass.open(identity, pass)
2557
+ } catch {
2558
+ return null
2559
+ }
2560
+ }
2561
+
2562
+ // its member row once it lands, or why the room turned this device's writer away under `invite`
2563
+ function admitted(db, id, invite) {
2253
2564
  return new Promise((resolve, reject) => {
2254
2565
  const done = (err, member) => {
2255
2566
  db.off('update', onupdate)
@@ -2259,7 +2570,9 @@ function admitted(db, id) {
2259
2570
  }
2260
2571
  const check = async () => {
2261
2572
  const { data } = await db.get('members', id)
2262
- if (data) done(null, data)
2573
+ if (data) return done(null, data)
2574
+ const refusal = await turned(db, invite)
2575
+ if (refusal) done(CeroError.DENIED(refusal.reason || null))
2263
2576
  }
2264
2577
  const onupdate = () => check().catch(done)
2265
2578
  const onclose = () => done(CeroError.CLOSED('Database'))
@@ -5,6 +5,7 @@ export const REMOVALS = 'removals'
5
5
  export const REFUSALS = 'refusals'
6
6
  export const SPENT = 'spent'
7
7
  export const ASKS = 'owed'
8
+ export const PASSES = 'seats'
8
9
 
9
10
  // Writer-admission / pairing timeout (ms).
10
11
  export const TIMEOUT = 30000
@@ -469,6 +469,24 @@ export function removed(ctx, id) {
469
469
  return ctx._removed(id)
470
470
  }
471
471
 
472
+ /**
473
+ * Let a member of another handle in, with no invite to pass on: her devices find it in `from` while
474
+ * they have it open, join on their own, and the handle shows up in her list. Taken back with
475
+ * `revoke` on the `invites` row whose `to` is her id. Rejects `DENIED` for a role above your own or
476
+ * when you cannot write in `from`, `UNKNOWN` when she or none of her devices is in `from`, `INVALID`
477
+ * when she is a member already.
478
+ *
479
+ * @param {Context} ctx The handle she is let into.
480
+ * @param {string} id Her member id.
481
+ * @param {{ from: Context, role?: string, ttl?: number | string }} opts `from`: a handle both are in. `role` is `member` by default.
482
+ * @returns {Promise<void>}
483
+ */
484
+ export async function seat(ctx, id, opts) {
485
+ // checked before anything crosses to the worker, which carries `from` as its id
486
+ if (!isOptions(opts)) throw CeroError.INVALID('seat options are an object: { from }')
487
+ return ctx._seat(id, opts)
488
+ }
489
+
472
490
  /**
473
491
  * Quit a handle for good: its row reads `leaving`, then `left` once the handle holds it, and it closes.
474
492
  *
package/src/rpc/client.js CHANGED
@@ -31,6 +31,7 @@ export const {
31
31
  deny,
32
32
  leave,
33
33
  removed,
34
+ seat,
34
35
  close,
35
36
  cancel,
36
37
  suspend,
@@ -379,6 +380,11 @@ const operators = {
379
380
  return this._verb('removed', id)
380
381
  },
381
382
 
383
+ /** @private */
384
+ _seat(id, { from, ...opts }) {
385
+ return this._verb('seat', id, { ...opts, from: from?.id ?? from })
386
+ },
387
+
382
388
  /** @private */
383
389
  _cancel(invite) {
384
390
  return this._verb('cancel', invite)
package/src/rpc/server.js CHANGED
@@ -18,6 +18,7 @@ import {
18
18
  revoke,
19
19
  rotate,
20
20
  removed,
21
+ seat,
21
22
  accept,
22
23
  deny,
23
24
  cancel,
@@ -39,6 +40,7 @@ const VERBS = new Map(
39
40
  revoke,
40
41
  rotate,
41
42
  removed,
43
+ seat,
42
44
  accept,
43
45
  deny,
44
46
  cancel,
@@ -45,6 +45,8 @@ export declare const main: {
45
45
  index: import("@cero-base/core").Prim;
46
46
  confirm: import("@cero-base/core").Prim;
47
47
  secret: import("@cero-base/core").Prim;
48
+ to: import("@cero-base/core").Prim;
49
+ keys: import("@cero-base/core").Prim;
48
50
  };
49
51
  handle: {
50
52
  id: import("@cero-base/core").Prim;
@@ -166,6 +168,13 @@ export declare const main: {
166
168
  standing: import("@cero-base/core").Prim;
167
169
  proof: import("@cero-base/core").Prim;
168
170
  };
171
+ pass: {
172
+ id: import("@cero-base/core").Prim;
173
+ to: import("@cero-base/core").Prim;
174
+ by: import("@cero-base/core").Prim;
175
+ pass: import("@cero-base/core").Prim;
176
+ createdAt: import("@cero-base/core").Prim;
177
+ };
169
178
  };
170
179
  export declare const local: {
171
180
  master: {
@@ -44,6 +44,11 @@ export declare const cero: {
44
44
  id: string;
45
45
  }, reason?: string): Promise<void>;
46
46
  removed(ctx: operators.Context, id: string): Promise<'removed' | 'left' | null>;
47
+ seat(ctx: operators.Context, id: string, opts: {
48
+ from: operators.Context;
49
+ role?: string;
50
+ ttl?: number | string;
51
+ }): Promise<void>;
47
52
  leave(ctx: operators.Context): Promise<void>;
48
53
  close(ctx: operators.Context): Promise<void>;
49
54
  cancel(me: operators.Context, code: string): Promise<boolean>;
@@ -191,6 +191,10 @@ export declare class Handle extends ReadyResource {
191
191
  /** @private */
192
192
  _taking;
193
193
  /** @private */
194
+ _held;
195
+ /** @private */
196
+ _retries;
197
+ /** @private */
194
198
  _coreKeys;
195
199
  /** @private */
196
200
  _offJoins;
@@ -241,6 +245,8 @@ export declare class Handle extends ReadyResource {
241
245
  _live;
242
246
  /** @private */
243
247
  _ac;
248
+ /** @private */
249
+ _offs;
244
250
  _queued: {
245
251
  root: boolean;
246
252
  children: Set<any>;
@@ -256,6 +262,8 @@ export declare class Handle extends ReadyResource {
256
262
  get signal(): AbortSignal;
257
263
  /** The top-most handle in the parent chain — itself for a root handle. */
258
264
  get root(): this;
265
+ /** @private */
266
+ private _onclose;
259
267
  /**
260
268
  * Lazily-built file server for this identity. Root-only — child handles
261
269
  * reach it through `this.root.fileServer`.
@@ -318,6 +326,8 @@ export declare class Handle extends ReadyResource {
318
326
  /** @private */
319
327
  private _removed;
320
328
  /** @private */
329
+ private _seat;
330
+ /** @private */
321
331
  private _tx;
322
332
  /** @private */
323
333
  private _leave;
@@ -325,6 +335,8 @@ export declare class Handle extends ReadyResource {
325
335
  private _depart;
326
336
  /** @private */
327
337
  private _ousted;
338
+ /** @private */
339
+ private _repass;
328
340
  /**
329
341
  * One holder done with it: a child stays open for the others. With its last, what they tied to it ends and it
330
342
  * stays open, idle, so a reopen finds it as it is; the root keeps `keepOpen` of them (16 by default) and one more
@@ -450,6 +462,14 @@ export declare class Handle extends ReadyResource {
450
462
  /** @private */
451
463
  private _run;
452
464
  /** @private */
465
+ private _take;
466
+ /** @private */
467
+ private _passes;
468
+ /** @private */
469
+ private _retry;
470
+ /** @private */
471
+ private _spent;
472
+ /** @private */
453
473
  private _cancel;
454
474
  /** @private */
455
475
  private _check;
@@ -5,5 +5,6 @@ export declare const REMOVALS = "removals";
5
5
  export declare const REFUSALS = "refusals";
6
6
  export declare const SPENT = "spent";
7
7
  export declare const ASKS = "owed";
8
+ export declare const PASSES = "seats";
8
9
  export declare const TIMEOUT = 30000;
9
10
  export declare const KEEP_OPEN = 16;
@@ -197,6 +197,23 @@ export declare function deny(ctx: Context, request: {
197
197
  * @returns {Promise<'removed' | 'left' | null>}
198
198
  */
199
199
  export declare function removed(ctx: Context, id: string): Promise<'removed' | 'left' | null>;
200
+ /**
201
+ * Let a member of another handle in, with no invite to pass on: her devices find it in `from` while
202
+ * they have it open, join on their own, and the handle shows up in her list. Taken back with
203
+ * `revoke` on the `invites` row whose `to` is her id. Rejects `DENIED` for a role above your own or
204
+ * when you cannot write in `from`, `UNKNOWN` when she or none of her devices is in `from`, `INVALID`
205
+ * when she is a member already.
206
+ *
207
+ * @param {Context} ctx The handle she is let into.
208
+ * @param {string} id Her member id.
209
+ * @param {{ from: Context, role?: string, ttl?: number | string }} opts `from`: a handle both are in. `role` is `member` by default.
210
+ * @returns {Promise<void>}
211
+ */
212
+ export declare function seat(ctx: Context, id: string, opts: {
213
+ from: Context;
214
+ role?: string;
215
+ ttl?: number | string;
216
+ }): Promise<void>;
200
217
  /**
201
218
  * Quit a handle for good: its row reads `leaving`, then `left` once the handle holds it, and it closes.
202
219
  *
@@ -36,6 +36,11 @@ declare const remote: {
36
36
  id: string;
37
37
  }, reason?: string): Promise<void>;
38
38
  removed(ctx: verbs.Context, id: string): Promise<'removed' | 'left' | null>;
39
+ seat(ctx: verbs.Context, id: string, opts: {
40
+ from: verbs.Context;
41
+ role?: string;
42
+ ttl?: number | string;
43
+ }): Promise<void>;
39
44
  leave(ctx: verbs.Context): Promise<void>;
40
45
  close(ctx: verbs.Context): Promise<void>;
41
46
  cancel(me: verbs.Context, code: string): Promise<boolean>;
@@ -66,7 +71,7 @@ declare const remote: {
66
71
  topic?: string;
67
72
  }): Promise<void>;
68
73
  };
69
- export declare const put: typeof verbs.put, set: typeof verbs.set, get: typeof verbs.get, del: typeof verbs.del, watch: typeof verbs.watch, call: typeof verbs.call, supports: typeof verbs.supports, open: typeof verbs.open, invite: typeof verbs.invite, revoke: typeof verbs.revoke, rotate: typeof verbs.rotate, accept: typeof verbs.accept, deny: typeof verbs.deny, leave: typeof verbs.leave, removed: typeof verbs.removed, close: typeof verbs.close, cancel: typeof verbs.cancel, suspend: typeof verbs.suspend, resume: typeof verbs.resume, activate: typeof verbs.activate, deactivate: typeof verbs.deactivate, phrase: typeof verbs.phrase, nearby: typeof verbs.nearby;
74
+ export declare const put: typeof verbs.put, set: typeof verbs.set, get: typeof verbs.get, del: typeof verbs.del, watch: typeof verbs.watch, call: typeof verbs.call, supports: typeof verbs.supports, open: typeof verbs.open, invite: typeof verbs.invite, revoke: typeof verbs.revoke, rotate: typeof verbs.rotate, accept: typeof verbs.accept, deny: typeof verbs.deny, leave: typeof verbs.leave, removed: typeof verbs.removed, seat: typeof verbs.seat, close: typeof verbs.close, cancel: typeof verbs.cancel, suspend: typeof verbs.suspend, resume: typeof verbs.resume, activate: typeof verbs.activate, deactivate: typeof verbs.deactivate, phrase: typeof verbs.phrase, nearby: typeof verbs.nearby;
70
75
  export { t, schema };
71
76
  export type BaseRPCClient = import('@cero-base/core/rpc').RPCClient;
72
77
  export type RefInfo = import('../lib/spec.js').RefInfo;