@minca/core 0.1.9 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +1 -1
  2. package/dist/identity/abilities.d.ts +3 -3
  3. package/dist/identity/abilities.d.ts.map +1 -1
  4. package/dist/identity/abilities.js +9 -11
  5. package/dist/identity/abilities.js.map +1 -1
  6. package/dist/identity/root-signer.d.ts +0 -5
  7. package/dist/identity/root-signer.d.ts.map +1 -1
  8. package/dist/identity/root-signer.js +0 -1
  9. package/dist/identity/root-signer.js.map +1 -1
  10. package/dist/index.d.ts +1 -1
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js.map +1 -1
  13. package/dist/node/node.d.ts.map +1 -1
  14. package/dist/node/node.js +230 -253
  15. package/dist/node/node.js.map +1 -1
  16. package/dist/node/remote.d.ts +6 -5
  17. package/dist/node/remote.d.ts.map +1 -1
  18. package/dist/node/remote.js +141 -194
  19. package/dist/node/remote.js.map +1 -1
  20. package/dist/node/space-runtime.d.ts.map +1 -1
  21. package/dist/node/space-runtime.js +69 -82
  22. package/dist/node/space-runtime.js.map +1 -1
  23. package/dist/node/types.d.ts +12 -4
  24. package/dist/node/types.d.ts.map +1 -1
  25. package/dist/node/worker.d.ts +1 -1
  26. package/dist/node/worker.d.ts.map +1 -1
  27. package/dist/node/worker.js +10 -6
  28. package/dist/node/worker.js.map +1 -1
  29. package/dist/session/auth.d.ts +20 -0
  30. package/dist/session/auth.d.ts.map +1 -1
  31. package/dist/session/auth.js +80 -63
  32. package/dist/session/auth.js.map +1 -1
  33. package/dist/session/connect.d.ts +50 -8
  34. package/dist/session/connect.d.ts.map +1 -1
  35. package/dist/session/connect.js +91 -27
  36. package/dist/session/connect.js.map +1 -1
  37. package/dist/session/connection.d.ts +39 -6
  38. package/dist/session/connection.d.ts.map +1 -1
  39. package/dist/session/connection.js +107 -38
  40. package/dist/session/connection.js.map +1 -1
  41. package/dist/session/hosting.d.ts +15 -0
  42. package/dist/session/hosting.d.ts.map +1 -1
  43. package/dist/session/hosting.js +55 -4
  44. package/dist/session/hosting.js.map +1 -1
  45. package/dist/session/index.d.ts +5 -5
  46. package/dist/session/index.d.ts.map +1 -1
  47. package/dist/session/index.js +2 -2
  48. package/dist/session/index.js.map +1 -1
  49. package/dist/space/account-registry.d.ts +14 -4
  50. package/dist/space/account-registry.d.ts.map +1 -1
  51. package/dist/space/account-registry.js +12 -3
  52. package/dist/space/account-registry.js.map +1 -1
  53. package/dist/space/roles.d.ts +59 -140
  54. package/dist/space/roles.d.ts.map +1 -1
  55. package/dist/space/roles.js +328 -427
  56. package/dist/space/roles.js.map +1 -1
  57. package/docs/actions.md +3 -3
  58. package/docs/agents.md +2 -2
  59. package/docs/blueprints-and-guides.md +20 -1
  60. package/docs/bots.md +1 -1
  61. package/docs/node.md +99 -53
  62. package/docs/sign-in.md +16 -9
  63. package/docs/storage.md +1 -1
  64. package/package.json +1 -1
package/dist/node/node.js CHANGED
@@ -12,7 +12,7 @@ import { nameOf, plainQuery, } from '../query/types.js';
12
12
  import { createP256Provider } from '../identity/crypto-p256.js';
13
13
  import { didOf } from '../identity/did.js';
14
14
  import { verifyNote } from '../identity/ucan.js';
15
- import { ACCOUNT_COMMAND, ACCOUNT_REQUIREMENT, ALL_COMMAND, grantsRecordsOnly, noteGrants, noteSpaces, } from '../identity/abilities.js';
15
+ import { actsForAccount, ALL_COMMAND, grantsRecordsOnly, noteSpaces } from '../identity/abilities.js';
16
16
  import { createSigner } from '../schema/signer.js';
17
17
  import { createSchemaEngine } from '../schema/schema-engine.js';
18
18
  import { createSpaceManager, encodeSpaceInvite, parseSpaceInvite, bareInvite, previewInvite, } from '../space/space-manager.js';
@@ -37,7 +37,7 @@ import { contact as contactSchema, contactRequest as contactRequestSchema, door
37
37
  import { checkAnswer, clip, doorTopic, encodeDoorCode, KNOCK_TTL_SECONDS, knockId, MAX_DOOR_RELAYS, openKnock, parseDoorCode, sealKnock, signAnswer, signPurge, } from '../doors/doors.js';
38
38
  import { createMailboxClient } from '../network/mailbox.js';
39
39
  import { team } from '../space/presets.js';
40
- import { CARRIER_COLLECTION, deriveAccountRegistry, deriveContactsSpace, MEMBERSHIP_COLLECTION, PROFILE_COLLECTION, PROFILE_KEY, isAvatarRef, } from '../space/account-registry.js';
40
+ import { CARRIER_COLLECTION, deriveAccountRegistry, deriveCarrySpace, deriveContactsSpace, MEMBERSHIP_COLLECTION, PROFILE_COLLECTION, PROFILE_KEY, isAvatarRef, } from '../space/account-registry.js';
41
41
  import { CARRY_CLOSED_KEY, makePass, PASS_COLLECTION, passKey } from '../space/pass.js';
42
42
  import { checkOwnAutomation, OWN_AUTOMATIONS, WAKE_COLLECTION, linkedWakes, wakeFor, } from '../space/own-automations.js';
43
43
  import { createHostClient, connectorOffers, createSpaceHostClient, describeHost, hostPeerAddress, HOSTING_COLLECTION, HostError, newSubscriptionSeed, readStatus, subscriptionKey, } from '../session/hosting.js';
@@ -45,8 +45,6 @@ import { base32Encode, hashedKey } from '../utils/hash.js';
45
45
  /** Everything a session key may do: every command, about the whole account */
46
46
  export const SESSION_COMMAND = ALL_COMMAND;
47
47
  const DEFAULT_TTL_SECONDS = 3600;
48
- /** How long a removed carrier's space is kept open, for the carrier to hear it was removed */
49
- const FORGET_CARRIER_AFTER_MS = 30 * 24 * 3600 * 1000;
50
48
  /** How long leaving waits for a peer to take the account's removal before forgetting the space anyway */
51
49
  const LEAVE_WAIT_MS = 5000;
52
50
  function summarize(record) {
@@ -134,12 +132,12 @@ export async function createNode(config) {
134
132
  const writers = createWriters((did) => did !== sessionDid ? handedIn : (claimed?.heads ?? (config.sessionKey ? handedIn : null)));
135
133
  const mesh = meshFor(config.network, sessionDid);
136
134
  /**
137
- * A node whose note doesn't grant `account/write` — an agent on someone's
138
- * computer running a node of its own, say. It follows the account, but never
139
- * writes for it: no list of spaces, no passes, no name. Every peer would
140
- * ignore those.
135
+ * A node whose note doesn't let it act as the account itself — an app, or
136
+ * an agent on someone's computer running a node of its own. It may follow
137
+ * the account, but never writes for it: no list of spaces, no passes, no
138
+ * name, no doors. Every peer would ignore those (spec 01 §8).
141
139
  */
142
- const narrowNote = !noteGrants(current, ACCOUNT_REQUIREMENT);
140
+ const narrowNote = !actsForAccount(current);
143
141
  // ─── Events ────────────────────────────────────────────────────────
144
142
  const events = createListeners('node event');
145
143
  const { emit } = events;
@@ -172,8 +170,14 @@ export async function createNode(config) {
172
170
  if (contactsRecord && !(await registry.get(contactsRecord.space.id))) {
173
171
  await joinRegistry(await encodeSpaceInvite(contactsRecord, config.signer.did));
174
172
  }
175
- /** Whether a space is the account's own machinery, not one it uses */
176
- const hidden = (spaceId) => carrySpaces.has(spaceId) || spaceId === contactsSpaceId;
173
+ /** Which of the account's own spaces this is, or null for one it uses */
174
+ async function kindOf(spaceId) {
175
+ if (spaceId === accountSpaceId)
176
+ return 'registry';
177
+ if (spaceId === contactsSpaceId)
178
+ return 'contacts';
179
+ return (await isCarrySpace(spaceId)) ? 'carry' : null;
180
+ }
177
181
  /** The contact key, for a node allowed to open contact requests */
178
182
  const contactKeys = config.contactKey ? await contactKeyPair(config.contactKey) : null;
179
183
  /**
@@ -190,7 +194,10 @@ export async function createNode(config) {
190
194
  });
191
195
  }
192
196
  async function findRecord(spaceId) {
193
- return spaceId === accountSpaceId ? account : registry.get(spaceId);
197
+ if (spaceId === accountSpaceId)
198
+ return account;
199
+ const held = await registry.get(spaceId);
200
+ return held ?? (await carrierRecords()).find(({ carry }) => carry.space.id === spaceId)?.carry ?? null;
194
201
  }
195
202
  async function requireRecord(spaceId) {
196
203
  const record = await findRecord(spaceId);
@@ -216,17 +223,16 @@ export async function createNode(config) {
216
223
  if (spaceId !== accountSpaceId)
217
224
  emit({ type: 'status', space: spaceId });
218
225
  }
219
- if (event.type === 'records')
220
- void runtimes
221
- .get(event.space)
222
- ?.then((rt) => checkRevoked(event.space, rt))
223
- .catch(() => { });
224
- if (event.type === 'records' && event.space !== accountSpaceId)
225
- void keepSpaceHosts(event.space).catch(() => { });
226
+ if (event.type !== 'records')
227
+ return;
228
+ void runtimes
229
+ .get(event.space)
230
+ ?.then((rt) => checkRevoked(event.space, rt))
231
+ .catch(() => { });
232
+ void keepSpaceHosts(event.space).catch(() => { });
226
233
  // A space joined with an invite whose record had not arrived: perhaps it has now.
227
- if (event.type === 'records' && event.space !== accountSpaceId)
228
- void finishJoining(event.space);
229
- if (event.type === 'records' && event.space === accountSpaceId) {
234
+ void finishJoining(event.space);
235
+ if (event.space === accountSpaceId) {
230
236
  emit({ type: 'account' });
231
237
  void reconcile();
232
238
  // A rename on another device reaches the spaces open here too.
@@ -262,15 +268,13 @@ export async function createNode(config) {
262
268
  };
263
269
  }
264
270
  const ownName = async () => (await ownProfile())?.name ?? null;
265
- /** Whether a space is the account's own machinery: its registry, its contacts, a carry space */
266
- const ownSpace = (spaceId) => spaceId === accountSpaceId || hidden(spaceId);
267
271
  /**
268
272
  * Tells a space who this account is. Done when the space opens and when the
269
273
  * name changes — not by opening every space, which would start syncing them
270
274
  * all; a space not open now hears on its next open.
271
275
  */
272
276
  async function publishProfile(spaceId, open) {
273
- if (spaceId === accountSpaceId || spaceId === contactsSpaceId || narrowNote)
277
+ if (narrowNote || (await kindOf(spaceId)))
274
278
  return;
275
279
  const own = await ownProfile();
276
280
  if (!own)
@@ -323,61 +327,61 @@ export async function createNode(config) {
323
327
  return Promise.reject(new Error('Node is closed'));
324
328
  let open = runtimes.get(spaceId);
325
329
  if (!open) {
326
- open = requireRecord(spaceId).then(async (record) => openSpaceRuntime({
327
- record,
328
- writers,
329
- stores: config.stores,
330
- provider,
331
- signer,
332
- schemas,
333
- session,
334
- rootDid: config.signer.did,
335
- ...(config.network ? { network: config.network } : {}),
336
- ...(mesh ? { mesh } : {}),
337
- accountOnly: ownSpace(spaceId),
338
- // The account's own spaces are always held whole: every device needs all of them.
339
- ...(config.cache && !ownSpace(spaceId) ? { cache: config.cache } : {}),
340
- watchIntervalMs: config.watchIntervalMs ?? 2000,
341
- ...(config.fetchFiles ? { fetchFiles: config.fetchFiles } : {}),
342
- emit: fromRuntime,
343
- onRole: (role) => {
344
- if (spaceId === accountSpaceId)
345
- return;
346
- // Holding a role now — perhaps just joined — means the space may hear who this is.
347
- if (role !== null)
348
- void runtimes
349
- .get(spaceId)
350
- ?.then((rt) => publishProfile(spaceId, rt))
351
- .catch(() => { });
352
- if (role !== null)
353
- void keepSpaceHosts(spaceId).catch(() => { });
354
- if (record.role === role)
355
- return;
356
- void registry.setRole(spaceId, role).then(() => emit({ type: 'spaces' }));
357
- },
358
- onJoined: () => {
359
- if (!record.invite)
360
- return;
361
- void registry.clearInvite(spaceId).then(() => emit({ type: 'spaces' }));
362
- },
363
- memberKey: spaceId === accountSpaceId
364
- ? null
365
- : config.accountKey
366
- ? await deriveMemberKeyBytes(config.accountKey, spaceId)
367
- : (record.memberKey ?? null),
368
- onRelays: async (relays) => {
369
- if (spaceId !== accountSpaceId)
370
- await registry.setRelays(spaceId, relays);
371
- },
372
- onKeys: async (keys, current) => {
373
- if (spaceId === accountSpaceId)
374
- return;
375
- await registry.addKeys(spaceId, keys, current);
376
- // The account's other devices, and its carriers, follow the new key.
377
- await remember(spaceId, { refresh: true });
378
- void reconcile();
379
- },
380
- }));
330
+ open = requireRecord(spaceId).then(async (record) => {
331
+ const kind = await kindOf(spaceId);
332
+ return openSpaceRuntime({
333
+ record,
334
+ writers,
335
+ stores: config.stores,
336
+ provider,
337
+ signer,
338
+ schemas,
339
+ session,
340
+ rootDid: config.signer.did,
341
+ ...(config.network ? { network: config.network } : {}),
342
+ ...(mesh ? { mesh } : {}),
343
+ accountOnly: kind !== null,
344
+ // The account's own spaces are always held whole: every device needs all of them.
345
+ ...(config.cache && !kind ? { cache: config.cache } : {}),
346
+ watchIntervalMs: config.watchIntervalMs ?? 2000,
347
+ ...(config.fetchFiles ? { fetchFiles: config.fetchFiles } : {}),
348
+ emit: fromRuntime,
349
+ onRole: (role) => {
350
+ // Holding a role now — perhaps just joined — means the space may hear who this is.
351
+ if (role !== null)
352
+ void runtimes
353
+ .get(spaceId)
354
+ ?.then((rt) => publishProfile(spaceId, rt))
355
+ .catch(() => { });
356
+ if (role !== null)
357
+ void keepSpaceHosts(spaceId).catch(() => { });
358
+ if (record.role === role)
359
+ return;
360
+ void registry.setRole(spaceId, role).then(() => emit({ type: 'spaces' }));
361
+ },
362
+ onJoined: () => {
363
+ if (!record.invite)
364
+ return;
365
+ void registry.clearInvite(spaceId).then(() => emit({ type: 'spaces' }));
366
+ },
367
+ memberKey: kind === 'registry'
368
+ ? null
369
+ : config.accountKey
370
+ ? await deriveMemberKeyBytes(config.accountKey, spaceId)
371
+ : (record.memberKey ?? null),
372
+ // Kept only for a space in the list: the registry is not in it.
373
+ onRelays: (relays) => registry.setRelays(spaceId, relays),
374
+ onKeys: async (keys, current) => {
375
+ if (kind === 'registry')
376
+ return;
377
+ await registry.addKeys(spaceId, keys, current);
378
+ // The account's other devices follow the new key, and its carriers: passes and wakes, not a whole reconcile.
379
+ if (!kind)
380
+ await remember(spaceId, { refresh: true });
381
+ void passAll().catch(() => { });
382
+ },
383
+ });
384
+ });
381
385
  // A failed open must not be cached, or the space stays broken until restart.
382
386
  open.catch(() => runtimes.delete(spaceId));
383
387
  void open.then((rt) => publishProfile(spaceId, rt)).catch(() => { });
@@ -432,7 +436,9 @@ export async function createNode(config) {
432
436
  if (!open)
433
437
  return;
434
438
  runtimes.delete(spaceId);
435
- await (await open).close();
439
+ // One still opening when the node closes fails to open ("Node is closed"): there is nothing to close.
440
+ const rt = await open.catch(() => null);
441
+ await rt?.close();
436
442
  }
437
443
  // ─── Memberships ───────────────────────────────────────────────────
438
444
  //
@@ -466,11 +472,12 @@ export async function createNode(config) {
466
472
  return;
467
473
  const open = await runtime(accountSpaceId);
468
474
  const known = await open.get(membershipKey(spaceId));
475
+ if (known && (!options.refresh || known.deleted))
476
+ return;
469
477
  // A view-only invite: what lets the account write is its role in the
470
478
  // space, which every device reads there. Invite secrets are never kept.
471
479
  const invite = await inviteTo(spaceId);
472
- if (known &&
473
- (!options.refresh || known.deleted || inviteKeyOf(known.body?.invite) === inviteKeyOf(invite)))
480
+ if (known && inviteKeyOf(known.body?.invite) === inviteKeyOf(invite))
474
481
  return;
475
482
  await open.upsertSystem(MEMBERSHIP_COLLECTION, membershipKey(spaceId), {
476
483
  space: spaceId,
@@ -496,37 +503,50 @@ export async function createNode(config) {
496
503
  }
497
504
  // ─── Carriers ──────────────────────────────────────────────────────
498
505
  //
499
- // One record per carrier in the registry, naming the carry space shared with
500
- // it. Every device of the account opens that space and keeps a pass in it
501
- // for each of the account's spaces (`space/pass.ts`) — so a space joined in
502
- // any app is carried, with nothing to do in the home.
506
+ // One record per carrier in the registry. Its carry space is derived from
507
+ // the account key and the carrier's key, so every device finds the same one
508
+ // and none is stored. Every device of the account opens it and keeps a pass
509
+ // in it for each of the account's spaces (`space/pass.ts`) — so a space
510
+ // joined in any app is carried, with nothing to do in the home.
503
511
  const carrierKey = async (spaceId) => (await passKey(spaceId)).replace(/^pass:/, 'carrier:');
504
- /**
505
- * Carrier records the account wrote, live and removed, each with its carry
506
- * space — for a removed one, as its last version with a body said.
507
- */
512
+ /** Whether a `sys.carrier` record of the account's, live or not, is keyed by this space */
513
+ async function isCarrySpace(spaceId) {
514
+ if (!accountSpaceId)
515
+ return false;
516
+ const versions = await (await runtime(accountSpaceId)).history(await carrierKey(spaceId));
517
+ return versions.some((version) => version.collection === CARRIER_COLLECTION && version.verified && version.root === config.signer.did);
518
+ }
519
+ const derivedCarry = new Map();
520
+ /** A carrier's carry space: derived, or for one added before they were, the one its invite names */
521
+ async function carrySpaceOf(carrier) {
522
+ if (carrier.invite && carrier.space)
523
+ return (await registry.get(carrier.space)) ?? joinRegistry(carrier.invite).catch(() => null);
524
+ if (!config.accountKey)
525
+ return null;
526
+ const at = `${carrier.did}|${carrier.gen ?? 0}`;
527
+ const known = derivedCarry.get(at);
528
+ if (known)
529
+ return known;
530
+ const derived = deriveCarrySpace(config.accountKey, config.signer.did, carrier.did, carrier.gen ?? 0, provider);
531
+ derivedCarry.set(at, derived);
532
+ return derived;
533
+ }
534
+ /** The account's carriers, live and removed, each with its carry space */
508
535
  async function carrierRecords() {
509
536
  if (!accountSpaceId)
510
537
  return [];
511
- const open = await runtime(accountSpaceId);
512
538
  const found = [];
513
- for (const record of await ownRecords(open, {
514
- collection: CARRIER_COLLECTION,
515
- includeDeleted: true,
516
- })) {
517
- if (!record.deleted) {
518
- if (typeof record.body?.space === 'string' && typeof record.body.invite === 'string')
519
- found.push({ record, space: record.body.space });
520
- continue;
521
- }
522
- const before = (await open.history(record.key)).find((version) => typeof version.body?.space === 'string');
523
- if (before?.body)
524
- found.push({ record, space: before.body.space });
539
+ for (const record of await ownRecords(await runtime(accountSpaceId), { collection: CARRIER_COLLECTION },
540
+ // A generation is a count: anything else names no carry space.
541
+ (one) => typeof one.body?.did === 'string' &&
542
+ (one.body.gen === undefined || (Number.isSafeInteger(one.body.gen) && one.body.gen >= 0)))) {
543
+ const carry = await carrySpaceOf(record.body);
544
+ // Its key names its carry space: that is how every device knows the space is one.
545
+ if (carry && record.key === (await carrierKey(carry.space.id)))
546
+ found.push({ key: record.key, body: record.body, carry });
525
547
  }
526
548
  return found;
527
549
  }
528
- /** Every carry space, live or not — kept out of the account's own list */
529
- let carrySpaces = new Set();
530
550
  /**
531
551
  * Puts a pass in a carrier's space for each of the account's spaces, and
532
552
  * takes away the rest; and a wake for each of its own automations, each value replaced by
@@ -543,7 +563,7 @@ export async function createNode(config) {
543
563
  if (contactsRecord)
544
564
  passes.set(await passKey(contactsRecord.space.id), await makePass(contactsRecord));
545
565
  for (const membership of await memberships()) {
546
- if (membership.deleted || !membership.body || hidden(membership.body.space))
566
+ if (membership.deleted || !membership.body || (await kindOf(membership.body.space)))
547
567
  continue;
548
568
  const record = await registry.get(membership.body.space);
549
569
  if (!record)
@@ -565,9 +585,9 @@ export async function createNode(config) {
565
585
  }
566
586
  }
567
587
  // Removed meanwhile, on this device or another: its passes stay deleted.
568
- if (!(await liveCarriers()).some((live) => live.space === carrier.space))
588
+ if (!(await liveCarriers()).some((live) => live.key === carrier.key))
569
589
  return;
570
- const carry = await runtime(carrier.space);
590
+ const carry = await runtime(carrier.carry.space.id);
571
591
  await writeExactly(carry, PASS_COLLECTION, passes, (key) => key.startsWith('pass:'));
572
592
  const wakes = new Map();
573
593
  for (const own of owned) {
@@ -602,7 +622,7 @@ export async function createNode(config) {
602
622
  .sort((a, b) => a.since.localeCompare(b.since));
603
623
  }
604
624
  /** The carriers the account uses now */
605
- const liveCarriers = async () => (await carrierRecords()).flatMap(({ record }) => (!record.deleted && record.body ? [record.body] : []));
625
+ const liveCarriers = async () => (await carrierRecords()).filter(({ body }) => !body.removed);
606
626
  /**
607
627
  * Names the account's carriers — its extensions, its hosts — as keepers of
608
628
  * a space it manages, and stops naming ones it removed, so apps there hold
@@ -611,21 +631,14 @@ export async function createNode(config) {
611
631
  * manage is left to whoever does.
612
632
  */
613
633
  async function nameKeepers(spaceId, rt) {
614
- if (!account || narrowNote || spaceId === accountSpaceId || hidden(spaceId))
634
+ if (!account || narrowNote || (await kindOf(spaceId)))
615
635
  return;
616
636
  if (!(await rt.may(SPACE_KEEPERS)))
617
637
  return;
618
638
  const access = await rt.access();
619
639
  const carriers = await carrierRecords();
620
- const active = await liveCarriers();
621
- const gone = new Set();
622
- for (const { record } of carriers) {
623
- if (!record.deleted)
624
- continue;
625
- for (const version of await (await runtime(accountSpaceId)).history(record.key))
626
- if (version.body?.did)
627
- gone.add(version.body.did);
628
- }
640
+ const active = carriers.filter(({ body }) => !body.removed).map(({ body }) => body);
641
+ const gone = new Set(carriers.filter(({ body }) => body.removed).map(({ body }) => body.did));
629
642
  for (const carrier of active)
630
643
  gone.delete(carrier.did);
631
644
  const kept = access.keepers.filter((keeper) => !gone.has(keeper.did));
@@ -647,34 +660,6 @@ export async function createNode(config) {
647
660
  const held = new Set((await registry.list()).map((record) => record.space.id));
648
661
  const known = new Set();
649
662
  let changed = false;
650
- // Carry spaces first: they are the account's, but not spaces it uses.
651
- const carriers = await carrierRecords();
652
- carrySpaces = new Set([...carrySpaces, ...carriers.map(({ space }) => space)]);
653
- for (const { record, space: spaceId } of carriers) {
654
- if (record.deleted) {
655
- // Removed on some device. Its carry space stays open a while, so the
656
- // carrier — perhaps offline now — still hears that it should forget.
657
- if (!held.has(spaceId) || Date.now() - Date.parse(record.updatedAt) < FORGET_CARRIER_AFTER_MS)
658
- continue;
659
- await closeRuntime(spaceId);
660
- await registry.remove(spaceId);
661
- held.delete(spaceId);
662
- }
663
- else if (!held.has(spaceId)) {
664
- try {
665
- await joinRegistry(record.body.invite);
666
- held.add(spaceId);
667
- }
668
- catch {
669
- // An unreadable invite; the next version written for it will do.
670
- }
671
- }
672
- }
673
- for (const spaceId of carrySpaces)
674
- known.add(spaceId);
675
- // Derived on every device: nothing to record.
676
- if (contactsSpaceId)
677
- known.add(contactsSpaceId);
678
663
  for (const membership of await memberships()) {
679
664
  const spaceId = membership.key.slice('space:'.length);
680
665
  known.add(spaceId);
@@ -697,10 +682,10 @@ export async function createNode(config) {
697
682
  }
698
683
  // Held here but never recorded — joined before the registry existed, or on
699
684
  // a node without the account key. Recorded now, so other devices follow.
700
- // Held still: a carrier that failed while this ran has taken its carry space back out.
685
+ // Held still: one left while this ran stays left.
701
686
  const stillHeld = new Set((await registry.list()).map((record) => record.space.id));
702
687
  for (const spaceId of held) {
703
- if (!known.has(spaceId) && stillHeld.has(spaceId) && !carrySpaces.has(spaceId))
688
+ if (!known.has(spaceId) && stillHeld.has(spaceId) && !(await kindOf(spaceId)))
704
689
  await remember(spaceId);
705
690
  }
706
691
  // Not awaited: it opens every space the account holds, which from a data
@@ -728,7 +713,6 @@ export async function createNode(config) {
728
713
  resolve(false);
729
714
  });
730
715
  });
731
- /** Every carrier the account uses gets its passes and wakes as they are now, one run at a time */
732
716
  /** Writing in carry spaces, one thing at a time: a removal never lands in the middle of a refill */
733
717
  let carryTurn = Promise.resolve();
734
718
  const inCarryTurn = (work) => {
@@ -736,14 +720,13 @@ export async function createNode(config) {
736
720
  carryTurn = run;
737
721
  return run;
738
722
  };
723
+ /** Every carrier the account uses gets its passes and wakes as they are now, one run at a time */
739
724
  const passAll = serial(() => inCarryTurn(async () => {
740
- for (const { record, space: spaceId } of await carrierRecords()) {
725
+ for (const carrier of await liveCarriers()) {
741
726
  if (closed)
742
727
  return;
743
- if (record.deleted || !record.body || !(await registry.get(spaceId)))
744
- continue;
745
728
  // Only a device that may write in the carry space can do this; others leave it to one that can.
746
- await syncPasses(record.body).catch(() => { });
729
+ await syncPasses(carrier).catch(() => { });
747
730
  }
748
731
  }));
749
732
  const reconcile = serial(() => reconcileOnce().catch((error) => {
@@ -752,7 +735,11 @@ export async function createNode(config) {
752
735
  }));
753
736
  const spaces = Object.freeze({
754
737
  async list() {
755
- return (await registry.list()).filter((record) => !hidden(record.space.id)).map(summarize);
738
+ const used = [];
739
+ for (const record of await registry.list())
740
+ if (!(await kindOf(record.space.id)))
741
+ used.push(record);
742
+ return used.map(summarize);
756
743
  },
757
744
  async get(spaceId) {
758
745
  const record = await findRecord(spaceId);
@@ -810,10 +797,9 @@ export async function createNode(config) {
810
797
  return summarize((await registry.get(record.space.id)) ?? record);
811
798
  },
812
799
  async leave(spaceId) {
813
- if (spaceId === accountSpaceId)
814
- throw new Error('The account registry cannot be left');
815
- if (spaceId === contactsSpaceId)
816
- throw new Error('The contacts space cannot be left');
800
+ const kind = await kindOf(spaceId);
801
+ if (kind)
802
+ throw new Error(`The ${kind === 'registry' ? 'account registry' : `${kind} space`} cannot be left`);
817
803
  await giveUpPlace(spaceId);
818
804
  await forget(spaceId);
819
805
  await closeRuntime(spaceId);
@@ -851,7 +837,7 @@ export async function createNode(config) {
851
837
  // A peer's key does not say whose it is. But only this account's devices
852
838
  // and apps can read the account registry, so a peer there is one of ours
853
839
  // — except a carrier, which the registry names by its key.
854
- const carrierKeys = new Set((await liveCarriers()).map((carrier) => carrier.did));
840
+ const carrierKeys = new Set((await liveCarriers()).map(({ body }) => body.did));
855
841
  const inRegistry = new Set((await (await runtime(accountSpaceId)).status()).peers);
856
842
  return {
857
843
  ...status,
@@ -967,84 +953,72 @@ export async function createNode(config) {
967
953
  return taken;
968
954
  },
969
955
  });
970
- /** Carriers being added now, by key */
971
- const adding = new Map();
972
- async function addCarrier(carrier) {
973
- const registryRt = await requireAccount('Using a carrier');
974
- // The same carrier again keeps its carry space: what it holds stays good, and nothing is closed under it.
975
- const known = (await liveCarriers()).find((c) => c.did === carrier.did);
976
- if (known) {
977
- void passAll().catch(() => { });
978
- return { space: known.space, invite: known.invite };
979
- }
980
- const name = carrier.name.trim().slice(0, 80) || 'Carrier';
981
- // Private, so the passes in it are sealed; the account alone may write there.
982
- const record = await registry.create({
983
- name: `Carried by ${name}`,
984
- visibility: 'private',
985
- creator: config.signer.did,
986
- });
987
- carrySpaces.add(record.space.id);
988
- let body;
989
- try {
990
- const invite = await registry.createInvite(record.space.id, config.signer.did);
991
- body = { space: record.space.id, invite, did: carrier.did, name, since: new Date().toISOString() };
992
- await registryRt.upsertSystem(CARRIER_COLLECTION, await carrierKey(record.space.id), body);
993
- }
994
- catch (error) {
995
- // Without its record nothing says it is a carry space: held, a restart would list it as one the account uses.
996
- // Left in `carrySpaces`: a reconcile already under way must not record it either.
997
- await closeRuntime(record.space.id);
998
- await registry.remove(record.space.id);
999
- throw error;
1000
- }
1001
- // Its passes before its invite, as one batch: a carrier joining an empty carry space takes spaces as they trickle in.
1002
- // Not in turn behind a refill: nothing removes a carrier that is only now being added.
1003
- await syncPasses(body);
1004
- return { space: record.space.id, invite: body.invite };
1005
- }
1006
956
  const carriers = Object.freeze({
1007
- list: async () => (await liveCarriers()).map(({ space, did, name, since }) => ({ space, did, name, since })),
1008
- add(carrier) {
1009
- // Asked again while the first is under way (a click and a reconcile, say): the same answer, not a second carry space.
1010
- const pending = adding.get(carrier.did);
1011
- if (pending)
1012
- return pending;
1013
- const made = addCarrier(carrier).finally(() => adding.delete(carrier.did));
1014
- adding.set(carrier.did, made);
1015
- return made;
957
+ list: async () => (await liveCarriers()).map(({ body: { did, name, since }, carry }) => ({
958
+ space: carry.space.id,
959
+ did,
960
+ name,
961
+ since,
962
+ })),
963
+ async add(carrier) {
964
+ const registryRt = await requireAccount('Using a carrier');
965
+ const all = await carrierRecords();
966
+ // The same carrier again keeps its carry space: what it holds stays good, and nothing is closed under it.
967
+ let entry = all.find(({ body }) => body.did === carrier.did && !body.removed);
968
+ if (entry)
969
+ void passAll().catch(() => { });
970
+ else {
971
+ // Added again after a removal, a new carry space: the last one tells it to forget. One past the
972
+ // highest seen, not a count: a device that hasn't synced every earlier one must not land on a closed space.
973
+ const gens = all.filter(({ body }) => body.did === carrier.did).map(({ body }) => body.gen ?? 0);
974
+ const gen = gens.length ? Math.max(...gens) + 1 : 0;
975
+ const body = {
976
+ did: carrier.did,
977
+ name: carrier.name.trim().slice(0, 80) || 'Carrier',
978
+ since: new Date().toISOString(),
979
+ ...(gen ? { gen } : {}),
980
+ };
981
+ const carry = (await carrySpaceOf(body));
982
+ // Two devices adding it at once write the one record, for the one space.
983
+ entry = { key: await carrierKey(carry.space.id), body, carry };
984
+ await registryRt.upsertSystem(CARRIER_COLLECTION, entry.key, body);
985
+ // Its passes before its invite, as one batch: a carrier joining an empty carry space takes spaces as they trickle in.
986
+ // Not in turn behind a refill: nothing removes a carrier that is only now being added.
987
+ await syncPasses(entry);
988
+ }
989
+ return { space: entry.carry.space.id, invite: await encodeSpaceInvite(entry.carry, config.signer.did) };
1016
990
  },
1017
991
  settled: (waitMs) => within(passAll.done(), waitMs),
1018
992
  async reached(spaceId, waitMs) {
1019
- const carrier = (await liveCarriers()).find((c) => c.space === spaceId);
1020
- if (!carrier || !accountSpaceId)
993
+ const did = (await liveCarriers()).find(({ carry }) => carry.space.id === spaceId)?.body.did;
994
+ if (!did || !accountSpaceId)
1021
995
  return false;
1022
996
  const deadline = Date.now() + waitMs;
1023
997
  // Level with the passes and wakes as they are now: a refill under way first, within the same time.
1024
998
  await within(passAll.done(), waitMs);
1025
999
  // Its passes first: only through them does it come to the registry, and hold its own record there.
1026
- if (!(await (await runtime(spaceId)).syncedWith(carrier.did, Math.max(0, deadline - Date.now()))))
1000
+ if (!(await (await runtime(spaceId)).syncedWith(did, Math.max(0, deadline - Date.now()))))
1027
1001
  return false;
1028
- return (await runtime(accountSpaceId)).syncedWith(carrier.did, Math.max(0, deadline - Date.now()));
1002
+ return (await runtime(accountSpaceId)).syncedWith(did, Math.max(0, deadline - Date.now()));
1029
1003
  },
1030
1004
  async remove(spaceId) {
1031
1005
  const registryRt = await requireAccount('Removing a carrier');
1032
1006
  // In turn with any refill, which would otherwise put the passes back.
1033
1007
  await inCarryTurn(async () => {
1034
- const live = (await carrierRecords()).filter(({ record }) => !record.deleted && record.body);
1035
- const did = live.find(({ space }) => space === spaceId)?.record.body?.did;
1036
- if (!did)
1037
- return;
1038
- // Every carry space it has: added on two devices at once, it may hold the other one (spec 06 §4.2).
1039
- for (const { record, space } of live) {
1040
- if (record.body?.did !== did)
1041
- continue;
1042
- const carry = await runtime(space);
1008
+ const live = await liveCarriers();
1009
+ const did = live.find(({ carry }) => carry.space.id === spaceId)?.body.did;
1010
+ // Every carry space it has: one added on two devices at once, before they were derived, has two.
1011
+ for (const { key, body, carry } of live.filter((one) => one.body.did === did)) {
1012
+ const rt = await runtime(carry.space.id);
1043
1013
  // Passes gone first, then the word to forget everything, then the carrier's record.
1044
- for (const pass of await ownRecords(carry, { collection: PASS_COLLECTION }, (r) => r.key.startsWith('pass:')))
1045
- await carry.removeSystem(pass.key);
1046
- await carry.upsertSystem(PASS_COLLECTION, CARRY_CLOSED_KEY, { v: 1, closed: true });
1047
- await registryRt.removeSystem(record.key);
1014
+ for (const pass of await ownRecords(rt, { collection: PASS_COLLECTION }, (r) => r.key.startsWith('pass:')))
1015
+ await rt.removeSystem(pass.key);
1016
+ await rt.upsertSystem(PASS_COLLECTION, CARRY_CLOSED_KEY, { v: 1, closed: true });
1017
+ // Kept, so adding it again counts this one and takes a new carry space.
1018
+ await registryRt.upsertSystem(CARRIER_COLLECTION, key, {
1019
+ ...body,
1020
+ removed: new Date().toISOString(),
1021
+ });
1048
1022
  }
1049
1023
  });
1050
1024
  },
@@ -1074,13 +1048,6 @@ export async function createNode(config) {
1074
1048
  throw new Error("The host at this address has another key now, so it's another host");
1075
1049
  return description;
1076
1050
  }
1077
- /** The carry space shared with a host: the one the account made for it, or a new one */
1078
- async function carryFor(hosting) {
1079
- const known = (await liveCarriers()).find((carrier) => carrier.did === hosting.host);
1080
- return known
1081
- ? known.invite
1082
- : (await carriers.add({ did: hosting.host, name: new URL(hosting.url).host })).invite;
1083
- }
1084
1051
  /** Last time each host was handed the spaces, or refused them — so asking again waits a while */
1085
1052
  const handedAt = new Map();
1086
1053
  const HAND_AGAIN_MS = 60_000;
@@ -1132,7 +1099,9 @@ export async function createNode(config) {
1132
1099
  }
1133
1100
  else if (!status.carrying && paid && due && !narrowNote) {
1134
1101
  handedAt.set(hosting.url, Date.now());
1135
- const attaching = carryFor(hosting).then((invite) => client.attach(config.signer.did, invite));
1102
+ const attaching = carriers
1103
+ .add({ did: hosting.host, name: new URL(hosting.url).host })
1104
+ .then(({ invite }) => client.attach(config.signer.did, invite));
1136
1105
  handing.set(hosting.url, attaching);
1137
1106
  try {
1138
1107
  ({ status, receipt } = await attaching);
@@ -1285,7 +1254,8 @@ export async function createNode(config) {
1285
1254
  }
1286
1255
  /** Hands the hosts a space names its pass, when they were paid and don't carry it with its key yet */
1287
1256
  async function keepSpaceHosts(spaceId) {
1288
- if (ownSpace(spaceId))
1257
+ // Only while it is open: a change heard as it closed must not open it again.
1258
+ if ((await kindOf(spaceId)) || !runtimes.has(spaceId))
1289
1259
  return;
1290
1260
  const hosts = await namedHosts(spaceId);
1291
1261
  await reachHosts(spaceId, hosts);
@@ -1345,7 +1315,8 @@ export async function createNode(config) {
1345
1315
  ];
1346
1316
  if (spaceId === accountSpaceId)
1347
1317
  hosts.push(...(config.network.hosts ?? []).map((url) => ({ url })));
1348
- if (!ownSpace(spaceId))
1318
+ // Asked only while it is still open: asking would open it again.
1319
+ if (!(await kindOf(spaceId)) && runtimes.get(spaceId) === open)
1349
1320
  hosts.push(...(spaceHosts ?? (await namedHosts(spaceId))));
1350
1321
  const peers = [
1351
1322
  ...new Set((await Promise.all(hosts.map(peerOf))).filter((peer) => peer !== null)),
@@ -1461,9 +1432,9 @@ export async function createNode(config) {
1461
1432
  const known = await requireHosting(url);
1462
1433
  const { client } = await hostClient(known);
1463
1434
  await client.detach().catch(() => { });
1464
- const carrier = (await liveCarriers()).find((found) => found.did === known.host);
1435
+ const carrier = (await liveCarriers()).find(({ body }) => body.did === known.host);
1465
1436
  if (carrier)
1466
- await carriers.remove(carrier.space);
1437
+ await carriers.remove(carrier.carry.space.id);
1467
1438
  await registryRt.removeSystem(await hostingKey(known.url));
1468
1439
  },
1469
1440
  });
@@ -1487,7 +1458,7 @@ export async function createNode(config) {
1487
1458
  /** Making and joining spaces for two needs a note good for every space — whole-account access. */
1488
1459
  function requireEverywhere(what) {
1489
1460
  // As a knock needs: `/account/write` for the whole account (spec 01 §8, 07).
1490
- if (!noteGrants(current, ACCOUNT_REQUIREMENT)) {
1461
+ if (narrowNote) {
1491
1462
  throw new Error(`${what} makes or joins a space, which needs access to your whole account. Connect to your account home again, and ask for it.`);
1492
1463
  }
1493
1464
  }
@@ -1552,7 +1523,7 @@ export async function createNode(config) {
1552
1523
  return null;
1553
1524
  // Asking makes a space for two for the account, as a knock does: only a note that may write for all of it.
1554
1525
  const note = await (await runtime(spaceId)).noteOf(record.key);
1555
- if (!noteGrants(note, ACCOUNT_REQUIREMENT))
1526
+ if (!actsForAccount(note))
1556
1527
  return null;
1557
1528
  const from = record.root;
1558
1529
  if (!from || record.createdBy !== from || from === config.signer.did)
@@ -1722,9 +1693,8 @@ export async function createNode(config) {
1722
1693
  /** Knocks seen at this node's doors, by id: opened (null when they didn't check out), and until when to keep them */
1723
1694
  const knockCache = new Map();
1724
1695
  const DAY_MS = 24 * 3600 * 1000;
1725
- /** Doors live in the contacts space: a note must grant `/account/write` there, as every peer checks */
1726
- const doorsAllowed = () => contactsSpaceId !== null &&
1727
- noteGrants(current, { space: contactsSpaceId, cmd: ACCOUNT_COMMAND, args: { space: contactsSpaceId } });
1696
+ /** Doors are the account's own, in its contacts space: only a key acting as the account opens one, as every peer checks */
1697
+ const doorsAllowed = () => contactsSpaceId !== null && !narrowNote;
1728
1698
  function requireContactKey(what) {
1729
1699
  // Doors are the account's: a key whose note doesn't grant `/account/write` never opens one or knocks.
1730
1700
  if (!doorsAllowed())
@@ -2302,6 +2272,7 @@ export async function createNode(config) {
2302
2272
  delegation: () => note,
2303
2273
  iceServers: () => node.iceServers(),
2304
2274
  asAgent: person('start another agent'),
2275
+ revokeKey: person('revoke a key'),
2305
2276
  revokeSelf: person('sign the account out'),
2306
2277
  subscribe: (listener) => node.subscribe((event) => {
2307
2278
  if (!('space' in event) || allowed(event.space))
@@ -2332,17 +2303,28 @@ export async function createNode(config) {
2332
2303
  reconnect: () => mesh?.reconnect(),
2333
2304
  }),
2334
2305
  subscribe: events.subscribe,
2306
+ async revokeKey(key, options = {}) {
2307
+ // Everywhere the account writes, unless told where: the listed spaces, its carry spaces and contacts space.
2308
+ const ids = options.spaces ?? [
2309
+ ...new Set([
2310
+ ...(await spaces.list()).filter((space) => space.writable).map((space) => space.id),
2311
+ ...(await carrierRecords()).map(({ carry }) => carry.space.id),
2312
+ ...(contactsSpaceId ? [contactsSpaceId] : []),
2313
+ ]),
2314
+ ];
2315
+ const wait = options.waitMs === undefined ? {} : { waitMs: options.waitMs };
2316
+ // Each its own store: one that can't be written (a space gone, or no longer the account's
2317
+ // to write in) has nothing to send, and must not keep the rest from happening.
2318
+ const taken = await Promise.all([
2319
+ ...ids.map((spaceId) => spaces.revoke(spaceId, key, wait).catch(() => true)),
2320
+ ...(options.spaces ? [] : [node.account.revoke(key, wait).catch(() => true)]),
2321
+ ]);
2322
+ return taken.every(Boolean);
2323
+ },
2335
2324
  async revokeSelf(options = {}) {
2336
- const key = sessionDid;
2337
2325
  // Forgotten first: a tab closed while the revokes wait must not leave a
2338
2326
  // revoked key behind, to be claimed and refused on every write after.
2339
2327
  await claimed?.forget().catch(() => { });
2340
- // Every space it may write in: the listed ones, its carry spaces and the contacts space.
2341
- const ids = new Set([
2342
- ...(await spaces.list()).filter((space) => space.writable).map((space) => space.id),
2343
- ...carrySpaces,
2344
- ...(contactsSpaceId ? [contactsSpaceId] : []),
2345
- ]);
2346
2328
  // With anyone online, every revoke waits for a peer to take it in, closed
2347
2329
  // spaces too, which open for it. With nobody, waiting would only keep a
2348
2330
  // person signing out looking at a spinner: they go out with the next sync.
@@ -2352,12 +2334,7 @@ export async function createNode(config) {
2352
2334
  if (rt && (await rt.status()).peers.length > 0)
2353
2335
  anyone = true;
2354
2336
  }
2355
- const wait = anyone ? options : {};
2356
- // Each its own store: one that can't be done must not keep the rest from happening.
2357
- await Promise.all([
2358
- ...[...ids].map((spaceId) => spaces.revoke(spaceId, key, wait).catch(() => false)),
2359
- node.account.revoke(key, wait).catch(() => false),
2360
- ]);
2337
+ await node.revokeKey(sessionDid, anyone ? options : {});
2361
2338
  },
2362
2339
  async close() {
2363
2340
  if (closed)