@minca/core 0.1.10 → 0.1.12

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 (229) hide show
  1. package/README.md +1 -1
  2. package/dist/identity/abilities.js +1 -1
  3. package/dist/identity/channel.d.ts +1 -1
  4. package/dist/identity/channel.d.ts.map +1 -1
  5. package/dist/identity/channel.js +1 -1
  6. package/dist/identity/channel.js.map +1 -1
  7. package/dist/identity/contact-key.d.ts +15 -15
  8. package/dist/identity/contact-key.d.ts.map +1 -1
  9. package/dist/identity/contact-key.js +21 -28
  10. package/dist/identity/contact-key.js.map +1 -1
  11. package/dist/inbox/inbox.d.ts +132 -0
  12. package/dist/inbox/inbox.d.ts.map +1 -0
  13. package/dist/inbox/inbox.js +197 -0
  14. package/dist/inbox/inbox.js.map +1 -0
  15. package/dist/inbox/index.d.ts +9 -0
  16. package/dist/inbox/index.d.ts.map +1 -0
  17. package/dist/inbox/index.js +7 -0
  18. package/dist/inbox/index.js.map +1 -0
  19. package/dist/index.d.ts +8 -6
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +3 -3
  22. package/dist/index.js.map +1 -1
  23. package/dist/network/introductions.d.ts +1 -1
  24. package/dist/network/introductions.d.ts.map +1 -1
  25. package/dist/network/mesh.d.ts +4 -2
  26. package/dist/network/mesh.d.ts.map +1 -1
  27. package/dist/network/mesh.js +31 -45
  28. package/dist/network/mesh.js.map +1 -1
  29. package/dist/network/peer-auth.d.ts +4 -0
  30. package/dist/network/peer-auth.d.ts.map +1 -1
  31. package/dist/network/peer-auth.js +9 -7
  32. package/dist/network/peer-auth.js.map +1 -1
  33. package/dist/network/relay-minca.d.ts +6 -0
  34. package/dist/network/relay-minca.d.ts.map +1 -0
  35. package/dist/network/relay-minca.js +146 -0
  36. package/dist/network/relay-minca.js.map +1 -0
  37. package/dist/network/relay-nostr.d.ts +10 -0
  38. package/dist/network/relay-nostr.d.ts.map +1 -0
  39. package/dist/network/relay-nostr.js +247 -0
  40. package/dist/network/relay-nostr.js.map +1 -0
  41. package/dist/network/relay-socket.d.ts +87 -0
  42. package/dist/network/relay-socket.d.ts.map +1 -0
  43. package/dist/network/{signaling.js → relay-socket.js} +201 -167
  44. package/dist/network/relay-socket.js.map +1 -0
  45. package/dist/network/relays.d.ts +87 -0
  46. package/dist/network/relays.d.ts.map +1 -0
  47. package/dist/network/relays.js +43 -0
  48. package/dist/network/relays.js.map +1 -0
  49. package/dist/network/remote-transport.d.ts +1 -1
  50. package/dist/network/remote-transport.d.ts.map +1 -1
  51. package/dist/network/remote-transport.js +6 -31
  52. package/dist/network/remote-transport.js.map +1 -1
  53. package/dist/network/rendezvous.d.ts +59 -0
  54. package/dist/network/rendezvous.d.ts.map +1 -0
  55. package/dist/network/rendezvous.js +380 -0
  56. package/dist/network/rendezvous.js.map +1 -0
  57. package/dist/network/rtc-transport.d.ts.map +1 -1
  58. package/dist/network/rtc-transport.js +32 -17
  59. package/dist/network/rtc-transport.js.map +1 -1
  60. package/dist/network/transport.d.ts +7 -5
  61. package/dist/network/transport.d.ts.map +1 -1
  62. package/dist/node/actions.d.ts.map +1 -1
  63. package/dist/node/actions.js +28 -18
  64. package/dist/node/actions.js.map +1 -1
  65. package/dist/node/api.d.ts +11 -10
  66. package/dist/node/api.d.ts.map +1 -1
  67. package/dist/node/api.js +11 -10
  68. package/dist/node/api.js.map +1 -1
  69. package/dist/node/carrier.d.ts +11 -5
  70. package/dist/node/carrier.d.ts.map +1 -1
  71. package/dist/node/carrier.js +43 -2
  72. package/dist/node/carrier.js.map +1 -1
  73. package/dist/node/copy.d.ts +1 -1
  74. package/dist/node/copy.d.ts.map +1 -1
  75. package/dist/node/copy.js +10 -4
  76. package/dist/node/copy.js.map +1 -1
  77. package/dist/node/host.d.ts +2 -0
  78. package/dist/node/host.d.ts.map +1 -1
  79. package/dist/node/host.js +2 -0
  80. package/dist/node/host.js.map +1 -1
  81. package/dist/node/index.d.ts +1 -1
  82. package/dist/node/index.d.ts.map +1 -1
  83. package/dist/node/node.d.ts.map +1 -1
  84. package/dist/node/node.js +490 -298
  85. package/dist/node/node.js.map +1 -1
  86. package/dist/node/remote.d.ts.map +1 -1
  87. package/dist/node/remote.js +0 -2
  88. package/dist/node/remote.js.map +1 -1
  89. package/dist/node/space-runtime.d.ts +6 -2
  90. package/dist/node/space-runtime.d.ts.map +1 -1
  91. package/dist/node/space-runtime.js +5 -8
  92. package/dist/node/space-runtime.js.map +1 -1
  93. package/dist/node/types.d.ts +75 -46
  94. package/dist/node/types.d.ts.map +1 -1
  95. package/dist/react/use-invite-link.d.ts +1 -1
  96. package/dist/react/use-invite-link.d.ts.map +1 -1
  97. package/dist/react/use-invite-link.js +18 -11
  98. package/dist/react/use-invite-link.js.map +1 -1
  99. package/dist/records/loose.d.ts +52 -0
  100. package/dist/records/loose.d.ts.map +1 -0
  101. package/dist/records/loose.js +86 -0
  102. package/dist/records/loose.js.map +1 -0
  103. package/dist/schema/version.d.ts +2 -0
  104. package/dist/schema/version.d.ts.map +1 -1
  105. package/dist/schema/version.js +2 -1
  106. package/dist/schema/version.js.map +1 -1
  107. package/dist/schemas/choosing.d.ts +19 -0
  108. package/dist/schemas/choosing.d.ts.map +1 -0
  109. package/dist/schemas/choosing.js +69 -0
  110. package/dist/schemas/choosing.js.map +1 -0
  111. package/dist/schemas/contacts.d.ts +34 -87
  112. package/dist/schemas/contacts.d.ts.map +1 -1
  113. package/dist/schemas/contacts.js +32 -76
  114. package/dist/schemas/contacts.js.map +1 -1
  115. package/dist/schemas/index.d.ts +2 -2
  116. package/dist/schemas/index.d.ts.map +1 -1
  117. package/dist/schemas/index.js +1 -1
  118. package/dist/schemas/index.js.map +1 -1
  119. package/dist/schemas/library/annotations.d.ts +17 -285
  120. package/dist/schemas/library/annotations.d.ts.map +1 -1
  121. package/dist/schemas/library/annotations.js +9 -65
  122. package/dist/schemas/library/annotations.js.map +1 -1
  123. package/dist/schemas/library/community.d.ts +9 -17
  124. package/dist/schemas/library/community.d.ts.map +1 -1
  125. package/dist/schemas/library/community.js +5 -5
  126. package/dist/schemas/library/community.js.map +1 -1
  127. package/dist/schemas/library/life.d.ts +3 -3
  128. package/dist/schemas/library/life.d.ts.map +1 -1
  129. package/dist/schemas/library/life.js +2 -2
  130. package/dist/schemas/library/life.js.map +1 -1
  131. package/dist/schemas/library/media.d.ts +148 -541
  132. package/dist/schemas/library/media.d.ts.map +1 -1
  133. package/dist/schemas/library/media.js +28 -64
  134. package/dist/schemas/library/media.js.map +1 -1
  135. package/dist/schemas/library/money.d.ts +8 -8
  136. package/dist/schemas/library/money.d.ts.map +1 -1
  137. package/dist/schemas/library/money.js +4 -4
  138. package/dist/schemas/library/money.js.map +1 -1
  139. package/dist/schemas/library/planning.d.ts +23 -87
  140. package/dist/schemas/library/planning.d.ts.map +1 -1
  141. package/dist/schemas/library/planning.js +10 -26
  142. package/dist/schemas/library/planning.js.map +1 -1
  143. package/dist/schemas/library/publishing.d.ts +14 -14
  144. package/dist/schemas/library/publishing.d.ts.map +1 -1
  145. package/dist/schemas/library/publishing.js +7 -7
  146. package/dist/schemas/library/publishing.js.map +1 -1
  147. package/dist/schemas/library/social.d.ts +2 -2
  148. package/dist/schemas/library/social.d.ts.map +1 -1
  149. package/dist/schemas/library/social.js +1 -1
  150. package/dist/schemas/library/social.js.map +1 -1
  151. package/dist/schemas/standard.d.ts +1 -1
  152. package/dist/schemas/standard.d.ts.map +1 -1
  153. package/dist/schemas/standard.js +3 -3
  154. package/dist/schemas/standard.js.map +1 -1
  155. package/dist/session/auth.d.ts +5 -6
  156. package/dist/session/auth.d.ts.map +1 -1
  157. package/dist/session/auth.js +5 -6
  158. package/dist/session/auth.js.map +1 -1
  159. package/dist/session/channel-room.d.ts.map +1 -1
  160. package/dist/session/channel-room.js +3 -2
  161. package/dist/session/channel-room.js.map +1 -1
  162. package/dist/session/connect-code.d.ts +69 -55
  163. package/dist/session/connect-code.d.ts.map +1 -1
  164. package/dist/session/connect-code.js +189 -89
  165. package/dist/session/connect-code.js.map +1 -1
  166. package/dist/session/connect.d.ts +11 -15
  167. package/dist/session/connect.d.ts.map +1 -1
  168. package/dist/session/connect.js +8 -21
  169. package/dist/session/connect.js.map +1 -1
  170. package/dist/session/index.d.ts +2 -2
  171. package/dist/session/index.d.ts.map +1 -1
  172. package/dist/session/index.js +1 -1
  173. package/dist/session/index.js.map +1 -1
  174. package/dist/space/account-registry.d.ts +22 -0
  175. package/dist/space/account-registry.d.ts.map +1 -1
  176. package/dist/space/account-registry.js +18 -0
  177. package/dist/space/account-registry.js.map +1 -1
  178. package/dist/space/invitation.d.ts +61 -0
  179. package/dist/space/invitation.d.ts.map +1 -0
  180. package/dist/space/invitation.js +84 -0
  181. package/dist/space/invitation.js.map +1 -0
  182. package/dist/space/invite-link.d.ts +64 -0
  183. package/dist/space/invite-link.d.ts.map +1 -0
  184. package/dist/space/invite-link.js +212 -0
  185. package/dist/space/invite-link.js.map +1 -0
  186. package/dist/space/roles.d.ts.map +1 -1
  187. package/dist/space/roles.js +4 -2
  188. package/dist/space/roles.js.map +1 -1
  189. package/dist/space/space-manager.d.ts +21 -6
  190. package/dist/space/space-manager.d.ts.map +1 -1
  191. package/dist/space/space-manager.js +40 -23
  192. package/dist/space/space-manager.js.map +1 -1
  193. package/dist/types.d.ts +2 -0
  194. package/dist/types.d.ts.map +1 -1
  195. package/dist/types.js.map +1 -1
  196. package/docs/README.md +2 -2
  197. package/docs/actions.md +37 -37
  198. package/docs/agents.md +59 -37
  199. package/docs/automations.md +2 -2
  200. package/docs/blueprints-and-guides.md +44 -3
  201. package/docs/building-an-app.md +2 -2
  202. package/docs/contacts.md +48 -69
  203. package/docs/inbox.md +145 -0
  204. package/docs/node.md +68 -45
  205. package/docs/query-format.md +1 -1
  206. package/docs/sign-in.md +5 -7
  207. package/docs/spaces.md +33 -5
  208. package/docs/standard-library.md +111 -86
  209. package/package.json +6 -5
  210. package/dist/doors/doors.d.ts +0 -140
  211. package/dist/doors/doors.d.ts.map +0 -1
  212. package/dist/doors/doors.js +0 -226
  213. package/dist/doors/doors.js.map +0 -1
  214. package/dist/doors/index.d.ts +0 -9
  215. package/dist/doors/index.d.ts.map +0 -1
  216. package/dist/doors/index.js +0 -7
  217. package/dist/doors/index.js.map +0 -1
  218. package/dist/network/mailbox.d.ts +0 -45
  219. package/dist/network/mailbox.d.ts.map +0 -1
  220. package/dist/network/mailbox.js +0 -135
  221. package/dist/network/mailbox.js.map +0 -1
  222. package/dist/network/multi-signaling.d.ts +0 -41
  223. package/dist/network/multi-signaling.d.ts.map +0 -1
  224. package/dist/network/multi-signaling.js +0 -209
  225. package/dist/network/multi-signaling.js.map +0 -1
  226. package/dist/network/signaling.d.ts +0 -95
  227. package/dist/network/signaling.d.ts.map +0 -1
  228. package/dist/network/signaling.js.map +0 -1
  229. package/docs/doors.md +0 -151
package/dist/node/node.js CHANGED
@@ -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';
38
- import { createMailboxClient } from '../network/mailbox.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';
39
+ import { createMailboxClient } from '../network/relays.js';
39
40
  import { team } from '../space/presets.js';
40
- import { CARRIER_COLLECTION, deriveAccountRegistry, deriveCarrySpace, 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';
@@ -47,6 +48,8 @@ export const SESSION_COMMAND = ALL_COMMAND;
47
48
  const DEFAULT_TTL_SECONDS = 3600;
48
49
  /** How long leaving waits for a peer to take the account's removal before forgetting the space anyway */
49
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;
50
53
  function summarize(record) {
51
54
  const { space, key } = record;
52
55
  return Object.freeze({
@@ -130,14 +133,16 @@ export async function createNode(config) {
130
133
  // node's stores (`node/writers.ts`).
131
134
  const handedIn = await config.stores('writers');
132
135
  const writers = createWriters((did) => did !== sessionDid ? handedIn : (claimed?.heads ?? (config.sessionKey ? handedIn : null)));
133
- const mesh = meshFor(config.network, sessionDid);
136
+ const mesh = meshFor(config.network, session);
134
137
  /**
135
138
  * A node whose note doesn't let it act as the account itself — an app, or
136
139
  * an agent on someone's computer running a node of its own. It may follow
137
140
  * the account, but never writes for it: no list of spaces, no passes, no
138
- * name, no doors. Every peer would ignore those (spec 01 §8).
141
+ * name, no inbox. Every peer would ignore those (spec 01 §8).
139
142
  */
140
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 });
141
146
  // ─── Events ────────────────────────────────────────────────────────
142
147
  const events = createListeners('node event');
143
148
  const { emit } = events;
@@ -168,7 +173,7 @@ export async function createNode(config) {
168
173
  const contactsSpaceId = contactsRecord?.space.id ?? config.contactsSpace ?? null;
169
174
  // Kept in the node's own list like a joined space, so it can be shared with an app like one.
170
175
  if (contactsRecord && !(await registry.get(contactsRecord.space.id))) {
171
- await joinRegistry(await encodeSpaceInvite(contactsRecord, config.signer.did));
176
+ await joinRegistry(await encodeSpaceInvite(contactsRecord, looseSigner(), provider));
172
177
  }
173
178
  /** Which of the account's own spaces this is, or null for one it uses */
174
179
  async function kindOf(spaceId) {
@@ -188,11 +193,34 @@ export async function createNode(config) {
188
193
  async function inviteTo(spaceId, options = {}) {
189
194
  const named = (await findRecord(spaceId))?.relays ?? [];
190
195
  const own = usableRelays(config.network).slice(0, MAX_RELAYS);
191
- return registry.createInvite(spaceId, config.signer.did, {
196
+ const nodes = await nodesOf(spaceId);
197
+ return registry.createInvite(spaceId, looseSigner(), {
192
198
  ...options,
193
199
  ...(named.length ? {} : own.length ? { relays: own } : {}),
200
+ ...(nodes.length ? { nodes } : {}),
194
201
  });
195
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
+ }
196
224
  async function findRecord(spaceId) {
197
225
  if (spaceId === accountSpaceId)
198
226
  return account;
@@ -589,6 +617,11 @@ export async function createNode(config) {
589
617
  return;
590
618
  const carry = await runtime(carrier.carry.space.id);
591
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:'));
592
625
  const wakes = new Map();
593
626
  for (const own of owned) {
594
627
  const wake = await wakeFor(own, spaces, config.signer.did);
@@ -720,8 +753,190 @@ export async function createNode(config) {
720
753
  carryTurn = run;
721
754
  return run;
722
755
  };
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()) {
848
+ if (closed)
849
+ return;
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);
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
+ }
723
936
  /** Every carrier the account uses gets its passes and wakes as they are now, one run at a time */
724
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(() => { });
725
940
  for (const carrier of await liveCarriers()) {
726
941
  if (closed)
727
942
  return;
@@ -762,8 +977,11 @@ export async function createNode(config) {
762
977
  return summarize(record);
763
978
  },
764
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);
765
983
  if (options.write === false)
766
- return inviteTo(spaceId);
984
+ return share();
767
985
  const open = await runtime(spaceId);
768
986
  const { roles, founder, mine } = await open.access();
769
987
  const member = founder || mine.length > 0;
@@ -778,14 +996,22 @@ export async function createNode(config) {
778
996
  throw new Error(member
779
997
  ? `There is no role "${options.role}"`
780
998
  : 'You hold no role here, so you can only share it to view');
781
- return inviteTo(spaceId);
999
+ return share();
782
1000
  }
783
- const { secret } = await open.openInvite(role);
784
- 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 } : {}) };
785
1012
  },
786
- preview: previewInvite,
787
1013
  async join(invite, options = {}) {
788
- const record = await joinRegistry(bareInvite(invite));
1014
+ const record = await joinRegistry((await resolveInvite(invite)).long);
789
1015
  if (options.memberKey)
790
1016
  await registry.setMemberKey(record.space.id, options.memberKey);
791
1017
  // A runtime opened before the key arrived would still be unable to read.
@@ -845,6 +1071,28 @@ export async function createNode(config) {
845
1071
  carriers: status.peers.filter((peer) => carrierKeys.has(peer)),
846
1072
  };
847
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
+ },
848
1096
  profiles: perSpace((rt) => rt.profiles()),
849
1097
  access: perSpace((rt) => rt.access()),
850
1098
  may: perSpace((rt, cmd, args, account) => rt.may(cmd, args, account)),
@@ -864,13 +1112,20 @@ export async function createNode(config) {
864
1112
  async closeInvite(spaceId, keyOrLink) {
865
1113
  let key = keyOrLink;
866
1114
  // The link itself will do: its secret names the invite.
867
- 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:')) {
868
1121
  const secret = parseSpaceInvite(bareInvite(keyOrLink)).invite;
869
1122
  if (!secret)
870
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).');
871
1124
  key = (await deriveInviteKey(base64UrlDecode(secret), provider)).did;
872
1125
  }
873
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);
874
1129
  },
875
1130
  revoke: perSpace((rt, key, options) => rt.revoke(key, options)),
876
1131
  changeKey: perSpace((rt) => rt.rotateKey()),
@@ -986,7 +1241,10 @@ export async function createNode(config) {
986
1241
  // Not in turn behind a refill: nothing removes a carrier that is only now being added.
987
1242
  await syncPasses(entry);
988
1243
  }
989
- return { space: entry.carry.space.id, invite: await encodeSpaceInvite(entry.carry, config.signer.did) };
1244
+ return {
1245
+ space: entry.carry.space.id,
1246
+ invite: await encodeSpaceInvite(entry.carry, looseSigner(), provider),
1247
+ };
990
1248
  },
991
1249
  settled: (waitMs) => within(passAll.done(), waitMs),
992
1250
  async reached(spaceId, waitMs) {
@@ -1318,8 +1576,15 @@ export async function createNode(config) {
1318
1576
  // Asked only while it is still open: asking would open it again.
1319
1577
  if (!(await kindOf(spaceId)) && runtimes.get(spaceId) === open)
1320
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] ?? '')));
1321
1586
  const peers = [
1322
- ...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)),
1323
1588
  ].sort();
1324
1589
  const said = peers.join(' ');
1325
1590
  if (reaching.get(spaceId) === said || runtimes.get(spaceId) !== open)
@@ -1441,15 +1706,12 @@ export async function createNode(config) {
1441
1706
  // ─── Contacts ──────────────────────────────────────────────────────
1442
1707
  //
1443
1708
  // One `std.contact` per person in the contacts space, keyed by their DID, so
1444
- // there is one per person on every device. Asking someone is a
1445
- // `std.contact-request` in a space you share: the invite to a new space for
1446
- // two, sealed with their contact key, bound to the space it was posted in and
1447
- // to who asked whom — so it opens only for them, only there, and only as
1448
- // 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.
1449
1713
  // The key `onePer: ['did']` derives, so the record for someone is the same one on every device.
1450
1714
  const contactRecordKey = async (did) => (await contactsRuntime()).onePerKey(contactSchema.name, { did }, { onePer: contactSchema.rules.onePer });
1451
- /** The HPKE label a contact request is sealed under; bound to `{ space, from, to }` */
1452
- const REQUEST_LABEL = 'minca/contact-request/v1';
1453
1715
  async function contactsRuntime() {
1454
1716
  if (!contactsSpaceId)
1455
1717
  throw new Error('This app was not given your contacts. Connect to your account home again, and allow contacts.');
@@ -1515,38 +1777,49 @@ export async function createNode(config) {
1515
1777
  return;
1516
1778
  await spaces.leave(spaceId);
1517
1779
  }
1518
- /** A contact request, opened — or null when it isn't one for this account, from the account that wrote it */
1519
- async function openRequest(spaceId, record) {
1520
- if (!contactKeys || !record.verified || record.collection !== contactRequestSchema.name)
1521
- return null;
1522
- if (record.body?.to !== config.signer.did || typeof record.body.sealed !== 'string')
1523
- return null;
1524
- // Asking makes a space for two for the account, as a knock does: only a note that may write for all of it.
1525
- const note = await (await runtime(spaceId)).noteOf(record.key);
1526
- if (!actsForAccount(note))
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)
1527
1789
  return null;
1528
- const from = record.root;
1529
- 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')
1530
1792
  return null;
1531
- const value = await openValueFrom(contactKeys, REQUEST_LABEL, { space: spaceId, from, to: config.signer.did }, record.body.sealed);
1532
- if (!isRecord(value) || typeof value.invite !== 'string')
1793
+ const opened = await openKnock([config.contactKey], body.sealed, provider);
1794
+ if (!opened || opened.from !== record.root || opened.from === config.signer.did)
1533
1795
  return null;
1534
- 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
+ });
1535
1810
  try {
1536
- 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 };
1537
1818
  }
1538
- catch {
1539
- return null;
1819
+ catch (error) {
1820
+ await spaces.leave(pair.id).catch(() => { });
1821
+ throw error;
1540
1822
  }
1541
- // A private space the asker made, and the key to it: anything else isn't a space for two from them.
1542
- if (soleFounder(invited.space) !== from || invited.space.visibility !== 'private' || !invited.key)
1543
- return null;
1544
- return {
1545
- from,
1546
- invite: value.invite,
1547
- ...(typeof value.note === 'string' && value.note ? { note: value.note.slice(0, 2000) } : {}),
1548
- pairSpace: invited.space.id,
1549
- };
1550
1823
  }
1551
1824
  const contacts = Object.freeze({
1552
1825
  async space() {
@@ -1567,14 +1840,11 @@ export async function createNode(config) {
1567
1840
  const name = contact.name.trim().slice(0, 200);
1568
1841
  if (!name)
1569
1842
  throw new Error('A contact needs a name');
1570
- // An answer to their knock still to be written stays to be written.
1571
- const pending = (await contactRecords()).find((record) => record.body.did === contact.did)?.body?.door;
1572
1843
  return writeContact({
1573
1844
  did: contact.did,
1574
1845
  name,
1575
1846
  ...(contact.space ? { space: contact.space } : {}),
1576
1847
  ...(contact.note ? { note: contact.note.slice(0, 2000) } : {}),
1577
- ...(pending ? { door: pending } : {}),
1578
1848
  });
1579
1849
  },
1580
1850
  async remove(did) {
@@ -1608,15 +1878,16 @@ export async function createNode(config) {
1608
1878
  if (!theirs?.contactKey) {
1609
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.");
1610
1880
  }
1611
- await ensureDefined(shared, contactRequestSchema);
1612
1881
  const mine = (await ownName()) ?? profiles.find((profile) => profile.did === config.signer.did)?.name ?? 'Me';
1613
- const pair = await spaces.create({ name: `${mine} & ${theirs.name}`, visibility: 'private', ...team });
1614
- const invite = await spaces.invite(pair.id, { role: 'editor' });
1615
- await writeContact({ did, name: theirs.name, space: pair.id });
1616
1882
  const note = options.note?.trim().slice(0, 2000);
1617
- const sealed = await sealValueTo(theirs.contactKey, REQUEST_LABEL, { space: spaceId, from: config.signer.did, to: did }, { invite, ...(note ? { note } : {}) });
1618
- const request = await shared.put(contactRequestSchema.name, { to: did, sealed });
1619
- 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 };
1620
1891
  },
1621
1892
  async requests(spaceId) {
1622
1893
  requireContactKeys();
@@ -1624,10 +1895,8 @@ export async function createNode(config) {
1624
1895
  const blocked = await blockedDids();
1625
1896
  const names = new Map((await shared.profiles()).map((profile) => [profile.did, profile.name]));
1626
1897
  const found = [];
1627
- for (const record of await shared.list({
1628
- collection: contactRequestSchema.name,
1629
- })) {
1630
- const opened = await openRequest(spaceId, record);
1898
+ for (const record of await shared.list({ collection: contactRequestSchema.name })) {
1899
+ const opened = await openMail(record);
1631
1900
  if (!opened || blocked.has(opened.from))
1632
1901
  continue;
1633
1902
  // Already accepted, here or on another device.
@@ -1649,14 +1918,13 @@ export async function createNode(config) {
1649
1918
  requireEverywhere('Accepting a contact request');
1650
1919
  requireContactKeys();
1651
1920
  const shared = await runtime(spaceId);
1652
- const record = await shared.get(requestKey);
1653
- const opened = record ? await openRequest(spaceId, record) : null;
1921
+ const opened = await openMail(await shared.get(requestKey));
1654
1922
  if (!opened)
1655
1923
  throw new Error('That contact request is gone, or is not for you.');
1656
1924
  await spaces.join(opened.invite);
1657
1925
  const name = (await shared.profiles()).find((profile) => profile.did === opened.from)?.name ??
1658
1926
  (await contacts.get(opened.from))?.name ??
1659
- opened.from;
1927
+ opened.name;
1660
1928
  return writeContact({ did: opened.from, name, space: opened.pairSpace });
1661
1929
  },
1662
1930
  async others(did) {
@@ -1677,117 +1945,103 @@ export async function createNode(config) {
1677
1945
  return [...seen].filter((account) => account !== config.signer.did && account !== did).sort();
1678
1946
  },
1679
1947
  });
1680
- // ─── Doors ─────────────────────────────────────────────────────────
1948
+ // ─── The inbox ─────────────────────────────────────────────────────
1681
1949
  //
1682
- // A door is a `std.door` in the contacts space; its keys are derived from
1683
- // the contact key and its id, so every device with the contact key opens the
1684
- // 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.
1685
1953
  //
1686
- // A knock you left is a `std.knock` until the person behind the door
1687
- // answers in the space for two — a `std.knock-answer` signed with the
1688
- // door's signing key — when it becomes a contact and the invite is closed.
1689
- // Accepting a knock writes that answer as soon as this account's membership
1690
- // there has landed; until then the contact carries the door's id.
1691
- // See `packages/core/src/doors/doors.ts`.
1692
- const mailbox = config.mailbox ?? createMailboxClient();
1693
- /** 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 */
1694
1959
  const knockCache = new Map();
1960
+ /** Knocks that didn't check out, by id, and until when they are not opened again: one dated a little ahead may pass later */
1961
+ const failed = new Map();
1695
1962
  const DAY_MS = 24 * 3600 * 1000;
1696
- /** Doors are the account's own, in its contacts space: only a key acting as the account opens one, as every peer checks */
1697
- const doorsAllowed = () => contactsSpaceId !== null && !narrowNote;
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;
1698
1965
  function requireContactKey(what) {
1699
- // Doors are the account's: a key whose note doesn't grant `/account/write` never opens one or knocks.
1700
- if (!doorsAllowed())
1701
- 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.`);
1702
1969
  if (!config.contactKey)
1703
1970
  throw new Error(`${what} needs your contact key. Connect to your account home again, and allow contacts.`);
1704
1971
  return config.contactKey;
1705
1972
  }
1706
- /** A door's keys, from the contact key and its id */
1707
- async function doorKeys(id) {
1708
- const contactKey = requireContactKey('A door');
1709
- const key = await deriveDoorKeyBytes(contactKey, id);
1710
- 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);
1711
1978
  const signPublic = contactPublicKey(sign);
1712
- return { key, sign, publicKey: contactPublicKey(key), signPublic, topic: await doorTopic(signPublic) };
1979
+ return { key, sign, publicKey: contactPublicKey(key), signPublic, topic: await inboxTopic(signPublic) };
1713
1980
  }
1714
- async function doorRecords() {
1981
+ /** The account's inbox: the newest `std.inbox` of the highest gen */
1982
+ async function inboxRecord() {
1715
1983
  if (!contactsSpaceId)
1716
- return [];
1717
- 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);
1718
1987
  }
1719
- const doorById = async (id) => (await doorRecords()).find((record) => record.body.id === id);
1720
- const forgetKnocksAt = (door) => {
1721
- for (const [knock, cached] of knockCache)
1722
- if (cached.door === door)
1723
- knockCache.delete(knock);
1724
- };
1725
- async function doorView(record) {
1988
+ async function inboxView(record) {
1726
1989
  const body = record.body;
1727
- const keys = await doorKeys(body.id);
1990
+ const keys = await inboxKeys(body.gen);
1728
1991
  return Object.freeze({
1729
- id: body.id,
1730
- ...(body.label ? { label: body.label } : {}),
1992
+ gen: body.gen,
1731
1993
  ...(body.name ? { name: body.name } : {}),
1732
1994
  key: keys.publicKey,
1733
1995
  sign: keys.signPublic,
1734
- relays: Object.freeze([...body.relays]),
1735
- code: encodeDoorCode({
1996
+ places: Object.freeze([...body.places]),
1997
+ code: await encodeInbox(keys.sign, {
1736
1998
  key: keys.publicKey,
1737
1999
  sign: keys.signPublic,
1738
- relays: body.relays,
2000
+ gen: body.gen,
2001
+ places: body.places,
1739
2002
  ...(body.name ? { name: body.name } : {}),
1740
- }),
1741
- createdAt: record.createdAt,
2003
+ }, provider),
2004
+ updatedAt: record.updatedAt,
1742
2005
  });
1743
2006
  }
1744
- /** Clears knocks from every relay a door names, as its owner; how many relays did */
1745
- async function purgeDoor(door, ids) {
1746
- const keys = await doorKeys(door.id);
1747
- 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))));
1748
2019
  return done.filter((result) => result.status === 'fulfilled').length;
1749
2020
  }
1750
2021
  async function sentRecords() {
1751
2022
  if (!contactsSpaceId)
1752
2023
  return [];
1753
- return ownRecords(await contactsRuntime(), { collection: knockSchema.name }, (record) => typeof record.body?.space === 'string' &&
1754
- typeof record.body.sign === 'string' &&
1755
- typeof record.body.invite === 'string');
2024
+ return ownRecords(await contactsRuntime(), { collection: knockSchema.name }, (record) => typeof record.body?.space === 'string' && typeof record.body.invite === 'string');
1756
2025
  }
1757
2026
  /**
1758
- * Knocks of yours: answered ones become contacts, and the invite is closed;
1759
- * 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.
1760
2029
  */
1761
2030
  async function settleSent() {
1762
2031
  for (const record of await sentRecords()) {
1763
- const { space, name, sign, invite } = record.body;
2032
+ const { space, name, invite } = record.body;
1764
2033
  if (!(await registry.get(space))) {
1765
2034
  await (await contactsRuntime()).remove(record.key);
1766
2035
  continue;
1767
2036
  }
1768
2037
  const open = await runtime(space);
1769
- const { members } = await open.access();
1770
- let answered = null;
1771
- for (const answer of await open.list({ collection: knockAnswerSchema.name })) {
1772
- const did = answer.root;
1773
- if (!answer.verified ||
1774
- !did ||
1775
- did === config.signer.did ||
1776
- answer.createdBy !== did ||
1777
- typeof answer.body?.sig !== 'string')
1778
- continue;
1779
- if (!members.some((member) => member.did === did))
1780
- continue;
1781
- if (await checkAnswer(sign, space, did, answer.body.sig)) {
1782
- answered = did;
1783
- break;
1784
- }
1785
- }
1786
- 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) {
1787
2041
  // Whoever else the invite reached, nobody more joins with it.
1788
2042
  await spaces.closeInvite(space, invite).catch(() => { });
1789
- const given = (await open.profiles()).find((profile) => profile.did === answered)?.name;
1790
- 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 });
1791
2045
  await (await contactsRuntime()).remove(record.key);
1792
2046
  }
1793
2047
  else if (Date.now() - Date.parse(record.createdAt) > KNOCK_TTL_SECONDS * 1000 + DAY_MS) {
@@ -1796,69 +2050,41 @@ export async function createNode(config) {
1796
2050
  }
1797
2051
  }
1798
2052
  }
1799
- /** Writes the answer to knocks this account accepted, once it can write in the space for two */
1800
- async function answerAccepted() {
1801
- for (const record of await contactRecords()) {
1802
- const { did, space, door } = record.body;
1803
- if (typeof door !== 'string' || typeof space !== 'string')
1804
- continue;
1805
- if (!(await registry.get(space)))
1806
- continue;
1807
- const open = await runtime(space);
1808
- const { founder, mine } = await open.access();
1809
- if (!founder && mine.length === 0)
1810
- continue;
1811
- const { sign } = await doorKeys(door);
1812
- try {
1813
- await open.put(knockAnswerSchema.name, {
1814
- sig: await signAnswer(sign, space, config.signer.did),
1815
- });
1816
- }
1817
- catch {
1818
- continue; // The space's definition of answers hasn't arrived yet.
1819
- }
1820
- const { door: _answered, ...rest } = record.body;
1821
- await writeContact({ ...rest, did });
1822
- }
1823
- }
1824
- /** What the mailboxes of this node's doors hold now, opened and cached */
1825
- async function readDoors() {
2053
+ /** What the mailboxes of this node's inbox hold now, opened and cached */
2054
+ async function readKnocks() {
1826
2055
  const now = Date.now();
1827
2056
  for (const [id, cached] of knockCache)
1828
2057
  if (cached.until <= now)
1829
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, nor what failed to.
2067
+ const held = new Map();
2068
+ const fetched = await Promise.allSettled(places.map((place) => mailbox.fetch(place, keys.topic)));
2069
+ for (const result of fetched) {
2070
+ if (result.status !== 'fulfilled')
2071
+ continue;
2072
+ // A relay's id is only its word: file the knock under the hash of what it is.
2073
+ for (const item of result.value)
2074
+ held.set(await knockId(item.blob), item.blob);
2075
+ }
1830
2076
  const found = [];
1831
- for (const record of await doorRecords()) {
1832
- const { id: doorId, relays } = record.body;
1833
- const keys = await doorKeys(doorId);
1834
- // Every relay, in full: a door holds 64 knocks at most, and a knock
1835
- // cleared from another device should go from here too. What was opened
1836
- // once is not opened again.
1837
- const held = new Map();
1838
- for (const result of await Promise.allSettled(relays.map((relay) => mailbox.fetch(relay, keys.topic)))) {
1839
- if (result.status !== 'fulfilled')
1840
- continue;
1841
- for (const item of result.value) {
1842
- // A relay's id is only its word: file the knock under the hash of what it is.
1843
- const id = await knockId(item.blob);
1844
- const seen = held.get(id);
1845
- if (!seen || item.at < seen.at)
1846
- held.set(id, { blob: item.blob, at: item.at });
1847
- }
1848
- }
1849
- for (const [id, item] of held) {
1850
- let cached = knockCache.get(id);
1851
- if (!cached) {
1852
- cached = {
1853
- opened: await openKnock(keys.key, item.blob, item.at, provider),
1854
- door: doorId,
1855
- until: item.at + KNOCK_TTL_SECONDS * 1000,
1856
- };
1857
- knockCache.set(id, cached);
1858
- }
1859
- if (cached.opened)
1860
- found.push({ id, door: doorId, opened: cached.opened });
2077
+ for (const [id, blob] of held) {
2078
+ let opened = knockCache.get(id)?.opened ?? null;
2079
+ if (!opened && (failed.get(id) ?? 0) <= now) {
2080
+ opened = await openKnock([keys.key], blob, provider);
2081
+ if (opened)
2082
+ knockCache.set(id, { opened, until: opened.at + KNOCK_TTL_SECONDS * 1000 });
2083
+ else
2084
+ failed.set(id, now + 15 * 60_000);
1861
2085
  }
2086
+ if (opened)
2087
+ found.push({ id, opened });
1862
2088
  }
1863
2089
  return found;
1864
2090
  }
@@ -1923,102 +2149,76 @@ export async function createNode(config) {
1923
2149
  return found.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.key.localeCompare(b.key));
1924
2150
  },
1925
2151
  });
1926
- const doors = Object.freeze({
1927
- async list() {
1928
- if (!config.contactKey || !doorsAllowed())
1929
- return [];
1930
- return Promise.all((await doorRecords()).map(doorView));
2152
+ const inbox = Object.freeze({
2153
+ async get() {
2154
+ if (!config.contactKey || !inboxAllowed())
2155
+ return null;
2156
+ const record = await inboxRecord();
2157
+ return record ? inboxView(record) : null;
1931
2158
  },
1932
2159
  async open(options = {}) {
1933
- requireContactKey('Opening a door');
2160
+ requireContactKey('Opening your inbox');
1934
2161
  if (!contactsSpaceId)
1935
2162
  await contactsRuntime();
1936
- const relays = [...(options.relays ?? usableRelays(config.network))].slice(0, MAX_DOOR_RELAYS);
1937
- if (relays.length === 0)
1938
- throw new Error('A door needs a relay to hold its knocks, and this node has none.');
1939
- const name = clip((options.name ?? (await ownName()) ?? '').trim(), 64);
1940
- const label = options.label ? clip(options.label.trim(), 64) : '';
1941
- const id = base64UrlEncode(globalThis.crypto.getRandomValues(new Uint8Array(16)));
1942
- // Checks the relays and name the way a knocker will.
1943
- const keys = await doorKeys(id);
1944
- encodeDoorCode({ key: keys.publicKey, sign: keys.signPublic, relays, ...(name ? { name } : {}) });
1945
- const open = await contactsRuntime();
1946
- await ensureDefined(open, doorSchema);
1947
- return doorView(await open.put(doorSchema.name, {
1948
- id,
1949
- relays,
1950
- ...(name ? { name } : {}),
1951
- ...(label ? { label } : {}),
1952
- }));
2163
+ const current = await inboxRecord();
2164
+ const places = [...(options.places ?? current?.body?.places ?? usableRelays(config.network))].slice(0, MAX_INBOX_PLACES);
2165
+ if (places.length === 0)
2166
+ throw new Error('An inbox needs a mailbox to hold its knocks, and this node has none.');
2167
+ const name = clip((options.name ?? current?.body?.name ?? (await ownName()) ?? '').trim(), 64);
2168
+ return writeInbox({ gen: current?.body?.gen ?? 0, places, ...(name ? { name } : {}) }, current);
1953
2169
  },
1954
- async close(id) {
1955
- const found = await doorById(id);
1956
- if (found)
1957
- await (await contactsRuntime()).remove(found.key);
1958
- forgetKnocksAt(id);
2170
+ async rotate() {
2171
+ requireContactKey('Replacing your inbox');
2172
+ const current = await inboxRecord();
2173
+ if (!current)
2174
+ return inbox.open();
2175
+ // What waits in the old one goes with it.
2176
+ await purgeInbox(current.body, null).catch(() => 0);
2177
+ knockCache.clear();
2178
+ failed.clear();
2179
+ return writeInbox({ ...current.body, gen: current.body.gen + 1 }, current);
1959
2180
  },
1960
- async clear(id) {
1961
- requireContactKey('Clearing a door');
1962
- const found = await doorById(id);
1963
- if (!found)
1964
- throw new Error('There is no such door');
1965
- if ((await purgeDoor(found.body, null)) === 0)
1966
- throw new Error("None of the door's relays could be reached to clear it.");
1967
- forgetKnocksAt(id);
2181
+ async clear() {
2182
+ requireContactKey('Clearing your inbox');
2183
+ const current = await inboxRecord();
2184
+ if (!current)
2185
+ throw new Error('Your inbox is not open');
2186
+ if ((await purgeInbox(current.body, null)) === 0)
2187
+ throw new Error("None of your inbox's mailboxes could be reached to clear it.");
2188
+ knockCache.clear();
2189
+ failed.clear();
1968
2190
  },
1969
2191
  async knock(code, options = {}) {
1970
- requireContactKey('Knocking on a door');
1971
- requireEverywhere('Knocking on a door');
1972
- const door = parseDoorCode(code);
1973
- for (const mine of await doors.list())
1974
- if (mine.key === door.key)
1975
- throw new Error('That is one of your own doors');
2192
+ requireContactKey('Knocking');
2193
+ requireEverywhere('Knocking');
2194
+ const theirs = await readInboxCode(code, provider);
2195
+ if ((await inbox.get())?.key === theirs.key)
2196
+ throw new Error('That is your own inbox');
1976
2197
  if (!contactsSpaceId)
1977
2198
  await contactsRuntime();
1978
2199
  const mine = (await ownName()) ?? 'Someone';
1979
- const theirs = door.name ?? 'Contact';
1980
- const pair = await spaces.create({
1981
- name: `${clip(mine, 64)} & ${theirs}`,
1982
- visibility: 'private',
1983
- ...team,
1984
- });
1985
- let invite;
1986
- try {
1987
- // Defined now, by the one who may: the answer is written by someone who joins as an editor.
1988
- await ensureDefined(await runtime(pair.id), knockAnswerSchema);
1989
- invite = await spaces.invite(pair.id, { role: 'editor' });
1990
- 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);
1991
- const topic = await doorTopic(door.sign);
1992
- const left = await Promise.allSettled(door.relays.map((relay) => mailbox.drop(relay, topic, blob, KNOCK_TTL_SECONDS)));
1993
- if (!left.some((result) => result.status === 'fulfilled')) {
1994
- const reasons = left
1995
- .map((result) => (result.status === 'rejected' ? reasonText(result.reason) : ''))
1996
- .filter(Boolean);
1997
- throw new Error(`None of their door's relays took the knock. ${reasons.join('; ')}`);
1998
- }
1999
- }
2000
- catch (error) {
2001
- await spaces.leave(pair.id).catch(() => { });
2002
- throw error;
2200
+ const name = theirs.name ?? 'Contact';
2201
+ const made = await makePair(theirs.key, { mine, theirs: name }, options.note);
2202
+ const topic = await inboxTopic(theirs.sign);
2203
+ const left = await Promise.allSettled(theirs.places.map((place) => mailbox.drop(place, topic, made.sealed, KNOCK_TTL_SECONDS)));
2204
+ if (!left.some((result) => result.status === 'fulfilled')) {
2205
+ await spaces.leave(made.space).catch(() => { });
2206
+ const reasons = left
2207
+ .map((result) => (result.status === 'rejected' ? reasonText(result.reason) : ''))
2208
+ .filter(Boolean);
2209
+ throw new Error(`None of their inbox's mailboxes took the knock. ${reasons.join('; ')}`);
2003
2210
  }
2004
2211
  const open = await contactsRuntime();
2005
2212
  await ensureDefined(open, knockSchema);
2006
- await open.put(knockSchema.name, {
2007
- space: pair.id,
2008
- name: theirs,
2009
- door: door.key,
2010
- sign: door.sign,
2011
- invite,
2012
- });
2013
- return { space: pair.id };
2213
+ await open.put(knockSchema.name, { space: made.space, name, invite: made.invite });
2214
+ return { space: made.space, carried: made.carried };
2014
2215
  },
2015
2216
  async knocks() {
2016
2217
  requireContactKey('Reading knocks');
2017
2218
  await settleSent().catch(() => { });
2018
- await answerAccepted().catch(() => { });
2019
2219
  const blocked = await blockedDids();
2020
2220
  const found = [];
2021
- for (const { id, door, opened } of await readDoors()) {
2221
+ for (const { id, opened } of await readKnocks()) {
2022
2222
  if (opened.from === config.signer.did || blocked.has(opened.from))
2023
2223
  continue;
2024
2224
  // Already accepted, here or on another device.
@@ -2026,7 +2226,6 @@ export async function createNode(config) {
2026
2226
  continue;
2027
2227
  found.push(Object.freeze({
2028
2228
  id,
2029
- door,
2030
2229
  from: opened.from,
2031
2230
  name: opened.name,
2032
2231
  ...(opened.note ? { note: opened.note } : {}),
@@ -2041,40 +2240,32 @@ export async function createNode(config) {
2041
2240
  return (await sentRecords()).map((record) => Object.freeze({ space: record.body.space, name: record.body.name, at: record.createdAt }));
2042
2241
  },
2043
2242
  async accept(id) {
2044
- requireContactKey('Opening the door to someone');
2045
- requireEverywhere('Opening the door to someone');
2243
+ requireContactKey('Accepting a knock');
2244
+ requireEverywhere('Accepting a knock');
2046
2245
  if (!knockCache.get(id)?.opened)
2047
- await readDoors();
2048
- const cached = knockCache.get(id);
2049
- const knocked = cached?.opened;
2050
- if (!cached || !knocked)
2051
- throw new Error('That knock is gone: it expired, or the door was closed or cleared.');
2246
+ await readKnocks();
2247
+ const knocked = knockCache.get(id)?.opened;
2248
+ if (!knocked)
2249
+ throw new Error('That knock is gone: it expired, or your inbox was cleared or replaced.');
2052
2250
  await spaces.join(knocked.invite);
2053
2251
  const known = await contacts.get(knocked.from);
2054
2252
  const contact = await writeContact({
2055
2253
  did: knocked.from,
2056
2254
  name: known?.name ?? knocked.name,
2057
2255
  space: knocked.pairSpace,
2058
- door: cached.door,
2059
2256
  });
2060
- await answerAccepted().catch(() => { });
2061
2257
  // Done with: nobody needs it in the mailboxes any more.
2062
- const door = await doorById(cached.door);
2063
- if (door)
2064
- await purgeDoor(door.body, [id]).catch(() => 0);
2258
+ const current = await inboxRecord();
2259
+ if (current)
2260
+ await purgeInbox(current.body, [id]).catch(() => 0);
2065
2261
  knockCache.delete(id);
2066
2262
  return contact;
2067
2263
  },
2068
2264
  async dismiss(id) {
2069
2265
  requireContactKey('Dismissing a knock');
2070
- if (!knockCache.has(id))
2071
- await readDoors();
2072
- const cached = knockCache.get(id);
2073
- if (!cached)
2074
- return;
2075
- const door = await doorById(cached.door);
2076
- if (door)
2077
- await purgeDoor(door.body, [id]);
2266
+ const current = await inboxRecord();
2267
+ if (current)
2268
+ await purgeInbox(current.body, [id]);
2078
2269
  knockCache.delete(id);
2079
2270
  },
2080
2271
  });
@@ -2245,7 +2436,7 @@ export async function createNode(config) {
2245
2436
  get: async (did) => (contactsGiven() ? contacts.get(did) : null),
2246
2437
  },
2247
2438
  direct: { reachable: async (spaceId) => (allowed(spaceId) ? direct.reachable(spaceId) : []) },
2248
- doors: { list: async () => [] },
2439
+ inbox: { get: async () => null },
2249
2440
  };
2250
2441
  const person = (what) => async () => {
2251
2442
  throw new Error(`An agent can't ${what}. Ask the person to do it.`);
@@ -2294,7 +2485,7 @@ export async function createNode(config) {
2294
2485
  automations,
2295
2486
  contacts,
2296
2487
  direct,
2297
- doors,
2488
+ inbox,
2298
2489
  asAgent,
2299
2490
  delegation: () => current,
2300
2491
  iceServers: async () => (mesh ? mesh.iceServers() : (config.network?.iceServers ?? DEFAULT_ICE_SERVERS)),
@@ -2343,6 +2534,7 @@ export async function createNode(config) {
2343
2534
  stopWatchingNetwork?.();
2344
2535
  if (renewTimer)
2345
2536
  clearTimeout(renewTimer);
2537
+ clearInterval(linkTimer);
2346
2538
  const open = [...runtimes.keys()];
2347
2539
  await Promise.all(open.map((spaceId) => closeRuntime(spaceId)));
2348
2540
  // Let go of the registry too: an open database connection blocks the