@minca/core 0.1.9 → 0.1.11

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 (195) hide show
  1. package/README.md +2 -2
  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/contact-key.d.ts +15 -15
  7. package/dist/identity/contact-key.d.ts.map +1 -1
  8. package/dist/identity/contact-key.js +21 -28
  9. package/dist/identity/contact-key.js.map +1 -1
  10. package/dist/identity/root-signer.d.ts +0 -5
  11. package/dist/identity/root-signer.d.ts.map +1 -1
  12. package/dist/identity/root-signer.js +0 -1
  13. package/dist/identity/root-signer.js.map +1 -1
  14. package/dist/inbox/inbox.d.ts +140 -0
  15. package/dist/inbox/inbox.d.ts.map +1 -0
  16. package/dist/inbox/inbox.js +212 -0
  17. package/dist/inbox/inbox.js.map +1 -0
  18. package/dist/inbox/index.d.ts +9 -0
  19. package/dist/inbox/index.d.ts.map +1 -0
  20. package/dist/inbox/index.js +7 -0
  21. package/dist/inbox/index.js.map +1 -0
  22. package/dist/index.d.ts +3 -3
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +1 -1
  25. package/dist/index.js.map +1 -1
  26. package/dist/network/mailbox.d.ts +4 -4
  27. package/dist/network/mailbox.d.ts.map +1 -1
  28. package/dist/network/mailbox.js +5 -5
  29. package/dist/network/mailbox.js.map +1 -1
  30. package/dist/node/actions.d.ts.map +1 -1
  31. package/dist/node/actions.js +28 -18
  32. package/dist/node/actions.js.map +1 -1
  33. package/dist/node/api.d.ts +11 -10
  34. package/dist/node/api.d.ts.map +1 -1
  35. package/dist/node/api.js +11 -10
  36. package/dist/node/api.js.map +1 -1
  37. package/dist/node/carrier.d.ts +11 -5
  38. package/dist/node/carrier.d.ts.map +1 -1
  39. package/dist/node/carrier.js +42 -1
  40. package/dist/node/carrier.js.map +1 -1
  41. package/dist/node/copy.d.ts +1 -1
  42. package/dist/node/copy.d.ts.map +1 -1
  43. package/dist/node/copy.js +10 -4
  44. package/dist/node/copy.js.map +1 -1
  45. package/dist/node/host.d.ts +2 -0
  46. package/dist/node/host.d.ts.map +1 -1
  47. package/dist/node/host.js +2 -0
  48. package/dist/node/host.js.map +1 -1
  49. package/dist/node/index.d.ts +1 -1
  50. package/dist/node/index.d.ts.map +1 -1
  51. package/dist/node/node.d.ts.map +1 -1
  52. package/dist/node/node.js +720 -542
  53. package/dist/node/node.js.map +1 -1
  54. package/dist/node/remote.d.ts +6 -5
  55. package/dist/node/remote.d.ts.map +1 -1
  56. package/dist/node/remote.js +140 -195
  57. package/dist/node/remote.js.map +1 -1
  58. package/dist/node/space-runtime.d.ts +2 -1
  59. package/dist/node/space-runtime.d.ts.map +1 -1
  60. package/dist/node/space-runtime.js +71 -84
  61. package/dist/node/space-runtime.js.map +1 -1
  62. package/dist/node/types.d.ts +84 -47
  63. package/dist/node/types.d.ts.map +1 -1
  64. package/dist/node/worker.d.ts +1 -1
  65. package/dist/node/worker.d.ts.map +1 -1
  66. package/dist/node/worker.js +10 -6
  67. package/dist/node/worker.js.map +1 -1
  68. package/dist/react/use-invite-link.d.ts +1 -1
  69. package/dist/react/use-invite-link.d.ts.map +1 -1
  70. package/dist/react/use-invite-link.js +18 -11
  71. package/dist/react/use-invite-link.js.map +1 -1
  72. package/dist/records/loose.d.ts +52 -0
  73. package/dist/records/loose.d.ts.map +1 -0
  74. package/dist/records/loose.js +86 -0
  75. package/dist/records/loose.js.map +1 -0
  76. package/dist/schema/version.d.ts +2 -0
  77. package/dist/schema/version.d.ts.map +1 -1
  78. package/dist/schema/version.js +2 -1
  79. package/dist/schema/version.js.map +1 -1
  80. package/dist/schemas/choosing.d.ts +19 -0
  81. package/dist/schemas/choosing.d.ts.map +1 -0
  82. package/dist/schemas/choosing.js +69 -0
  83. package/dist/schemas/choosing.js.map +1 -0
  84. package/dist/schemas/contacts.d.ts +34 -87
  85. package/dist/schemas/contacts.d.ts.map +1 -1
  86. package/dist/schemas/contacts.js +32 -76
  87. package/dist/schemas/contacts.js.map +1 -1
  88. package/dist/schemas/index.d.ts +2 -2
  89. package/dist/schemas/index.d.ts.map +1 -1
  90. package/dist/schemas/index.js +1 -1
  91. package/dist/schemas/index.js.map +1 -1
  92. package/dist/schemas/library/annotations.d.ts +17 -285
  93. package/dist/schemas/library/annotations.d.ts.map +1 -1
  94. package/dist/schemas/library/annotations.js +9 -65
  95. package/dist/schemas/library/annotations.js.map +1 -1
  96. package/dist/schemas/library/community.d.ts +9 -17
  97. package/dist/schemas/library/community.d.ts.map +1 -1
  98. package/dist/schemas/library/community.js +5 -5
  99. package/dist/schemas/library/community.js.map +1 -1
  100. package/dist/schemas/library/life.d.ts +3 -3
  101. package/dist/schemas/library/life.d.ts.map +1 -1
  102. package/dist/schemas/library/life.js +2 -2
  103. package/dist/schemas/library/life.js.map +1 -1
  104. package/dist/schemas/library/media.d.ts +148 -541
  105. package/dist/schemas/library/media.d.ts.map +1 -1
  106. package/dist/schemas/library/media.js +28 -64
  107. package/dist/schemas/library/media.js.map +1 -1
  108. package/dist/schemas/library/money.d.ts +8 -8
  109. package/dist/schemas/library/money.d.ts.map +1 -1
  110. package/dist/schemas/library/money.js +4 -4
  111. package/dist/schemas/library/money.js.map +1 -1
  112. package/dist/schemas/library/planning.d.ts +23 -87
  113. package/dist/schemas/library/planning.d.ts.map +1 -1
  114. package/dist/schemas/library/planning.js +10 -26
  115. package/dist/schemas/library/planning.js.map +1 -1
  116. package/dist/schemas/library/publishing.d.ts +14 -14
  117. package/dist/schemas/library/publishing.d.ts.map +1 -1
  118. package/dist/schemas/library/publishing.js +7 -7
  119. package/dist/schemas/library/publishing.js.map +1 -1
  120. package/dist/schemas/library/social.d.ts +2 -2
  121. package/dist/schemas/library/social.d.ts.map +1 -1
  122. package/dist/schemas/library/social.js +1 -1
  123. package/dist/schemas/library/social.js.map +1 -1
  124. package/dist/schemas/standard.d.ts +1 -1
  125. package/dist/schemas/standard.d.ts.map +1 -1
  126. package/dist/schemas/standard.js +3 -3
  127. package/dist/schemas/standard.js.map +1 -1
  128. package/dist/session/auth.d.ts +20 -0
  129. package/dist/session/auth.d.ts.map +1 -1
  130. package/dist/session/auth.js +81 -64
  131. package/dist/session/auth.js.map +1 -1
  132. package/dist/session/connect.d.ts +50 -8
  133. package/dist/session/connect.d.ts.map +1 -1
  134. package/dist/session/connect.js +91 -27
  135. package/dist/session/connect.js.map +1 -1
  136. package/dist/session/connection.d.ts +39 -6
  137. package/dist/session/connection.d.ts.map +1 -1
  138. package/dist/session/connection.js +107 -38
  139. package/dist/session/connection.js.map +1 -1
  140. package/dist/session/hosting.d.ts +15 -0
  141. package/dist/session/hosting.d.ts.map +1 -1
  142. package/dist/session/hosting.js +55 -4
  143. package/dist/session/hosting.js.map +1 -1
  144. package/dist/session/index.d.ts +5 -5
  145. package/dist/session/index.d.ts.map +1 -1
  146. package/dist/session/index.js +2 -2
  147. package/dist/session/index.js.map +1 -1
  148. package/dist/space/account-registry.d.ts +36 -4
  149. package/dist/space/account-registry.d.ts.map +1 -1
  150. package/dist/space/account-registry.js +30 -3
  151. package/dist/space/account-registry.js.map +1 -1
  152. package/dist/space/invitation.d.ts +61 -0
  153. package/dist/space/invitation.d.ts.map +1 -0
  154. package/dist/space/invitation.js +84 -0
  155. package/dist/space/invitation.js.map +1 -0
  156. package/dist/space/invite-link.d.ts +64 -0
  157. package/dist/space/invite-link.d.ts.map +1 -0
  158. package/dist/space/invite-link.js +212 -0
  159. package/dist/space/invite-link.js.map +1 -0
  160. package/dist/space/roles.d.ts +59 -140
  161. package/dist/space/roles.d.ts.map +1 -1
  162. package/dist/space/roles.js +328 -427
  163. package/dist/space/roles.js.map +1 -1
  164. package/dist/space/space-manager.d.ts +21 -6
  165. package/dist/space/space-manager.d.ts.map +1 -1
  166. package/dist/space/space-manager.js +40 -23
  167. package/dist/space/space-manager.js.map +1 -1
  168. package/dist/types.d.ts +2 -0
  169. package/dist/types.d.ts.map +1 -1
  170. package/dist/types.js.map +1 -1
  171. package/docs/README.md +2 -2
  172. package/docs/actions.md +40 -40
  173. package/docs/agents.md +2 -2
  174. package/docs/automations.md +2 -2
  175. package/docs/blueprints-and-guides.md +61 -1
  176. package/docs/bots.md +1 -1
  177. package/docs/building-an-app.md +2 -2
  178. package/docs/contacts.md +48 -69
  179. package/docs/inbox.md +145 -0
  180. package/docs/node.md +135 -76
  181. package/docs/query-format.md +1 -1
  182. package/docs/sign-in.md +16 -9
  183. package/docs/spaces.md +33 -5
  184. package/docs/standard-library.md +111 -86
  185. package/docs/storage.md +1 -1
  186. package/package.json +5 -5
  187. package/dist/doors/doors.d.ts +0 -140
  188. package/dist/doors/doors.d.ts.map +0 -1
  189. package/dist/doors/doors.js +0 -226
  190. package/dist/doors/doors.js.map +0 -1
  191. package/dist/doors/index.d.ts +0 -9
  192. package/dist/doors/index.d.ts.map +0 -1
  193. package/dist/doors/index.js +0 -7
  194. package/dist/doors/index.js.map +0 -1
  195. package/docs/doors.md +0 -151
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';
@@ -23,21 +23,22 @@ import { meshFor, CANNOT_DEFINE, usableRelays, openSpaceRuntime, } from './space
23
23
  import { createServerAuth } from '../network/peer-auth.js';
24
24
  import { DEFAULT_ICE_SERVERS } from '../network/rtc-transport.js';
25
25
  import { deriveInviteKey } from '../space/space-access.js';
26
- import { foundersOf, soleFounder } from '../space/constitution.js';
27
- import { base64UrlDecode, base64UrlEncode } from '../utils/encoding.js';
26
+ import { encodeInviteLink, generateLinkSecret, inviteLinkKeys, isShortInvite, linkInviteSecret, linkTopic, MAX_INVITE_NODES, MAX_LINK_PLACES, openInvite, parseInviteLink, pinOf, relayOfNode, sealInvite, } from '../space/invite-link.js';
27
+ import { checkInvitation, readInvitation, writeInvitation } from '../space/invitation.js';
28
+ import { foundersOf } from '../space/constitution.js';
29
+ import { base64UrlDecode, base64UrlEncode, bytesToHex, hexToBytes } from '../utils/encoding.js';
28
30
  import { isRecord, unref } from '../utils/guards.js';
29
31
  import { createListeners } from '../utils/events.js';
30
32
  import { serial } from '../utils/serial.js';
31
33
  import { buildNamespaces, callMethod, givenFor } from './api.js';
32
- import { contactKeyPair, contactPublicKey, deriveDoorKeyBytes, deriveDoorSignKeyBytes, deriveMemberKeyBytes, } from '../identity/contact-key.js';
33
- import { openValueFrom, sealValueTo } from '../identity/hpke.js';
34
+ import { contactKeyPair, contactPublicKey, deriveInboxKeyBytes, deriveInboxSignKeyBytes, deriveMemberKeyBytes, } from '../identity/contact-key.js';
34
35
  import { direct as directSchema } from '../schemas/library/publishing.js';
35
36
  import { openDirect, sealDirect } from '../privacy/direct.js';
36
- import { contact as contactSchema, contactRequest as contactRequestSchema, door as doorSchema, knock as knockSchema, knockAnswer as knockAnswerSchema, } from '../schemas/contacts.js';
37
- import { checkAnswer, clip, doorTopic, encodeDoorCode, KNOCK_TTL_SECONDS, knockId, MAX_DOOR_RELAYS, openKnock, parseDoorCode, sealKnock, signAnswer, signPurge, } from '../doors/doors.js';
37
+ import { contact as contactSchema, contactRequest as contactRequestSchema, inbox as inboxSchema, knock as knockSchema, } from '../schemas/contacts.js';
38
+ import { clip, encodeInbox, inboxTopic, KNOCK_TTL_SECONDS, knockId, MAX_INBOX_PLACES, openKnock, readInbox as readInboxCode, sealKnock, signPurge, } from '../inbox/inbox.js';
38
39
  import { createMailboxClient } from '../network/mailbox.js';
39
40
  import { team } from '../space/presets.js';
40
- import { CARRIER_COLLECTION, deriveAccountRegistry, deriveContactsSpace, MEMBERSHIP_COLLECTION, PROFILE_COLLECTION, PROFILE_KEY, isAvatarRef, } from '../space/account-registry.js';
41
+ import { CARRIER_COLLECTION, isKeptLink, LINK_COLLECTION, deriveAccountRegistry, deriveCarrySpace, deriveContactsSpace, MEMBERSHIP_COLLECTION, PROFILE_COLLECTION, PROFILE_KEY, isAvatarRef, } from '../space/account-registry.js';
41
42
  import { CARRY_CLOSED_KEY, makePass, PASS_COLLECTION, passKey } from '../space/pass.js';
42
43
  import { checkOwnAutomation, OWN_AUTOMATIONS, WAKE_COLLECTION, linkedWakes, wakeFor, } from '../space/own-automations.js';
43
44
  import { createHostClient, connectorOffers, createSpaceHostClient, describeHost, hostPeerAddress, HOSTING_COLLECTION, HostError, newSubscriptionSeed, readStatus, subscriptionKey, } from '../session/hosting.js';
@@ -45,10 +46,10 @@ import { base32Encode, hashedKey } from '../utils/hash.js';
45
46
  /** Everything a session key may do: every command, about the whole account */
46
47
  export const SESSION_COMMAND = ALL_COMMAND;
47
48
  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
49
  /** How long leaving waits for a peer to take the account's removal before forgetting the space anyway */
51
50
  const LEAVE_WAIT_MS = 5000;
51
+ /** How long `spaces.carried` waits, by default: a short loading step, not a promise */
52
+ const CARRIED_WAIT_MS = 3000;
52
53
  function summarize(record) {
53
54
  const { space, key } = record;
54
55
  return Object.freeze({
@@ -134,12 +135,14 @@ export async function createNode(config) {
134
135
  const writers = createWriters((did) => did !== sessionDid ? handedIn : (claimed?.heads ?? (config.sessionKey ? handedIn : null)));
135
136
  const mesh = meshFor(config.network, sessionDid);
136
137
  /**
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.
138
+ * A node whose note doesn't let it act as the account itself — an app, or
139
+ * an agent on someone's computer running a node of its own. It may follow
140
+ * the account, but never writes for it: no list of spaces, no passes, no
141
+ * name, no inbox. Every peer would ignore those (spec 01 §8).
141
142
  */
142
- const narrowNote = !noteGrants(current, ACCOUNT_REQUIREMENT);
143
+ const narrowNote = !actsForAccount(current);
144
+ /** What signs this node's loose versions — invitations, knocks: the session key, under the note as it is now */
145
+ const looseSigner = () => ({ did: session.did, key: session.key, proof: current });
143
146
  // ─── Events ────────────────────────────────────────────────────────
144
147
  const events = createListeners('node event');
145
148
  const { emit } = events;
@@ -170,10 +173,16 @@ export async function createNode(config) {
170
173
  const contactsSpaceId = contactsRecord?.space.id ?? config.contactsSpace ?? null;
171
174
  // Kept in the node's own list like a joined space, so it can be shared with an app like one.
172
175
  if (contactsRecord && !(await registry.get(contactsRecord.space.id))) {
173
- await joinRegistry(await encodeSpaceInvite(contactsRecord, config.signer.did));
176
+ await joinRegistry(await encodeSpaceInvite(contactsRecord, looseSigner(), provider));
177
+ }
178
+ /** Which of the account's own spaces this is, or null for one it uses */
179
+ async function kindOf(spaceId) {
180
+ if (spaceId === accountSpaceId)
181
+ return 'registry';
182
+ if (spaceId === contactsSpaceId)
183
+ return 'contacts';
184
+ return (await isCarrySpace(spaceId)) ? 'carry' : null;
174
185
  }
175
- /** Whether a space is the account's own machinery, not one it uses */
176
- const hidden = (spaceId) => carrySpaces.has(spaceId) || spaceId === contactsSpaceId;
177
186
  /** The contact key, for a node allowed to open contact requests */
178
187
  const contactKeys = config.contactKey ? await contactKeyPair(config.contactKey) : null;
179
188
  /**
@@ -184,13 +193,39 @@ export async function createNode(config) {
184
193
  async function inviteTo(spaceId, options = {}) {
185
194
  const named = (await findRecord(spaceId))?.relays ?? [];
186
195
  const own = usableRelays(config.network).slice(0, MAX_RELAYS);
187
- return registry.createInvite(spaceId, config.signer.did, {
196
+ const nodes = await nodesOf(spaceId);
197
+ return registry.createInvite(spaceId, looseSigner(), {
188
198
  ...options,
189
199
  ...(named.length ? {} : own.length ? { relays: own } : {}),
200
+ ...(nodes.length ? { nodes } : {}),
190
201
  });
191
202
  }
203
+ /**
204
+ * The always-on nodes an invite names, so a joiner reaches one with nobody
205
+ * else online: the account's hosts, the space's own, and those the invite
206
+ * that brought this node here named. A host that can't be described in a
207
+ * few seconds is left out rather than holding the invite up.
208
+ */
209
+ async function nodesOf(spaceId) {
210
+ if (!config.network)
211
+ return [];
212
+ const hosts = [
213
+ ...(await hostingRecords()),
214
+ ...((await kindOf(spaceId)) ? [] : await namedHosts(spaceId).catch(() => [])),
215
+ ];
216
+ const inTime = (peer) => Promise.race([peer, new Promise((resolve) => unref(setTimeout(() => resolve(null), 3000)))]);
217
+ // Not the nodes an invite gave this node: nothing vouches for them, so they are used here and never passed on.
218
+ const peers = await Promise.all(hosts.map((host) => inTime(peerOf(host).catch(() => null))));
219
+ const pinned = [
220
+ ...new Set(peers.filter((peer) => peer !== null && peer.includes('#did:key:'))),
221
+ ];
222
+ return pinned.slice(0, MAX_INVITE_NODES);
223
+ }
192
224
  async function findRecord(spaceId) {
193
- return spaceId === accountSpaceId ? account : registry.get(spaceId);
225
+ if (spaceId === accountSpaceId)
226
+ return account;
227
+ const held = await registry.get(spaceId);
228
+ return held ?? (await carrierRecords()).find(({ carry }) => carry.space.id === spaceId)?.carry ?? null;
194
229
  }
195
230
  async function requireRecord(spaceId) {
196
231
  const record = await findRecord(spaceId);
@@ -216,17 +251,16 @@ export async function createNode(config) {
216
251
  if (spaceId !== accountSpaceId)
217
252
  emit({ type: 'status', space: spaceId });
218
253
  }
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(() => { });
254
+ if (event.type !== 'records')
255
+ return;
256
+ void runtimes
257
+ .get(event.space)
258
+ ?.then((rt) => checkRevoked(event.space, rt))
259
+ .catch(() => { });
260
+ void keepSpaceHosts(event.space).catch(() => { });
226
261
  // 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) {
262
+ void finishJoining(event.space);
263
+ if (event.space === accountSpaceId) {
230
264
  emit({ type: 'account' });
231
265
  void reconcile();
232
266
  // A rename on another device reaches the spaces open here too.
@@ -262,15 +296,13 @@ export async function createNode(config) {
262
296
  };
263
297
  }
264
298
  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
299
  /**
268
300
  * Tells a space who this account is. Done when the space opens and when the
269
301
  * name changes — not by opening every space, which would start syncing them
270
302
  * all; a space not open now hears on its next open.
271
303
  */
272
304
  async function publishProfile(spaceId, open) {
273
- if (spaceId === accountSpaceId || spaceId === contactsSpaceId || narrowNote)
305
+ if (narrowNote || (await kindOf(spaceId)))
274
306
  return;
275
307
  const own = await ownProfile();
276
308
  if (!own)
@@ -323,61 +355,61 @@ export async function createNode(config) {
323
355
  return Promise.reject(new Error('Node is closed'));
324
356
  let open = runtimes.get(spaceId);
325
357
  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
- }));
358
+ open = requireRecord(spaceId).then(async (record) => {
359
+ const kind = await kindOf(spaceId);
360
+ return openSpaceRuntime({
361
+ record,
362
+ writers,
363
+ stores: config.stores,
364
+ provider,
365
+ signer,
366
+ schemas,
367
+ session,
368
+ rootDid: config.signer.did,
369
+ ...(config.network ? { network: config.network } : {}),
370
+ ...(mesh ? { mesh } : {}),
371
+ accountOnly: kind !== null,
372
+ // The account's own spaces are always held whole: every device needs all of them.
373
+ ...(config.cache && !kind ? { cache: config.cache } : {}),
374
+ watchIntervalMs: config.watchIntervalMs ?? 2000,
375
+ ...(config.fetchFiles ? { fetchFiles: config.fetchFiles } : {}),
376
+ emit: fromRuntime,
377
+ onRole: (role) => {
378
+ // Holding a role now — perhaps just joined — means the space may hear who this is.
379
+ if (role !== null)
380
+ void runtimes
381
+ .get(spaceId)
382
+ ?.then((rt) => publishProfile(spaceId, rt))
383
+ .catch(() => { });
384
+ if (role !== null)
385
+ void keepSpaceHosts(spaceId).catch(() => { });
386
+ if (record.role === role)
387
+ return;
388
+ void registry.setRole(spaceId, role).then(() => emit({ type: 'spaces' }));
389
+ },
390
+ onJoined: () => {
391
+ if (!record.invite)
392
+ return;
393
+ void registry.clearInvite(spaceId).then(() => emit({ type: 'spaces' }));
394
+ },
395
+ memberKey: kind === 'registry'
396
+ ? null
397
+ : config.accountKey
398
+ ? await deriveMemberKeyBytes(config.accountKey, spaceId)
399
+ : (record.memberKey ?? null),
400
+ // Kept only for a space in the list: the registry is not in it.
401
+ onRelays: (relays) => registry.setRelays(spaceId, relays),
402
+ onKeys: async (keys, current) => {
403
+ if (kind === 'registry')
404
+ return;
405
+ await registry.addKeys(spaceId, keys, current);
406
+ // The account's other devices follow the new key, and its carriers: passes and wakes, not a whole reconcile.
407
+ if (!kind)
408
+ await remember(spaceId, { refresh: true });
409
+ void passAll().catch(() => { });
410
+ },
411
+ });
412
+ });
381
413
  // A failed open must not be cached, or the space stays broken until restart.
382
414
  open.catch(() => runtimes.delete(spaceId));
383
415
  void open.then((rt) => publishProfile(spaceId, rt)).catch(() => { });
@@ -432,7 +464,9 @@ export async function createNode(config) {
432
464
  if (!open)
433
465
  return;
434
466
  runtimes.delete(spaceId);
435
- await (await open).close();
467
+ // One still opening when the node closes fails to open ("Node is closed"): there is nothing to close.
468
+ const rt = await open.catch(() => null);
469
+ await rt?.close();
436
470
  }
437
471
  // ─── Memberships ───────────────────────────────────────────────────
438
472
  //
@@ -466,11 +500,12 @@ export async function createNode(config) {
466
500
  return;
467
501
  const open = await runtime(accountSpaceId);
468
502
  const known = await open.get(membershipKey(spaceId));
503
+ if (known && (!options.refresh || known.deleted))
504
+ return;
469
505
  // A view-only invite: what lets the account write is its role in the
470
506
  // space, which every device reads there. Invite secrets are never kept.
471
507
  const invite = await inviteTo(spaceId);
472
- if (known &&
473
- (!options.refresh || known.deleted || inviteKeyOf(known.body?.invite) === inviteKeyOf(invite)))
508
+ if (known && inviteKeyOf(known.body?.invite) === inviteKeyOf(invite))
474
509
  return;
475
510
  await open.upsertSystem(MEMBERSHIP_COLLECTION, membershipKey(spaceId), {
476
511
  space: spaceId,
@@ -496,37 +531,50 @@ export async function createNode(config) {
496
531
  }
497
532
  // ─── Carriers ──────────────────────────────────────────────────────
498
533
  //
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.
534
+ // One record per carrier in the registry. Its carry space is derived from
535
+ // the account key and the carrier's key, so every device finds the same one
536
+ // and none is stored. Every device of the account opens it and keeps a pass
537
+ // in it for each of the account's spaces (`space/pass.ts`) — so a space
538
+ // joined in any app is carried, with nothing to do in the home.
503
539
  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
- */
540
+ /** Whether a `sys.carrier` record of the account's, live or not, is keyed by this space */
541
+ async function isCarrySpace(spaceId) {
542
+ if (!accountSpaceId)
543
+ return false;
544
+ const versions = await (await runtime(accountSpaceId)).history(await carrierKey(spaceId));
545
+ return versions.some((version) => version.collection === CARRIER_COLLECTION && version.verified && version.root === config.signer.did);
546
+ }
547
+ const derivedCarry = new Map();
548
+ /** A carrier's carry space: derived, or for one added before they were, the one its invite names */
549
+ async function carrySpaceOf(carrier) {
550
+ if (carrier.invite && carrier.space)
551
+ return (await registry.get(carrier.space)) ?? joinRegistry(carrier.invite).catch(() => null);
552
+ if (!config.accountKey)
553
+ return null;
554
+ const at = `${carrier.did}|${carrier.gen ?? 0}`;
555
+ const known = derivedCarry.get(at);
556
+ if (known)
557
+ return known;
558
+ const derived = deriveCarrySpace(config.accountKey, config.signer.did, carrier.did, carrier.gen ?? 0, provider);
559
+ derivedCarry.set(at, derived);
560
+ return derived;
561
+ }
562
+ /** The account's carriers, live and removed, each with its carry space */
508
563
  async function carrierRecords() {
509
564
  if (!accountSpaceId)
510
565
  return [];
511
- const open = await runtime(accountSpaceId);
512
566
  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 });
567
+ for (const record of await ownRecords(await runtime(accountSpaceId), { collection: CARRIER_COLLECTION },
568
+ // A generation is a count: anything else names no carry space.
569
+ (one) => typeof one.body?.did === 'string' &&
570
+ (one.body.gen === undefined || (Number.isSafeInteger(one.body.gen) && one.body.gen >= 0)))) {
571
+ const carry = await carrySpaceOf(record.body);
572
+ // Its key names its carry space: that is how every device knows the space is one.
573
+ if (carry && record.key === (await carrierKey(carry.space.id)))
574
+ found.push({ key: record.key, body: record.body, carry });
525
575
  }
526
576
  return found;
527
577
  }
528
- /** Every carry space, live or not — kept out of the account's own list */
529
- let carrySpaces = new Set();
530
578
  /**
531
579
  * Puts a pass in a carrier's space for each of the account's spaces, and
532
580
  * takes away the rest; and a wake for each of its own automations, each value replaced by
@@ -543,7 +591,7 @@ export async function createNode(config) {
543
591
  if (contactsRecord)
544
592
  passes.set(await passKey(contactsRecord.space.id), await makePass(contactsRecord));
545
593
  for (const membership of await memberships()) {
546
- if (membership.deleted || !membership.body || hidden(membership.body.space))
594
+ if (membership.deleted || !membership.body || (await kindOf(membership.body.space)))
547
595
  continue;
548
596
  const record = await registry.get(membership.body.space);
549
597
  if (!record)
@@ -565,10 +613,15 @@ export async function createNode(config) {
565
613
  }
566
614
  }
567
615
  // Removed meanwhile, on this device or another: its passes stay deleted.
568
- if (!(await liveCarriers()).some((live) => live.space === carrier.space))
616
+ if (!(await liveCarriers()).some((live) => live.key === carrier.key))
569
617
  return;
570
- const carry = await runtime(carrier.space);
618
+ const carry = await runtime(carrier.carry.space.id);
571
619
  await writeExactly(carry, PASS_COLLECTION, passes, (key) => key.startsWith('pass:'));
620
+ // The links the account keeps, for the carrier to serve while every device is away.
621
+ const links = new Map();
622
+ for (const link of await keptLinks())
623
+ links.set(link.key, link.body);
624
+ await writeExactly(carry, LINK_COLLECTION, links, (key) => key.startsWith('link:'));
572
625
  const wakes = new Map();
573
626
  for (const own of owned) {
574
627
  const wake = await wakeFor(own, spaces, config.signer.did);
@@ -602,7 +655,7 @@ export async function createNode(config) {
602
655
  .sort((a, b) => a.since.localeCompare(b.since));
603
656
  }
604
657
  /** The carriers the account uses now */
605
- const liveCarriers = async () => (await carrierRecords()).flatMap(({ record }) => (!record.deleted && record.body ? [record.body] : []));
658
+ const liveCarriers = async () => (await carrierRecords()).filter(({ body }) => !body.removed);
606
659
  /**
607
660
  * Names the account's carriers — its extensions, its hosts — as keepers of
608
661
  * a space it manages, and stops naming ones it removed, so apps there hold
@@ -611,21 +664,14 @@ export async function createNode(config) {
611
664
  * manage is left to whoever does.
612
665
  */
613
666
  async function nameKeepers(spaceId, rt) {
614
- if (!account || narrowNote || spaceId === accountSpaceId || hidden(spaceId))
667
+ if (!account || narrowNote || (await kindOf(spaceId)))
615
668
  return;
616
669
  if (!(await rt.may(SPACE_KEEPERS)))
617
670
  return;
618
671
  const access = await rt.access();
619
672
  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
- }
673
+ const active = carriers.filter(({ body }) => !body.removed).map(({ body }) => body);
674
+ const gone = new Set(carriers.filter(({ body }) => body.removed).map(({ body }) => body.did));
629
675
  for (const carrier of active)
630
676
  gone.delete(carrier.did);
631
677
  const kept = access.keepers.filter((keeper) => !gone.has(keeper.did));
@@ -647,34 +693,6 @@ export async function createNode(config) {
647
693
  const held = new Set((await registry.list()).map((record) => record.space.id));
648
694
  const known = new Set();
649
695
  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
696
  for (const membership of await memberships()) {
679
697
  const spaceId = membership.key.slice('space:'.length);
680
698
  known.add(spaceId);
@@ -697,10 +715,10 @@ export async function createNode(config) {
697
715
  }
698
716
  // Held here but never recorded — joined before the registry existed, or on
699
717
  // 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.
718
+ // Held still: one left while this ran stays left.
701
719
  const stillHeld = new Set((await registry.list()).map((record) => record.space.id));
702
720
  for (const spaceId of held) {
703
- if (!known.has(spaceId) && stillHeld.has(spaceId) && !carrySpaces.has(spaceId))
721
+ if (!known.has(spaceId) && stillHeld.has(spaceId) && !(await kindOf(spaceId)))
704
722
  await remember(spaceId);
705
723
  }
706
724
  // Not awaited: it opens every space the account holds, which from a data
@@ -728,7 +746,6 @@ export async function createNode(config) {
728
746
  resolve(false);
729
747
  });
730
748
  });
731
- /** Every carrier the account uses gets its passes and wakes as they are now, one run at a time */
732
749
  /** Writing in carry spaces, one thing at a time: a removal never lands in the middle of a refill */
733
750
  let carryTurn = Promise.resolve();
734
751
  const inCarryTurn = (work) => {
@@ -736,14 +753,195 @@ export async function createNode(config) {
736
753
  carryTurn = run;
737
754
  return run;
738
755
  };
739
- const passAll = serial(() => inCarryTurn(async () => {
740
- for (const { record, space: spaceId } of await carrierRecords()) {
756
+ const mailbox = config.mailbox ?? createMailboxClient();
757
+ // ── Short invite links (spec 03 §7.7) ──
758
+ //
759
+ // The link holds a secret and the hash of one sealed invite; the invite
760
+ // sits in mailboxes: the account's host's first, which keeps it while every
761
+ // device is away, then the relays where the space's members meet.
762
+ /** Where a link's sealed invite is left: its nodes' relays, then the space's or this node's */
763
+ async function linkPlaces(spaceId, nodes) {
764
+ const named = (await findRecord(spaceId))?.relays ?? [];
765
+ const relays = named.length ? named : usableRelays(config.network).slice(0, MAX_RELAYS);
766
+ return [...new Set([...nodes.map(relayOfNode), ...relays])];
767
+ }
768
+ /**
769
+ * A short link to a space: the invite `inviteTo` would give, sealed under a
770
+ * fresh secret and left in mailboxes. Where none takes it, or it is too large
771
+ * for one, the long invite is given instead: it works the same.
772
+ */
773
+ async function shortInvite(spaceId, secret, options, until) {
774
+ const long = await inviteTo(spaceId, options);
775
+ // The invitation as signed: its secret is the link's to give.
776
+ const invite = parseSpaceInvite(long);
777
+ let sealed;
778
+ try {
779
+ sealed = await sealInvite(secret, { invite: invite.signed, ...(until !== undefined ? { until } : {}) });
780
+ }
781
+ catch {
782
+ return long;
783
+ }
784
+ const topic = await linkTopic(sealed.pin);
785
+ const ttl = until !== undefined ? Math.max(60, Math.ceil((until - Date.now()) / 1000)) : undefined;
786
+ const hosts = new Set((invite.nodes ?? []).map(relayOfNode));
787
+ const places = await linkPlaces(spaceId, invite.nodes ?? []);
788
+ const kept = (await Promise.all(places.map((place) => mailbox.drop(place, topic, sealed.blob, ttl).then(() => place, () => null)))).filter((place) => place !== null);
789
+ if (kept.length === 0)
790
+ return long;
791
+ await keepLink(spaceId, sealed, options, until);
792
+ // A host first, which keeps it; then a relay, so one going away leaves the other.
793
+ const host = kept.find((place) => hosts.has(place));
794
+ const relay = kept.find((place) => !hosts.has(place));
795
+ const named = [host, relay].filter((place) => place !== undefined);
796
+ return encodeInviteLink({ secret, pin: sealed.pin, places: named.slice(0, MAX_LINK_PLACES) });
797
+ }
798
+ /** The links the account keeps, as its registry holds them */
799
+ async function keptLinks() {
800
+ if (!accountSpaceId || narrowNote)
801
+ return [];
802
+ const records = await ownRecords(await runtime(accountSpaceId), { collection: LINK_COLLECTION }, (record) => record.key.startsWith('link:') && isKeptLink(record.body));
803
+ return records.map((record) => ({ key: record.key, body: record.body }));
804
+ }
805
+ /**
806
+ * Keeps a short link's sealed invite in the account registry: what it is
807
+ * for, never its secret. Every device then drops it again while it lasts,
808
+ * and closes its invite when it ends; carriers serve it meanwhile.
809
+ */
810
+ async function keepLink(spaceId, sealed, options, until) {
811
+ if (!accountSpaceId || narrowNote)
812
+ return;
813
+ const record = await findRecord(spaceId);
814
+ const body = {
815
+ space: spaceId,
816
+ blob: sealed.blob,
817
+ ...(options.secret ? { invite: (await deriveInviteKey(options.secret, provider)).did } : {}),
818
+ ...(record?.key ? { keyId: record.key.id } : {}),
819
+ ...(until !== undefined ? { until } : {}),
820
+ };
821
+ await (await runtime(accountSpaceId)).upsertSystem(LINK_COLLECTION, `link:${bytesToHex(sealed.pin)}`, body);
822
+ void passAll().catch(() => { });
823
+ }
824
+ /** Stops keeping the links `which` picks */
825
+ async function forgetLinks(which) {
826
+ if (!accountSpaceId || narrowNote)
827
+ return;
828
+ const registryRt = await runtime(accountSpaceId);
829
+ let forgot = false;
830
+ for (const { key, body } of await keptLinks())
831
+ if (which(body)) {
832
+ await registryRt.removeSystem(key);
833
+ forgot = true;
834
+ }
835
+ if (forgot)
836
+ void passAll().catch(() => { });
837
+ }
838
+ /**
839
+ * Looks after every link the account keeps. One past its `until`, for a
840
+ * space this device no longer holds, or carrying a key the space has moved
841
+ * on from, has ended: its role invite is closed, so nobody holding the
842
+ * space's current key can still join with it, and it is forgotten. The
843
+ * rest are dropped again where the space's members meet; a relay already
844
+ * holding one stores nothing new.
845
+ */
846
+ const keepLinks = serial(async () => {
847
+ for (const { key, body } of await keptLinks()) {
741
848
  if (closed)
742
849
  return;
743
- if (record.deleted || !record.body || !(await registry.get(spaceId)))
850
+ const record = await registry.get(body.space);
851
+ // Ended only on what this device knows: one behind on a key change, or not holding the space yet,
852
+ // would otherwise end a link another device of the account just made.
853
+ if (!record)
854
+ continue;
855
+ const moved = body.keyId !== undefined &&
856
+ record.key !== null &&
857
+ record.key.id !== body.keyId &&
858
+ (record.keys ?? []).some((held) => held.id === body.keyId);
859
+ if (moved || (body.until !== undefined && body.until <= Date.now())) {
860
+ if (body.invite)
861
+ await closeIfOpen(body.space, body.invite).catch(() => { });
862
+ await forgetLinks((link) => link.blob === body.blob);
744
863
  continue;
864
+ }
865
+ const topic = await linkTopic(hexToBytes(key.slice('link:'.length)));
866
+ const ttl = body.until !== undefined ? Math.ceil((body.until - Date.now()) / 1000) : undefined;
867
+ for (const place of await linkPlaces(body.space, []))
868
+ void mailbox.drop(place, topic, body.blob, ttl).catch(() => { });
869
+ }
870
+ });
871
+ /** Closes an invite unless it is closed already, or this account may not */
872
+ async function closeIfOpen(spaceId, inviteDid) {
873
+ const rt = await runtime(spaceId);
874
+ const invite = (await rt.access()).invites.find((held) => held.key === inviteDid);
875
+ if (invite?.open)
876
+ await rt.closeInvite(inviteDid);
877
+ }
878
+ // Relays forget after two weeks or a restart: every hour, whatever is gone goes back.
879
+ const linkTimer = setInterval(() => void keepLinks().catch(() => { }), 60 * 60 * 1000);
880
+ unref(linkTimer);
881
+ /** Pages of a topic read for a short link: a relay holds 64 blobs, at least four a page */
882
+ const INVITE_PAGES = 16;
883
+ /** A short link's invite, fetched once and kept: a preview and the join that follows ask once */
884
+ const resolved = new Map();
885
+ /** The long invite a text holds or a short link names, and when its inviter stops sharing it */
886
+ function resolveInvite(text) {
887
+ const bare = bareInvite(text);
888
+ if (!isShortInvite(bare))
889
+ return Promise.resolve({ long: bare });
890
+ let found = resolved.get(bare);
891
+ if (!found) {
892
+ found = fetchInvite(bare);
893
+ // A preview and the join after it ask once; a few links are remembered, not every one ever read.
894
+ const oldest = resolved.keys().next();
895
+ if (resolved.size >= 16 && !oldest.done)
896
+ resolved.delete(oldest.value);
897
+ resolved.set(bare, found);
898
+ found.catch(() => resolved.delete(bare));
899
+ }
900
+ return found;
901
+ }
902
+ /**
903
+ * Asks every place the link names, and this node's relays, for its topic.
904
+ * Of what comes back, only the blob that hashes to the pin is taken — any
905
+ * other, whoever left it, is ignored unopened.
906
+ */
907
+ async function fetchInvite(bare) {
908
+ const link = parseInviteLink(bare);
909
+ const { topic, inviteSecret } = await inviteLinkKeys(link.secret, link.pin);
910
+ const places = [...new Set([...link.places, ...usableRelays(config.network)])];
911
+ if (places.length === 0)
912
+ throw new Error('That invite names no place to find it, and this app knows none');
913
+ const blobs = new Set();
914
+ // A slow place can't hold the join up for long: what has come back by then is all there is.
915
+ await Promise.race([
916
+ new Promise((resolve) => unref(setTimeout(resolve, 20_000))),
917
+ Promise.all(places.map((place) => mailbox.fetch(place, topic, 0, INVITE_PAGES).then((items) => items.forEach((item) => blobs.add(item.blob)), () => { }))),
918
+ ]);
919
+ // Only blobs whose hash is the pin; any other, whoever left it, is never opened.
920
+ const named = [];
921
+ for (const blob of blobs)
922
+ if ((await pinOf(blob)).every((byte, i) => byte === link.pin[i]))
923
+ named.push(blob);
924
+ // Only the inviter could make two blobs share a pin, and then neither is trusted.
925
+ if (named.length > 1)
926
+ throw new Error('That invite link names more than one invite, so it is not used');
927
+ const opened = named[0] ? await openInvite(link, named[0]) : null;
928
+ if (!opened)
929
+ throw new Error('That invite was not found. It may have expired, or the places it names may be down.');
930
+ const { invite, until } = opened;
931
+ // The invitation as its inviter signed it, and beside it the secret the link's own gives a role link.
932
+ const signed = readInvitation(writeInvitation(invite)).version;
933
+ const long = writeInvitation(signed, typeof signed.body.role === 'string' ? inviteSecret : undefined);
934
+ return { long, ...(until !== undefined ? { until } : {}) };
935
+ }
936
+ /** Every carrier the account uses gets its passes and wakes as they are now, one run at a time */
937
+ const passAll = serial(() => inCarryTurn(async () => {
938
+ // First: a key change that ends a link is seen here, before its record would be copied on.
939
+ await keepLinks().catch(() => { });
940
+ for (const carrier of await liveCarriers()) {
941
+ if (closed)
942
+ return;
745
943
  // 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(() => { });
944
+ await syncPasses(carrier).catch(() => { });
747
945
  }
748
946
  }));
749
947
  const reconcile = serial(() => reconcileOnce().catch((error) => {
@@ -752,7 +950,11 @@ export async function createNode(config) {
752
950
  }));
753
951
  const spaces = Object.freeze({
754
952
  async list() {
755
- return (await registry.list()).filter((record) => !hidden(record.space.id)).map(summarize);
953
+ const used = [];
954
+ for (const record of await registry.list())
955
+ if (!(await kindOf(record.space.id)))
956
+ used.push(record);
957
+ return used.map(summarize);
756
958
  },
757
959
  async get(spaceId) {
758
960
  const record = await findRecord(spaceId);
@@ -775,8 +977,11 @@ export async function createNode(config) {
775
977
  return summarize(record);
776
978
  },
777
979
  async invite(spaceId, options = {}) {
980
+ // A short link's secret comes first: a role invite's own secret is derived from it.
981
+ const link = options.short ? generateLinkSecret() : null;
982
+ const share = (opened = {}) => link ? shortInvite(spaceId, link, opened, options.until) : inviteTo(spaceId, opened);
778
983
  if (options.write === false)
779
- return inviteTo(spaceId);
984
+ return share();
780
985
  const open = await runtime(spaceId);
781
986
  const { roles, founder, mine } = await open.access();
782
987
  const member = founder || mine.length > 0;
@@ -791,14 +996,22 @@ export async function createNode(config) {
791
996
  throw new Error(member
792
997
  ? `There is no role "${options.role}"`
793
998
  : 'You hold no role here, so you can only share it to view');
794
- return inviteTo(spaceId);
999
+ return share();
795
1000
  }
796
- const { secret } = await open.openInvite(role);
797
- return inviteTo(spaceId, { secret, role });
1001
+ const { secret } = await open.openInvite(role, link ? await linkInviteSecret(link) : undefined);
1002
+ return share({ secret, role });
1003
+ },
1004
+ async preview(invite) {
1005
+ const { long, until } = await resolveInvite(invite);
1006
+ // Who it says invited is shown before joining, so it is checked as joining checks it.
1007
+ const parsed = parseSpaceInvite(long);
1008
+ const unsigned = await checkInvitation(parsed.signed, provider, parsed.invite);
1009
+ if (unsigned)
1010
+ throw new Error(`That invite doesn't check out: ${unsigned}.`);
1011
+ return { ...previewInvite(long), ...(until !== undefined ? { until } : {}) };
798
1012
  },
799
- preview: previewInvite,
800
1013
  async join(invite, options = {}) {
801
- const record = await joinRegistry(bareInvite(invite));
1014
+ const record = await joinRegistry((await resolveInvite(invite)).long);
802
1015
  if (options.memberKey)
803
1016
  await registry.setMemberKey(record.space.id, options.memberKey);
804
1017
  // A runtime opened before the key arrived would still be unable to read.
@@ -810,10 +1023,9 @@ export async function createNode(config) {
810
1023
  return summarize((await registry.get(record.space.id)) ?? record);
811
1024
  },
812
1025
  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');
1026
+ const kind = await kindOf(spaceId);
1027
+ if (kind)
1028
+ throw new Error(`The ${kind === 'registry' ? 'account registry' : `${kind} space`} cannot be left`);
817
1029
  await giveUpPlace(spaceId);
818
1030
  await forget(spaceId);
819
1031
  await closeRuntime(spaceId);
@@ -851,7 +1063,7 @@ export async function createNode(config) {
851
1063
  // A peer's key does not say whose it is. But only this account's devices
852
1064
  // and apps can read the account registry, so a peer there is one of ours
853
1065
  // — except a carrier, which the registry names by its key.
854
- const carrierKeys = new Set((await liveCarriers()).map((carrier) => carrier.did));
1066
+ const carrierKeys = new Set((await liveCarriers()).map(({ body }) => body.did));
855
1067
  const inRegistry = new Set((await (await runtime(accountSpaceId)).status()).peers);
856
1068
  return {
857
1069
  ...status,
@@ -859,6 +1071,28 @@ export async function createNode(config) {
859
1071
  carriers: status.peers.filter((peer) => carrierKeys.has(peer)),
860
1072
  };
861
1073
  },
1074
+ async carried(spaceId, options = {}) {
1075
+ if (!accountSpaceId || narrowNote || !config.network)
1076
+ return false;
1077
+ // Only with a carrier connected now, as the account registry shows it: else nothing is coming.
1078
+ const carriers = new Set((await liveCarriers()).map(({ body }) => body.did));
1079
+ const online = (await (await runtime(accountSpaceId)).status()).peers;
1080
+ if (!online.some((peer) => carriers.has(peer)))
1081
+ return false;
1082
+ const deadline = Date.now() + (options.waitMs ?? CARRIED_WAIT_MS);
1083
+ const open = await runtime(spaceId);
1084
+ // Named a keeper, and given its pass now rather than whenever the next round comes.
1085
+ await nameKeepers(spaceId, open).catch(() => { });
1086
+ void passAll().catch(() => { });
1087
+ while (!closed && Date.now() < deadline) {
1088
+ // Level with a carrier: it holds the genesis, and any invite opened since.
1089
+ for (const peer of (await spaces.status(spaceId)).carriers)
1090
+ if (await open.syncedWith(peer, Math.max(0, Math.min(2000, deadline - Date.now()))))
1091
+ return true;
1092
+ await new Promise((resolve) => unref(setTimeout(resolve, 250)));
1093
+ }
1094
+ return false;
1095
+ },
862
1096
  profiles: perSpace((rt) => rt.profiles()),
863
1097
  access: perSpace((rt) => rt.access()),
864
1098
  may: perSpace((rt, cmd, args, account) => rt.may(cmd, args, account)),
@@ -878,13 +1112,20 @@ export async function createNode(config) {
878
1112
  async closeInvite(spaceId, keyOrLink) {
879
1113
  let key = keyOrLink;
880
1114
  // The link itself will do: its secret names the invite.
881
- if (!keyOrLink.startsWith('did:key:')) {
1115
+ if (!keyOrLink.startsWith('did:key:') && isShortInvite(bareInvite(keyOrLink))) {
1116
+ // A short link's invite secret is derived from its own; a view-only one has no record to close.
1117
+ const secret = await linkInviteSecret(parseInviteLink(bareInvite(keyOrLink)).secret);
1118
+ key = (await deriveInviteKey(secret, provider)).did;
1119
+ }
1120
+ else if (!keyOrLink.startsWith('did:key:')) {
882
1121
  const secret = parseSpaceInvite(bareInvite(keyOrLink)).invite;
883
1122
  if (!secret)
884
1123
  throw new Error('That invite is view-only — there is nothing to close. To stop it working, give the space a new key (changeKey).');
885
1124
  key = (await deriveInviteKey(base64UrlDecode(secret), provider)).did;
886
1125
  }
887
1126
  await (await runtime(spaceId)).closeInvite(key);
1127
+ // Its link, if the account keeps one, is no longer served.
1128
+ await forgetLinks((link) => link.space === spaceId && link.invite === key);
888
1129
  },
889
1130
  revoke: perSpace((rt, key, options) => rt.revoke(key, options)),
890
1131
  changeKey: perSpace((rt) => rt.rotateKey()),
@@ -967,84 +1208,75 @@ export async function createNode(config) {
967
1208
  return taken;
968
1209
  },
969
1210
  });
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
1211
  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;
1212
+ list: async () => (await liveCarriers()).map(({ body: { did, name, since }, carry }) => ({
1213
+ space: carry.space.id,
1214
+ did,
1215
+ name,
1216
+ since,
1217
+ })),
1218
+ async add(carrier) {
1219
+ const registryRt = await requireAccount('Using a carrier');
1220
+ const all = await carrierRecords();
1221
+ // The same carrier again keeps its carry space: what it holds stays good, and nothing is closed under it.
1222
+ let entry = all.find(({ body }) => body.did === carrier.did && !body.removed);
1223
+ if (entry)
1224
+ void passAll().catch(() => { });
1225
+ else {
1226
+ // Added again after a removal, a new carry space: the last one tells it to forget. One past the
1227
+ // highest seen, not a count: a device that hasn't synced every earlier one must not land on a closed space.
1228
+ const gens = all.filter(({ body }) => body.did === carrier.did).map(({ body }) => body.gen ?? 0);
1229
+ const gen = gens.length ? Math.max(...gens) + 1 : 0;
1230
+ const body = {
1231
+ did: carrier.did,
1232
+ name: carrier.name.trim().slice(0, 80) || 'Carrier',
1233
+ since: new Date().toISOString(),
1234
+ ...(gen ? { gen } : {}),
1235
+ };
1236
+ const carry = (await carrySpaceOf(body));
1237
+ // Two devices adding it at once write the one record, for the one space.
1238
+ entry = { key: await carrierKey(carry.space.id), body, carry };
1239
+ await registryRt.upsertSystem(CARRIER_COLLECTION, entry.key, body);
1240
+ // Its passes before its invite, as one batch: a carrier joining an empty carry space takes spaces as they trickle in.
1241
+ // Not in turn behind a refill: nothing removes a carrier that is only now being added.
1242
+ await syncPasses(entry);
1243
+ }
1244
+ return {
1245
+ space: entry.carry.space.id,
1246
+ invite: await encodeSpaceInvite(entry.carry, looseSigner(), provider),
1247
+ };
1016
1248
  },
1017
1249
  settled: (waitMs) => within(passAll.done(), waitMs),
1018
1250
  async reached(spaceId, waitMs) {
1019
- const carrier = (await liveCarriers()).find((c) => c.space === spaceId);
1020
- if (!carrier || !accountSpaceId)
1251
+ const did = (await liveCarriers()).find(({ carry }) => carry.space.id === spaceId)?.body.did;
1252
+ if (!did || !accountSpaceId)
1021
1253
  return false;
1022
1254
  const deadline = Date.now() + waitMs;
1023
1255
  // Level with the passes and wakes as they are now: a refill under way first, within the same time.
1024
1256
  await within(passAll.done(), waitMs);
1025
1257
  // 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()))))
1258
+ if (!(await (await runtime(spaceId)).syncedWith(did, Math.max(0, deadline - Date.now()))))
1027
1259
  return false;
1028
- return (await runtime(accountSpaceId)).syncedWith(carrier.did, Math.max(0, deadline - Date.now()));
1260
+ return (await runtime(accountSpaceId)).syncedWith(did, Math.max(0, deadline - Date.now()));
1029
1261
  },
1030
1262
  async remove(spaceId) {
1031
1263
  const registryRt = await requireAccount('Removing a carrier');
1032
1264
  // In turn with any refill, which would otherwise put the passes back.
1033
1265
  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);
1266
+ const live = await liveCarriers();
1267
+ const did = live.find(({ carry }) => carry.space.id === spaceId)?.body.did;
1268
+ // Every carry space it has: one added on two devices at once, before they were derived, has two.
1269
+ for (const { key, body, carry } of live.filter((one) => one.body.did === did)) {
1270
+ const rt = await runtime(carry.space.id);
1043
1271
  // 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);
1272
+ for (const pass of await ownRecords(rt, { collection: PASS_COLLECTION }, (r) => r.key.startsWith('pass:')))
1273
+ await rt.removeSystem(pass.key);
1274
+ await rt.upsertSystem(PASS_COLLECTION, CARRY_CLOSED_KEY, { v: 1, closed: true });
1275
+ // Kept, so adding it again counts this one and takes a new carry space.
1276
+ await registryRt.upsertSystem(CARRIER_COLLECTION, key, {
1277
+ ...body,
1278
+ removed: new Date().toISOString(),
1279
+ });
1048
1280
  }
1049
1281
  });
1050
1282
  },
@@ -1074,13 +1306,6 @@ export async function createNode(config) {
1074
1306
  throw new Error("The host at this address has another key now, so it's another host");
1075
1307
  return description;
1076
1308
  }
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
1309
  /** Last time each host was handed the spaces, or refused them — so asking again waits a while */
1085
1310
  const handedAt = new Map();
1086
1311
  const HAND_AGAIN_MS = 60_000;
@@ -1132,7 +1357,9 @@ export async function createNode(config) {
1132
1357
  }
1133
1358
  else if (!status.carrying && paid && due && !narrowNote) {
1134
1359
  handedAt.set(hosting.url, Date.now());
1135
- const attaching = carryFor(hosting).then((invite) => client.attach(config.signer.did, invite));
1360
+ const attaching = carriers
1361
+ .add({ did: hosting.host, name: new URL(hosting.url).host })
1362
+ .then(({ invite }) => client.attach(config.signer.did, invite));
1136
1363
  handing.set(hosting.url, attaching);
1137
1364
  try {
1138
1365
  ({ status, receipt } = await attaching);
@@ -1285,7 +1512,8 @@ export async function createNode(config) {
1285
1512
  }
1286
1513
  /** Hands the hosts a space names its pass, when they were paid and don't carry it with its key yet */
1287
1514
  async function keepSpaceHosts(spaceId) {
1288
- if (ownSpace(spaceId))
1515
+ // Only while it is open: a change heard as it closed must not open it again.
1516
+ if ((await kindOf(spaceId)) || !runtimes.has(spaceId))
1289
1517
  return;
1290
1518
  const hosts = await namedHosts(spaceId);
1291
1519
  await reachHosts(spaceId, hosts);
@@ -1345,10 +1573,18 @@ export async function createNode(config) {
1345
1573
  ];
1346
1574
  if (spaceId === accountSpaceId)
1347
1575
  hosts.push(...(config.network.hosts ?? []).map((url) => ({ url })));
1348
- if (!ownSpace(spaceId))
1576
+ // Asked only while it is still open: asking would open it again.
1577
+ if (!(await kindOf(spaceId)) && runtimes.get(spaceId) === open)
1349
1578
  hosts.push(...(spaceHosts ?? (await namedHosts(spaceId))));
1579
+ // The nodes the invite that brought it here named: the inviter's hosts, reached before the space's own
1580
+ // records are. Once the space names its keepers, only those of them it names: an invite is unauthenticated.
1581
+ const named = (await registry.get(spaceId))?.nodes ?? [];
1582
+ const keepers = new Set(named.length > 0
1583
+ ? ((await (await open).access().catch(() => null))?.keepers ?? []).map((keeper) => keeper.did)
1584
+ : []);
1585
+ const invited = named.filter((node) => keepers.size === 0 || keepers.has(decodeURIComponent(node.split('#')[1] ?? '')));
1350
1586
  const peers = [
1351
- ...new Set((await Promise.all(hosts.map(peerOf))).filter((peer) => peer !== null)),
1587
+ ...new Set([...(await Promise.all(hosts.map(peerOf))), ...invited].filter((peer) => peer !== null)),
1352
1588
  ].sort();
1353
1589
  const said = peers.join(' ');
1354
1590
  if (reaching.get(spaceId) === said || runtimes.get(spaceId) !== open)
@@ -1461,24 +1697,21 @@ export async function createNode(config) {
1461
1697
  const known = await requireHosting(url);
1462
1698
  const { client } = await hostClient(known);
1463
1699
  await client.detach().catch(() => { });
1464
- const carrier = (await liveCarriers()).find((found) => found.did === known.host);
1700
+ const carrier = (await liveCarriers()).find(({ body }) => body.did === known.host);
1465
1701
  if (carrier)
1466
- await carriers.remove(carrier.space);
1702
+ await carriers.remove(carrier.carry.space.id);
1467
1703
  await registryRt.removeSystem(await hostingKey(known.url));
1468
1704
  },
1469
1705
  });
1470
1706
  // ─── Contacts ──────────────────────────────────────────────────────
1471
1707
  //
1472
1708
  // One `std.contact` per person in the contacts space, keyed by their DID, so
1473
- // there is one per person on every device. Asking someone is a
1474
- // `std.contact-request` in a space you share: the invite to a new space for
1475
- // two, sealed with their contact key, bound to the space it was posted in and
1476
- // to who asked whom — so it opens only for them, only there, and only as
1477
- // coming from the account that wrote it.
1709
+ // there is one per person on every device. Asking someone is a knock left
1710
+ // as a `std.contact-request` in a space you share: the signed invite to a new space for
1711
+ // two, sealed to their contact key, so it opens only for them, and only as
1712
+ // coming from the account that left it.
1478
1713
  // The key `onePer: ['did']` derives, so the record for someone is the same one on every device.
1479
1714
  const contactRecordKey = async (did) => (await contactsRuntime()).onePerKey(contactSchema.name, { did }, { onePer: contactSchema.rules.onePer });
1480
- /** The HPKE label a contact request is sealed under; bound to `{ space, from, to }` */
1481
- const REQUEST_LABEL = 'minca/contact-request/v1';
1482
1715
  async function contactsRuntime() {
1483
1716
  if (!contactsSpaceId)
1484
1717
  throw new Error('This app was not given your contacts. Connect to your account home again, and allow contacts.');
@@ -1487,7 +1720,7 @@ export async function createNode(config) {
1487
1720
  /** Making and joining spaces for two needs a note good for every space — whole-account access. */
1488
1721
  function requireEverywhere(what) {
1489
1722
  // As a knock needs: `/account/write` for the whole account (spec 01 §8, 07).
1490
- if (!noteGrants(current, ACCOUNT_REQUIREMENT)) {
1723
+ if (narrowNote) {
1491
1724
  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
1725
  }
1493
1726
  }
@@ -1544,38 +1777,49 @@ export async function createNode(config) {
1544
1777
  return;
1545
1778
  await spaces.leave(spaceId);
1546
1779
  }
1547
- /** A contact request, opened — or null when it isn't one for this account, from the account that wrote it */
1548
- async function openRequest(spaceId, record) {
1549
- if (!contactKeys || !record.verified || record.collection !== contactRequestSchema.name)
1550
- return null;
1551
- if (record.body?.to !== config.signer.did || typeof record.body.sealed !== 'string')
1552
- return null;
1553
- // Asking makes a space for two for the account, as a knock does: only a note that may write for all of it.
1554
- const note = await (await runtime(spaceId)).noteOf(record.key);
1555
- if (!noteGrants(note, ACCOUNT_REQUIREMENT))
1780
+ /**
1781
+ * A knock left in a space as a contact request, opened — or null when it
1782
+ * isn't one sealed to this account's contact key, by the account that wrote it.
1783
+ */
1784
+ async function openMail(record) {
1785
+ if (!config.contactKey ||
1786
+ !contactKeys ||
1787
+ !record?.verified ||
1788
+ record.collection !== contactRequestSchema.name)
1556
1789
  return null;
1557
- const from = record.root;
1558
- if (!from || record.createdBy !== from || from === config.signer.did)
1790
+ const body = record.body;
1791
+ if (!isRecord(body) || body.to !== contactKeys.publicKey || typeof body.sealed !== 'string')
1559
1792
  return null;
1560
- const value = await openValueFrom(contactKeys, REQUEST_LABEL, { space: spaceId, from, to: config.signer.did }, record.body.sealed);
1561
- if (!isRecord(value) || typeof value.invite !== 'string')
1793
+ const opened = await openKnock([config.contactKey], body.sealed, null, provider);
1794
+ if (!opened || opened.from !== record.root || opened.from === config.signer.did)
1562
1795
  return null;
1563
- let invited;
1796
+ return opened;
1797
+ }
1798
+ /**
1799
+ * A space for two and a knock that invites someone to it, sealed to `to`:
1800
+ * their inbox key or their contact key. The space waits for a carrier to
1801
+ * hold it before the knock is made, so they can join with every device of
1802
+ * this account away (`spaces.carried`).
1803
+ */
1804
+ async function makePair(to, names, note) {
1805
+ const pair = await spaces.create({
1806
+ name: `${clip(names.mine, 64)} & ${clip(names.theirs, 64)}`,
1807
+ visibility: 'private',
1808
+ ...team,
1809
+ });
1564
1810
  try {
1565
- invited = parseSpaceInvite(value.invite);
1811
+ const invite = await spaces.invite(pair.id, { role: 'editor' });
1812
+ const { signed, invite: secret } = parseSpaceInvite(invite);
1813
+ if (!secret)
1814
+ throw new Error('The invite to the space for two opens no role');
1815
+ const carried = await spaces.carried(pair.id);
1816
+ const sealed = await sealKnock(to, { invite: signed, secret: base64UrlDecode(secret), name: names.mine, ...(note ? { note } : {}) }, looseSigner(), provider);
1817
+ return { space: pair.id, invite, sealed, carried };
1566
1818
  }
1567
- catch {
1568
- return null;
1819
+ catch (error) {
1820
+ await spaces.leave(pair.id).catch(() => { });
1821
+ throw error;
1569
1822
  }
1570
- // A private space the asker made, and the key to it: anything else isn't a space for two from them.
1571
- if (soleFounder(invited.space) !== from || invited.space.visibility !== 'private' || !invited.key)
1572
- return null;
1573
- return {
1574
- from,
1575
- invite: value.invite,
1576
- ...(typeof value.note === 'string' && value.note ? { note: value.note.slice(0, 2000) } : {}),
1577
- pairSpace: invited.space.id,
1578
- };
1579
1823
  }
1580
1824
  const contacts = Object.freeze({
1581
1825
  async space() {
@@ -1596,14 +1840,11 @@ export async function createNode(config) {
1596
1840
  const name = contact.name.trim().slice(0, 200);
1597
1841
  if (!name)
1598
1842
  throw new Error('A contact needs a name');
1599
- // An answer to their knock still to be written stays to be written.
1600
- const pending = (await contactRecords()).find((record) => record.body.did === contact.did)?.body?.door;
1601
1843
  return writeContact({
1602
1844
  did: contact.did,
1603
1845
  name,
1604
1846
  ...(contact.space ? { space: contact.space } : {}),
1605
1847
  ...(contact.note ? { note: contact.note.slice(0, 2000) } : {}),
1606
- ...(pending ? { door: pending } : {}),
1607
1848
  });
1608
1849
  },
1609
1850
  async remove(did) {
@@ -1637,15 +1878,16 @@ export async function createNode(config) {
1637
1878
  if (!theirs?.contactKey) {
1638
1879
  throw new Error("They can't be asked here yet: their profile in this space has no contact key. It appears once they open the space in an up-to-date app.");
1639
1880
  }
1640
- await ensureDefined(shared, contactRequestSchema);
1641
1881
  const mine = (await ownName()) ?? profiles.find((profile) => profile.did === config.signer.did)?.name ?? 'Me';
1642
- const pair = await spaces.create({ name: `${mine} & ${theirs.name}`, visibility: 'private', ...team });
1643
- const invite = await spaces.invite(pair.id, { role: 'editor' });
1644
- await writeContact({ did, name: theirs.name, space: pair.id });
1645
1882
  const note = options.note?.trim().slice(0, 2000);
1646
- const sealed = await sealValueTo(theirs.contactKey, REQUEST_LABEL, { space: spaceId, from: config.signer.did, to: did }, { invite, ...(note ? { note } : {}) });
1647
- const request = await shared.put(contactRequestSchema.name, { to: did, sealed });
1648
- return { space: pair.id, request: request.key };
1883
+ const made = await makePair(theirs.contactKey, { mine, theirs: theirs.name }, note);
1884
+ await ensureDefined(shared, contactRequestSchema);
1885
+ await writeContact({ did, name: theirs.name, space: made.space });
1886
+ const request = await shared.put(contactRequestSchema.name, {
1887
+ to: theirs.contactKey,
1888
+ sealed: made.sealed,
1889
+ });
1890
+ return { space: made.space, request: request.key, carried: made.carried };
1649
1891
  },
1650
1892
  async requests(spaceId) {
1651
1893
  requireContactKeys();
@@ -1653,10 +1895,8 @@ export async function createNode(config) {
1653
1895
  const blocked = await blockedDids();
1654
1896
  const names = new Map((await shared.profiles()).map((profile) => [profile.did, profile.name]));
1655
1897
  const found = [];
1656
- for (const record of await shared.list({
1657
- collection: contactRequestSchema.name,
1658
- })) {
1659
- const opened = await openRequest(spaceId, record);
1898
+ for (const record of await shared.list({ collection: contactRequestSchema.name })) {
1899
+ const opened = await openMail(record);
1660
1900
  if (!opened || blocked.has(opened.from))
1661
1901
  continue;
1662
1902
  // Already accepted, here or on another device.
@@ -1678,14 +1918,13 @@ export async function createNode(config) {
1678
1918
  requireEverywhere('Accepting a contact request');
1679
1919
  requireContactKeys();
1680
1920
  const shared = await runtime(spaceId);
1681
- const record = await shared.get(requestKey);
1682
- const opened = record ? await openRequest(spaceId, record) : null;
1921
+ const opened = await openMail(await shared.get(requestKey));
1683
1922
  if (!opened)
1684
1923
  throw new Error('That contact request is gone, or is not for you.');
1685
1924
  await spaces.join(opened.invite);
1686
1925
  const name = (await shared.profiles()).find((profile) => profile.did === opened.from)?.name ??
1687
1926
  (await contacts.get(opened.from))?.name ??
1688
- opened.from;
1927
+ opened.name;
1689
1928
  return writeContact({ did: opened.from, name, space: opened.pairSpace });
1690
1929
  },
1691
1930
  async others(did) {
@@ -1706,118 +1945,103 @@ export async function createNode(config) {
1706
1945
  return [...seen].filter((account) => account !== config.signer.did && account !== did).sort();
1707
1946
  },
1708
1947
  });
1709
- // ─── Doors ─────────────────────────────────────────────────────────
1948
+ // ─── The inbox ─────────────────────────────────────────────────────
1710
1949
  //
1711
- // A door is a `std.door` in the contacts space; its keys are derived from
1712
- // the contact key and its id, so every device with the contact key opens the
1713
- // same doors. Knocks wait in the mailboxes of the relays a door names.
1950
+ // The inbox's settings are a `std.inbox` in the contacts space; its keys
1951
+ // are derived from the contact key and its `gen`, so every device with the
1952
+ // contact key opens the same inbox. Knocks wait in the mailboxes it names.
1714
1953
  //
1715
- // A knock you left is a `std.knock` until the person behind the door
1716
- // answers in the space for two — a `std.knock-answer` signed with the
1717
- // door's signing key — when it becomes a contact and the invite is closed.
1718
- // Accepting a knock writes that answer as soon as this account's membership
1719
- // there has landed; until then the contact carries the door's id.
1720
- // See `packages/core/src/doors/doors.ts`.
1721
- const mailbox = config.mailbox ?? createMailboxClient();
1722
- /** Knocks seen at this node's doors, by id: opened (null when they didn't check out), and until when to keep them */
1954
+ // A knock you left is a `std.knock` until someone other than you joins
1955
+ // the space for two: only the holder of the inbox key could open the
1956
+ // invite, so whoever joins is them. Then it becomes a contact, and the
1957
+ // invite is closed. See `packages/core/src/inbox/inbox.ts`.
1958
+ /** Knocks seen in this node's inbox, by id: opened (null when they didn't check out), and until when to keep them */
1723
1959
  const knockCache = new Map();
1960
+ /** Copies of knocks that didn't check out, by id and mailbox: not opened again */
1961
+ const failed = new Set();
1724
1962
  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 } });
1963
+ /** The inbox is the account's own, in its contacts space: only a key acting as the account opens one, as every peer checks */
1964
+ const inboxAllowed = () => contactsSpaceId !== null && !narrowNote;
1728
1965
  function requireContactKey(what) {
1729
- // Doors are the account's: a key whose note doesn't grant `/account/write` never opens one or knocks.
1730
- if (!doorsAllowed())
1731
- throw new Error(`This key's note doesn't let it use doors. ${what} is the person's to do.`);
1966
+ // The inbox is the account's: a key whose note doesn't grant `/account/write` never opens one or knocks.
1967
+ if (!inboxAllowed())
1968
+ throw new Error(`This key's note doesn't let it use your inbox. ${what} is the person's to do.`);
1732
1969
  if (!config.contactKey)
1733
1970
  throw new Error(`${what} needs your contact key. Connect to your account home again, and allow contacts.`);
1734
1971
  return config.contactKey;
1735
1972
  }
1736
- /** A door's keys, from the contact key and its id */
1737
- async function doorKeys(id) {
1738
- const contactKey = requireContactKey('A door');
1739
- const key = await deriveDoorKeyBytes(contactKey, id);
1740
- const sign = await deriveDoorSignKeyBytes(contactKey, id);
1973
+ /** An inbox's keys, from the contact key and its gen */
1974
+ async function inboxKeys(gen) {
1975
+ const contactKey = requireContactKey('Your inbox');
1976
+ const key = await deriveInboxKeyBytes(contactKey, gen);
1977
+ const sign = await deriveInboxSignKeyBytes(contactKey, gen);
1741
1978
  const signPublic = contactPublicKey(sign);
1742
- return { key, sign, publicKey: contactPublicKey(key), signPublic, topic: await doorTopic(signPublic) };
1979
+ return { key, sign, publicKey: contactPublicKey(key), signPublic, topic: await inboxTopic(signPublic) };
1743
1980
  }
1744
- async function doorRecords() {
1981
+ /** The account's inbox: the newest `std.inbox` of the highest gen */
1982
+ async function inboxRecord() {
1745
1983
  if (!contactsSpaceId)
1746
- return [];
1747
- return ownRecords(await contactsRuntime(), { collection: doorSchema.name }, (record) => typeof record.body?.id === 'string' && Array.isArray(record.body.relays));
1984
+ return null;
1985
+ const records = await ownRecords(await contactsRuntime(), { collection: inboxSchema.name }, (record) => Number.isSafeInteger(record.body?.gen) && record.body.gen >= 0 && Array.isArray(record.body.places));
1986
+ return (records.sort((a, b) => b.body.gen - a.body.gen || b.updatedAt.localeCompare(a.updatedAt))[0] ?? null);
1748
1987
  }
1749
- const doorById = async (id) => (await doorRecords()).find((record) => record.body.id === id);
1750
- const forgetKnocksAt = (door) => {
1751
- for (const [knock, cached] of knockCache)
1752
- if (cached.door === door)
1753
- knockCache.delete(knock);
1754
- };
1755
- async function doorView(record) {
1988
+ async function inboxView(record) {
1756
1989
  const body = record.body;
1757
- const keys = await doorKeys(body.id);
1990
+ const keys = await inboxKeys(body.gen);
1758
1991
  return Object.freeze({
1759
- id: body.id,
1760
- ...(body.label ? { label: body.label } : {}),
1992
+ gen: body.gen,
1761
1993
  ...(body.name ? { name: body.name } : {}),
1762
1994
  key: keys.publicKey,
1763
1995
  sign: keys.signPublic,
1764
- relays: Object.freeze([...body.relays]),
1765
- code: encodeDoorCode({
1996
+ places: Object.freeze([...body.places]),
1997
+ code: await encodeInbox(keys.sign, {
1766
1998
  key: keys.publicKey,
1767
1999
  sign: keys.signPublic,
1768
- relays: body.relays,
2000
+ gen: body.gen,
2001
+ places: body.places,
1769
2002
  ...(body.name ? { name: body.name } : {}),
1770
- }),
1771
- createdAt: record.createdAt,
2003
+ }, provider),
2004
+ updatedAt: record.updatedAt,
1772
2005
  });
1773
2006
  }
1774
- /** Clears knocks from every relay a door names, as its owner; how many relays did */
1775
- async function purgeDoor(door, ids) {
1776
- const keys = await doorKeys(door.id);
1777
- const done = await Promise.allSettled(door.relays.map((relay) => mailbox.purge(relay, keys.topic, keys.signPublic, ids, (nonce) => signPurge(keys.sign, keys.topic, nonce, ids))));
2007
+ /** Writes the inbox's settings, checked the way a knocker will read its code */
2008
+ async function writeInbox(body, current) {
2009
+ const keys = await inboxKeys(body.gen);
2010
+ await encodeInbox(keys.sign, { ...body, key: keys.publicKey, sign: keys.signPublic }, provider);
2011
+ const open = await contactsRuntime();
2012
+ await ensureDefined(open, inboxSchema);
2013
+ return inboxView(current ? await open.update(current.key, body) : await open.put(inboxSchema.name, body));
2014
+ }
2015
+ /** Clears knocks from every mailbox an inbox names, as its owner; how many did */
2016
+ async function purgeInbox(body, ids) {
2017
+ const keys = await inboxKeys(body.gen);
2018
+ const done = await Promise.allSettled(body.places.map((place) => mailbox.purge(place, keys.topic, keys.signPublic, ids, (nonce) => signPurge(keys.sign, keys.topic, nonce, ids))));
1778
2019
  return done.filter((result) => result.status === 'fulfilled').length;
1779
2020
  }
1780
2021
  async function sentRecords() {
1781
2022
  if (!contactsSpaceId)
1782
2023
  return [];
1783
- return ownRecords(await contactsRuntime(), { collection: knockSchema.name }, (record) => typeof record.body?.space === 'string' &&
1784
- typeof record.body.sign === 'string' &&
1785
- typeof record.body.invite === 'string');
2024
+ return ownRecords(await contactsRuntime(), { collection: knockSchema.name }, (record) => typeof record.body?.space === 'string' && typeof record.body.invite === 'string');
1786
2025
  }
1787
2026
  /**
1788
- * Knocks of yours: answered ones become contacts, and the invite is closed;
1789
- * ones nobody answered within the knock's life are let go, space and all.
2027
+ * Knocks of yours: one someone joined becomes a contact, and its invite is
2028
+ * closed; one nobody joined within the knock's life is let go, space and all.
1790
2029
  */
1791
2030
  async function settleSent() {
1792
2031
  for (const record of await sentRecords()) {
1793
- const { space, name, sign, invite } = record.body;
2032
+ const { space, name, invite } = record.body;
1794
2033
  if (!(await registry.get(space))) {
1795
2034
  await (await contactsRuntime()).remove(record.key);
1796
2035
  continue;
1797
2036
  }
1798
2037
  const open = await runtime(space);
1799
- const { members } = await open.access();
1800
- let answered = null;
1801
- for (const answer of await open.list({ collection: knockAnswerSchema.name })) {
1802
- const did = answer.root;
1803
- if (!answer.verified ||
1804
- !did ||
1805
- did === config.signer.did ||
1806
- answer.createdBy !== did ||
1807
- typeof answer.body?.sig !== 'string')
1808
- continue;
1809
- if (!members.some((member) => member.did === did))
1810
- continue;
1811
- if (await checkAnswer(sign, space, did, answer.body.sig)) {
1812
- answered = did;
1813
- break;
1814
- }
1815
- }
1816
- if (answered) {
2038
+ // Only the holder of the inbox key could open the invite: whoever joined first is them.
2039
+ const joiner = (await open.access()).members.find((member) => member.did !== config.signer.did)?.did;
2040
+ if (joiner) {
1817
2041
  // Whoever else the invite reached, nobody more joins with it.
1818
2042
  await spaces.closeInvite(space, invite).catch(() => { });
1819
- const given = (await open.profiles()).find((profile) => profile.did === answered)?.name;
1820
- await writeContact({ did: answered, name: given ?? name, space });
2043
+ const given = (await open.profiles()).find((profile) => profile.did === joiner)?.name;
2044
+ await writeContact({ did: joiner, name: given ?? name, space });
1821
2045
  await (await contactsRuntime()).remove(record.key);
1822
2046
  }
1823
2047
  else if (Date.now() - Date.parse(record.createdAt) > KNOCK_TTL_SECONDS * 1000 + DAY_MS) {
@@ -1826,69 +2050,50 @@ export async function createNode(config) {
1826
2050
  }
1827
2051
  }
1828
2052
  }
1829
- /** Writes the answer to knocks this account accepted, once it can write in the space for two */
1830
- async function answerAccepted() {
1831
- for (const record of await contactRecords()) {
1832
- const { did, space, door } = record.body;
1833
- if (typeof door !== 'string' || typeof space !== 'string')
1834
- continue;
1835
- if (!(await registry.get(space)))
1836
- continue;
1837
- const open = await runtime(space);
1838
- const { founder, mine } = await open.access();
1839
- if (!founder && mine.length === 0)
1840
- continue;
1841
- const { sign } = await doorKeys(door);
1842
- try {
1843
- await open.put(knockAnswerSchema.name, {
1844
- sig: await signAnswer(sign, space, config.signer.did),
1845
- });
1846
- }
1847
- catch {
1848
- continue; // The space's definition of answers hasn't arrived yet.
1849
- }
1850
- const { door: _answered, ...rest } = record.body;
1851
- await writeContact({ ...rest, did });
1852
- }
1853
- }
1854
- /** What the mailboxes of this node's doors hold now, opened and cached */
1855
- async function readDoors() {
2053
+ /** What the mailboxes of this node's inbox hold now, opened and cached */
2054
+ async function readKnocks() {
1856
2055
  const now = Date.now();
1857
2056
  for (const [id, cached] of knockCache)
1858
2057
  if (cached.until <= now)
1859
2058
  knockCache.delete(id);
2059
+ const record = await inboxRecord();
2060
+ if (!record)
2061
+ return [];
2062
+ const { gen, places } = record.body;
2063
+ const keys = await inboxKeys(gen);
2064
+ // Every mailbox, in full: an inbox holds 64 knocks at most, and a knock
2065
+ // cleared from another device should go from here too. What was opened
2066
+ // once is not opened again.
2067
+ // One copy per mailbox, at the earliest time that mailbox gives for it.
2068
+ const held = new Map();
2069
+ const fetched = await Promise.allSettled(places.map((place) => mailbox.fetch(place, keys.topic)));
2070
+ for (const [index, result] of fetched.entries()) {
2071
+ if (result.status !== 'fulfilled')
2072
+ continue;
2073
+ const place = places[index];
2074
+ for (const item of result.value) {
2075
+ // A relay's id is only its word: file the knock under the hash of what it is.
2076
+ const id = await knockId(item.blob);
2077
+ const copy = held.get(id) ?? held.set(id, { blob: item.blob, at: new Map() }).get(id);
2078
+ copy.at.set(place, Math.min(copy.at.get(place) ?? item.at, item.at));
2079
+ }
2080
+ }
1860
2081
  const found = [];
1861
- for (const record of await doorRecords()) {
1862
- const { id: doorId, relays } = record.body;
1863
- const keys = await doorKeys(doorId);
1864
- // Every relay, in full: a door holds 64 knocks at most, and a knock
1865
- // cleared from another device should go from here too. What was opened
1866
- // once is not opened again.
1867
- const held = new Map();
1868
- for (const result of await Promise.allSettled(relays.map((relay) => mailbox.fetch(relay, keys.topic)))) {
1869
- if (result.status !== 'fulfilled')
2082
+ for (const [id, copy] of held) {
2083
+ // Each mailbox's copy is judged once, by its own time: one that lies about
2084
+ // when it took a knock can't hide it while another tells the truth.
2085
+ let opened = knockCache.get(id)?.opened ?? null;
2086
+ for (const [place, at] of copy.at) {
2087
+ if (opened || failed.has(`${id}|${place}`))
1870
2088
  continue;
1871
- for (const item of result.value) {
1872
- // A relay's id is only its word: file the knock under the hash of what it is.
1873
- const id = await knockId(item.blob);
1874
- const seen = held.get(id);
1875
- if (!seen || item.at < seen.at)
1876
- held.set(id, { blob: item.blob, at: item.at });
1877
- }
1878
- }
1879
- for (const [id, item] of held) {
1880
- let cached = knockCache.get(id);
1881
- if (!cached) {
1882
- cached = {
1883
- opened: await openKnock(keys.key, item.blob, item.at, provider),
1884
- door: doorId,
1885
- until: item.at + KNOCK_TTL_SECONDS * 1000,
1886
- };
1887
- knockCache.set(id, cached);
1888
- }
1889
- if (cached.opened)
1890
- found.push({ id, door: doorId, opened: cached.opened });
2089
+ opened = await openKnock([keys.key], copy.blob, at, provider);
2090
+ if (opened)
2091
+ knockCache.set(id, { opened, until: at + KNOCK_TTL_SECONDS * 1000 });
2092
+ else
2093
+ failed.add(`${id}|${place}`);
1891
2094
  }
2095
+ if (opened)
2096
+ found.push({ id, opened });
1892
2097
  }
1893
2098
  return found;
1894
2099
  }
@@ -1953,102 +2158,76 @@ export async function createNode(config) {
1953
2158
  return found.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.key.localeCompare(b.key));
1954
2159
  },
1955
2160
  });
1956
- const doors = Object.freeze({
1957
- async list() {
1958
- if (!config.contactKey || !doorsAllowed())
1959
- return [];
1960
- return Promise.all((await doorRecords()).map(doorView));
2161
+ const inbox = Object.freeze({
2162
+ async get() {
2163
+ if (!config.contactKey || !inboxAllowed())
2164
+ return null;
2165
+ const record = await inboxRecord();
2166
+ return record ? inboxView(record) : null;
1961
2167
  },
1962
2168
  async open(options = {}) {
1963
- requireContactKey('Opening a door');
2169
+ requireContactKey('Opening your inbox');
1964
2170
  if (!contactsSpaceId)
1965
2171
  await contactsRuntime();
1966
- const relays = [...(options.relays ?? usableRelays(config.network))].slice(0, MAX_DOOR_RELAYS);
1967
- if (relays.length === 0)
1968
- throw new Error('A door needs a relay to hold its knocks, and this node has none.');
1969
- const name = clip((options.name ?? (await ownName()) ?? '').trim(), 64);
1970
- const label = options.label ? clip(options.label.trim(), 64) : '';
1971
- const id = base64UrlEncode(globalThis.crypto.getRandomValues(new Uint8Array(16)));
1972
- // Checks the relays and name the way a knocker will.
1973
- const keys = await doorKeys(id);
1974
- encodeDoorCode({ key: keys.publicKey, sign: keys.signPublic, relays, ...(name ? { name } : {}) });
1975
- const open = await contactsRuntime();
1976
- await ensureDefined(open, doorSchema);
1977
- return doorView(await open.put(doorSchema.name, {
1978
- id,
1979
- relays,
1980
- ...(name ? { name } : {}),
1981
- ...(label ? { label } : {}),
1982
- }));
2172
+ const current = await inboxRecord();
2173
+ const places = [...(options.places ?? current?.body?.places ?? usableRelays(config.network))].slice(0, MAX_INBOX_PLACES);
2174
+ if (places.length === 0)
2175
+ throw new Error('An inbox needs a mailbox to hold its knocks, and this node has none.');
2176
+ const name = clip((options.name ?? current?.body?.name ?? (await ownName()) ?? '').trim(), 64);
2177
+ return writeInbox({ gen: current?.body?.gen ?? 0, places, ...(name ? { name } : {}) }, current);
1983
2178
  },
1984
- async close(id) {
1985
- const found = await doorById(id);
1986
- if (found)
1987
- await (await contactsRuntime()).remove(found.key);
1988
- forgetKnocksAt(id);
2179
+ async rotate() {
2180
+ requireContactKey('Replacing your inbox');
2181
+ const current = await inboxRecord();
2182
+ if (!current)
2183
+ return inbox.open();
2184
+ // What waits in the old one goes with it.
2185
+ await purgeInbox(current.body, null).catch(() => 0);
2186
+ knockCache.clear();
2187
+ failed.clear();
2188
+ return writeInbox({ ...current.body, gen: current.body.gen + 1 }, current);
1989
2189
  },
1990
- async clear(id) {
1991
- requireContactKey('Clearing a door');
1992
- const found = await doorById(id);
1993
- if (!found)
1994
- throw new Error('There is no such door');
1995
- if ((await purgeDoor(found.body, null)) === 0)
1996
- throw new Error("None of the door's relays could be reached to clear it.");
1997
- forgetKnocksAt(id);
2190
+ async clear() {
2191
+ requireContactKey('Clearing your inbox');
2192
+ const current = await inboxRecord();
2193
+ if (!current)
2194
+ throw new Error('Your inbox is not open');
2195
+ if ((await purgeInbox(current.body, null)) === 0)
2196
+ throw new Error("None of your inbox's mailboxes could be reached to clear it.");
2197
+ knockCache.clear();
2198
+ failed.clear();
1998
2199
  },
1999
2200
  async knock(code, options = {}) {
2000
- requireContactKey('Knocking on a door');
2001
- requireEverywhere('Knocking on a door');
2002
- const door = parseDoorCode(code);
2003
- for (const mine of await doors.list())
2004
- if (mine.key === door.key)
2005
- throw new Error('That is one of your own doors');
2201
+ requireContactKey('Knocking');
2202
+ requireEverywhere('Knocking');
2203
+ const theirs = await readInboxCode(code, provider);
2204
+ if ((await inbox.get())?.key === theirs.key)
2205
+ throw new Error('That is your own inbox');
2006
2206
  if (!contactsSpaceId)
2007
2207
  await contactsRuntime();
2008
2208
  const mine = (await ownName()) ?? 'Someone';
2009
- const theirs = door.name ?? 'Contact';
2010
- const pair = await spaces.create({
2011
- name: `${clip(mine, 64)} & ${theirs}`,
2012
- visibility: 'private',
2013
- ...team,
2014
- });
2015
- let invite;
2016
- try {
2017
- // Defined now, by the one who may: the answer is written by someone who joins as an editor.
2018
- await ensureDefined(await runtime(pair.id), knockAnswerSchema);
2019
- invite = await spaces.invite(pair.id, { role: 'editor' });
2020
- const blob = await sealKnock(door.key, { from: config.signer.did, name: mine, invite, ...(options.note ? { note: options.note } : {}) }, { did: session.did, key: session.key, proof: current }, provider);
2021
- const topic = await doorTopic(door.sign);
2022
- const left = await Promise.allSettled(door.relays.map((relay) => mailbox.drop(relay, topic, blob, KNOCK_TTL_SECONDS)));
2023
- if (!left.some((result) => result.status === 'fulfilled')) {
2024
- const reasons = left
2025
- .map((result) => (result.status === 'rejected' ? reasonText(result.reason) : ''))
2026
- .filter(Boolean);
2027
- throw new Error(`None of their door's relays took the knock. ${reasons.join('; ')}`);
2028
- }
2029
- }
2030
- catch (error) {
2031
- await spaces.leave(pair.id).catch(() => { });
2032
- throw error;
2209
+ const name = theirs.name ?? 'Contact';
2210
+ const made = await makePair(theirs.key, { mine, theirs: name }, options.note);
2211
+ const topic = await inboxTopic(theirs.sign);
2212
+ const left = await Promise.allSettled(theirs.places.map((place) => mailbox.drop(place, topic, made.sealed, KNOCK_TTL_SECONDS)));
2213
+ if (!left.some((result) => result.status === 'fulfilled')) {
2214
+ await spaces.leave(made.space).catch(() => { });
2215
+ const reasons = left
2216
+ .map((result) => (result.status === 'rejected' ? reasonText(result.reason) : ''))
2217
+ .filter(Boolean);
2218
+ throw new Error(`None of their inbox's mailboxes took the knock. ${reasons.join('; ')}`);
2033
2219
  }
2034
2220
  const open = await contactsRuntime();
2035
2221
  await ensureDefined(open, knockSchema);
2036
- await open.put(knockSchema.name, {
2037
- space: pair.id,
2038
- name: theirs,
2039
- door: door.key,
2040
- sign: door.sign,
2041
- invite,
2042
- });
2043
- return { space: pair.id };
2222
+ await open.put(knockSchema.name, { space: made.space, name, invite: made.invite });
2223
+ return { space: made.space, carried: made.carried };
2044
2224
  },
2045
2225
  async knocks() {
2046
2226
  requireContactKey('Reading knocks');
2047
2227
  await settleSent().catch(() => { });
2048
- await answerAccepted().catch(() => { });
2049
2228
  const blocked = await blockedDids();
2050
2229
  const found = [];
2051
- for (const { id, door, opened } of await readDoors()) {
2230
+ for (const { id, opened } of await readKnocks()) {
2052
2231
  if (opened.from === config.signer.did || blocked.has(opened.from))
2053
2232
  continue;
2054
2233
  // Already accepted, here or on another device.
@@ -2056,7 +2235,6 @@ export async function createNode(config) {
2056
2235
  continue;
2057
2236
  found.push(Object.freeze({
2058
2237
  id,
2059
- door,
2060
2238
  from: opened.from,
2061
2239
  name: opened.name,
2062
2240
  ...(opened.note ? { note: opened.note } : {}),
@@ -2071,40 +2249,32 @@ export async function createNode(config) {
2071
2249
  return (await sentRecords()).map((record) => Object.freeze({ space: record.body.space, name: record.body.name, at: record.createdAt }));
2072
2250
  },
2073
2251
  async accept(id) {
2074
- requireContactKey('Opening the door to someone');
2075
- requireEverywhere('Opening the door to someone');
2252
+ requireContactKey('Accepting a knock');
2253
+ requireEverywhere('Accepting a knock');
2076
2254
  if (!knockCache.get(id)?.opened)
2077
- await readDoors();
2078
- const cached = knockCache.get(id);
2079
- const knocked = cached?.opened;
2080
- if (!cached || !knocked)
2081
- throw new Error('That knock is gone: it expired, or the door was closed or cleared.');
2255
+ await readKnocks();
2256
+ const knocked = knockCache.get(id)?.opened;
2257
+ if (!knocked)
2258
+ throw new Error('That knock is gone: it expired, or your inbox was cleared or replaced.');
2082
2259
  await spaces.join(knocked.invite);
2083
2260
  const known = await contacts.get(knocked.from);
2084
2261
  const contact = await writeContact({
2085
2262
  did: knocked.from,
2086
2263
  name: known?.name ?? knocked.name,
2087
2264
  space: knocked.pairSpace,
2088
- door: cached.door,
2089
2265
  });
2090
- await answerAccepted().catch(() => { });
2091
2266
  // Done with: nobody needs it in the mailboxes any more.
2092
- const door = await doorById(cached.door);
2093
- if (door)
2094
- await purgeDoor(door.body, [id]).catch(() => 0);
2267
+ const current = await inboxRecord();
2268
+ if (current)
2269
+ await purgeInbox(current.body, [id]).catch(() => 0);
2095
2270
  knockCache.delete(id);
2096
2271
  return contact;
2097
2272
  },
2098
2273
  async dismiss(id) {
2099
2274
  requireContactKey('Dismissing a knock');
2100
- if (!knockCache.has(id))
2101
- await readDoors();
2102
- const cached = knockCache.get(id);
2103
- if (!cached)
2104
- return;
2105
- const door = await doorById(cached.door);
2106
- if (door)
2107
- await purgeDoor(door.body, [id]);
2275
+ const current = await inboxRecord();
2276
+ if (current)
2277
+ await purgeInbox(current.body, [id]);
2108
2278
  knockCache.delete(id);
2109
2279
  },
2110
2280
  });
@@ -2275,7 +2445,7 @@ export async function createNode(config) {
2275
2445
  get: async (did) => (contactsGiven() ? contacts.get(did) : null),
2276
2446
  },
2277
2447
  direct: { reachable: async (spaceId) => (allowed(spaceId) ? direct.reachable(spaceId) : []) },
2278
- doors: { list: async () => [] },
2448
+ inbox: { get: async () => null },
2279
2449
  };
2280
2450
  const person = (what) => async () => {
2281
2451
  throw new Error(`An agent can't ${what}. Ask the person to do it.`);
@@ -2302,6 +2472,7 @@ export async function createNode(config) {
2302
2472
  delegation: () => note,
2303
2473
  iceServers: () => node.iceServers(),
2304
2474
  asAgent: person('start another agent'),
2475
+ revokeKey: person('revoke a key'),
2305
2476
  revokeSelf: person('sign the account out'),
2306
2477
  subscribe: (listener) => node.subscribe((event) => {
2307
2478
  if (!('space' in event) || allowed(event.space))
@@ -2323,7 +2494,7 @@ export async function createNode(config) {
2323
2494
  automations,
2324
2495
  contacts,
2325
2496
  direct,
2326
- doors,
2497
+ inbox,
2327
2498
  asAgent,
2328
2499
  delegation: () => current,
2329
2500
  iceServers: async () => (mesh ? mesh.iceServers() : (config.network?.iceServers ?? DEFAULT_ICE_SERVERS)),
@@ -2332,17 +2503,28 @@ export async function createNode(config) {
2332
2503
  reconnect: () => mesh?.reconnect(),
2333
2504
  }),
2334
2505
  subscribe: events.subscribe,
2506
+ async revokeKey(key, options = {}) {
2507
+ // Everywhere the account writes, unless told where: the listed spaces, its carry spaces and contacts space.
2508
+ const ids = options.spaces ?? [
2509
+ ...new Set([
2510
+ ...(await spaces.list()).filter((space) => space.writable).map((space) => space.id),
2511
+ ...(await carrierRecords()).map(({ carry }) => carry.space.id),
2512
+ ...(contactsSpaceId ? [contactsSpaceId] : []),
2513
+ ]),
2514
+ ];
2515
+ const wait = options.waitMs === undefined ? {} : { waitMs: options.waitMs };
2516
+ // Each its own store: one that can't be written (a space gone, or no longer the account's
2517
+ // to write in) has nothing to send, and must not keep the rest from happening.
2518
+ const taken = await Promise.all([
2519
+ ...ids.map((spaceId) => spaces.revoke(spaceId, key, wait).catch(() => true)),
2520
+ ...(options.spaces ? [] : [node.account.revoke(key, wait).catch(() => true)]),
2521
+ ]);
2522
+ return taken.every(Boolean);
2523
+ },
2335
2524
  async revokeSelf(options = {}) {
2336
- const key = sessionDid;
2337
2525
  // Forgotten first: a tab closed while the revokes wait must not leave a
2338
2526
  // revoked key behind, to be claimed and refused on every write after.
2339
2527
  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
2528
  // With anyone online, every revoke waits for a peer to take it in, closed
2347
2529
  // spaces too, which open for it. With nobody, waiting would only keep a
2348
2530
  // person signing out looking at a spinner: they go out with the next sync.
@@ -2352,12 +2534,7 @@ export async function createNode(config) {
2352
2534
  if (rt && (await rt.status()).peers.length > 0)
2353
2535
  anyone = true;
2354
2536
  }
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
- ]);
2537
+ await node.revokeKey(sessionDid, anyone ? options : {});
2361
2538
  },
2362
2539
  async close() {
2363
2540
  if (closed)
@@ -2366,6 +2543,7 @@ export async function createNode(config) {
2366
2543
  stopWatchingNetwork?.();
2367
2544
  if (renewTimer)
2368
2545
  clearTimeout(renewTimer);
2546
+ clearInterval(linkTimer);
2369
2547
  const open = [...runtimes.keys()];
2370
2548
  await Promise.all(open.map((spaceId) => closeRuntime(spaceId)));
2371
2549
  // Let go of the registry too: an open database connection blocks the