@cero-base/cero 3.1.0 → 3.3.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.1.0",
3
+ "version": "3.3.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.1.0",
116
+ "@cero-base/core": "^3.3.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
  },
@@ -59,7 +59,9 @@ export const main = {
59
59
  // their answers
60
60
  secret: bytes,
61
61
  // the member it was made for: nobody else joins with it
62
- to: string
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
63
65
  },
64
66
  handle: {
65
67
  id: required(string),
@@ -346,7 +348,7 @@ export const local = {
346
348
 
347
349
  // what a write means to apply. A release that changes it without changing what is stored bumps
348
350
  // this, so an app's next build raises its contract and devices on the old release skip the new writes
349
- export const contract = { version: 5 }
351
+ export const contract = { version: 6 }
350
352
 
351
353
  export const rpc = {
352
354
  'req-empty': {
@@ -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, PASSES, SPENT, TIMEOUT } from '../lib/constants.js'
25
+ import { KEEP_OPEN, LOOKS, 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,8 @@ 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._looks = parent ? null : new Map() // room open here → its reads of its passes, and the look at each room they name
142
+ /** @private */
141
143
  this._coreKeys = parent ? null : new Map()
142
144
  /** @private */
143
145
  this._offJoins = null
@@ -238,7 +240,7 @@ export class Handle extends ReadyResource {
238
240
  /** @private */
239
241
  this._ac = new AbortController()
240
242
  if (this.closed) this._ac.abort()
241
- else this.once('close', () => this._ac.abort())
243
+ else this._onclose(() => this._ac.abort())
242
244
  }
243
245
  return this._ac.signal
244
246
  }
@@ -250,6 +252,17 @@ export class Handle extends ReadyResource {
250
252
  return h
251
253
  }
252
254
 
255
+ // what is tied to this handle while it is open is undone as it closes, by one listener however many there are
256
+ /** @private */
257
+ _onclose(fn) {
258
+ if (!this._offs) {
259
+ /** @private */
260
+ this._offs = []
261
+ this.once('close', () => this._offs.forEach((off) => off()))
262
+ }
263
+ this._offs.push(fn)
264
+ }
265
+
253
266
  /**
254
267
  * Lazily-built file server for this identity. Root-only — child handles
255
268
  * reach it through `this.root.fileServer`.
@@ -325,10 +338,10 @@ export class Handle extends ReadyResource {
325
338
  this._pruneAll().catch(this._onerror)
326
339
  this._tellClosed()
327
340
  })
328
- this.once('close', prune)
341
+ this._onclose(prune)
329
342
  if (this._bluetooth) {
330
343
  const off = this.store.onUpdate('profile', () => this._tell().catch(this._onerror))
331
- this.once('close', off)
344
+ this._onclose(off)
332
345
  await this._tell()
333
346
  }
334
347
  // the joins on their way, at launch and as their rows move
@@ -340,7 +353,7 @@ export class Handle extends ReadyResource {
340
353
  this._tellClosed()
341
354
  // the handles rows, keyed by push topic, for a cold push process that cannot read the root
342
355
  const off = this.store.onUpdate('handles', () => this._index().catch(this._onerror))
343
- this.once('close', off)
356
+ this._onclose(off)
344
357
  await this._index()
345
358
  }
346
359
  }
@@ -444,6 +457,7 @@ export class Handle extends ReadyResource {
444
457
  // device checks its chain against
445
458
  /** @private */
446
459
  async _invite(opts = {}) {
460
+ if (opts.from != null) return this._seat(opts)
447
461
  if (this.parent) {
448
462
  const invite = await this._pair.invite(opts)
449
463
  // a close right after the invite must not drop the row that reopens this handle at boot
@@ -482,20 +496,24 @@ export class Handle extends ReadyResource {
482
496
  // an invite made to her, sealed with this room's keys to her devices in a room both are in, where
483
497
  // they find it. `from` crosses the bridge as its id
484
498
  /** @private */
485
- async _seat(id, { from, role = 'member', ttl } = {}) {
486
- if (!this.parent) throw CeroError.INVALID('a device is linked, not seated')
499
+ async _seat({ from, ...opts }) {
500
+ const id = opts.to
501
+ if (!this.parent) throw CeroError.INVALID("the root's invite links a device: no 'from'")
502
+ if (id == null) throw CeroError.INVALID("an invite 'from' a handle is made 'to' a member of it")
503
+ // its pass is sized before the invite is minted, as one that carries none
504
+ if (opts.data != null) throw CeroError.INVALID("an invite 'from' a handle carries no data")
487
505
  if (typeof from === 'string') {
488
506
  const { data: row } = await this.root.store.get('handles', from)
489
507
  if (!row) throw CeroError.UNKNOWN('handle', from)
490
508
  const shared = await this.root._load(row.type, from)
491
509
  try {
492
- return await this._seat(id, { from: shared, role, ttl })
510
+ return await this._seat({ ...opts, from: shared })
493
511
  } finally {
494
512
  await shared.close()
495
513
  }
496
514
  }
497
515
  if (!(from instanceof Handle) || !from.parent) {
498
- throw CeroError.INVALID('seat takes { from }: a room she is in')
516
+ throw CeroError.INVALID("'from' is a handle you both are in")
499
517
  }
500
518
  const { store } = from
501
519
  const { data: me } = await store.get('members', this.identity.id)
@@ -509,7 +527,7 @@ export class Handle extends ReadyResource {
509
527
  }
510
528
  const { data: invites } = await this.store.get('invites')
511
529
  if (invites.some((i) => i.to === id && !(i.expires && i.expires <= Date.now()))) {
512
- throw CeroError.INVALID(`${id} has a seat already`)
530
+ throw CeroError.INVALID(`${id} has an invite here already`)
513
531
  }
514
532
  // what would keep its pass out of `from` is checked first: an invite minted is live
515
533
  const at = Math.min(store.version, await store.dispatcher.version(store.view))
@@ -523,10 +541,17 @@ export class Handle extends ReadyResource {
523
541
  `this room has too many keys to seal to her ${devices.length} devices`
524
542
  )
525
543
  }
526
- const invite = await this._invite({ role, ttl, to: id })
527
- const pass = Pass.seal(devices, { ...fields, invite })
544
+ const invite = await this._invite({ ...opts, keys: devices.map((d) => d.key) })
545
+ // a rotation under way as the invite went in may not name her: its key is read once it ends
546
+ await this.store.rotation.settled()
547
+ const epochs = keyring.all()
548
+ // spent or revoked since: the rotation after that leaves her out, and so does this
549
+ const { data: live } = await this.store.get('invites', b4a.toHex(Invite.parse(invite).id))
550
+ if (!live) return invite
551
+ const pass = Pass.seal(devices, { ...fields, epochs, invite })
528
552
  const row = { id: b4a.toHex(Identity.randomBytes(16)), to: id, pass, createdAt: Date.now() }
529
553
  await store.call('add-pass', row)
554
+ return invite
530
555
  }
531
556
 
532
557
  // the same context, its refs writing into one batch; a fn that ignores it would write outside
@@ -601,16 +626,20 @@ export class Handle extends ReadyResource {
601
626
  this._departing.set(id, going)
602
627
  }
603
628
 
604
- // a device that applies its own identity's removal writes it on the row, with who removed her
629
+ // a device that applies its own identity's removal writes it on the row, with who removed her; `out`, a seat
630
+ // she holds no more with no removal to read, as a seat of hers that never counted there, with why
631
+ // the room turned it away
605
632
  /** @private */
606
- async _ousted(child) {
607
- const removal = await child.store.removal(this.identity.id)
608
- if (!removal) return
633
+ async _ousted(child, out = false) {
609
634
  const { data: row } = await this.store.get('handles', child.id)
610
635
  // only a seat held is lost: a row asking or joining is a rejoin under way, one ended is over
611
636
  if (!row || !['in', 'leaving'].includes(row.state || 'in')) return
612
- const fields = { by: removal.by, reason: null, encryptionKey: null, epochs: null }
613
- await this.store.set('handles', { id: child.id, state: 'removed', ...fields })
637
+ const removal = await child.store.removal(this.identity.id)
638
+ const refusal = removal ? null : await refused(child.store, this.identity)
639
+ if (!removal && !refusal && !out) return
640
+ const fields = { by: removal?.by ?? null, reason: refusal?.reason || null }
641
+ const ended = { state: 'removed', ...fields, encryptionKey: null, epochs: null }
642
+ await this.store.set('handles', { id: child.id, ...ended })
614
643
  }
615
644
 
616
645
  /**
@@ -1233,7 +1262,16 @@ export class Handle extends ReadyResource {
1233
1262
  const id = hid.encode(Invite.parse(invite).key)
1234
1263
  let join = this._joining.get(id)
1235
1264
  if (!join) {
1236
- join = { id, type, invite: null, pass, writer: null, waiting: 0, end: null, running: null }
1265
+ join = {
1266
+ id,
1267
+ type,
1268
+ invite: null,
1269
+ pass,
1270
+ writer: null,
1271
+ waiting: 0,
1272
+ end: null,
1273
+ running: null
1274
+ }
1237
1275
  join.done = new Promise((resolve, reject) => {
1238
1276
  join.resolve = resolve
1239
1277
  join.reject = reject
@@ -1242,8 +1280,9 @@ export class Handle extends ReadyResource {
1242
1280
  this._joining.set(id, join)
1243
1281
  }
1244
1282
  // a join past its reply enters with those keys: a newer invite waits on it, and one waiting
1245
- // for a reply takes the keys a pass hands it
1246
- if ((join.invite !== invite || (pass && !join.pass)) && !join.entering) {
1283
+ // for a reply takes the keys a pass hands it. A pass waits for another pass's join to end
1284
+ const other = join.invite !== invite && !(pass && join.pass && join.invite)
1285
+ if ((other || (pass && !join.pass)) && !join.entering) {
1247
1286
  join.pass = pass
1248
1287
  this._run(join, invite)
1249
1288
  }
@@ -1297,46 +1336,33 @@ export class Handle extends ReadyResource {
1297
1336
  if (end.code !== 'CLOSED') {
1298
1337
  await this._over(join.id, end, { invite, writer: join.writer }).catch(report)
1299
1338
  }
1300
- // a pass whose room did not show in time is tried again, nothing on the root
1301
- if (err.code !== 'CLOSED' && err.code !== 'TIMEOUT' && alone) this._onerror(err)
1339
+ if (err.code !== 'CLOSED' && alone) this._onerror(err)
1302
1340
  settle(join.reject, end)
1303
1341
  }
1304
1342
  }
1305
1343
 
1306
- // a pass's join: its invite read in the room its keys open, as nobody, before anything is written;
1307
- // then asked, written and seated by this device's own claim. Null when that takes longer: it goes
1308
- // on as a plain join
1344
+ // a room as a pass's keys open it, apart from any open here
1345
+ /** @private */
1346
+ _apart(type, { key, encryptionKey, epochs }, keyPair) {
1347
+ const spec = pickHandle(this.spec, type)
1348
+ const namespace = `${NS}/handle/${type}/${randomNs()}`
1349
+ return this._room({ spec, namespace, key, encryptionKey, epochs, keyPair })
1350
+ }
1351
+
1352
+ // a pass's join, its invite seen in its room by the look that took it: asked, written and seated
1353
+ // by this device's own claim. Null when that takes longer: it goes on as a plain join
1309
1354
  /** @private */
1310
1355
  async _take(join, invite, signal) {
1311
1356
  const { type, pass } = join
1312
1357
  const id = hid.encode(pass.key)
1313
1358
  const spec = pickHandle(this.spec, type)
1314
- const { key, encryptionKey, epochs } = pass
1315
- const room = (keyPair) => {
1316
- const namespace = `${NS}/handle/${type}/${randomNs()}`
1317
- return this._room({ spec, namespace, key, encryptionKey, epochs, keyPair })
1318
- }
1319
- const reader = room(Identity.randomKeyPair())
1320
- try {
1321
- await reader.ready()
1322
- const { store } = reader
1323
- const inviteId = b4a.toHex(Invite.parse(invite).id)
1324
- const shows = async () =>
1325
- !!(await store.get('invites', inviteId)).data ||
1326
- !!(await store.view.get(`@${store.ns}/${SPENT}`, { id: inviteId }))
1327
- if (!(await until(store, shows, TIMEOUT, signal))) {
1328
- throw signal.aborted ? CeroError.CLOSED('join') : CeroError.TIMEOUT('join')
1329
- }
1330
- } finally {
1331
- await reader._end().catch(safetyCatch)
1332
- }
1333
1359
  const { data: kept } = await this.local.store.get('handle-keypairs', id)
1334
1360
  const { publicKey, secretKey } = kept?.invite === invite ? kept : Identity.randomKeyPair()
1335
1361
  const writer = (join.writer = { publicKey, secretKey })
1336
1362
  // asked before its join is written: a retry, or the latest ask, finds its writer
1337
1363
  await this._ask(type, invite, writer)
1338
1364
  await Pairing.write(this.mailbox, invite, { identity: this.identity, spec, writer })
1339
- const child = room(writer)
1365
+ const child = this._apart(type, pass, writer)
1340
1366
  try {
1341
1367
  await child.ready()
1342
1368
  const { store } = child
@@ -1358,33 +1384,136 @@ export class Handle extends ReadyResource {
1358
1384
  return null
1359
1385
  }
1360
1386
 
1361
- // the passes this device opens in a room open here: each starts its join
1387
+ // the passes for this identity in a room open here, read as it opens, whenever its seats change
1388
+ // and when a join one of them began ends: each room they name is looked at once, for all of them
1362
1389
  /** @private */
1363
1390
  async _passes(from) {
1391
+ const mine = this._looks.get(from)
1392
+ if (!mine) return
1393
+ // a read begun since has the newer rows: it sets the looks
1394
+ const turn = ++mine.turn
1364
1395
  const { store } = from
1365
1396
  const rows = await store.view.find(`@${store.ns}/${PASSES}`, {}).toArray()
1397
+ rows.sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0))
1398
+ const rooms = new Map()
1399
+ const left = new Map()
1366
1400
  for (const row of rows) {
1367
1401
  if (row.to !== this.identity.id) continue
1368
1402
  const pass = opens(this.identity, row.pass)
1369
1403
  const type = pass?.data && b4a.toString(pass.data)
1370
1404
  if (!type || !this.spec.handles?.[type]) continue
1371
1405
  if (await this._spent(from, row, pass)) continue
1372
- const spend = () =>
1373
- this._spent(from, row, pass).catch((err) => this.closing || this._onerror(err))
1374
- this._start(pass.invite, type, pass).done.then(spend, spend)
1406
+ // each opens a room: the newest of one member, so that none holds this device or another's passes up
1407
+ const count = (left.get(row.by) || 0) + 1
1408
+ left.set(row.by, count)
1409
+ if (count > LOOKS) continue
1410
+ const id = hid.encode(pass.key)
1411
+ rooms.set(id, [...(rooms.get(id) || []), { row, pass, type }])
1412
+ }
1413
+ if (turn !== mine.turn || this._looks.get(from) !== mine) return
1414
+ for (const [id, look] of mine.rooms) {
1415
+ if (rooms.has(id)) continue
1416
+ look.stop.abort()
1417
+ mine.rooms.delete(id)
1418
+ }
1419
+ for (const [id, passes] of rooms) this._look(from, id, passes)
1420
+ }
1421
+
1422
+ // one look a room for the passes that name it, begun again only once they are others
1423
+ /** @private */
1424
+ _look(from, id, passes) {
1425
+ const { rooms } = this._looks.get(from)
1426
+ const rows = passes.map((entry) => entry.row.id).join()
1427
+ const was = rooms.get(id)
1428
+ if (was?.rows === rows) return
1429
+ was?.stop.abort()
1430
+ const look = { rows, stop: new AbortController() }
1431
+ rooms.set(id, look)
1432
+ this._watch(from, id, passes, look).catch((err) => this.closing || this._onerror(err))
1433
+ }
1434
+
1435
+ // the room its passes name, open as nobody until each has its end, each through the keys it
1436
+ // holds: its invite is read there before anything is written. The newest she can still take is
1437
+ // joined; one she sits in already, or whose invite ended with her in, goes; one that ended waits
1438
+ // for every newer one to show; one that opens nothing keeps no other waiting
1439
+ /** @private */
1440
+ async _watch(from, id, passes, look) {
1441
+ const { signal } = look.stop
1442
+ const readers = passes.map(({ type, pass }) =>
1443
+ this._apart(type, pass, Identity.randomKeyPair())
1444
+ )
1445
+ const left = new Map()
1446
+ let taken = null
1447
+ try {
1448
+ const ready = await Promise.allSettled(readers.map((reader) => reader.ready()))
1449
+ for (const [i, { status, reason }] of ready.entries()) {
1450
+ if (status === 'fulfilled') left.set(passes[i], readers[i])
1451
+ else if (!this.closing) this._onerror(reason)
1452
+ }
1453
+ const read = async () => {
1454
+ let unseen = false
1455
+ for (const [entry, reader] of left) {
1456
+ const { store } = reader
1457
+ // a join of the room that ended since, under its invite, is its end
1458
+ if (await this._spent(from, entry.row, entry.pass)) {
1459
+ left.delete(entry)
1460
+ continue
1461
+ }
1462
+ const inviteId = b4a.toHex(Invite.parse(entry.pass.invite).id)
1463
+ const live = !!(await store.get('invites', inviteId)).data
1464
+ if (!live && !(await store.view.get(`@${store.ns}/${SPENT}`, { id: inviteId }))) {
1465
+ unseen = true
1466
+ continue
1467
+ }
1468
+ // a seat lost, or one that never counted there, ends on the root before she asks again: the
1469
+ // room holds neither her nor a promise to her at a seat made after she was out. Only an invite
1470
+ // she can still take says so: one that ended is read in a room that may not hold her join yet
1471
+ const seated = await promised(store, this.identity)
1472
+ await this._ousted(reader, live && !seated)
1473
+ const { data: row } = await this.store.get('handles', id)
1474
+ if (row && (row.state || 'in') === 'in' && (seated || !live)) {
1475
+ left.delete(entry)
1476
+ await this._delPass(from, entry.row)
1477
+ } else if (live || !unseen) {
1478
+ taken = entry
1479
+ return true
1480
+ }
1481
+ }
1482
+ return left.size === 0
1483
+ }
1484
+ const stores = [...left.values()].map((reader) => reader.store)
1485
+ await until(stores, read, signal)
1486
+ } finally {
1487
+ await Promise.all(readers.map((reader) => reader._end().catch(safetyCatch)))
1375
1488
  }
1489
+ if (!taken || signal.aborted) return
1490
+ const join = this._start(taken.pass.invite, taken.type, taken.pass)
1491
+ const again = () => {
1492
+ const mine = this._looks.get(from)
1493
+ if (!mine) return
1494
+ // the room's join ended under another invite: these are looked at again
1495
+ if (join.invite !== taken.pass.invite && mine.rooms.get(id) === look) mine.rooms.delete(id)
1496
+ return this._passes(from)
1497
+ }
1498
+ join.done.then(again, again).catch((err) => this.closing || this._onerror(err))
1376
1499
  }
1377
1500
 
1378
- // a pass goes once its room is on the root, the join under its invite ended, or it ran out
1379
1501
  /** @private */
1380
- async _spent(from, row, pass) {
1381
- const { data: was } = await this.store.get('handles', hid.encode(pass.key))
1382
- const state = was && (was.state || 'in')
1383
- const ended = SWEPT.includes(state) && was.invite === pass.invite
1384
- if (state !== 'in' && !ended && !Invite.parse(pass.invite).expired) return false
1502
+ async _delPass(from, row) {
1385
1503
  if (from.store.writable && !from.closing && !from.closed) {
1386
1504
  await from.store.call('del-pass', { id: row.id })
1387
1505
  }
1506
+ }
1507
+
1508
+ // a pass goes once its join is in or ended, or it ran out. A room in under another invite is a
1509
+ // seat she may have lost since, unheard on a device that keeps it closed
1510
+ /** @private */
1511
+ async _spent(from, row, pass) {
1512
+ const { data: was } = await this.store.get('handles', hid.encode(pass.key))
1513
+ const state = was && (was.state || 'in')
1514
+ const done = was?.invite === pass.invite && (state === 'in' || SWEPT.includes(state))
1515
+ if (!done && !Invite.parse(pass.invite).expired) return false
1516
+ await this._delPass(from, row)
1388
1517
  return true
1389
1518
  }
1390
1519
 
@@ -1502,8 +1631,8 @@ export class Handle extends ReadyResource {
1502
1631
  const mine = !!kept?.invite && (state === 'joining' || latest)
1503
1632
  if (mine && (state === 'joining' || row.invite === invite)) return id
1504
1633
  if (ENDS[state] && row.invite === invite) throw ENDS[state](row.reason)
1505
- // a pass's join asks with the writer its join is already written with
1506
- const writer = mine ? kept : given || Identity.randomKeyPair()
1634
+ // a pass's join asks with the writer its join is written with, whatever ask stood before
1635
+ const writer = given || (mine ? kept : Identity.randomKeyPair())
1507
1636
  await this._saveKeyPair(id, writer, invite)
1508
1637
  // a room another device of this identity already has the keys of is joined with them
1509
1638
  if (state === 'joining') return id
@@ -1590,10 +1719,13 @@ export class Handle extends ReadyResource {
1590
1719
  */
1591
1720
  async _enter(type, reply, invite, taken = null) {
1592
1721
  const id = hid.encode(reply.key)
1593
- // a room this identity lost its seat in stays open on its old writer: it ends before the new seat opens it
1722
+ // open here on another writer than the seat it enters on, the room is one this identity lost, or
1723
+ // whose seat never counted: it ends before the new seat opens it
1594
1724
  const stale = [...this.children].find((c) => c.id === id && !c.closing)
1595
- const out = stale && (await stale.store.removed(this.identity.id))
1596
- if (out) await stale._end().catch(safetyCatch)
1725
+ const writer = taken ? taken.store.writerKey : reply.writer?.publicKey
1726
+ if (stale && writer && !b4a.equals(stale.store.writerKey, writer)) {
1727
+ await stale._end().catch(safetyCatch)
1728
+ }
1597
1729
  // a pass's join is already open, seated
1598
1730
  const child = /** @type {Child} */ (
1599
1731
  taken ||
@@ -1617,7 +1749,11 @@ export class Handle extends ReadyResource {
1617
1749
  // let in by a promise, this device seats itself: its claim writes the member row
1618
1750
  await child.store.claim({ timeout: 0 })
1619
1751
  // admitted once our member row lands; the same apply seats a writer, a reader has no seat
1620
- const member = await admitted(child.store, this.identity.id)
1752
+ const member = await admitted(
1753
+ child.store,
1754
+ this.identity.id,
1755
+ b4a.toHex(Invite.parse(invite).id)
1756
+ )
1621
1757
  if (member.role !== 'reader' && !child.store.writable) {
1622
1758
  await child.store.whenWritable({ timeout: 0 })
1623
1759
  }
@@ -1776,7 +1912,7 @@ export class Handle extends ReadyResource {
1776
1912
  const child = new Handle({ parent: this, ...opts })
1777
1913
  for (const hook of this._typeHooks) hook.apply(child)
1778
1914
  this._pending.add(child)
1779
- child.once('close', () => this._pending.delete(child))
1915
+ child._onclose(() => this._pending.delete(child))
1780
1916
  return child
1781
1917
  }
1782
1918
 
@@ -1810,11 +1946,17 @@ export class Handle extends ReadyResource {
1810
1946
  // it tells a handle nothing before it has a seat there
1811
1947
  const prune = () => this._prune(child).catch(this._onerror)
1812
1948
  child.store.on('writable', prune)
1813
- child.once('close', () => child.store.off('writable', prune))
1949
+ child._onclose(() => child.store.off('writable', prune))
1814
1950
  prune()
1815
1951
  this._seats(child)
1952
+ const looks = { turn: 0, rooms: new Map() }
1953
+ this._looks.set(child, looks)
1816
1954
  const take = () => this._passes(child).catch((err) => this.closing || this._onerror(err))
1817
- child.once('close', child.store.onUpdate(PASSES, take))
1955
+ child._onclose(child.store.onUpdate(PASSES, take))
1956
+ child._onclose(() => {
1957
+ this._looks.delete(child)
1958
+ for (const look of looks.rooms.values()) look.stop.abort()
1959
+ })
1818
1960
  take()
1819
1961
  // what a listener ties to the handle as it runs is no holder's: it stays through their last close
1820
1962
  child._arriving = true
@@ -1832,11 +1974,12 @@ export class Handle extends ReadyResource {
1832
1974
  const onchange = (touched) => {
1833
1975
  if (touched.has('*') || touched.has('devices') || touched.has('members')) {
1834
1976
  this._index(child).catch(this._onerror)
1835
- this._ousted(child).catch((err) => this.closing || this._onerror(err))
1836
1977
  }
1978
+ // whatever a batch touched: a reorder takes back a seat it read before
1979
+ this._ousted(child).catch((err) => this.closing || this._onerror(err))
1837
1980
  }
1838
1981
  child.store.on('update', onchange)
1839
- child.once('close', () => child.store.off('update', onchange))
1982
+ child._onclose(() => child.store.off('update', onchange))
1840
1983
  this._index(child).catch(this._onerror)
1841
1984
  }
1842
1985
 
@@ -2165,13 +2308,15 @@ export class Handle extends ReadyResource {
2165
2308
  }
2166
2309
  const touches = (name) => (touched) => touched.has('*') || touched.has(name)
2167
2310
  const onepoch = () => save().catch(this._onerror)
2168
- const onroot = (touched) => touches('handles')(touched) && read().catch(this._onerror)
2169
- const onchild = (touched) => touches('epochs')(touched) && read().catch(this._onerror)
2311
+ // a room that closed under the read says nothing
2312
+ const report = (err) => err.code === 'CLOSED' || this._onerror(err)
2313
+ const onroot = (touched) => touches('handles')(touched) && read().catch(report)
2314
+ const onchild = (touched) => touches('epochs')(touched) && read().catch(report)
2170
2315
  child.store.on('epoch', onepoch)
2171
2316
  child.store.on('update', onchild)
2172
2317
  this.store.on('update', onroot)
2173
2318
  this.store.on('epoch', onepoch)
2174
- child.once('close', () => {
2319
+ child._onclose(() => {
2175
2320
  child.store.off('epoch', onepoch)
2176
2321
  child.store.off('update', onchild)
2177
2322
  this.store.off('update', onroot)
@@ -2189,7 +2334,7 @@ export class Handle extends ReadyResource {
2189
2334
  apply: (child) => {
2190
2335
  if (child.type !== ref.type) return
2191
2336
  offs.set(child, attach(child))
2192
- child.once('close', () => offs.delete(child))
2337
+ child._onclose(() => offs.delete(child))
2193
2338
  }
2194
2339
  }
2195
2340
  this._typeHooks.add(hook)
@@ -2413,27 +2558,42 @@ function listed(rows, query = {}) {
2413
2558
  return { data, total: data.length, size: data.length }
2414
2559
  }
2415
2560
 
2416
- // whether `check` holds of a room within `ms` as its view updates: false once past, or stopped
2417
- function until(db, check, ms, signal) {
2418
- return new Promise((resolve, reject) => {
2419
- const done = (err, found) => {
2420
- clearTimeout(timer)
2421
- db.off('update', test)
2422
- db.off('close', closed)
2423
- signal.removeEventListener('abort', stop)
2424
- if (err) reject(err)
2425
- else resolve(found)
2426
- }
2427
- const test = () => check().then((found) => found && done(null, true), done)
2428
- const stop = () => done(null, false)
2429
- const closed = () => done(CeroError.CLOSED('Database'))
2430
- const timer = setTimeout(stop, ms)
2431
- db.on('update', test)
2432
- db.once('close', closed)
2433
- signal.addEventListener('abort', stop)
2434
- if (signal.aborted) stop()
2435
- else test()
2436
- })
2561
+ // whether `check` comes to hold as the views of these rooms update, read one at a time: false once stopped
2562
+ async function until(dbs, check, signal) {
2563
+ let wake = null
2564
+ const heard = () => wake?.()
2565
+ for (const db of dbs) {
2566
+ db.on('update', heard)
2567
+ db.on('close', heard)
2568
+ }
2569
+ signal.addEventListener('abort', heard)
2570
+ try {
2571
+ while (!signal.aborted) {
2572
+ // listened for before the read: an update during it is read after
2573
+ const next = new Promise((resolve) => (wake = resolve))
2574
+ if (await check()) return true
2575
+ await next
2576
+ }
2577
+ return false
2578
+ } finally {
2579
+ for (const db of dbs) {
2580
+ db.off('update', heard)
2581
+ db.off('close', heard)
2582
+ }
2583
+ signal.removeEventListener('abort', heard)
2584
+ }
2585
+ }
2586
+
2587
+ // the room turned this device's writer away, under `invite` when one is named
2588
+ async function turned(db, invite = null) {
2589
+ const refusal = await db.view.get(`@${db.ns}/${REFUSALS}`, { id: hid.encode(db.writerKey) })
2590
+ return refusal && (!invite || !refusal.invite || refusal.invite === invite) ? refusal : null
2591
+ }
2592
+
2593
+ // how the room turned away a seat this device took that never counted: no member row, and its writer refused
2594
+ async function refused(db, identity) {
2595
+ if ((await db.get('members', identity.id)).data) return null
2596
+ return turned(db)
2437
2597
  }
2438
2598
 
2439
2599
  // whether a room let this identity in, by any of its devices
@@ -2452,7 +2612,8 @@ function opens(identity, pass) {
2452
2612
  }
2453
2613
  }
2454
2614
 
2455
- function admitted(db, id) {
2615
+ // its member row once it lands, or why the room turned this device's writer away under `invite`
2616
+ function admitted(db, id, invite) {
2456
2617
  return new Promise((resolve, reject) => {
2457
2618
  const done = (err, member) => {
2458
2619
  db.off('update', onupdate)
@@ -2462,7 +2623,9 @@ function admitted(db, id) {
2462
2623
  }
2463
2624
  const check = async () => {
2464
2625
  const { data } = await db.get('members', id)
2465
- if (data) done(null, data)
2626
+ if (data) return done(null, data)
2627
+ const refusal = await turned(db, invite)
2628
+ if (refusal) done(CeroError.DENIED(refusal.reason || null))
2466
2629
  }
2467
2630
  const onupdate = () => check().catch(done)
2468
2631
  const onclose = () => done(CeroError.CLOSED('Database'))
@@ -12,3 +12,6 @@ export const TIMEOUT = 30000
12
12
 
13
13
  // How many handles nobody holds stay open for a reopen.
14
14
  export const KEEP_OPEN = 16
15
+
16
+ // How many passes left by one member a device looks at, at once.
17
+ export const LOOKS = 16
@@ -383,10 +383,14 @@ export async function open(ref, arg = {}) {
383
383
  const OPENS = new Set(['invite', 'id', 'name'])
384
384
 
385
385
  /**
386
- * Mint an invite code into a handle.
386
+ * Mint an invite code into a handle. With `from`, a handle you and the member it is made `to` are
387
+ * both in, nobody passes the code on: her devices find it in `from` while they have it open, join
388
+ * on their own, and the handle shows up in her list. Taken back with `revoke`. With `from` it
389
+ * rejects `DENIED` when you cannot write in `from`, `UNKNOWN` when she or none of her devices is in
390
+ * `from`, `INVALID` when she is a member already or has one waiting.
387
391
  *
388
392
  * @param {Context} ctx
389
- * @param {import('@cero-base/core/pairing').InviteOpts} [opts]
393
+ * @param {import('@cero-base/core/pairing').InviteOpts & { from?: Context }} [opts]
390
394
  * @returns {Promise<string>}
391
395
  */
392
396
  export async function invite(ctx, opts = {}) {
@@ -469,24 +473,6 @@ export function removed(ctx, id) {
469
473
  return ctx._removed(id)
470
474
  }
471
475
 
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
-
490
476
  /**
491
477
  * Quit a handle for good: its row reads `leaving`, then `left` once the handle holds it, and it closes.
492
478
  *
package/src/rpc/client.js CHANGED
@@ -31,7 +31,6 @@ export const {
31
31
  deny,
32
32
  leave,
33
33
  removed,
34
- seat,
35
34
  close,
36
35
  cancel,
37
36
  suspend,
@@ -350,9 +349,10 @@ const operators = {
350
349
 
351
350
  // the verbs in lib/operators.js land here, and cross to the worker, which runs the same operator
352
351
 
352
+ // the handle it is delivered `from` crosses as its id
353
353
  /** @private */
354
354
  _invite(opts) {
355
- return this._verb('invite', opts)
355
+ return this._verb('invite', { ...opts, from: opts.from?.id ?? opts.from })
356
356
  },
357
357
 
358
358
  /** @private */
@@ -380,11 +380,6 @@ const operators = {
380
380
  return this._verb('removed', id)
381
381
  },
382
382
 
383
- /** @private */
384
- _seat(id, { from, ...opts }) {
385
- return this._verb('seat', id, { ...opts, from: from?.id ?? from })
386
- },
387
-
388
383
  /** @private */
389
384
  _cancel(invite) {
390
385
  return this._verb('cancel', invite)
package/src/rpc/server.js CHANGED
@@ -18,7 +18,6 @@ import {
18
18
  revoke,
19
19
  rotate,
20
20
  removed,
21
- seat,
22
21
  accept,
23
22
  deny,
24
23
  cancel,
@@ -40,7 +39,6 @@ const VERBS = new Map(
40
39
  revoke,
41
40
  rotate,
42
41
  removed,
43
- seat,
44
42
  accept,
45
43
  deny,
46
44
  cancel,
@@ -46,6 +46,7 @@ export declare const main: {
46
46
  confirm: import("@cero-base/core").Prim;
47
47
  secret: import("@cero-base/core").Prim;
48
48
  to: import("@cero-base/core").Prim;
49
+ keys: import("@cero-base/core").Prim;
49
50
  };
50
51
  handle: {
51
52
  id: import("@cero-base/core").Prim;
@@ -29,7 +29,9 @@ export declare const cero: {
29
29
  id?: string;
30
30
  name?: string;
31
31
  } | undefined): Promise<operators.Context>;
32
- invite(ctx: operators.Context, opts?: import("@cero-base/core").InviteOpts): Promise<string>;
32
+ invite(ctx: operators.Context, opts?: import("@cero-base/core").InviteOpts & {
33
+ from?: operators.Context;
34
+ }): Promise<string>;
33
35
  revoke(ctx: operators.Context, code: string): Promise<boolean>;
34
36
  rotate(ctx: operators.Context): Promise<{
35
37
  epoch: number;
@@ -44,11 +46,6 @@ export declare const cero: {
44
46
  id: string;
45
47
  }, reason?: string): Promise<void>;
46
48
  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>;
52
49
  leave(ctx: operators.Context): Promise<void>;
53
50
  close(ctx: operators.Context): Promise<void>;
54
51
  cancel(me: operators.Context, code: string): Promise<boolean>;
@@ -191,6 +191,8 @@ export declare class Handle extends ReadyResource {
191
191
  /** @private */
192
192
  _taking;
193
193
  /** @private */
194
+ _looks;
195
+ /** @private */
194
196
  _coreKeys;
195
197
  /** @private */
196
198
  _offJoins;
@@ -241,6 +243,8 @@ export declare class Handle extends ReadyResource {
241
243
  _live;
242
244
  /** @private */
243
245
  _ac;
246
+ /** @private */
247
+ _offs;
244
248
  _queued: {
245
249
  root: boolean;
246
250
  children: Set<any>;
@@ -256,6 +260,8 @@ export declare class Handle extends ReadyResource {
256
260
  get signal(): AbortSignal;
257
261
  /** The top-most handle in the parent chain — itself for a root handle. */
258
262
  get root(): this;
263
+ /** @private */
264
+ private _onclose;
259
265
  /**
260
266
  * Lazily-built file server for this identity. Root-only — child handles
261
267
  * reach it through `this.root.fileServer`.
@@ -452,10 +458,18 @@ export declare class Handle extends ReadyResource {
452
458
  /** @private */
453
459
  private _run;
454
460
  /** @private */
461
+ private _apart;
462
+ /** @private */
455
463
  private _take;
456
464
  /** @private */
457
465
  private _passes;
458
466
  /** @private */
467
+ private _look;
468
+ /** @private */
469
+ private _watch;
470
+ /** @private */
471
+ private _delPass;
472
+ /** @private */
459
473
  private _spent;
460
474
  /** @private */
461
475
  private _cancel;
@@ -8,3 +8,4 @@ export declare const ASKS = "owed";
8
8
  export declare const PASSES = "seats";
9
9
  export declare const TIMEOUT = 30000;
10
10
  export declare const KEEP_OPEN = 16;
11
+ export declare const LOOKS = 16;
@@ -126,13 +126,19 @@ export declare function open(ref: Ref, arg?: string | {
126
126
  name?: string;
127
127
  } | undefined): Promise<Context>;
128
128
  /**
129
- * Mint an invite code into a handle.
129
+ * Mint an invite code into a handle. With `from`, a handle you and the member it is made `to` are
130
+ * both in, nobody passes the code on: her devices find it in `from` while they have it open, join
131
+ * on their own, and the handle shows up in her list. Taken back with `revoke`. With `from` it
132
+ * rejects `DENIED` when you cannot write in `from`, `UNKNOWN` when she or none of her devices is in
133
+ * `from`, `INVALID` when she is a member already or has one waiting.
130
134
  *
131
135
  * @param {Context} ctx
132
- * @param {import('@cero-base/core/pairing').InviteOpts} [opts]
136
+ * @param {import('@cero-base/core/pairing').InviteOpts & { from?: Context }} [opts]
133
137
  * @returns {Promise<string>}
134
138
  */
135
- export declare function invite(ctx: Context, opts?: import('@cero-base/core/pairing').InviteOpts): Promise<string>;
139
+ export declare function invite(ctx: Context, opts?: import('@cero-base/core/pairing').InviteOpts & {
140
+ from?: Context;
141
+ }): Promise<string>;
136
142
  /**
137
143
  * Kill an invite, for every member.
138
144
  *
@@ -197,23 +203,6 @@ export declare function deny(ctx: Context, request: {
197
203
  * @returns {Promise<'removed' | 'left' | null>}
198
204
  */
199
205
  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>;
217
206
  /**
218
207
  * Quit a handle for good: its row reads `leaving`, then `left` once the handle holds it, and it closes.
219
208
  *
@@ -22,7 +22,9 @@ declare const remote: {
22
22
  id?: string;
23
23
  name?: string;
24
24
  } | undefined): Promise<verbs.Context>;
25
- invite(ctx: verbs.Context, opts?: import("@cero-base/core").InviteOpts): Promise<string>;
25
+ invite(ctx: verbs.Context, opts?: import("@cero-base/core").InviteOpts & {
26
+ from?: verbs.Context;
27
+ }): Promise<string>;
26
28
  revoke(ctx: verbs.Context, code: string): Promise<boolean>;
27
29
  rotate(ctx: verbs.Context): Promise<{
28
30
  epoch: number;
@@ -36,11 +38,6 @@ declare const remote: {
36
38
  id: string;
37
39
  }, reason?: string): Promise<void>;
38
40
  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>;
44
41
  leave(ctx: verbs.Context): Promise<void>;
45
42
  close(ctx: verbs.Context): Promise<void>;
46
43
  cancel(me: verbs.Context, code: string): Promise<boolean>;
@@ -71,7 +68,7 @@ declare const remote: {
71
68
  topic?: string;
72
69
  }): Promise<void>;
73
70
  };
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;
71
+ 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;
75
72
  export { t, schema };
76
73
  export type BaseRPCClient = import('@cero-base/core/rpc').RPCClient;
77
74
  export type RefInfo = import('../lib/spec.js').RefInfo;