@minca/core 0.1.8 → 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 (157) hide show
  1. package/README.md +1 -1
  2. package/dist/files/file-id.d.ts +51 -0
  3. package/dist/files/file-id.d.ts.map +1 -0
  4. package/dist/files/file-id.js +97 -0
  5. package/dist/files/file-id.js.map +1 -0
  6. package/dist/files/seal.d.ts +20 -0
  7. package/dist/files/seal.d.ts.map +1 -0
  8. package/dist/files/seal.js +77 -0
  9. package/dist/files/seal.js.map +1 -0
  10. package/dist/files/space-files.d.ts +51 -0
  11. package/dist/files/space-files.d.ts.map +1 -0
  12. package/dist/files/space-files.js +476 -0
  13. package/dist/files/space-files.js.map +1 -0
  14. package/dist/identity/abilities.d.ts +3 -3
  15. package/dist/identity/abilities.d.ts.map +1 -1
  16. package/dist/identity/abilities.js +9 -11
  17. package/dist/identity/abilities.js.map +1 -1
  18. package/dist/identity/root-signer.d.ts +0 -5
  19. package/dist/identity/root-signer.d.ts.map +1 -1
  20. package/dist/identity/root-signer.js +0 -1
  21. package/dist/identity/root-signer.js.map +1 -1
  22. package/dist/index.d.ts +5 -4
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +3 -2
  25. package/dist/index.js.map +1 -1
  26. package/dist/node/api.d.ts +5 -1
  27. package/dist/node/api.d.ts.map +1 -1
  28. package/dist/node/api.js +10 -2
  29. package/dist/node/api.js.map +1 -1
  30. package/dist/node/carrier.d.ts +17 -2
  31. package/dist/node/carrier.d.ts.map +1 -1
  32. package/dist/node/carrier.js +26 -4
  33. package/dist/node/carrier.js.map +1 -1
  34. package/dist/node/copy.d.ts +0 -4
  35. package/dist/node/copy.d.ts.map +1 -1
  36. package/dist/node/copy.js +26 -0
  37. package/dist/node/copy.js.map +1 -1
  38. package/dist/node/host.d.ts +66 -1
  39. package/dist/node/host.d.ts.map +1 -1
  40. package/dist/node/host.js +571 -5
  41. package/dist/node/host.js.map +1 -1
  42. package/dist/node/index.d.ts +2 -2
  43. package/dist/node/index.d.ts.map +1 -1
  44. package/dist/node/index.js +1 -1
  45. package/dist/node/index.js.map +1 -1
  46. package/dist/node/node.d.ts.map +1 -1
  47. package/dist/node/node.js +328 -269
  48. package/dist/node/node.js.map +1 -1
  49. package/dist/node/remote.d.ts +6 -5
  50. package/dist/node/remote.d.ts.map +1 -1
  51. package/dist/node/remote.js +141 -194
  52. package/dist/node/remote.js.map +1 -1
  53. package/dist/node/space-runtime.d.ts +9 -0
  54. package/dist/node/space-runtime.d.ts.map +1 -1
  55. package/dist/node/space-runtime.js +194 -98
  56. package/dist/node/space-runtime.js.map +1 -1
  57. package/dist/node/stores.d.ts +44 -8
  58. package/dist/node/stores.d.ts.map +1 -1
  59. package/dist/node/stores.js +44 -7
  60. package/dist/node/stores.js.map +1 -1
  61. package/dist/node/types.d.ts +77 -10
  62. package/dist/node/types.d.ts.map +1 -1
  63. package/dist/node/usage.d.ts +54 -0
  64. package/dist/node/usage.d.ts.map +1 -0
  65. package/dist/node/usage.js +201 -0
  66. package/dist/node/usage.js.map +1 -0
  67. package/dist/node/worker.d.ts +1 -1
  68. package/dist/node/worker.d.ts.map +1 -1
  69. package/dist/node/worker.js +10 -6
  70. package/dist/node/worker.js.map +1 -1
  71. package/dist/schema/version.d.ts +5 -0
  72. package/dist/schema/version.d.ts.map +1 -1
  73. package/dist/schema/version.js +1 -0
  74. package/dist/schema/version.js.map +1 -1
  75. package/dist/schemas/fragments.d.ts +23 -2
  76. package/dist/schemas/fragments.d.ts.map +1 -1
  77. package/dist/schemas/fragments.js +5 -2
  78. package/dist/schemas/fragments.js.map +1 -1
  79. package/dist/schemas/library/annotations.d.ts +24 -0
  80. package/dist/schemas/library/annotations.d.ts.map +1 -1
  81. package/dist/schemas/library/community.d.ts +24 -0
  82. package/dist/schemas/library/community.d.ts.map +1 -1
  83. package/dist/schemas/library/life.d.ts +72 -0
  84. package/dist/schemas/library/life.d.ts.map +1 -1
  85. package/dist/schemas/library/media.d.ts +144 -0
  86. package/dist/schemas/library/media.d.ts.map +1 -1
  87. package/dist/schemas/library/money.d.ts +24 -0
  88. package/dist/schemas/library/money.d.ts.map +1 -1
  89. package/dist/schemas/library/publishing.d.ts +96 -0
  90. package/dist/schemas/library/publishing.d.ts.map +1 -1
  91. package/dist/schemas/library/social.d.ts +72 -0
  92. package/dist/schemas/library/social.d.ts.map +1 -1
  93. package/dist/session/auth.d.ts +20 -0
  94. package/dist/session/auth.d.ts.map +1 -1
  95. package/dist/session/auth.js +88 -64
  96. package/dist/session/auth.js.map +1 -1
  97. package/dist/session/connect.d.ts +50 -8
  98. package/dist/session/connect.d.ts.map +1 -1
  99. package/dist/session/connect.js +91 -27
  100. package/dist/session/connect.js.map +1 -1
  101. package/dist/session/connection.d.ts +39 -6
  102. package/dist/session/connection.d.ts.map +1 -1
  103. package/dist/session/connection.js +107 -38
  104. package/dist/session/connection.js.map +1 -1
  105. package/dist/session/hosting.d.ts +88 -28
  106. package/dist/session/hosting.d.ts.map +1 -1
  107. package/dist/session/hosting.js +137 -6
  108. package/dist/session/hosting.js.map +1 -1
  109. package/dist/session/index.d.ts +5 -5
  110. package/dist/session/index.d.ts.map +1 -1
  111. package/dist/session/index.js +2 -2
  112. package/dist/session/index.js.map +1 -1
  113. package/dist/session/places.d.ts +2 -0
  114. package/dist/session/places.d.ts.map +1 -1
  115. package/dist/session/places.js +8 -2
  116. package/dist/session/places.js.map +1 -1
  117. package/dist/space/account-registry.d.ts +27 -4
  118. package/dist/space/account-registry.d.ts.map +1 -1
  119. package/dist/space/account-registry.js +25 -3
  120. package/dist/space/account-registry.js.map +1 -1
  121. package/dist/space/roles.d.ts +59 -140
  122. package/dist/space/roles.d.ts.map +1 -1
  123. package/dist/space/roles.js +328 -427
  124. package/dist/space/roles.js.map +1 -1
  125. package/dist/storage/blob/directory.d.ts +14 -0
  126. package/dist/storage/blob/directory.d.ts.map +1 -0
  127. package/dist/storage/blob/directory.js +80 -0
  128. package/dist/storage/blob/directory.js.map +1 -0
  129. package/dist/storage/folder-adapter.d.ts +22 -0
  130. package/dist/storage/folder-adapter.d.ts.map +1 -1
  131. package/dist/storage/folder-adapter.js +5 -5
  132. package/dist/storage/folder-adapter.js.map +1 -1
  133. package/dist/storage/mirror.d.ts +9 -2
  134. package/dist/storage/mirror.d.ts.map +1 -1
  135. package/dist/storage/mirror.js +60 -35
  136. package/dist/storage/mirror.js.map +1 -1
  137. package/dist/storage/segment.d.ts +7 -2
  138. package/dist/storage/segment.d.ts.map +1 -1
  139. package/dist/storage/segment.js +25 -3
  140. package/dist/storage/segment.js.map +1 -1
  141. package/dist/sync/sync-engine.d.ts +2 -0
  142. package/dist/sync/sync-engine.d.ts.map +1 -1
  143. package/dist/sync/sync-engine.js +5 -0
  144. package/dist/sync/sync-engine.js.map +1 -1
  145. package/dist/sync/sync-messages.d.ts +24 -0
  146. package/dist/sync/sync-messages.d.ts.map +1 -1
  147. package/dist/sync/sync-messages.js.map +1 -1
  148. package/docs/actions.md +3 -3
  149. package/docs/agents.md +2 -2
  150. package/docs/blueprints-and-guides.md +20 -1
  151. package/docs/bots.md +1 -1
  152. package/docs/node.md +138 -75
  153. package/docs/sign-in.md +16 -9
  154. package/docs/spaces.md +18 -10
  155. package/docs/standard-library.md +16 -20
  156. package/docs/storage.md +121 -16
  157. 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, } 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.
@@ -252,25 +258,65 @@ export async function createNode(config) {
252
258
  if (!accountSpaceId)
253
259
  return null;
254
260
  const profile = await (await runtime(accountSpaceId)).get(PROFILE_KEY);
255
- return profile?.verified && profile.root === config.signer.did && typeof profile.body?.name === 'string'
256
- ? { name: profile.body.name, updatedAt: profile.updatedAt }
257
- : null;
261
+ if (!profile?.verified || profile.root !== config.signer.did || typeof profile.body?.name !== 'string')
262
+ return null;
263
+ const avatar = profile.body.avatar;
264
+ return {
265
+ name: profile.body.name,
266
+ updatedAt: profile.updatedAt,
267
+ ...(isAvatarRef(avatar) ? { avatar } : {}),
268
+ };
258
269
  }
259
270
  const ownName = async () => (await ownProfile())?.name ?? null;
260
- /** Whether a space is the account's own machinery: its registry, its contacts, a carry space */
261
- const ownSpace = (spaceId) => spaceId === accountSpaceId || hidden(spaceId);
262
271
  /**
263
272
  * Tells a space who this account is. Done when the space opens and when the
264
273
  * name changes — not by opening every space, which would start syncing them
265
274
  * all; a space not open now hears on its next open.
266
275
  */
267
276
  async function publishProfile(spaceId, open) {
268
- if (spaceId === accountSpaceId || spaceId === contactsSpaceId || narrowNote)
277
+ if (narrowNote || (await kindOf(spaceId)))
278
+ return;
279
+ const own = await ownProfile();
280
+ if (!own)
269
281
  return;
270
- const name = await ownName();
271
- if (name)
272
- await open.publishProfile({ name, ...(contactKeys ? { contactKey: contactKeys.publicKey } : {}) });
282
+ const base = { name: own.name, ...(contactKeys ? { contactKey: contactKeys.publicKey } : {}) };
283
+ const held = (await open.profiles()).find((profile) => profile.did === config.signer.did)?.avatar;
284
+ const current = isAvatarRef(held) && held.source === own.avatar?.hash ? held : undefined;
285
+ // The name and contact key go out now, with the picture the space already has; a new picture
286
+ // follows once it is copied, which may wait on its bytes reaching this device.
287
+ const shown = own.avatar ? (current ?? (isAvatarRef(held) ? held : undefined)) : undefined;
288
+ await open.publishProfile({ ...base, ...(shown ? { avatar: shown } : {}) });
289
+ if (own.avatar && !current)
290
+ void avatarIn(spaceId, open, own.avatar)
291
+ .then((avatar) => open.publishProfile({ ...base, avatar }))
292
+ .catch(() => {
293
+ // Its bytes are on a device that is away: copied next time the profile is published.
294
+ });
273
295
  }
296
+ /**
297
+ * The account's picture as a file of this space: a space's members can't
298
+ * read the registry, so each space holds its own copy, made once and named
299
+ * by the registry file it copies.
300
+ */
301
+ function avatarIn(spaceId, open, avatar) {
302
+ // One copy per space and picture, however many publishes ask at once (a space opening, a change).
303
+ const at = `${spaceId}:${avatar.hash}`;
304
+ let copying = avatarCopies.get(at);
305
+ if (!copying) {
306
+ copying = (async () => {
307
+ const held = (await open.profiles()).find((profile) => profile.did === config.signer.did)?.avatar;
308
+ if (isAvatarRef(held) && held.source === avatar.hash)
309
+ return held;
310
+ const registryRt = await runtime(accountSpaceId);
311
+ const copy = await open.addFile(await registryRt.readFile(avatar));
312
+ return { ...copy, mime: avatar.mime, source: avatar.hash };
313
+ })();
314
+ copying.catch(() => avatarCopies.delete(at));
315
+ avatarCopies.set(at, copying);
316
+ }
317
+ return copying;
318
+ }
319
+ const avatarCopies = new Map();
274
320
  async function publishProfileToOpenSpaces() {
275
321
  for (const [spaceId, open] of runtimes) {
276
322
  await open.then((rt) => publishProfile(spaceId, rt)).catch(() => { });
@@ -281,60 +327,61 @@ export async function createNode(config) {
281
327
  return Promise.reject(new Error('Node is closed'));
282
328
  let open = runtimes.get(spaceId);
283
329
  if (!open) {
284
- open = requireRecord(spaceId).then(async (record) => openSpaceRuntime({
285
- record,
286
- writers,
287
- stores: config.stores,
288
- provider,
289
- signer,
290
- schemas,
291
- session,
292
- rootDid: config.signer.did,
293
- ...(config.network ? { network: config.network } : {}),
294
- ...(mesh ? { mesh } : {}),
295
- accountOnly: ownSpace(spaceId),
296
- // The account's own spaces are always held whole: every device needs all of them.
297
- ...(config.cache && !ownSpace(spaceId) ? { cache: config.cache } : {}),
298
- watchIntervalMs: config.watchIntervalMs ?? 2000,
299
- emit: fromRuntime,
300
- onRole: (role) => {
301
- if (spaceId === accountSpaceId)
302
- return;
303
- // Holding a role now — perhaps just joined — means the space may hear who this is.
304
- if (role !== null)
305
- void runtimes
306
- .get(spaceId)
307
- ?.then((rt) => publishProfile(spaceId, rt))
308
- .catch(() => { });
309
- if (role !== null)
310
- void keepSpaceHosts(spaceId).catch(() => { });
311
- if (record.role === role)
312
- return;
313
- void registry.setRole(spaceId, role).then(() => emit({ type: 'spaces' }));
314
- },
315
- onJoined: () => {
316
- if (!record.invite)
317
- return;
318
- void registry.clearInvite(spaceId).then(() => emit({ type: 'spaces' }));
319
- },
320
- memberKey: spaceId === accountSpaceId
321
- ? null
322
- : config.accountKey
323
- ? await deriveMemberKeyBytes(config.accountKey, spaceId)
324
- : (record.memberKey ?? null),
325
- onRelays: async (relays) => {
326
- if (spaceId !== accountSpaceId)
327
- await registry.setRelays(spaceId, relays);
328
- },
329
- onKeys: async (keys, current) => {
330
- if (spaceId === accountSpaceId)
331
- return;
332
- await registry.addKeys(spaceId, keys, current);
333
- // The account's other devices, and its carriers, follow the new key.
334
- await remember(spaceId, { refresh: true });
335
- void reconcile();
336
- },
337
- }));
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
+ });
338
385
  // A failed open must not be cached, or the space stays broken until restart.
339
386
  open.catch(() => runtimes.delete(spaceId));
340
387
  void open.then((rt) => publishProfile(spaceId, rt)).catch(() => { });
@@ -389,7 +436,9 @@ export async function createNode(config) {
389
436
  if (!open)
390
437
  return;
391
438
  runtimes.delete(spaceId);
392
- 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();
393
442
  }
394
443
  // ─── Memberships ───────────────────────────────────────────────────
395
444
  //
@@ -423,11 +472,12 @@ export async function createNode(config) {
423
472
  return;
424
473
  const open = await runtime(accountSpaceId);
425
474
  const known = await open.get(membershipKey(spaceId));
475
+ if (known && (!options.refresh || known.deleted))
476
+ return;
426
477
  // A view-only invite: what lets the account write is its role in the
427
478
  // space, which every device reads there. Invite secrets are never kept.
428
479
  const invite = await inviteTo(spaceId);
429
- if (known &&
430
- (!options.refresh || known.deleted || inviteKeyOf(known.body?.invite) === inviteKeyOf(invite)))
480
+ if (known && inviteKeyOf(known.body?.invite) === inviteKeyOf(invite))
431
481
  return;
432
482
  await open.upsertSystem(MEMBERSHIP_COLLECTION, membershipKey(spaceId), {
433
483
  space: spaceId,
@@ -453,37 +503,50 @@ export async function createNode(config) {
453
503
  }
454
504
  // ─── Carriers ──────────────────────────────────────────────────────
455
505
  //
456
- // One record per carrier in the registry, naming the carry space shared with
457
- // it. Every device of the account opens that space and keeps a pass in it
458
- // for each of the account's spaces (`space/pass.ts`) — so a space joined in
459
- // 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.
460
511
  const carrierKey = async (spaceId) => (await passKey(spaceId)).replace(/^pass:/, 'carrier:');
461
- /**
462
- * Carrier records the account wrote, live and removed, each with its carry
463
- * space — for a removed one, as its last version with a body said.
464
- */
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 */
465
535
  async function carrierRecords() {
466
536
  if (!accountSpaceId)
467
537
  return [];
468
- const open = await runtime(accountSpaceId);
469
538
  const found = [];
470
- for (const record of await ownRecords(open, {
471
- collection: CARRIER_COLLECTION,
472
- includeDeleted: true,
473
- })) {
474
- if (!record.deleted) {
475
- if (typeof record.body?.space === 'string' && typeof record.body.invite === 'string')
476
- found.push({ record, space: record.body.space });
477
- continue;
478
- }
479
- const before = (await open.history(record.key)).find((version) => typeof version.body?.space === 'string');
480
- if (before?.body)
481
- 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 });
482
547
  }
483
548
  return found;
484
549
  }
485
- /** Every carry space, live or not — kept out of the account's own list */
486
- let carrySpaces = new Set();
487
550
  /**
488
551
  * Puts a pass in a carrier's space for each of the account's spaces, and
489
552
  * takes away the rest; and a wake for each of its own automations, each value replaced by
@@ -500,7 +563,7 @@ export async function createNode(config) {
500
563
  if (contactsRecord)
501
564
  passes.set(await passKey(contactsRecord.space.id), await makePass(contactsRecord));
502
565
  for (const membership of await memberships()) {
503
- if (membership.deleted || !membership.body || hidden(membership.body.space))
566
+ if (membership.deleted || !membership.body || (await kindOf(membership.body.space)))
504
567
  continue;
505
568
  const record = await registry.get(membership.body.space);
506
569
  if (!record)
@@ -522,9 +585,9 @@ export async function createNode(config) {
522
585
  }
523
586
  }
524
587
  // Removed meanwhile, on this device or another: its passes stay deleted.
525
- if (!(await liveCarriers()).some((live) => live.space === carrier.space))
588
+ if (!(await liveCarriers()).some((live) => live.key === carrier.key))
526
589
  return;
527
- const carry = await runtime(carrier.space);
590
+ const carry = await runtime(carrier.carry.space.id);
528
591
  await writeExactly(carry, PASS_COLLECTION, passes, (key) => key.startsWith('pass:'));
529
592
  const wakes = new Map();
530
593
  for (const own of owned) {
@@ -559,7 +622,7 @@ export async function createNode(config) {
559
622
  .sort((a, b) => a.since.localeCompare(b.since));
560
623
  }
561
624
  /** The carriers the account uses now */
562
- const liveCarriers = async () => (await carrierRecords()).flatMap(({ record }) => (!record.deleted && record.body ? [record.body] : []));
625
+ const liveCarriers = async () => (await carrierRecords()).filter(({ body }) => !body.removed);
563
626
  /**
564
627
  * Names the account's carriers — its extensions, its hosts — as keepers of
565
628
  * a space it manages, and stops naming ones it removed, so apps there hold
@@ -568,21 +631,14 @@ export async function createNode(config) {
568
631
  * manage is left to whoever does.
569
632
  */
570
633
  async function nameKeepers(spaceId, rt) {
571
- if (!account || narrowNote || spaceId === accountSpaceId || hidden(spaceId))
634
+ if (!account || narrowNote || (await kindOf(spaceId)))
572
635
  return;
573
636
  if (!(await rt.may(SPACE_KEEPERS)))
574
637
  return;
575
638
  const access = await rt.access();
576
639
  const carriers = await carrierRecords();
577
- const active = await liveCarriers();
578
- const gone = new Set();
579
- for (const { record } of carriers) {
580
- if (!record.deleted)
581
- continue;
582
- for (const version of await (await runtime(accountSpaceId)).history(record.key))
583
- if (version.body?.did)
584
- gone.add(version.body.did);
585
- }
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));
586
642
  for (const carrier of active)
587
643
  gone.delete(carrier.did);
588
644
  const kept = access.keepers.filter((keeper) => !gone.has(keeper.did));
@@ -604,34 +660,6 @@ export async function createNode(config) {
604
660
  const held = new Set((await registry.list()).map((record) => record.space.id));
605
661
  const known = new Set();
606
662
  let changed = false;
607
- // Carry spaces first: they are the account's, but not spaces it uses.
608
- const carriers = await carrierRecords();
609
- carrySpaces = new Set([...carrySpaces, ...carriers.map(({ space }) => space)]);
610
- for (const { record, space: spaceId } of carriers) {
611
- if (record.deleted) {
612
- // Removed on some device. Its carry space stays open a while, so the
613
- // carrier — perhaps offline now — still hears that it should forget.
614
- if (!held.has(spaceId) || Date.now() - Date.parse(record.updatedAt) < FORGET_CARRIER_AFTER_MS)
615
- continue;
616
- await closeRuntime(spaceId);
617
- await registry.remove(spaceId);
618
- held.delete(spaceId);
619
- }
620
- else if (!held.has(spaceId)) {
621
- try {
622
- await joinRegistry(record.body.invite);
623
- held.add(spaceId);
624
- }
625
- catch {
626
- // An unreadable invite; the next version written for it will do.
627
- }
628
- }
629
- }
630
- for (const spaceId of carrySpaces)
631
- known.add(spaceId);
632
- // Derived on every device: nothing to record.
633
- if (contactsSpaceId)
634
- known.add(contactsSpaceId);
635
663
  for (const membership of await memberships()) {
636
664
  const spaceId = membership.key.slice('space:'.length);
637
665
  known.add(spaceId);
@@ -654,10 +682,10 @@ export async function createNode(config) {
654
682
  }
655
683
  // Held here but never recorded — joined before the registry existed, or on
656
684
  // a node without the account key. Recorded now, so other devices follow.
657
- // 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.
658
686
  const stillHeld = new Set((await registry.list()).map((record) => record.space.id));
659
687
  for (const spaceId of held) {
660
- if (!known.has(spaceId) && stillHeld.has(spaceId) && !carrySpaces.has(spaceId))
688
+ if (!known.has(spaceId) && stillHeld.has(spaceId) && !(await kindOf(spaceId)))
661
689
  await remember(spaceId);
662
690
  }
663
691
  // Not awaited: it opens every space the account holds, which from a data
@@ -685,7 +713,6 @@ export async function createNode(config) {
685
713
  resolve(false);
686
714
  });
687
715
  });
688
- /** Every carrier the account uses gets its passes and wakes as they are now, one run at a time */
689
716
  /** Writing in carry spaces, one thing at a time: a removal never lands in the middle of a refill */
690
717
  let carryTurn = Promise.resolve();
691
718
  const inCarryTurn = (work) => {
@@ -693,14 +720,13 @@ export async function createNode(config) {
693
720
  carryTurn = run;
694
721
  return run;
695
722
  };
723
+ /** Every carrier the account uses gets its passes and wakes as they are now, one run at a time */
696
724
  const passAll = serial(() => inCarryTurn(async () => {
697
- for (const { record, space: spaceId } of await carrierRecords()) {
725
+ for (const carrier of await liveCarriers()) {
698
726
  if (closed)
699
727
  return;
700
- if (record.deleted || !record.body || !(await registry.get(spaceId)))
701
- continue;
702
728
  // Only a device that may write in the carry space can do this; others leave it to one that can.
703
- await syncPasses(record.body).catch(() => { });
729
+ await syncPasses(carrier).catch(() => { });
704
730
  }
705
731
  }));
706
732
  const reconcile = serial(() => reconcileOnce().catch((error) => {
@@ -709,7 +735,11 @@ export async function createNode(config) {
709
735
  }));
710
736
  const spaces = Object.freeze({
711
737
  async list() {
712
- 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);
713
743
  },
714
744
  async get(spaceId) {
715
745
  const record = await findRecord(spaceId);
@@ -767,10 +797,9 @@ export async function createNode(config) {
767
797
  return summarize((await registry.get(record.space.id)) ?? record);
768
798
  },
769
799
  async leave(spaceId) {
770
- if (spaceId === accountSpaceId)
771
- throw new Error('The account registry cannot be left');
772
- if (spaceId === contactsSpaceId)
773
- 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`);
774
803
  await giveUpPlace(spaceId);
775
804
  await forget(spaceId);
776
805
  await closeRuntime(spaceId);
@@ -808,7 +837,7 @@ export async function createNode(config) {
808
837
  // A peer's key does not say whose it is. But only this account's devices
809
838
  // and apps can read the account registry, so a peer there is one of ours
810
839
  // — except a carrier, which the registry names by its key.
811
- const carrierKeys = new Set((await liveCarriers()).map((carrier) => carrier.did));
840
+ const carrierKeys = new Set((await liveCarriers()).map(({ body }) => body.did));
812
841
  const inRegistry = new Set((await (await runtime(accountSpaceId)).status()).peers);
813
842
  return {
814
843
  ...status,
@@ -924,84 +953,72 @@ export async function createNode(config) {
924
953
  return taken;
925
954
  },
926
955
  });
927
- /** Carriers being added now, by key */
928
- const adding = new Map();
929
- async function addCarrier(carrier) {
930
- const registryRt = await requireAccount('Using a carrier');
931
- // The same carrier again keeps its carry space: what it holds stays good, and nothing is closed under it.
932
- const known = (await liveCarriers()).find((c) => c.did === carrier.did);
933
- if (known) {
934
- void passAll().catch(() => { });
935
- return { space: known.space, invite: known.invite };
936
- }
937
- const name = carrier.name.trim().slice(0, 80) || 'Carrier';
938
- // Private, so the passes in it are sealed; the account alone may write there.
939
- const record = await registry.create({
940
- name: `Carried by ${name}`,
941
- visibility: 'private',
942
- creator: config.signer.did,
943
- });
944
- carrySpaces.add(record.space.id);
945
- let body;
946
- try {
947
- const invite = await registry.createInvite(record.space.id, config.signer.did);
948
- body = { space: record.space.id, invite, did: carrier.did, name, since: new Date().toISOString() };
949
- await registryRt.upsertSystem(CARRIER_COLLECTION, await carrierKey(record.space.id), body);
950
- }
951
- catch (error) {
952
- // Without its record nothing says it is a carry space: held, a restart would list it as one the account uses.
953
- // Left in `carrySpaces`: a reconcile already under way must not record it either.
954
- await closeRuntime(record.space.id);
955
- await registry.remove(record.space.id);
956
- throw error;
957
- }
958
- // Its passes before its invite, as one batch: a carrier joining an empty carry space takes spaces as they trickle in.
959
- // Not in turn behind a refill: nothing removes a carrier that is only now being added.
960
- await syncPasses(body);
961
- return { space: record.space.id, invite: body.invite };
962
- }
963
956
  const carriers = Object.freeze({
964
- list: async () => (await liveCarriers()).map(({ space, did, name, since }) => ({ space, did, name, since })),
965
- add(carrier) {
966
- // Asked again while the first is under way (a click and a reconcile, say): the same answer, not a second carry space.
967
- const pending = adding.get(carrier.did);
968
- if (pending)
969
- return pending;
970
- const made = addCarrier(carrier).finally(() => adding.delete(carrier.did));
971
- adding.set(carrier.did, made);
972
- 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) };
973
990
  },
974
991
  settled: (waitMs) => within(passAll.done(), waitMs),
975
992
  async reached(spaceId, waitMs) {
976
- const carrier = (await liveCarriers()).find((c) => c.space === spaceId);
977
- if (!carrier || !accountSpaceId)
993
+ const did = (await liveCarriers()).find(({ carry }) => carry.space.id === spaceId)?.body.did;
994
+ if (!did || !accountSpaceId)
978
995
  return false;
979
996
  const deadline = Date.now() + waitMs;
980
997
  // Level with the passes and wakes as they are now: a refill under way first, within the same time.
981
998
  await within(passAll.done(), waitMs);
982
999
  // Its passes first: only through them does it come to the registry, and hold its own record there.
983
- 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()))))
984
1001
  return false;
985
- 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()));
986
1003
  },
987
1004
  async remove(spaceId) {
988
1005
  const registryRt = await requireAccount('Removing a carrier');
989
1006
  // In turn with any refill, which would otherwise put the passes back.
990
1007
  await inCarryTurn(async () => {
991
- const live = (await carrierRecords()).filter(({ record }) => !record.deleted && record.body);
992
- const did = live.find(({ space }) => space === spaceId)?.record.body?.did;
993
- if (!did)
994
- return;
995
- // Every carry space it has: added on two devices at once, it may hold the other one (spec 06 §4.2).
996
- for (const { record, space } of live) {
997
- if (record.body?.did !== did)
998
- continue;
999
- 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);
1000
1013
  // Passes gone first, then the word to forget everything, then the carrier's record.
1001
- for (const pass of await ownRecords(carry, { collection: PASS_COLLECTION }, (r) => r.key.startsWith('pass:')))
1002
- await carry.removeSystem(pass.key);
1003
- await carry.upsertSystem(PASS_COLLECTION, CARRY_CLOSED_KEY, { v: 1, closed: true });
1004
- 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
+ });
1005
1022
  }
1006
1023
  });
1007
1024
  },
@@ -1031,13 +1048,6 @@ export async function createNode(config) {
1031
1048
  throw new Error("The host at this address has another key now, so it's another host");
1032
1049
  return description;
1033
1050
  }
1034
- /** The carry space shared with a host: the one the account made for it, or a new one */
1035
- async function carryFor(hosting) {
1036
- const known = (await liveCarriers()).find((carrier) => carrier.did === hosting.host);
1037
- return known
1038
- ? known.invite
1039
- : (await carriers.add({ did: hosting.host, name: new URL(hosting.url).host })).invite;
1040
- }
1041
1051
  /** Last time each host was handed the spaces, or refused them — so asking again waits a while */
1042
1052
  const handedAt = new Map();
1043
1053
  const HAND_AGAIN_MS = 60_000;
@@ -1056,6 +1066,8 @@ export async function createNode(config) {
1056
1066
  kept.state === status.state &&
1057
1067
  kept.paidUntil === status.paidUntil &&
1058
1068
  kept.renews === status.renews &&
1069
+ kept.plan === status.plan &&
1070
+ JSON.stringify(kept.over ?? []) === JSON.stringify(status.over ?? []) &&
1059
1071
  hosting.name === name &&
1060
1072
  hosting.peer === peer;
1061
1073
  if (same)
@@ -1073,9 +1085,10 @@ export async function createNode(config) {
1073
1085
  const description = await describeKnown(hosting);
1074
1086
  let { status, receipt } = await client.status();
1075
1087
  const due = force || Date.now() - (handedAt.get(hosting.url) ?? 0) > HAND_AGAIN_MS;
1088
+ // A host with limits keeps an account's spaces with nothing paid: its free plan.
1076
1089
  const paid = status.state === 'active' ||
1077
1090
  status.state === 'grace' ||
1078
- (description.free && status.state !== 'lapsed');
1091
+ ((description.free || description.limits !== undefined) && status.state !== 'lapsed');
1079
1092
  const inFlight = handing.get(hosting.url);
1080
1093
  if (!status.carrying && inFlight) {
1081
1094
  // Another look is handing the spaces over right now: wait for it,
@@ -1086,7 +1099,9 @@ export async function createNode(config) {
1086
1099
  }
1087
1100
  else if (!status.carrying && paid && due && !narrowNote) {
1088
1101
  handedAt.set(hosting.url, Date.now());
1089
- 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));
1090
1105
  handing.set(hosting.url, attaching);
1091
1106
  try {
1092
1107
  ({ status, receipt } = await attaching);
@@ -1106,7 +1121,7 @@ export async function createNode(config) {
1106
1121
  name: description.name,
1107
1122
  status,
1108
1123
  live: true,
1109
- plans: plansFor(description, 'account'),
1124
+ fund: description.free ? null : (description.fund ?? null),
1110
1125
  reminds: description.remind === true,
1111
1126
  };
1112
1127
  }
@@ -1116,14 +1131,12 @@ export async function createNode(config) {
1116
1131
  name: hosting.name ?? new URL(hosting.url).host,
1117
1132
  status: kept,
1118
1133
  live: false,
1119
- plans: [],
1134
+ fund: null,
1120
1135
  reminds: false,
1121
1136
  error: error instanceof Error ? error.message : String(error),
1122
1137
  };
1123
1138
  }
1124
1139
  }
1125
- /** The plans a host describes for an account's subscription, or a space's own */
1126
- const plansFor = (description, who) => (description.plans ?? []).filter((plan) => Array.isArray(plan.for) && plan.for.includes(who));
1127
1140
  /** Every device keeps its hosts carrying: after the registry changes, ask each once more */
1128
1141
  async function keepHosted() {
1129
1142
  if (narrowNote)
@@ -1241,7 +1254,8 @@ export async function createNode(config) {
1241
1254
  }
1242
1255
  /** Hands the hosts a space names its pass, when they were paid and don't carry it with its key yet */
1243
1256
  async function keepSpaceHosts(spaceId) {
1244
- 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))
1245
1259
  return;
1246
1260
  const hosts = await namedHosts(spaceId);
1247
1261
  await reachHosts(spaceId, hosts);
@@ -1301,7 +1315,8 @@ export async function createNode(config) {
1301
1315
  ];
1302
1316
  if (spaceId === accountSpaceId)
1303
1317
  hosts.push(...(config.network.hosts ?? []).map((url) => ({ url })));
1304
- 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)
1305
1320
  hosts.push(...(spaceHosts ?? (await namedHosts(spaceId))));
1306
1321
  const peers = [
1307
1322
  ...new Set((await Promise.all(hosts.map(peerOf))).filter((peer) => peer !== null)),
@@ -1323,6 +1338,16 @@ export async function createNode(config) {
1323
1338
  async list() {
1324
1339
  return Promise.all((await hostingRecords()).map((known) => viewHosting(known)));
1325
1340
  },
1341
+ async over(spaceId) {
1342
+ const found = [];
1343
+ for (const hosting of await hostingRecords()) {
1344
+ const status = hosting.receipt ? await readStatus(hosting.receipt, hosting.host, provider) : null;
1345
+ const over = status?.over?.find((one) => one.space === spaceId);
1346
+ if (over)
1347
+ found.push({ url: hosting.url, name: hosting.name ?? new URL(hosting.url).host, over });
1348
+ }
1349
+ return found;
1350
+ },
1326
1351
  async use(address) {
1327
1352
  const registryRt = await requireAccount('Using a host');
1328
1353
  const base = checkAddress(address, 'A host').origin;
@@ -1342,11 +1367,8 @@ export async function createNode(config) {
1342
1367
  await registryRt.upsertSystem(HOSTING_COLLECTION, await hostingKey(base), record);
1343
1368
  return viewHosting(record, true);
1344
1369
  },
1345
- async pay(url, plan) {
1346
- return (await hostClient(await requireHosting(url))).client.pay(plan);
1347
- },
1348
- async manage(url) {
1349
- return (await hostClient(await requireHosting(url))).client.manage();
1370
+ async pay(url, payment) {
1371
+ return (await hostClient(await requireHosting(url))).client.pay(payment);
1350
1372
  },
1351
1373
  async remind(url, email) {
1352
1374
  await (await hostClient(await requireHosting(url))).client.remind(email);
@@ -1410,9 +1432,9 @@ export async function createNode(config) {
1410
1432
  const known = await requireHosting(url);
1411
1433
  const { client } = await hostClient(known);
1412
1434
  await client.detach().catch(() => { });
1413
- const carrier = (await liveCarriers()).find((found) => found.did === known.host);
1435
+ const carrier = (await liveCarriers()).find(({ body }) => body.did === known.host);
1414
1436
  if (carrier)
1415
- await carriers.remove(carrier.space);
1437
+ await carriers.remove(carrier.carry.space.id);
1416
1438
  await registryRt.removeSystem(await hostingKey(known.url));
1417
1439
  },
1418
1440
  });
@@ -1436,7 +1458,7 @@ export async function createNode(config) {
1436
1458
  /** Making and joining spaces for two needs a note good for every space — whole-account access. */
1437
1459
  function requireEverywhere(what) {
1438
1460
  // As a knock needs: `/account/write` for the whole account (spec 01 §8, 07).
1439
- if (!noteGrants(current, ACCOUNT_REQUIREMENT)) {
1461
+ if (narrowNote) {
1440
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.`);
1441
1463
  }
1442
1464
  }
@@ -1501,7 +1523,7 @@ export async function createNode(config) {
1501
1523
  return null;
1502
1524
  // Asking makes a space for two for the account, as a knock does: only a note that may write for all of it.
1503
1525
  const note = await (await runtime(spaceId)).noteOf(record.key);
1504
- if (!noteGrants(note, ACCOUNT_REQUIREMENT))
1526
+ if (!actsForAccount(note))
1505
1527
  return null;
1506
1528
  const from = record.root;
1507
1529
  if (!from || record.createdBy !== from || from === config.signer.did)
@@ -1671,9 +1693,8 @@ export async function createNode(config) {
1671
1693
  /** Knocks seen at this node's doors, by id: opened (null when they didn't check out), and until when to keep them */
1672
1694
  const knockCache = new Map();
1673
1695
  const DAY_MS = 24 * 3600 * 1000;
1674
- /** Doors live in the contacts space: a note must grant `/account/write` there, as every peer checks */
1675
- const doorsAllowed = () => contactsSpaceId !== null &&
1676
- 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;
1677
1698
  function requireContactKey(what) {
1678
1699
  // Doors are the account's: a key whose note doesn't grant `/account/write` never opens one or knocks.
1679
1700
  if (!doorsAllowed())
@@ -2070,12 +2091,36 @@ export async function createNode(config) {
2070
2091
  const trimmed = name.trim();
2071
2092
  if (!trimmed)
2072
2093
  throw new Error('A name cannot be empty');
2094
+ const avatar = (await ownProfile())?.avatar;
2073
2095
  const written = await registryRt.upsertSystem(PROFILE_COLLECTION, PROFILE_KEY, {
2074
2096
  name: trimmed,
2097
+ ...(avatar ? { avatar } : {}),
2098
+ });
2099
+ emit({ type: 'account' });
2100
+ await publishProfileToOpenSpaces();
2101
+ return { name: trimmed, updatedAt: written.updatedAt, ...(avatar ? { avatar } : {}) };
2102
+ },
2103
+ async setAvatar(image, options = {}) {
2104
+ const registryRt = await requireAccount('Changing the picture across devices');
2105
+ const name = (await ownName()) ?? options.name?.trim();
2106
+ if (!name)
2107
+ throw new Error('Give the account a name first');
2108
+ if (image && !image.mime.startsWith('image/'))
2109
+ throw new Error('A picture is an image');
2110
+ const avatar = image ? { ...(await registryRt.addFile(image.bytes)), mime: image.mime } : null;
2111
+ const written = await registryRt.upsertSystem(PROFILE_COLLECTION, PROFILE_KEY, {
2112
+ name,
2113
+ ...(avatar ? { avatar } : {}),
2075
2114
  });
2076
2115
  emit({ type: 'account' });
2077
2116
  await publishProfileToOpenSpaces();
2078
- return { name: trimmed, updatedAt: written.updatedAt };
2117
+ return { name, updatedAt: written.updatedAt, ...(avatar ? { avatar } : {}) };
2118
+ },
2119
+ async picture() {
2120
+ const avatar = (await ownProfile())?.avatar;
2121
+ if (!avatar || !accountSpaceId)
2122
+ return null;
2123
+ return { bytes: await (await runtime(accountSpaceId)).readFile(avatar), mime: avatar.mime };
2079
2124
  },
2080
2125
  revoke: async (key, options) => (await requireAccount('Revoking in the account registry')).revoke(key, options),
2081
2126
  });
@@ -2092,6 +2137,12 @@ export async function createNode(config) {
2092
2137
  linked: async (spaceId, key, options) => (await runtime(spaceId)).linked(key, options),
2093
2138
  delete: async (spaceId, key) => (await runtime(spaceId)).remove(key, as ? { as } : undefined),
2094
2139
  history: async (spaceId, key) => (await runtime(spaceId)).history(key),
2140
+ addFile: async (spaceId, bytes, about) => ({
2141
+ ...(await (await runtime(spaceId)).addFile(bytes)),
2142
+ mime: about.mime,
2143
+ ...(about.name !== undefined ? { name: about.name } : {}),
2144
+ }),
2145
+ readFile: async (spaceId, ref) => (await runtime(spaceId)).readFile(ref),
2095
2146
  can: perSpace((rt, action, target) => rt.can(action, target)),
2096
2147
  async query(spaceId, query) {
2097
2148
  const space = await runtime(spaceId);
@@ -2186,6 +2237,7 @@ export async function createNode(config) {
2186
2237
  throw new Error('That space was not given to this agent');
2187
2238
  return hosting.space(spaceId);
2188
2239
  },
2240
+ over: async (spaceId) => (allowed(spaceId) ? hosting.over(spaceId) : []),
2189
2241
  },
2190
2242
  contacts: {
2191
2243
  space: async () => (contactsGiven() ? contactsSpaceId : null),
@@ -2220,6 +2272,7 @@ export async function createNode(config) {
2220
2272
  delegation: () => note,
2221
2273
  iceServers: () => node.iceServers(),
2222
2274
  asAgent: person('start another agent'),
2275
+ revokeKey: person('revoke a key'),
2223
2276
  revokeSelf: person('sign the account out'),
2224
2277
  subscribe: (listener) => node.subscribe((event) => {
2225
2278
  if (!('space' in event) || allowed(event.space))
@@ -2250,17 +2303,28 @@ export async function createNode(config) {
2250
2303
  reconnect: () => mesh?.reconnect(),
2251
2304
  }),
2252
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
+ },
2253
2324
  async revokeSelf(options = {}) {
2254
- const key = sessionDid;
2255
2325
  // Forgotten first: a tab closed while the revokes wait must not leave a
2256
2326
  // revoked key behind, to be claimed and refused on every write after.
2257
2327
  await claimed?.forget().catch(() => { });
2258
- // Every space it may write in: the listed ones, its carry spaces and the contacts space.
2259
- const ids = new Set([
2260
- ...(await spaces.list()).filter((space) => space.writable).map((space) => space.id),
2261
- ...carrySpaces,
2262
- ...(contactsSpaceId ? [contactsSpaceId] : []),
2263
- ]);
2264
2328
  // With anyone online, every revoke waits for a peer to take it in, closed
2265
2329
  // spaces too, which open for it. With nobody, waiting would only keep a
2266
2330
  // person signing out looking at a spinner: they go out with the next sync.
@@ -2270,12 +2334,7 @@ export async function createNode(config) {
2270
2334
  if (rt && (await rt.status()).peers.length > 0)
2271
2335
  anyone = true;
2272
2336
  }
2273
- const wait = anyone ? options : {};
2274
- // Each its own store: one that can't be done must not keep the rest from happening.
2275
- await Promise.all([
2276
- ...[...ids].map((spaceId) => spaces.revoke(spaceId, key, wait).catch(() => false)),
2277
- node.account.revoke(key, wait).catch(() => false),
2278
- ]);
2337
+ await node.revokeKey(sessionDid, anyone ? options : {});
2279
2338
  },
2280
2339
  async close() {
2281
2340
  if (closed)