@minca/core 0.1.16 → 0.1.18

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 (125) hide show
  1. package/README.md +10 -9
  2. package/dist/elements/auth-styles.d.ts +1 -1
  3. package/dist/elements/auth-styles.d.ts.map +1 -1
  4. package/dist/elements/auth-styles.js +14 -5
  5. package/dist/elements/auth-styles.js.map +1 -1
  6. package/dist/elements/minca-auth.d.ts.map +1 -1
  7. package/dist/elements/minca-auth.js +18 -15
  8. package/dist/elements/minca-auth.js.map +1 -1
  9. package/dist/files/space-files.d.ts +2 -2
  10. package/dist/files/space-files.d.ts.map +1 -1
  11. package/dist/files/space-files.js +7 -5
  12. package/dist/files/space-files.js.map +1 -1
  13. package/dist/inbox/names.d.ts +1 -1
  14. package/dist/inbox/names.js +1 -1
  15. package/dist/index.d.ts +2 -0
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +2 -0
  18. package/dist/index.js.map +1 -1
  19. package/dist/network/ws-transport.d.ts.map +1 -1
  20. package/dist/network/ws-transport.js +3 -0
  21. package/dist/network/ws-transport.js.map +1 -1
  22. package/dist/node/actions.d.ts +5 -0
  23. package/dist/node/actions.d.ts.map +1 -1
  24. package/dist/node/actions.js +39 -20
  25. package/dist/node/actions.js.map +1 -1
  26. package/dist/node/api.d.ts +2 -0
  27. package/dist/node/api.d.ts.map +1 -1
  28. package/dist/node/api.js +2 -0
  29. package/dist/node/api.js.map +1 -1
  30. package/dist/node/carrier.js +1 -1
  31. package/dist/node/carrier.js.map +1 -1
  32. package/dist/node/node-carriers.d.ts.map +1 -1
  33. package/dist/node/node-carriers.js +6 -1
  34. package/dist/node/node-carriers.js.map +1 -1
  35. package/dist/node/node-contacts.d.ts.map +1 -1
  36. package/dist/node/node-contacts.js +1 -0
  37. package/dist/node/node-contacts.js.map +1 -1
  38. package/dist/node/node-hosting.d.ts.map +1 -1
  39. package/dist/node/node-hosting.js +11 -4
  40. package/dist/node/node-hosting.js.map +1 -1
  41. package/dist/node/node-records.d.ts.map +1 -1
  42. package/dist/node/node-records.js +6 -1
  43. package/dist/node/node-records.js.map +1 -1
  44. package/dist/node/node.d.ts.map +1 -1
  45. package/dist/node/node.js +14 -1
  46. package/dist/node/node.js.map +1 -1
  47. package/dist/node/remote.d.ts.map +1 -1
  48. package/dist/node/remote.js +7 -1
  49. package/dist/node/remote.js.map +1 -1
  50. package/dist/node/space-holding.d.ts +7 -3
  51. package/dist/node/space-holding.d.ts.map +1 -1
  52. package/dist/node/space-holding.js +90 -18
  53. package/dist/node/space-holding.js.map +1 -1
  54. package/dist/node/space-peers.d.ts.map +1 -1
  55. package/dist/node/space-peers.js +58 -24
  56. package/dist/node/space-peers.js.map +1 -1
  57. package/dist/node/space-runtime.d.ts +11 -3
  58. package/dist/node/space-runtime.d.ts.map +1 -1
  59. package/dist/node/space-runtime.js +22 -1
  60. package/dist/node/space-runtime.js.map +1 -1
  61. package/dist/node/space-writing.d.ts +2 -0
  62. package/dist/node/space-writing.d.ts.map +1 -1
  63. package/dist/node/space-writing.js +2 -0
  64. package/dist/node/space-writing.js.map +1 -1
  65. package/dist/node/types.d.ts +130 -36
  66. package/dist/node/types.d.ts.map +1 -1
  67. package/dist/query/types.d.ts +1 -0
  68. package/dist/query/types.d.ts.map +1 -1
  69. package/dist/query/types.js.map +1 -1
  70. package/dist/records/contract-builder.d.ts +22 -6
  71. package/dist/records/contract-builder.d.ts.map +1 -1
  72. package/dist/records/contract-builder.js.map +1 -1
  73. package/dist/schemas/automations.d.ts +6 -2
  74. package/dist/schemas/automations.d.ts.map +1 -1
  75. package/dist/schemas/automations.js.map +1 -1
  76. package/dist/schemas/connectors.d.ts +4 -3
  77. package/dist/schemas/connectors.d.ts.map +1 -1
  78. package/dist/schemas/connectors.js +4 -3
  79. package/dist/schemas/connectors.js.map +1 -1
  80. package/dist/schemas/library/media.js +1 -1
  81. package/dist/schemas/library/media.js.map +1 -1
  82. package/dist/schemas/library/social.d.ts +258 -0
  83. package/dist/schemas/library/social.d.ts.map +1 -1
  84. package/dist/schemas/library/social.js +28 -1
  85. package/dist/schemas/library/social.js.map +1 -1
  86. package/dist/session/auth.d.ts +7 -3
  87. package/dist/session/auth.d.ts.map +1 -1
  88. package/dist/session/auth.js.map +1 -1
  89. package/dist/session/hosting.d.ts.map +1 -1
  90. package/dist/session/hosting.js +8 -2
  91. package/dist/session/hosting.js.map +1 -1
  92. package/dist/space/presets.d.ts +2 -2
  93. package/dist/space/presets.d.ts.map +1 -1
  94. package/dist/space/presets.js +3 -2
  95. package/dist/space/presets.js.map +1 -1
  96. package/dist/storage/blob-store.d.ts +3 -0
  97. package/dist/storage/blob-store.d.ts.map +1 -1
  98. package/dist/types.d.ts +11 -2
  99. package/dist/types.d.ts.map +1 -1
  100. package/dist/types.js.map +1 -1
  101. package/docs/README.md +86 -93
  102. package/docs/actions.md +212 -144
  103. package/docs/agents.md +198 -155
  104. package/docs/automations.md +296 -204
  105. package/docs/blueprints-and-guides.md +405 -295
  106. package/docs/bots.md +208 -134
  107. package/docs/building-an-app.md +74 -163
  108. package/docs/collections.md +248 -328
  109. package/docs/computed.md +112 -89
  110. package/docs/contacts.md +151 -112
  111. package/docs/contracts.md +299 -120
  112. package/docs/direct-messages.md +80 -61
  113. package/docs/inbox.md +138 -93
  114. package/docs/node.md +1072 -972
  115. package/docs/permissions.md +142 -0
  116. package/docs/proposing-collections.md +74 -55
  117. package/docs/query-format.md +150 -126
  118. package/docs/records-and-queries.md +205 -126
  119. package/docs/sign-in.md +496 -418
  120. package/docs/spaces.md +261 -245
  121. package/docs/standard-library.md +473 -504
  122. package/docs/storage.md +325 -348
  123. package/docs/usernames.md +164 -97
  124. package/docs/warrants.md +100 -67
  125. package/package.json +1 -2
package/docs/node.md CHANGED
@@ -1,1066 +1,1166 @@
1
1
  # The node
2
2
 
3
- `createNode` and what it returns: configuration, root signers and notes, renewing
4
- the session note, stores, holding spaces, following the account, events, live
5
- messages, the rest of its surface, the network, acting as an agent, the
6
- app-side client, carriers and hosting, the inbox, and the React and element
7
- conveniences.
8
-
9
- > Not protocol. This page describes the reference library, and another
10
- > implementation may do it differently and still interoperate. What peers must
11
- > agree on is in the [spec](https://github.com/leifriksheim/minca/blob/main/spec/README.md).
3
+ A node is what takes part in Minca for an account. It holds the account's
4
+ spaces, signs what it writes, checks what peers send, and keeps everything in
5
+ sync. Most apps never make one: the connection starts it for you
6
+ ([building an app](building-an-app.md)). You make one yourself in a program
7
+ that holds the account's keys, such as a script, a server or a test.
8
+
9
+ ```ts
10
+ import { createNode, deriveAccountKey, generateSeed, indexedDBStores, rootFromSeed } from '@minca/core';
11
+
12
+ const seed = generateSeed();
13
+ const { signer } = await rootFromSeed(seed);
14
+
15
+ const node = await createNode({
16
+ signer,
17
+ accountKey: await deriveAccountKey(seed),
18
+ stores: indexedDBStores('my-app'),
19
+ network: { relays: ['wss://relay.minca.social'] },
20
+ });
21
+
22
+ const space = await node.spaces.create({ name: 'Notes', visibility: 'private' });
23
+ await node.records.put(space.id, 'app.note', { text: 'Hello' });
24
+ ```
12
25
 
13
26
  ## Configuration
14
27
 
15
- `createNode(config)` takes (`NodeConfig`):
16
-
17
- | Field | Type | Meaning |
18
- | ------------------- | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
19
- | `signer` | `RootSigner` | Who the node acts for. Asked only for session notes ([spec 06 §1.2](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)). |
20
- | `accountKey` | bytes, optional | The account key (`deriveAccountKey(seed)`). Enables the account registry and the contacts space ([spec 06 §1.3](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)). |
21
- | `contactKey` | bytes, optional | The contact key's secret. Opens knocks, in shared spaces and, through the keys derived from it, in the inbox; published on profiles. |
22
- | `contactsSpace` | string, optional | The contacts space's id, for a node given it without the account key (an app granted `contacts`, [spec 06 §2.5](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)). |
23
- | `stores` | `StoreFactory` | Where the registry and each space's store live ([stores](#stores)). |
24
- | `provider` | `CryptoProvider`, optional | Default: P-256 over WebCrypto. |
25
- | `collections` | `CollectionDef[]`, optional | Schemas the node knows, used when a space does not describe a collection itself. Writes are checked against them; reads are flagged `conforms`. Nothing is refused on arrival for its shape ([02](https://github.com/leifriksheim/minca/blob/main/spec/02-records.md)). |
26
- | `network` | optional | `relays` (where peers meet: Minca `wss://` and Nostr `nostr+wss://` relays), `nodes` (always-on nodes to dial, `wss://host/peer#<DID>`; the fragment pins the node, spec 04 §5.2; `ws://` only on this machine), `iceServers`, `transports` (extra transports per space). Omitted: offline. |
27
- | `sessionTtlSeconds` | number, optional | Lifetime of each session note. Default `3600`. |
28
- | `sessionKey` | `CryptoKeyPair`, optional | Sign with this key instead of a fresh one. Used when the signer's note names a specific key (an app's key, an agent's key, [spec 06 §2](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md), [spec 06 §3](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)). |
29
- | `writerKey` | `WriterKeySource`, optional | Keep a signing key across runs, so this device keeps one log in each space ([writer keys](#writer-keys)). Ignored with `sessionKey`. |
30
- | `watchIntervalMs` | number, optional | How often to look for writes another app, device or process made: a data folder's segments, a store file another process shares. `0` disables. Default `2000`. _Implementation detail._ |
31
- | `cache` | `CacheConfig`, optional | Hold only the collections used, in spaces that name a keeper ([holding part of a space](#holding-part-of-a-space)). |
32
- | `mailbox` | `MailboxClient`, optional | How the inbox and short links reach mailboxes ([07](https://github.com/leifriksheim/minca/blob/main/spec/07-inbox.md)). Default: a WebSocket to each relay. |
33
-
34
- _Source: `packages/core/src/node/types.ts` (`NodeConfig`, `NodeNetworkConfig`, `CacheConfig`). Tests: `packages/core/tests/node.test.ts`, `packages/core/tests/caches.test.ts`._
28
+ `createNode(config)` takes a [`NodeConfig`](https://minca.dev/api/core/interfaces/NodeConfig/),
29
+ whose page gives each field's meaning and default. The sections below explain
30
+ the ones that work together: [root signers](#root-signers-and-notes),
31
+ [stores](#stores), [writer keys](#writer-keys) and
32
+ [holding part of a space](#holding-part-of-a-space).
33
+
34
+ ### Collections the node knows
35
+
36
+ `collections` gives the node schemas to use when a space doesn't describe a
37
+ collection itself. Writes are checked against them, and reads are flagged
38
+ `conforms`. Nothing arriving from a peer is refused for its shape.
39
+
40
+ ### Network options
41
+
42
+ `network` is a [`NodeNetworkConfig`](https://minca.dev/api/core/interfaces/NodeNetworkConfig/):
43
+ the relays where peers meet, always-on nodes to dial, hosts to look for the
44
+ account registry at, and more. Omitted, the node stays offline.
45
+ [The network](#the-network) says how the node uses them.
35
46
 
36
47
  ## Lifecycle
37
48
 
38
- Starting a node does the following, in order:
39
-
40
- 1. Uses `config.sessionKey`; else claims a lasting key from `config.writerKey`
41
- ([writer keys](#writer-keys)); else generates a fresh P-256 key pair for this
42
- run. Its DID (`did:key`, P-256 multicodec) is `sessionDid`.
43
- 2. Asks `config.signer.delegate` for a session note ([spec 06 §1.2](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)) and waits for it.
44
- If the signer refuses, `createNode` fails.
45
- 3. Schedules renewal of the note ([renewing the session note](#renewing-the-session-note)).
46
- 4. Opens the `registry` store, sealed ([stores](#stores)).
47
- 5. With an account key: derives the account registry space and the contacts
48
- space ([03](https://github.com/leifriksheim/minca/blob/main/spec/03-spaces.md)). The contacts space is added to the node's own
49
- registry like a joined space (so it can be granted to an app like any other
50
- space), and both are _hidden_ from `spaces.list` ([following the account](#following-the-account)).
51
- 6. With an account key: opens the account registry space and reconciles
52
- ([following the account](#following-the-account)) before `createNode` returns.
53
-
54
- A node acts for one account (`node.did`) and signs with one session key
55
- (`node.sessionDid`) for its whole lifetime. To act for another account, start
56
- another node.
57
-
58
- `revokeKey(key, { spaces?, waitMs? })` revokes a key of the account, each
59
- revoke with a cutoff at what the key wrote: in `spaces`, or by default
60
- wherever the account writes (every space it lists, its carry spaces, the
61
- contacts space and the account registry). It says whether a peer took each in
62
- within `waitMs`. The account home's disconnect calls it for an app's key.
63
- `revokeSelf()` does the same for the node's own session key, and forgets a
64
- lasting key at once; the account home's sign-out calls it
65
- ([spec 01 §7.4](https://github.com/leifriksheim/minca/blob/main/spec/01-identity.md)).
66
- A record is judged with no time, so a revoke, not the note running out, is
67
- what ends what a key can write. An agent's view refuses both.
68
-
69
- `close()` stops renewal, closes every open space (flushing what each keeps,
70
- stopping sync and disconnecting its transports), closes the registry store,
71
- and drops all event listeners. After `close()`, any call that needs a space
72
- fails with `Node is closed`. Closing twice does nothing.
73
-
74
- _Source: `packages/core/src/node/node.ts` (`createNode`, `close`). Tests: `packages/core/tests/node.test.ts`._
49
+ When it starts, a node picks its signing key: `sessionKey` if given, else one
50
+ claimed from `writerKey`, else a fresh P-256 key for this run. Its DID is
51
+ `node.sessionDid`. Then it asks the signer for a session note and waits. If
52
+ the signer refuses, `createNode` fails.
53
+
54
+ With an account key, the node also opens the account registry and makes its
55
+ spaces match it before `createNode` returns
56
+ ([following the account](#following-the-account)).
57
+
58
+ A node acts for one account (`node.did`) and signs with one key for its whole
59
+ life. To act for another account, start another node.
60
+
61
+ ### Revoking keys
62
+
63
+ `revokeKey(key, { spaces?, waitMs? })` revokes one of the account's keys, with
64
+ a cutoff at what that key wrote. By default it does this wherever the account
65
+ writes: every space it lists, its carry spaces, the contacts space and the
66
+ account registry. It says whether a peer took each revoke in within `waitMs`.
67
+ The account home calls it when you disconnect an app.
68
+
69
+ `revokeSelf()` does the same for the node's own key, and forgets a lasting
70
+ key at once. The account home calls it on sign-out.
71
+
72
+ A record is judged with no clock, so it is a revoke, not the note running out,
73
+ that ends what a key can write. An agent can't call either.
74
+ [Spec 01 §7.4](https://github.com/leifriksheim/minca/blob/main/spec/01-identity.md).
75
+
76
+ ### Closing
77
+
78
+ `close()` stops renewing the note, closes every open space and the registry,
79
+ and drops all event listeners. After that, any call that needs a space fails
80
+ with `Node is closed`. Closing twice does nothing.
75
81
 
76
82
  ## Root signers and notes
77
83
 
78
- A node never holds the root key. It is given a **root signer** (`RootSigner`),
79
- which hides where the key lives and is asked only for notes. This is an
80
- in-process interface, not a wire format; what a note must be is
81
- [spec 01 §7](https://github.com/leifriksheim/minca/blob/main/spec/01-identity.md).
82
-
83
- | Member | Type | Meaning |
84
- | -------------------------------------------------------------- | -------------- | ------------------------------------------- |
85
- | `did` | string | The account DID |
86
- | `delegate({audience, command, subject?, policy?, expiration})` | → `Delegation` | Issue a note from the account to `audience` |
87
-
88
- - The **local** signer (`createLocalRootSigner`) calls `issueDelegation` with
89
- the root key. `subject` defaults to the account's own DID (the whole
90
- account), `policy` to none. It never sets `meta`.
91
- - The **grant** signer an app uses returns the one note the account home
92
- already issued to the app's key, unchanged, and refuses once the grant's
93
- `expiresAt` has passed. It cannot mint new notes
94
- ([spec 06 §2](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)).
95
- - A signer **across a port** (`serveSigner` on the side that holds the key,
96
- `remoteSigner` on the node's, as a page signs for its worker's node) signs
97
- only notes of the session note's shape below: `command` `/`, no `subject`,
98
- no `policy`. It refuses anything else without asking the signer behind it.
99
- The audience and expiration are the far end's to pick, so it bounds
100
- neither.
101
-
102
- The **session note** a node asks for when it starts:
84
+ A node never holds the account's root key. It gets a **root signer**, which
85
+ hides where the key lives and is only asked for notes.
86
+
87
+ Its interface is [`RootSigner`](https://minca.dev/api/core/interfaces/RootSigner/): the
88
+ account's DID, and `delegate`, which issues a note from the account to a key.
89
+
90
+ There are three kinds:
91
+
92
+ - **Local**, `createLocalRootSigner`, signs with the root key itself.
93
+ `subject` defaults to the whole account and `policy` to none.
94
+ - **Grant**, `grantSigner`, is what an app uses. It returns the one note the
95
+ account home gave the app, and refuses once the grant has expired. It can't
96
+ make new notes.
97
+ - **Across a port**, `serveSigner` on the side with the key and
98
+ `remoteSigner` on the node's side, as a page signs for its worker. It signs
99
+ only session notes (command `/`, no subject, no policy) and refuses anything
100
+ else without asking the signer behind it.
101
+
102
+ ### The session note
103
+
104
+ This is the note a node asks for when it starts:
103
105
 
104
106
  ```
105
107
  aud = session DID
106
108
  sub = the account's DID
107
- cmd = "/" (SESSION_COMMAND; a node acting as an agent signs under its grant, `/record`)
109
+ cmd = "/" (an agent's node signs under its grant, `/record`)
108
110
  pol = []
109
111
  exp = now + sessionTtlSeconds (default 3600)
110
- nbf = now − 300 (issueDelegation's default)
112
+ nbf = now − 300
111
113
  ```
112
114
 
113
- Its proof is that token. Peers check only that the note grants what each
114
- record needs, so the command is this node's choice, not a rule. The note is renewed before it runs out
115
- ([spec 06 §1.2](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)).
116
-
117
- **Issuing.** `issueDelegation` defaults `exp` to now + 3600, `nbf` to now − 300
118
- (`UCAN_CLOCK_SKEW_SECONDS`, so a peer whose clock is a little behind still
119
- accepts it), `nonce` to 12 random bytes in base64url, `subject` to the
120
- issuer's own DID and `policy` to `[]`; it signs in the low-S form only.
121
- Only the account's root signer issues notes peers accept: a note is one
122
- token from the account, never passed on
123
- ([spec 01 §7.5](https://github.com/leifriksheim/minca/blob/main/spec/01-identity.md)).
124
- A key that needs another key (a helper, a key per tab) asks the account,
125
- through its home or root signer, for a note of its own.
126
-
127
- **What a home grants.** `grantTerms(access, spaces)` (and `noteTerms` under it)
128
- turns a grant into a note's terms: `/`, `/record` or `/record/read`; the
129
- whole account, or one space as the subject, or several named by a policy on
130
- `.space`; none, as a policy nothing satisfies. `noteSpaces(note)` reads that
131
- back, for showing which spaces a note reaches, and reaches no space for a
132
- policy statement it can't read that way, so it never offers more than the
133
- note grants; peers judge each use against the note itself
134
- ([spec 06 §2.5](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)).
135
-
136
- _Source: `packages/core/src/identity/root-signer.ts`, `packages/core/src/node/remote.ts` (`serveSigner`, `remoteSigner`), `packages/core/src/identity/ucan.ts` (`issueDelegation`, `verifyNote`), `packages/core/src/identity/abilities.ts` (`noteTerms`, `noteSpaces`), `packages/core/src/node/node.ts` (`SESSION_COMMAND`, `delegate`), `packages/core/src/session/connect.ts` (`grantSigner`, `grantTerms`). Tests: `packages/core/tests/ucan.test.ts`, `packages/core/tests/remote.test.ts` ("the page's signer, from a worker"), `packages/core/tests/node.test.ts`, `packages/core/tests/connect.test.ts`._
115
+ Peers only check that the note grants what each record needs, so the command
116
+ is the node's choice.
137
117
 
138
- ## Renewing the session note
118
+ ### Issuing notes
119
+
120
+ `issueDelegation` defaults `exp` to an hour from now, `nbf` to five minutes
121
+ ago so a peer with a slow clock still accepts it, `nonce` to 12 random bytes,
122
+ `subject` to the issuer and `policy` to `[]`. It signs in low-S form only.
139
123
 
140
- The note format, and that every record carries it, are protocol
141
- ([spec 06 §1.2](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)). When to renew it is the node's own:
124
+ Only the account's root signer issues notes that peers accept, and a note is
125
+ never passed on. A key that needs another key, such as a helper or a key per
126
+ tab, asks the account for a note of its own.
142
127
 
143
- - The first renewal is asked for at `0.75 × ttl` seconds after start (2700 s
144
- with the default TTL), and each successful renewal schedules the next
145
- `0.75 × ttl` later.
146
- - If the signer refuses or cannot be reached, the node keeps the note it has
147
- and asks again after `min(60, ttl / 4)` seconds, repeating until it succeeds
148
- or the node closes. Once the held note expires, live checks (knocks, live
149
- messages, connecting to peers) refuse it; records it signs are judged with
150
- no time, so they count until its key is revoked.
128
+ ### What a home grants
151
129
 
152
- A signer need not be able to sign. `grantSigner(grant)` answers every
153
- `delegate` call with the one note an account home granted, unchanged, and
154
- refuses once `grant.expiresAt` has passed. `grantSigner(() => grant)` answers
155
- with whichever grant the getter returns, as the desktop app's node does when
156
- a renewed grant replaces the last. A node started from a grant
157
- therefore never gets a fresh note: its "renewal" returns the same note, and when
158
- it runs out the app must connect again ([spec 06 §2.9](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)).
130
+ `grantTerms(access, spaces)` turns a grant into a note's terms: the command
131
+ `/`, `/record` or `/record/read`, and the whole account, one space, or several
132
+ spaces named by a policy. `noteSpaces(note)` reads that back, to show which
133
+ spaces a note reaches. It never claims more than the note grants.
134
+ [Spec 01 §7](https://github.com/leifriksheim/minca/blob/main/spec/01-identity.md),
135
+ [spec 06 §2.5](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md).
159
136
 
160
- `node.delegation()` returns the note the session key writes under now.
137
+ ## Renewing the session note
161
138
 
162
- _Source: `packages/core/src/node/node.ts` (`delegate`, `scheduleRenewal`, `SESSION_COMMAND`), `packages/core/src/session/connect.ts` (`grantSigner`). Tests: `packages/core/tests/node.test.ts` ("the delegation is renewed before it expires")._
139
+ The node asks for a new note three quarters of the way through the old one:
140
+ 2700 seconds in, with the default lifetime. Each renewal schedules the next.
163
141
 
164
- ## Stores
142
+ If the signer refuses or can't be reached, the node keeps its note and asks
143
+ again after `min(60, ttl / 4)` seconds, until it succeeds or the node closes.
144
+ Once the note expires, live checks refuse it: knocks, live messages and
145
+ connecting to peers. Records it signed still count until its key is revoked.
165
146
 
166
- A node asks for stores by path through its `StoreFactory`:
167
-
168
- | Path | Holds | Sealed |
169
- | ------------------ | ---------------------------------------------------- | --------------------------------------- |
170
- | `registry` | the node's list of spaces and their keys | yes: the node asks for `{ seal: true }` |
171
- | `spaces/<spaceId>` | one space's records and what the node keeps about it | no |
172
- | `writers` | the last place each lasting key took in each line | no |
173
-
174
- What a path means is the factory's choice:
175
-
176
- - `indexedDBStores(prefix)` — one IndexedDB database per path, named
177
- `<prefix>:<path with / replaced by :>`. Never sealed: the browser profile
178
- already guards it.
179
- - `folderStores(directory, { basePath?, localKey?, local? })` — a data folder
180
- ([sync and storage](storage.md#data-folders)): the `registry` in the folder
181
- under `basePath`, sealed under `localKey` (`deriveLocalKey(seed)`) when one
182
- is given; every other path in `local`; and each space mirrored to the
183
- folder's segments, which the factory names as `folder`.
184
- - `directoryStores(directory, { localKey? })` — a directory on this device,
185
- one file per entry and per version; the `registry` sealed as above.
186
-
187
- Every version a node signs in a space takes the next place in its key's line
188
- for that collection there ([spec 02 §4.10](https://github.com/leifriksheim/minca/blob/main/spec/02-records.md)).
189
- Writes by one key in one space go one at a time, and the place is remembered
190
- before the version leaves the node. Where the places are kept depends on the key:
191
-
192
- - **A key made for this run** lives only as long as the node, so its places
193
- are kept in memory.
194
- - **A claimed writer key** (`config.writerKey`) keeps them in its slot, beside
195
- the key.
196
- - **A key handed in** (`config.sessionKey`, an agent's) or a carrier's own key
197
- keeps them in the `writers` store, and a restart carries on where it left off.
198
- Such a key may be signing in several nodes at once: every tab of an app
199
- signs with the app's key. So each place is taken under a Web Lock
200
- (`minca-writer:lines/<did>/<space>`) every tab and worker of the origin
201
- shares, and read afresh from the store inside it, never from a copy in
202
- memory. Nodes that share a key must share that store too, as tabs of one
203
- origin share IndexedDB; two nodes signing with one key from separate stores,
204
- or in separate processes without a shared lock, fork its lines, and every
205
- peer then withdraws what it signed in a forked collection from the fork on.
206
-
207
- _Source: `packages/core/src/node/writers.ts` (`createWriters`, `exclusively`). Tests: `packages/core/tests/writer-logs.test.ts` ("a writer’s log", "two nodes sharing a handed-in key…")._
147
+ A node started from a grant never gets a fresh note. `grantSigner(grant)`
148
+ answers every renewal with the same note, and when that runs out the app must
149
+ connect again. `grantSigner(() => grant)` answers with whatever grant the
150
+ getter returns, so a renewed grant can replace the last.
208
151
 
209
- ### Writer keys
152
+ `node.delegation()` returns the note the node writes under now.
153
+ [Spec 06 §1.2](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md).
210
154
 
211
- A node given `writerKey` claims a lasting key at start and signs with it
212
- until it closes, so the device keeps one log in each space instead of a new
213
- one each run. The source hands a key to one node at a time; a node that
214
- finds every key taken, or a source that can't lock one, gets none, and the
215
- node makes a key for this run as it would without a source.
216
-
217
- - `browserWriterKeys(name)` keeps keys in this origin's IndexedDB, one
218
- database per slot (`<name>:writer:<slot>`, up to 32), each claimed under a Web
219
- Lock of the same name. A tab or worker that finds a slot taken tries the
220
- next; one that closes, or crashes, frees its slot. The private key is
221
- non-extractable: a script in the page can sign with it while it runs, but
222
- can't take it away. Without IndexedDB or Web Locks it gives none.
223
- - A node started from a store description (`startPageNode`, a node in a
224
- worker) claims from `browserWriterKeys` under the account's IndexedDB prefix,
225
- whether its stores are in IndexedDB or a data folder, so signing out
226
- (`deleteBrowserData`) deletes the keys too. The key never goes in the data
227
- folder, which other apps and devices share.
228
- - `forget()` drops the key but keeps its places, which still count while it
229
- signs this run; the slot's next claim makes a new key and clears them.
230
- `revokeSelf` forgets the claimed key before it writes a single revoke, so a
231
- page closed while the revokes wait leaves no revoked key to claim again.
232
- With a peer connected in any open space, each revoke waits up to
233
- `waitMs` for one to take it in; with none, none wait. A node that claims a
234
- key the account registry has revoked anyway (one forgotten by an older
235
- version, say) forgets it and starts again on a key for this run alone; the
236
- next start claims a new lasting one.
237
- - A node never signs at a place behind one it took itself this run: if the
238
- slot has lost them (site data cleared while the page was open), every
239
- write fails until the page reloads, since signing on would fork the line
240
- and withdraw what the key wrote. A slot whose connection the browser
241
- closed opens again only while it still holds the key.
242
- - The CLI keeps them outside its home, in `<local>/writer-keys/slot-<n>/` (`localPath` in `packages/cli/src/home.ts`, [sync and storage](storage.md#data-folders)): the key as
243
- JWK in an envelope (spec 01 §9.1) under the account's local key, with label
244
- `minca/writer-key/v1` and bound `{ did: <account DID>, slot: <n> }`
245
- (`key.sealed`, mode 600), so a copy of the files can't sign, and a key file
246
- moved to another slot or account is refused rather than used; its places in
247
- `heads/`; and numbered `lock.<n>` files naming the process that holds the
248
- highest, taken over once that process is gone.
249
-
250
- _Source: `packages/core/src/node/writer-keys.ts` (`browserWriterKeys`), `packages/core/src/node/writers.ts` (`createWriters`), `packages/core/src/node/node.ts` (`createNode`, `revokeSelf`), `packages/core/src/node/stores.ts` (`writerKeysFor`), `packages/core/src/node/worker.ts` (`withWriterKey`), `packages/cli/src/writer-keys.ts` (`fileWriterKeys`), `packages/cli/src/home.ts` (`unlock`, `nodeFor`). Tests: `packages/core/tests/writer-logs.test.ts` ("a writer key that outlives the node"), `packages/cli/tests/writer-keys.test.ts` ("a key file moved to another slot, or to another account, does not open")._
251
-
252
- Sign-in ([sign-in](sign-in.md)) uses `storesFor(account)`: IndexedDB with prefix
253
- `minca:<dataPath with : for />` in the browser, or `folderStores(pod,
155
+ ## Stores
156
+
157
+ A node asks its `StoreFactory` for stores by path:
158
+
159
+ | Path | Holds | Sealed |
160
+ | ------------------ | ----------------------------------------------------- | ------ |
161
+ | `registry` | the node's list of spaces and their keys | yes |
162
+ | `spaces/<spaceId>` | one space's records, and what the node keeps about it | no |
163
+ | `writers` | each lasting key's place in each line | no |
164
+
165
+ It also opens `mirrors/<spaceId>/<n>` for a [mirror](storage.md#mirrors),
166
+ `folder/<spaceId>` for a data folder, and `host` for a host's subscriptions.
167
+
168
+ What a path means is up to the factory:
169
+
170
+ - `indexedDBStores(prefix)` makes one IndexedDB database per path, named
171
+ `<prefix>:<path with / replaced by :>`. It never seals, since the browser
172
+ profile already guards it.
173
+ - `folderStores(directory, { basePath?, localKey?, local? })` uses a
174
+ [data folder](storage.md#data-folders). The `registry` goes in the folder
175
+ under `basePath`, sealed under `localKey` (`deriveLocalKey(seed)`) when
176
+ given. Every other path goes in `local`, and each space is mirrored to the
177
+ folder's segments.
178
+ - `directoryStores(directory, { localKey? })` uses a directory on this
179
+ device, one file per entry and per version, sealing the `registry` the same
180
+ way.
181
+
182
+ [Sign-in](sign-in.md) picks stores with `storesFor(account)`: IndexedDB with
183
+ prefix `minca:<dataPath with : for />` in the browser, or `folderStores(pod,
254
184
  { basePath: account.dataPath, localKey })` in a pod, where `dataPath` is
255
- `accounts/<id>/stores`. A connected app uses `indexedDBStores('minca-app:<account DID>')`
256
- by default. These names are _implementation details_ ([sync and storage](storage.md#indexeddb));
257
- a pod's layout is in
258
- [05](https://github.com/leifriksheim/minca/blob/main/spec/05-sync-and-storage.md).
259
- A node also opens `mirrors/<spaceId>/<n>` for a mirror's writer state
260
- ([mirrors](storage.md#mirrors)), `folder/<spaceId>` for a data folder's, and
261
- a host `host` for its subscriptions.
185
+ `accounts/<id>/stores`. A connected app uses
186
+ `indexedDBStores('minca-app:<account DID>')`. These names may change
187
+ ([sync and storage](storage.md#indexeddb)). A pod's layout is in
188
+ [spec 05](https://github.com/leifriksheim/minca/blob/main/spec/05-sync-and-storage.md).
262
189
 
263
- `copyAccountData({ from, to, did, accountKey? })` copies every space an
264
- account holds, with its key and records, from one set of stores to another —
265
- the account registry too, when `accountKey` is given. It is a union: every
266
- version goes through the same ordering rule as sync, so copying into a store
267
- that holds some of it already is safe, and copying twice changes nothing.
190
+ ### Copying an account
268
191
 
269
- Copied versions are meant to pass the same checks as versions arriving by
270
- sync ([02 — Records](https://github.com/leifriksheim/minca/blob/main/spec/02-records.md), validation) before they are stored.
192
+ `copyAccountData({ from, to, did, accountKey? })` copies every space an
193
+ account holds, with its keys and records, from one set of stores to another.
194
+ With `accountKey` it copies the account registry too. It merges by the same
195
+ rule as sync, so copying into a store that has some of it already is safe,
196
+ and copying twice changes nothing.
197
+
198
+ > **Known defect:** `copyAccountData` stores versions without validating
199
+ > them, so a pod another origin wrote to can
200
+ > bring in versions a peer's would have been refused. Tracked in
201
+ > [#20](https://github.com/leifriksheim/minca/issues/20).
202
+
203
+ ### Places in a key's line
204
+
205
+ Every version a key signs in a space takes the next place in that key's line
206
+ for the collection. Writes by one key in one space go one at a time, and the
207
+ place is saved before the version leaves the node. Where it is saved depends
208
+ on the key:
209
+
210
+ - **A key made for this run** keeps its places in memory.
211
+ - **A writer key** (`config.writerKey`) keeps them beside the key.
212
+ - **A key handed in** (`config.sessionKey`) or a carrier's key keeps them in
213
+ the `writers` store, so a restart carries on.
214
+
215
+ A handed-in key may sign in several nodes at once: every tab of an app signs
216
+ with the app's key. So each place is taken under a Web Lock
217
+ (`minca-writer:lines/<did>/<space>`) shared by the origin's tabs and workers,
218
+ and read fresh from the store each time. Nodes that share a key must share
219
+ that store too. Two nodes signing with one key from separate stores fork its
220
+ lines, and every peer then withdraws what it signed in a forked collection
221
+ from the fork on.
222
+ [Spec 02 §4.10](https://github.com/leifriksheim/minca/blob/main/spec/02-records.md).
271
223
 
272
- > **Known defect:** `copyAccountData` stores each version with
273
- > `addVersion` directly, without running it through the validation
274
- > pipeline (`packages/core/src/node/copy.ts`). A pod or data folder that another origin
275
- > wrote to can bring versions this node would have refused from a peer. A fix
276
- > will validate on copy, as sync does.
277
- > Tracked in [#20](https://github.com/leifriksheim/minca/issues/20).
224
+ ### Writer keys
278
225
 
279
- _Source: `packages/core/src/node/stores.ts`, `packages/core/src/node/copy.ts`, `packages/core/src/session/places.ts` (`storesFor`). Tests: `packages/core/tests/account.test.ts`, `packages/core/tests/folder-adapter.test.ts`._
226
+ With `writerKey`, a node claims a lasting key when it starts and signs with
227
+ it until it closes. The device then keeps one log in each space, instead of
228
+ a new one each run. A key goes to one node at a time. If every key is taken,
229
+ or none can be locked, the node makes a key for this run instead.
230
+
231
+ In the browser, `browserWriterKeys(name)` keeps up to 32 keys in IndexedDB,
232
+ one database per slot (`<name>:writer:<slot>`), each claimed under a Web Lock
233
+ of the same name. A tab that finds a slot taken tries the next. A tab that
234
+ closes or crashes frees its slot. The private key can't be extracted: a
235
+ script in the page can sign with it while it runs, but can't take it away.
236
+ Without IndexedDB or Web Locks there are no writer keys.
237
+
238
+ A node started from a store description, such as `startPageNode` or a node in
239
+ a worker, claims its key under the account's IndexedDB prefix, even when its
240
+ stores are in a data folder. So signing out (`deleteBrowserData`) deletes the
241
+ keys too, and a key never goes in a data folder that other apps share.
242
+
243
+ What happens when a key goes away:
244
+
245
+ - `forget()` drops the key but keeps its places, which still count for this
246
+ run. The slot's next claim makes a new key and clears them.
247
+ - `revokeSelf` forgets the claimed key before it writes a single revoke, so a
248
+ page closed mid-way leaves no revoked key to claim again. With a peer
249
+ connected in any open space, each revoke waits up to `waitMs` for one to
250
+ take it in.
251
+ - A node that claims a key the account registry has revoked forgets it, and
252
+ uses a key for this run. The next start claims a new lasting one.
253
+ - A node never signs at a place behind one it already took this run. If the
254
+ slot lost its places (site data cleared while the page was open), every
255
+ write fails until the page reloads, since signing on would fork the line.
256
+ A slot whose connection the browser closed reopens only while it still
257
+ holds the key.
258
+
259
+ The CLI keeps its writer keys outside its home, in
260
+ `<local>/writer-keys/slot-<n>/` ([data folders](storage.md#data-folders)).
261
+ The key is sealed under the account's local key in `key.sealed` (mode 600,
262
+ label `minca/writer-key/v1`, bound to `{ did, slot }`), so a copy of the files
263
+ can't sign, and a key moved to another slot or account is refused. Its places
264
+ are in `heads/`, and numbered `lock.<n>` files name the process holding it,
265
+ taken over once that process is gone.
280
266
 
281
267
  ## Opening and holding spaces
282
268
 
283
- A space is opened (its store read, its peers joined, sync started) the first
284
- time anything asks for it — a read, a write, a status — and stays open until
285
- it is released or the node closes. Opening a space also: publishes the
286
- account's profile in it ([following the account](#following-the-account)), checks whether the session note was revoked
287
- there ([events](#events), `revoked`), and names the account's carriers as keepers if the
288
- account manages it ([spec 06 §4.2](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)).
269
+ A space opens the first time anything asks for it: a read, a write, a status.
270
+ Opening reads its store, joins its peers and starts syncing. It also
271
+ publishes the account's profile there, checks whether the node's note was
272
+ revoked there ([`revoked`](#events)), and names the account's carriers as
273
+ keepers if the account manages the space.
289
274
 
290
- `spaces.hold(id)` keeps a space open until released. It returns a function
291
- that lets go of that one hold:
275
+ The space stays open until it is released or the node closes.
276
+ `spaces.hold(id)` keeps it open, and resolves to a function that lets go:
292
277
 
293
- - Holds are counted per space. When the count reaches zero, the space closes.
294
- - Releasing twice does nothing.
295
- - A hold made before the space was closed for another reason (leaving it) is
296
- tied to that stretch of being held: releasing it later does nothing to a hold
297
- made after rejoining.
298
- - Reading or writing needs no hold.
278
+ ```ts
279
+ const release = await node.spaces.hold(space.id);
280
+ // later
281
+ await release();
282
+ ```
299
283
 
300
- > Rationale: anything that needs a space live holds it — a screen showing it, a
301
- > call in it — so a screen going away never cuts off a call in the same space.
284
+ - Holds are counted per space. At zero, the space closes.
285
+ - Releasing twice does nothing.
286
+ - A hold from before the space was left is tied to that time. Releasing it
287
+ later doesn't touch a hold made after rejoining.
288
+ - Reading and writing need no hold.
302
289
 
303
- _Source: `packages/core/src/node/node.ts` (`runtime`, `hold`, `closeRuntime`). Tests: `packages/core/tests/live.test.ts` ("holding a space")._
290
+ Anything that needs a space live holds it, such as a screen or a call. That
291
+ way a screen going away never cuts off a call in the same space.
304
292
 
305
293
  ## Leaving a space
306
294
 
307
- `spaces.leave(id)` first gives up the account's place in the space
308
- ([spec 03 §6.2](https://github.com/leifriksheim/minca/blob/main/spec/03-spaces.md)):
309
- it writes the account's own removal, `sys.remove` naming itself, so the
310
- others stop counting it a reader and a private space's key changes. Leaving
311
- needs no grant. A founder who leaves is a founder no more, for good; to stay
312
- without being one, `spaces.stepDown`
313
- ([spaces](spaces.md#the-top-and-founders)). Then it deletes
314
- the space's `sys.joined` record in the account registry, closes the space and
315
- forgets it with its keys. The account registry, the contacts space and carry
316
- spaces cannot be left.
317
-
318
- - The removal goes out only while the space is open, so `leave` waits up to
319
- 5 s for a peer of another account to say it has it. With nobody reachable,
320
- it leaves anyway.
321
- - Another device of the account that follows the deleted `sys.joined`, and
322
- still sees the account holding a place, writes the removal itself, and waits
323
- the same way.
324
- - Shared to view, or the only reader left, there is nothing to write and
295
+ `spaces.leave(id)` first gives up the account's place. It writes a
296
+ `sys.remove` naming the account, so the others stop counting it a reader and a
297
+ private space's key changes. Leaving needs no grant. Then it deletes the
298
+ space's `sys.joined` record, closes the space and forgets it with its keys.
299
+
300
+ A founder who leaves is a founder no more, for good. To stay without being
301
+ one, use [`spaces.stepDown`](permissions.md#the-top-and-founders).
302
+
303
+ - The removal waits up to 5 seconds for a peer of another account to have
304
+ it. With nobody reachable, the node leaves anyway.
305
+ - Another device of the account that sees the `sys.joined` record go, while
306
+ the account still holds a place, writes the removal itself.
307
+ - Shared to view, or the last reader left, there's nothing to write, and
325
308
  `leave` returns at once.
326
- - A note that may not change access (a narrow app note) can't write the
327
- removal; `leave` still forgets the space, and another device writes it.
309
+ - A narrow app note that may not change access can't write the removal.
310
+ `leave` still forgets the space, and another device writes it.
328
311
 
312
+ The account registry, the contacts space and carry spaces can't be left.
329
313
  `contacts.remove` and `contacts.block` leave the space for two this way.
330
-
331
- _Source: `packages/core/src/node/node.ts` (`spaces.leave`, `giveUpPlace`, `forget`, `LEAVE_WAIT_MS`), `packages/core/src/node/space-membership.ts` (`giveUpPlace`), `packages/core/src/node/space-peers.ts` (`writeUntilStored`). Tests: `packages/core/tests/key-change.test.ts` ("leaving a private space"), `packages/core/tests/contacts.test.ts` ("removing a contact gives up your place"), `packages/core/tests/node.test.ts` ("the account registry"), `packages/core/tests/carrier.test.ts` ("its carry space cannot be left…")._
314
+ [Spec 03 §6.2](https://github.com/leifriksheim/minca/blob/main/spec/03-spaces.md).
332
315
 
333
316
  ## Holding part of a space
334
317
 
335
- With `config.cache`, and once a space names at least one keeper
336
- ([03](https://github.com/leifriksheim/minca/blob/main/spec/03-spaces.md), `sys.keepers`), the node holds only the collections it
337
- uses, besides the space's own `sys.*` collections. Everything about this is the
338
- node's own choice; how it tells peers what it holds is in
339
- [05](https://github.com/leifriksheim/minca/blob/main/spec/05-sync-and-storage.md). As implemented:
340
-
341
- - Collections listed in `cache.collections` are held from the start and never
342
- dropped.
343
- - A query marks the collections it reads (its own and every `include … from`)
344
- as used; sync then fetches them. A query's result has `complete: false`
345
- until, for every collection it reads, the node has once been level with a
346
- node holding the whole space, **and** it lacks nothing a writer's line in
347
- that collection names
348
- ([spec 02 §4.10](https://github.com/leifriksheim/minca/blob/main/spec/02-records.md)).
349
- A version naming one not here adds it to `missing` and asks every peer for
350
- it by id; when it arrives it comes off. They are asked again whenever the
351
- collection is level with a peer.
352
- - Until the node has once caught up fully with a node holding the whole space,
353
- it cannot know whether the space names keepers, so it holds only what it uses.
354
- - The node's own writes are _pending_ until `min(keepers named, max(copies ?? 2,
355
- cache.copies ?? 0))` of the space's named keepers have them. A collection
356
- holding a pending write is never dropped.
357
- - A collection unused for `cache.unusedAfterDays` (default 30) days is dropped
358
- when the space opens and every 6 hours while it stays open. It stops being
359
- held _before_ its versions are removed, so nothing syncs it back meanwhile.
360
- - A space that names no keeper is held whole, and the node may itself be one
361
- of its copies.
362
- - When what it holds changes (whole or part, or a newly used collection), the
363
- node says hello to every peer.
364
-
365
- A keeper confirms a write the way the spec says: by `stored`, or by being
366
- level with the writer on its collection. Only a peer named in `sys.keepers`
367
- counts ([spec 05 §9](https://github.com/leifriksheim/minca/blob/main/spec/05-sync-and-storage.md)).
368
-
369
- This state is kept in the space's own store (`spaces/<spaceId>`):
370
-
371
- | Key | Value (UTF-8 JSON) |
372
- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
373
- | `cache` | `{ "settled": boolean, "used": { [collection]: ms }, "level": { [collection]: ms }, "missing": { [collection]: [version id…] } }`. `settled`: has synced with a whole-space peer; `used`: when a query last used it; `level`: when it was first level with a whole-space peer; `missing`: what a writer's line there names that isn't here |
374
- | `pending/<version id>` | `{ "collection": string, "by": [keeper DID…] }`, deleted once `by` reaches the target |
375
-
376
- What a keeper withholds from the middle of a writer's line shows up as
377
- missing, whichever peer the node was level with. A writer's newest versions
378
- are named by no line yet; holding those back needs every peer the node syncs
379
- with to do it.
380
-
381
- The account registry, the contacts space and carry spaces are always held
382
- whole. Apps connected to an account home use `cache: {}` by default ([the app-side client](#the-app-side-client)).
383
-
384
- _Source: `packages/core/src/node/space-holding.ts` (`openSpaceHolding`), `packages/core/src/node/types.ts` (`CacheConfig`). Tests: `packages/core/tests/caches.test.ts`, `packages/core/tests/reconcile.test.ts` ("holding part of a space")._
318
+ A node doesn't need every record in a space. With `config.cache`, once a space
319
+ names at least one keeper, the node holds only the collections it uses, plus
320
+ the space's own `sys.*` collections. Apps connected to an account home do this
321
+ by default.
322
+
323
+ ```ts
324
+ declare const signer: RootSigner;
325
+ // ---cut---
326
+ import { createNode, indexedDBStores, type RootSigner } from '@minca/core';
327
+
328
+ const node = await createNode({
329
+ signer,
330
+ stores: indexedDBStores('my-app'),
331
+ cache: { collections: ['app.todo.item'] },
332
+ });
333
+ ```
385
334
 
386
- ### Planned: caches that widen and trim
335
+ `cache` is a [`CacheConfig`](https://minca.dev/api/core/interfaces/CacheConfig/): the
336
+ collections to hold from the start, when to drop one nothing uses, and how
337
+ many keepers a write must reach.
338
+
339
+ ### What gets held
340
+
341
+ - A query marks every collection it reads as used, including each
342
+ `include … from`, and a write marks the one it writes. Sync then fetches
343
+ them.
344
+ - Until the node has caught up once with a node holding the whole space, it
345
+ can't know whether the space names keepers, so it holds only what it uses.
346
+ - An unused collection is dropped when the space opens, and every 6 hours
347
+ while it stays open. It stops being held before its versions go, so nothing
348
+ syncs it back meanwhile. A collection with a pending write is never dropped.
349
+ - A space that names no keeper is held whole.
350
+ - The account registry, the contacts space and carry spaces are always held
351
+ whole.
352
+ - When what it holds changes, the node says hello to every peer again.
353
+
354
+ ### Complete results
355
+
356
+ A query's result has `complete: false` until, for every collection it reads,
357
+ the node has been level once with a node holding the whole space, and it
358
+ lacks nothing a writer's line there names. A version that names one the node
359
+ doesn't have adds it to `missing`, and the node asks every peer for it by id.
360
+ It asks again whenever the collection is level with a peer.
361
+
362
+ So what a keeper withholds from the middle of a writer's line shows up as
363
+ missing. A writer's newest versions aren't named by any line yet, so holding
364
+ those back would take every peer the node syncs with.
365
+
366
+ ### Pending writes
367
+
368
+ In a space that names keepers, every node's own writes are _pending_ until
369
+ `min(keepers named, max(copies ?? 2, cache.copies ?? 0))` keepers have them. A
370
+ keeper's own node counts as one. A keeper confirms a write with `stored`, or by
371
+ being level with the writer on its collection. Only peers named in
372
+ `sys.keepers` count. A node holding part of a space keeps pending writes in
373
+ its store across runs. One holding all of it keeps the latest 4096 in memory.
374
+
375
+ `node.spaces.kept(spaceId, waitMs, since?)` waits up to `waitMs`, at most a
376
+ minute, for this node's writes to be kept elsewhere:
377
+
378
+ - In a space with keepers, it says `'keepers'` once none of its writes from
379
+ `since` (ms) on is pending.
380
+ - In a space without, it says `'peer'` once a connected peer holds all this
381
+ node does. That's less sure, since the peer may be a device that goes away.
382
+ - It says `null` if nobody had them in time.
383
+
384
+ Wait on it before a node stops: a tab about to close, a command about to exit,
385
+ a server's node at the end of its job.
386
+
387
+ ### What the node stores
388
+
389
+ This state lives in the space's own store, `spaces/<spaceId>`:
390
+
391
+ | Key | Value (JSON) |
392
+ | ---------------------- | -------------------------------------------------------------------- |
393
+ | `cache` | `{ settled, used, level, missing }`, below |
394
+ | `pending/<version id>` | `{ collection, by: [keeper DID…], at }`, deleted once `by` is enough |
395
+
396
+ In `cache`, `settled` says whether the node has synced with a whole-space
397
+ peer. `used` maps each collection to when a query last used it, `level` to
398
+ when it was first level with a whole-space peer, and `missing` to the version
399
+ ids a writer's line names that aren't here.
400
+ [Spec 05 §9](https://github.com/leifriksheim/minca/blob/main/spec/05-sync-and-storage.md).
387
401
 
388
- > **Planned.** None of it changes what other nodes see. Fetching linked
389
- > records by key, and holding less than a collection, need new messages and
390
- > are planned in [spec 05 §9.1](https://github.com/leifriksheim/minca/blob/main/spec/05-sync-and-storage.md).
402
+ ### Planned: caches that widen and trim
391
403
 
392
- - **Widening.** A node holding part of a space starts holding all of it when
393
- too few keepers are online (Holochain's arcs: nodes grow their share when
394
- others go missing). Opt-in only (`cache.widen: true`), since done on its own
395
- it could fill a disk at a bad moment. Open: what "too few" is, and for how
396
- long. Today a cache only widens as queries use collections.
397
- - **Trimming by size.** `cache.maxBytes`: above it, drop least recently used
398
- collections first, undeclared ones before declared. Also trim when
399
- `navigator.storage.estimate()` says room is low, before the browser clears
400
- the site. Pending writes are never dropped.
404
+ > **Planned.** A node holding part of a space would hold all of it when too
405
+ > few keepers are online (opt-in, `cache.widen: true`), and drop least
406
+ > recently used collections above `cache.maxBytes` or when the browser runs
407
+ > low on room. Fetching linked records by key, and holding less than a
408
+ > collection, are planned in
409
+ > [spec 05 §9.1](https://github.com/leifriksheim/minca/blob/main/spec/05-sync-and-storage.md).
401
410
 
402
411
  ## Following the account
403
412
 
404
- What counts in the account's list of spaces, and what a device with the
405
- account key must keep current for carriers, is protocol
406
- ([spec 06 §1.3](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)). How the reference node does it:
407
-
408
- The node's `registry` store ([stores](#stores)) lists every space it holds,
409
- with its key(s), its invite secret while one is waiting to be used, its place
410
- (`founder`, or a role it holds) as last seen, the relays the space names and, for an app without the account
411
- key, its member key. Its format is the node's own
412
- (`packages/core/src/space/space-manager.ts`).
413
-
414
- Three kinds of space are the account's own machinery and are hidden from
415
- `spaces.list`:
416
-
417
- | Space | Derived from | Notes |
418
- | -------------------- | ------------------------------------------ | -------------------------------------------------------------- |
419
- | The account registry | the account key | Never in the node's registry; opened directly. Cannot be left. |
420
- | The contacts space | the account key, or `config.contactsSpace` | Held in the registry, hidden. Cannot be left. |
421
- | Carry spaces | the account key and the carrier's key | Never in the node's registry; opened directly. Cannot be left. |
422
-
423
- **Reconciling.** With an account key, the node makes its spaces match the
424
- account's list of `sys.joined` records. This runs at start and whenever
425
- records change in the account registry, one run at a time. It:
426
-
427
- 1. joins every space a live `sys.joined` record names that the node does not
428
- hold, using the view-only invite in the record;
429
- 2. leaves every space whose `sys.joined` record is deleted;
430
- 3. writes a `sys.joined` record for any space held here that the account
431
- registry has never heard of (joined before the registry existed, or on a
432
- node without the account key);
433
- 4. brings every carrier's passes and wakes up to date
434
- ([spec 06 §4.2](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md));
435
- 5. names the account's carriers as keepers of the open spaces it manages
436
- (also whenever a space opens);
437
- 6. asks every host the account uses how it stands, handing it the spaces if it
438
- has been paid since ([carriers and hosting](#carriers-hosting-and-notifications)),
439
- without waiting for the answer.
440
-
441
- Creating or joining a space writes its `sys.joined` record; leaving deletes it.
442
-
443
- **Profiles.** When a space opens, when the node's account takes a place in it,
444
- and when the account's name changes on any device, the node publishes the
445
- account's profile in that space: `{ name, contactKey? }`, with the name taken
446
- from the account registry's `sys.profile` record and `contactKey` only when
447
- the node holds the contact key. It does this only in spaces other than the
448
- account registry and the contacts space, only with an account name to publish,
449
- and never under a note that lacks `/account/write`, such as an agent's. The profile record format is in
450
- [03](https://github.com/leifriksheim/minca/blob/main/spec/03-spaces.md).
451
-
452
- **Joining.** `spaces.join(invite)` accepts a bare invite or any link carrying
453
- `#invite=…`, `?invite=…` or `&invite=…`, long or short; a short one is
454
- fetched from its mailboxes first ([spaces](spaces.md#invites)). It stores the space (and its key, for
455
- a private space), stores `memberKey` when given, writes the `sys.joined`
456
- record, then tries to use the invite's role secret at once. If the space's
457
- invite record has not reached this device yet, the space is held with
458
- `joining: true` and the node tries again each time records arrive in it.
459
-
460
- **Leaving.** `spaces.leave(id)` gives up the account's place in the space,
461
- then deletes the `sys.joined` record, closes the space and forgets it with its
462
- key ([leaving a space](#leaving-a-space)).
463
-
464
- _Source: `packages/core/src/node/node.ts` (`reconcileOnce`, `remember`, `forget`, `finishJoining`, `spaces`), `packages/core/src/node/node-contacts.ts` (`publishProfile`), `packages/core/src/space/space-manager.ts`. Tests: `packages/core/tests/node.test.ts` ("the account registry"), `packages/core/tests/profiles.test.ts`, `packages/core/tests/space-access.test.ts`._
413
+ With the account key, a node keeps its spaces in step with the account's
414
+ list in the account registry. Join a space on your phone, and your laptop
415
+ joins it too.
416
+
417
+ The node's own `registry` store lists each space it holds: its keys, an
418
+ invite secret while one waits to be used, the account's place there as last
419
+ seen, the relays the space names, and, for an app without the account key,
420
+ its member key.
421
+
422
+ Three kinds of space are the account's own machinery, and `spaces.list`
423
+ hides them:
424
+
425
+ | Space | Derived from | Notes |
426
+ | -------------------- | ------------------------------------------ | ---------------------------------------------------------------------- |
427
+ | The account registry | the account key | Opened directly. Can't be left. |
428
+ | The contacts space | the account key, or `config.contactsSpace` | In the node's registry, so it can be granted to an app. Can't be left. |
429
+ | Carry spaces | the account key and the carrier's key | Opened directly. Can't be left. |
430
+
431
+ ### Reconciling
432
+
433
+ At start, and whenever the account registry changes, the node reconciles,
434
+ one run at a time:
435
+
436
+ 1. It joins every space a `sys.joined` record names that it doesn't hold,
437
+ with the view-only invite in the record.
438
+ 2. It leaves every space whose `sys.joined` record was deleted.
439
+ 3. It writes a `sys.joined` record for a space it holds that the registry
440
+ doesn't know.
441
+ 4. It brings every carrier's passes and wakes up to date.
442
+ 5. It names the account's carriers as keepers of the open spaces it manages.
443
+ 6. It asks each host the account uses how it stands, without waiting, and
444
+ hands it the spaces if it was paid ([hosting](#carriers-hosting-and-notifications)).
445
+
446
+ Creating or joining a space writes its `sys.joined` record. Leaving deletes it.
447
+
448
+ ### Profiles
449
+
450
+ The node publishes the account's profile, `{ name, contactKey? }`, in a space
451
+ when it opens, when the account takes a place there, and when the name
452
+ changes on any device. The name comes from the registry's `sys.profile`
453
+ record, and `contactKey` is included only when the node holds it. It skips
454
+ the account registry and the contacts space, an account with no name, and
455
+ any note without `/account/write`, such as an agent's.
456
+
457
+ ### Joining
458
+
459
+ `spaces.join(invite)` takes a bare invite, or any link with `#invite=…`,
460
+ `?invite=…` or `&invite=…`. A short link is fetched from its mailboxes first
461
+ ([invites](spaces.md#invites)). It stores the space and its key, and
462
+ `memberKey` when given, writes the `sys.joined` record, then uses the
463
+ invite's role secret. If the space's invite record hasn't arrived yet, the
464
+ space shows `joining: true`, and the node tries again each time records
465
+ arrive.
466
+ [Spec 06 §1.3](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md).
465
467
 
466
468
  ## Events
467
469
 
468
- `node.subscribe(listener)` delivers `NodeEvent`s and returns an unsubscribe
469
- function. A listener that throws does not stop the others.
470
+ `node.subscribe(listener)` tells you what happens, and returns a function to
471
+ stop. A listener that throws doesn't stop the others.
470
472
 
471
- | `type` | Fields | When |
472
- | ---------- | ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
473
- | `records` | `space` | Records were added, changed or deleted in a space, locally or by sync. |
474
- | `status` | `space` | Connection state or peers changed. A status change in the account registry is re-emitted for every open space (which peers are the account's own is read off the registry's peers). |
475
- | `spaces` | — | The node's list of spaces changed: created, joined, left, a role or waiting invite changed. |
476
- | `account` | — | The account's profile may have changed (records changed in the account registry, or `setName`). |
477
- | `rejected` | `space`, `peer`, `reason` | A peer sent a version that failed validation. |
478
- | `message` | `space`, `from`, `peer`, `recordsOnly`, `message` | A live message arrived ([live messages and status](#live-messages-and-status)). |
479
- | `revoked` | `space` | The note this node writes under was revoked in that space. Emitted at most once per space per node. |
473
+ ```ts
474
+ const stop = node.subscribe((event) => {
475
+ if (event.type === 'records') console.log('changed in', event.space);
476
+ });
477
+ ```
480
478
 
481
- _Source: `packages/core/src/node/types.ts` (`NodeEvent`), `packages/core/src/node/node.ts` (`fromRuntime`, `checkRevoked`). Tests: `packages/core/tests/node.test.ts` ("events announce local writes"), `packages/core/tests/connect.test.ts` ("disconnecting revokes the note")._
479
+ Each event is a [`NodeEvent`](https://minca.dev/api/core/type-aliases/NodeEvent/), told
480
+ apart by its `type`: records changed, status, the list of spaces, the account,
481
+ a refused version, a live message, a revoked note, or the network.
482
+
483
+ A `status` change in the account registry is sent for every open space too,
484
+ since that is where the node learns which peers are the account's own.
482
485
 
483
486
  ### Versions that wait or are refused
484
487
 
485
- A version from a peer stands, waits or is refused
486
- ([spec 02 §9.5](https://github.com/leifriksheim/minca/blob/main/spec/02-records.md)).
487
- What the node does with each is its own:
488
-
489
- - A batch from a peer is admitted `sys.collection` versions first, then by
490
- ascending `seq`, so definitions and first versions are in before what
491
- depends on them and little has to wait.
492
- - A version that waits is held in memory, at most 1,000, the oldest dropped
493
- when full, and judged again whenever something new is stored. A version
494
- waiting for its first version, or the one before it, asks the peer for
495
- them at once.
496
- - A withdrawn version (allowed when written, then taken away by a removal or
497
- a revoke it had not seen) is stored and passed on like one that stands,
498
- emits no `rejected` event, and never shows as a record: `records.get` and queries skip
499
- it. It is there for proofs that cite it ([spec 09 §6](https://github.com/leifriksheim/minca/blob/main/spec/09-contracts.md)).
500
- - A version that fails its collection's contract stands: it is stored and
501
- passed on, emits no `rejected` event, and `records.get` and queries skip
502
- it ([contracts](contracts.md)).
503
- - A refused version emits a `rejected` event with the peer and the reason,
504
- and is remembered as (peer, id), at most 10,000, so it is not asked of that
505
- peer again. Never by id alone: a copy with a mangled signature has the
506
- genuine version's id.
507
-
508
- _Source: `packages/core/src/sync/sync-engine.ts` (`admit`, `admitAll`, `rank`, `MAX_WAITING`, `MAX_REFUSED`). Tests: `packages/core/tests/reconcile.test.ts` ("a refused version is not asked for again", "a version that waits for its first version asks for it at once, and is acknowledged once in")._
488
+ A version from a peer stands, waits or is refused. What the node does with
489
+ each:
490
+
491
+ - A batch is taken in `sys.collection` versions first, then by `seq`, so
492
+ what others depend on is in first and little has to wait.
493
+ - A version that waits is held in memory, at most 1,000, oldest dropped
494
+ first, and judged again whenever something new is stored. One waiting for
495
+ an earlier version asks the peer for it at once.
496
+ - A withdrawn version, allowed when written but taken away by a removal or a
497
+ revoke it hadn't seen, is stored and passed on. It sends no `rejected`
498
+ event and never shows as a record. It is kept for proofs that cite it
499
+ ([spec 09 §6](https://github.com/leifriksheim/minca/blob/main/spec/09-contracts.md)).
500
+ - A version that breaks its collection's [contract](contracts.md) is also
501
+ stored and passed on, with no `rejected` event, and `records.get` and
502
+ queries skip it.
503
+ - A refused version sends a `rejected` event and is remembered by peer and
504
+ id, at most 10,000, so it isn't asked of that peer again. Never by id
505
+ alone: a copy with a mangled signature has the real version's id.
506
+
507
+ [Spec 02 §9.5](https://github.com/leifriksheim/minca/blob/main/spec/02-records.md).
509
508
 
510
509
  ## Live messages and status
511
510
 
512
- `spaces.send(id, message, to?)` sends a JSON value to the peers connected in
513
- the space right now, kept nowhere and signed as nothing. The message is
514
- `JSON.stringify(message ?? null)`; if that is longer than 65 536 characters
515
- the call throws "A live message can be at most 64 KB". It goes as a `live`
516
- message to every connected peer of the space, once per peer, over whichever
517
- network that peer was last connected on. With `to`, it goes only to peers
518
- whose session DID equals `to` (one device), or whose account DID, as learned
519
- from their `who`, equals `to` (every device of that account); a peer whose
520
- `who` has not been checked yet is matched by session DID only. In a private
521
- space, nothing goes to someone removed or who left, and nothing from them is
522
- emitted. An agent's node
523
- refuses `send` ([acting as an agent](#a-node-acting-as-an-agent)). The wire
524
- format, the per-peer allowance (a burst of 60, then 20 per second) and how the
525
- sender's account is established are in
526
- [spec 04 §9](https://github.com/leifriksheim/minca/blob/main/spec/04-network.md).
527
-
528
- A received live message is emitted as a `message` event,
529
- `{ type: "message", space, from, peer, recordsOnly, message }`:
530
-
531
- | Field | Meaning |
532
- | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
533
- | `from` | The account behind the sending device, proven by the note it showed, made out to the key the connection proved. `null` for a peer that showed no note (a carrier, a node serving sockets). |
534
- | `peer` | The sending device's session DID — also where a reply to that device goes. |
535
- | `recordsOnly` | `true` when the sender's note grants writing records in this space and nothing more (`/record`): it can't define collections there ([spec 01 §8](https://github.com/leifriksheim/minca/blob/main/spec/01-identity.md)). `false` for a note that only reads. |
536
- | `message` | The value sent. |
537
-
538
- `spaces.status(id)` returns `SpaceStatus`:
539
-
540
- | Field | Meaning |
541
- | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
542
- | `connection` | `offline` (no network), `connecting`, `connected` (while any one transport is connected: a relay socket open, or a peer), `error` (the first connect failed and nothing has connected since). A space whose relays all drop and whose peers leave is `connecting` again, not `connected`. |
543
- | `peers` | Session DIDs connected in the space. |
544
- | `own` | Of `peers`, the account's own other devices and apps: those also connected in the account registry, minus carriers. Empty without an account key. |
545
- | `carriers` | Of `peers`, the account's carriers, by the keys `sys.carrier` records name. |
546
- | `accounts` | Session DID → account, for each peer that showed a valid note. |
547
- | `fingerprint` | A fingerprint of every version held; equal on two nodes means identical data ([the store in memory](storage.md#the-store-in-memory)). |
548
- | `rejected` | How many versions peers sent failed validation. |
549
- | `holds` | `"all"`, or the sorted list of collections held ([holding part of a space](#holding-part-of-a-space)). |
550
- | `pending` | This node's writes still waiting for keepers ([holding part of a space](#holding-part-of-a-space)). |
551
-
552
- > Rationale: a peer's key does not say whose it is, but only the account's own
553
- > devices and apps can read its registry, so a peer there is one of ours.
554
-
555
- _Source: `packages/core/src/node/node.ts` (`spaces.send`, `spaces.status`), `packages/core/src/node/space-peers.ts` (`send`, `onLive`), `packages/core/src/node/space-runtime.ts` (`status`). Tests: `packages/core/tests/live.test.ts`._
511
+ `spaces.send(id, message, to?)` sends any JSON value to the peers connected
512
+ in the space right now. It isn't stored or signed. Use it for things like
513
+ "typing…" or a cursor.
514
+
515
+ ```ts
516
+ await node.spaces.send(space.id, { typing: true });
517
+ ```
518
+
519
+ - The message, as JSON, can be at most 65,536 characters. Longer throws
520
+ "A live message can be at most 64 KB".
521
+ - It goes once to each connected peer, over whichever network it last used.
522
+ - With `to`, it goes only to the peer with that session DID (one device), or
523
+ to every device of the account with that DID. A peer whose account isn't
524
+ checked yet is matched by session DID only.
525
+ - In a private space, nothing goes to someone removed or who left, and
526
+ nothing from them arrives.
527
+ - An agent's node refuses `send`.
528
+
529
+ Each peer may send a burst of 60, then 20 a second.
530
+
531
+ A message that arrives is a `message` [event](https://minca.dev/api/core/type-aliases/NodeEvent/),
532
+ with the value sent, the sender's account and the device it came from.
533
+
534
+ [Spec 04 §9](https://github.com/leifriksheim/minca/blob/main/spec/04-network.md).
535
+
536
+ ### Status
537
+
538
+ `spaces.status(id)` tells you how a space is connected, as a
539
+ [`SpaceStatus`](https://minca.dev/api/core/interfaces/SpaceStatus/): its connection, the peers
540
+ connected and whose they are, a fingerprint of what it holds, and what it
541
+ holds and still has pending.
542
+
543
+ `connection` is `offline` with no network, and `connected` while any one
544
+ relay socket or peer is. A space whose relays all drop and whose peers leave
545
+ goes back to `connecting`. It is `error` only when the first connect failed
546
+ and nothing has connected since.
547
+
548
+ A peer's key doesn't say whose it is. But only the account's own devices and
549
+ apps can read its registry, so a peer there is one of ours. That is how `own`
550
+ is worked out.
556
551
 
557
552
  ## The rest of the node's surface
558
553
 
559
- The node's other parts are specified where their data lives; the node only
560
- exposes them. Every value a node method returns is JSON-serialisable, so the
561
- same calls can be exposed over a command line, MCP and WebMCP
562
- ([actions](actions.md)).
563
-
564
- - `node.spaces` — create, invite, preview, join, leave, access, `may`,
565
- `holdsRole`, `defineRole`, `assign`, `unassign`, `removeMember`, `stepDown`,
566
- `succeed`, `closeInvite`,
567
- `changeKey`, `setRelays`, `setKeepers`, `revoke`, `profiles`,
568
- `authenticator` ([03](https://github.com/leifriksheim/minca/blob/main/spec/03-spaces.md),
569
- [04](https://github.com/leifriksheim/minca/blob/main/spec/04-network.md)). Default invite role: `member` when
570
- the inviter may assign it, else the first role by name it may assign; with
571
- none, a view-only invite ([spaces](spaces.md#invites)).
572
- - `access(id)` answers `{ roles, members, invites, founder, top, headless,
573
- successors, mine, heads, key, relays, keepers, copies, forks, flagged }`
574
- ([spaces](spaces.md#the-top-and-founders)). Each role has its
575
- current `definitions` (one, or rivals that hold only the grants they
576
- share), each with `event`, `by` (null for the constitution's), `grants`
577
- and `nests`. Each member is `{ did, founder, roles }`. `founder` and
578
- `mine` say what this account is here.
579
- - `may(id, cmd, args?, account?)` asks whether this account, or another,
580
- may invoke a command with these arguments now, as the replay judges it
581
- ([spec 03 §2](https://github.com/leifriksheim/minca/blob/main/spec/03-spaces.md)).
582
- Apps use it to show what someone can do; peers judge each version on
583
- its own.
584
- - `holdsRole(id, role, account?)` asks whether this account, or another,
585
- holds every grant a role gives, each as wide or wider: its own grant's
586
- command covers it, and every statement of its policy is among the
587
- role's. Only the words are compared, so it can say no where the
588
- policies would allow, never yes where they wouldn't. Apps use it before
589
- giving a bot a role, and `minca agent` before taking instructions.
590
- - `defineRole(id, { name, title?, grants, nests? })` writes the role's
591
- definition, each grant a delegation from this account to the role. It
592
- holds only what this account could invoke itself.
593
- - `assign(id, did, role)` and `unassign(id, did, role)` give and take a
594
- role; taking your own needs no grant. `removeMember(id, did)` removes an
595
- account with every role it holds; removing yourself is leaving. Taking
596
- power away writes a cutoff of what this node holds of theirs
597
- ([spec 03 §6.3](https://github.com/leifriksheim/minca/blob/main/spec/03-spaces.md)).
598
- - `node.records`, `node.collections` — [02](https://github.com/leifriksheim/minca/blob/main/spec/02-records.md). `records.watch`
599
- re-runs a query after every `records` event for its space, one run at a time,
600
- with at most one more queued.
601
- - `node.account` — `profile()`, `setName(name)` (writes `sys.profile`, key
602
- `profile`, in the account registry, then republishes the profile in every
603
- open space), `setAvatar({ bytes, mime } | null, { name? })` and `picture()`
604
- (the account's picture, likewise; see [spaces](spaces.md)), `revoke(key, { waitMs? })` (one of the account's keys, by DID, in the account registry). All need the account
605
- key.
606
- - `spaces.revoke(space, key, { waitMs? })` and `account.revoke` resolve once the revoke is written; with
607
- `waitMs`, once a peer says it has taken it in, or that long has passed (`true` when one did). A node
608
- with no network configured can't send it anywhere, so that is `false` at once. A node about
609
- to stop waits like that: it sends nothing afterwards.
610
- - `node.contacts` — [contacts.md](contacts.md). `ask` and `accept` make or join a space
611
- for two, so they need a note granting `/account/write` over the whole
612
- account (whole-account access).
613
- - `node.direct` — [direct-messages.md](direct-messages.md): `reachable`, `send`
614
- and `list`. Needs the account's member key for the space.
615
- - `node.inbox` — [inbox.md](inbox.md), [07](https://github.com/leifriksheim/minca/blob/main/spec/07-inbox.md). Needs the contact key; knocking and
554
+ Every value a node method returns can be turned into JSON. So the same calls
555
+ work over a command line, MCP and WebMCP ([actions](actions.md)).
556
+
557
+ ### Spaces
558
+
559
+ `node.spaces` creates, invites, previews, joins and leaves spaces, and
560
+ manages who is in them: `access`, `may`, `holdsRole`, `defineRole`, `assign`,
561
+ `unassign`, `removeMember`, `stepDown`, `succeed`, `closeInvite`,
562
+ `changeKey`, `setRelays`, `setKeepers`, `revoke`, `profiles` and
563
+ `authenticator` ([spaces](spaces.md)).
564
+
565
+ An invite is for `member` when the inviter may give that role. Otherwise it's
566
+ for the first role by name the inviter may give, or view-only with none
567
+ ([invites](spaces.md#invites)).
568
+
569
+ - `access(id)` gives a [`SpaceAccess`](https://minca.dev/api/core/interfaces/SpaceAccess/):
570
+ the roles with their current definitions, the members, invites, founders,
571
+ successors, keepers and more
572
+ ([the top and founders](permissions.md#the-top-and-founders)).
573
+ - `may(id, cmd, args?, account?)` asks whether an account may run a command
574
+ with these arguments now. Apps use it to show what someone can do. Peers
575
+ still judge each version on its own.
576
+ - `holdsRole(id, role, account?)` asks whether an account holds every grant a
577
+ role gives, each as wide or wider. It compares the words only, so it may
578
+ say no where the policies would allow, but never yes where they wouldn't.
579
+ Apps use it before giving a bot a role.
580
+ - `defineRole(id, { name, title?, grants, nests? })` writes a role. It can
581
+ hold only what this account could do itself.
582
+ - `assign(id, did, role)` and `unassign(id, did, role)` give and take a role.
583
+ Taking your own needs no grant. `removeMember(id, did)` removes an account
584
+ with all its roles, and removing yourself is leaving. Taking power away
585
+ writes a cutoff at what this node holds of theirs.
586
+
587
+ [Spec 03](https://github.com/leifriksheim/minca/blob/main/spec/03-spaces.md).
588
+
589
+ ### Revokes
590
+
591
+ `spaces.revoke(space, key, { waitMs? })` and `account.revoke(key, { waitMs? })`
592
+ resolve once the revoke is written. With `waitMs`, they wait until a peer has
593
+ taken it in or that time has passed, and say `true` when one did. With no
594
+ network, that is `false` at once. A node about to stop should wait like
595
+ this, since it sends nothing afterwards.
596
+
597
+ ### Records and the account
598
+
599
+ - `node.records` and `node.collections` read and write records
600
+ ([records and queries](records-and-queries.md), [collections](collections.md)).
601
+ `records.watch` runs a query again after each `records` event for its
602
+ space, one run at a time, with at most one more queued.
603
+ - `node.account` needs the account key. `profile()` reads the profile.
604
+ `setName(name)` writes it to the registry, then publishes it in every open
605
+ space. `setAvatar({ bytes, mime } | null, { name? })` and `picture()` do the
606
+ same for the account's picture ([spaces](spaces.md)). `revoke` revokes one
607
+ of the account's keys in the registry.
608
+ - `account.space()` is the registry's id. Keep what is the person's own
609
+ across their devices there, like an app's settings: define a collection of
610
+ yours and write records, as in any space. Every device of the account and
611
+ every app given the whole account reads them. Writing there needs the
612
+ whole account's write access: what an agent writes there counts for
613
+ nothing. Keep it small, settings and not files or lists that grow: every
614
+ device holds the registry whole, and carriers carry it. Leave the `sys.*`
615
+ records alone, and give a collection one definition, shared by every app
616
+ that uses it. An app given only some spaces has no registry: it keeps its
617
+ settings in a space it was given, or on the device.
618
+ - `node.contacts` ([contacts](contacts.md)). `ask` and `accept` make a space
619
+ for two, so they need whole-account access (`/account/write`).
620
+ - `node.direct` ([direct messages](direct-messages.md)): `reachable`, `send`
621
+ and `list`. It needs the account's member key for the space.
622
+ - `node.inbox` ([the inbox](#the-inbox)) needs the contact key. Knocking and
616
623
  accepting also need whole-account access.
617
- - `node.carriers`, `node.hosting`, `node.notifications` — [carriers and hosting](#carriers-hosting-and-notifications), [spec 06 §4](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md).
618
- - `node.iceServers()` — the configured ICE servers plus TURN servers a relay
619
- offers ([the network](#the-network)); what [calls](../../calls/README.md#connections) use.
620
- - `node.network` — `status()`: each relay's state (open, or waiting to redial,
621
- when and why), the connections open and those still being made, and whether
622
- a relay offered TURN; `reconnect()` redials a waiting relay now
623
- ([the network](#the-network), [spec 04 §2](https://github.com/leifriksheim/minca/blob/main/spec/04-network.md)). A `network` event follows every change.
624
- Local only: nothing here goes over the wire.
625
- - `node.asAgent({ keys, note })` — [acting as an agent](#a-node-acting-as-an-agent).
626
-
627
- _Source: `packages/core/src/node/types.ts`, `packages/core/src/node/node.ts` (`spaces`), `packages/core/src/node/space-membership.ts` (`access`, `may`, `holdsRole`, `defineRole`, `assign`, `removeAccount`), `packages/core/src/space/roles.ts` (`holdsRole`). Tests: `packages/core/tests/roles.test.ts` ("holding what a role gives"), `packages/core/tests/node.test.ts`, `packages/core/tests/space-access.test.ts`, `packages/core/tests/contacts.test.ts`, `packages/core/tests/direct.test.ts`, `packages/core/tests/profiles.test.ts`._
624
+ - `node.carriers`, `node.hosting` and `node.notifications`
625
+ ([carriers and hosting](#carriers-hosting-and-notifications)).
626
+
627
+ ### The network and agents
628
+
629
+ - `node.iceServers()` gives the ICE servers for your own connections, such as
630
+ [calls](../../calls/README.md#connections) ([the network](#the-network)).
631
+ - `node.network.status()` shows each relay's state, the connections open and
632
+ being made, and whether a relay offered TURN. `reconnect()` redials a
633
+ waiting relay now. A `network` event follows each change. This is local
634
+ only.
635
+ - `node.asAgent({ keys, note })` ([acting as an agent](#a-node-acting-as-an-agent)).
628
636
 
629
637
  ## The network
630
638
 
631
- How the node uses relays, always-on nodes and WebRTC, where
632
- [spec 04](https://github.com/leifriksheim/minca/blob/main/spec/04-network.md)
633
- leaves it the choice. Another implementation may pick other values and still
634
- meet this one.
635
-
636
- **Redialling a relay** (spec 04 §2.1). The client waits 1, 2, 4, 8, 16 s and
637
- then 30 s between attempts, each ±25% so peers that dropped together do not
638
- return together, and never stops until `disconnect`. It tries at once when the page becomes visible again, and when asked
639
- (`reconnect`). A successful open resets the count. A socket can die without
640
- closing, and after a sleep it has: so the client looks at the clock every
641
- 5 s, and a look more than 30 s after the last means the device slept; it
642
- then lets go of its socket and dials again at once, as it does when the
643
- browser reports `online`. An open socket to a Minca relay that has heard
644
- nothing for 30 s also sends `ping`; once its relay has answered one, two going unanswered end
645
- the socket ("The relay stopped answering.") and it redials. Each relay's state
646
- (`connecting`, `open`, `waiting` with the time of the next attempt and why the
647
- last one failed, `stopped`) is readable as `RelayStatus`, and through a node
648
- as `network.status()`.
649
-
650
- **Meeting** (spec 04 §2, §3). A node says hello in each room when it joins,
651
- on every relay as its socket opens, and every 2 minutes. It remembers, per
652
- room, the times it acted on from each peer in the last 2 minutes (at most
653
- 256 a peer), and the failed tries of the last 512 peers. It
654
- says hello back in a room at most once every 10 s; one due sooner waits
655
- for the 10 s, once for everyone who said hello meanwhile. Each socket
656
- sends at most 20 messages a second, in bursts of 40, and queues the rest. A
657
- connection attempt that times out is retried on the peer's next hello. `requestIce`
658
- asks every connected relay whose kind can hand out TURN passwords. Each WebRTC
659
- offer or answer waits for ICE gathering to finish, or 2 s, and carries what it
660
- found.
661
-
662
- **Kinds of relay** (spec 04 §1.2). `network.relays` may mix kinds:
663
- `['wss://relay.minca.social', 'nostr+wss://relay.damus.io']`. A relay of a kind
664
- this library doesn't speak is left out of `network.status()`. On a Nostr
665
- relay, each event is signed with a key made for it and forgotten.
666
-
667
- **A space's relays** (spec 04 §4). A relay socket opened only for spaces'
668
- own relays is closed once no room needs it. A node whose account may invoke
669
- `/space/relays` in a space that names no relays names its own configured relays (the valid ones,
670
- at most 8) by itself.
671
-
672
- **Always-on nodes** (spec 04 §5.2). `network.nodes` lists the node URLs to
673
- dial, one socket per node per space. After an unexpected close the client
674
- redials without limit, waiting `min(1 s · 2ⁿ, 30 s)`, ±25%, like a relay
675
- (`backoff` in `packages/core/src/utils/backoff.ts`); a deliberate close is
676
- never redialled. The
677
- `/peer` endpoint waits 10 s for the hello (configurable).
678
-
679
- **In-process links** (spec 04 §5.4). `createLocalHub()` links every
680
- transport made from it that has connected, delivering on a later task with
681
- the bytes copied, as on a real wire. It performs no handshake. A carrier uses
682
- it to link its own copy of a space with the copy in the person's pod folder,
683
- so the usual sync keeps the two level.
684
-
685
- **The mesh** (spec 04 §7). Admission raises `peer-connected` for the room. A
686
- newly opened connection that no room takes up within 10 s is closed. A
687
- connection attempt is given 20 s, doubling with each failed attempt at the
688
- same peer up to 5 min. The node remembers the last 512 relayed signals it passed on, by their signatures.
689
- When a node that must prove read access holds no read key, the handshake
690
- throws and the room times out.
691
-
692
- **ICE servers** (spec 04 §10). The defaults are STUN only:
693
- `stun:stun.l.google.com:19302` and `stun:stun1.l.google.com:19302`.
694
- `network.iceServers` replaces them. Each new WebRTC connection uses the
695
- configured servers plus the TURN servers relays offered, the latter only while
696
- `expiresAt` is in the future. `node.iceServers()` returns the same list for
697
- the application's own connections (a call's). Before answering it refreshes:
698
- if any relay is connected and the TURN passwords held are missing or expire
699
- within 10 minutes, and it has not asked in the last 10 minutes, it asks every
700
- connected relay that can and waits up to 1.5 s for an answer (relays without
701
- TURN never answer), then returns what it has. A node with no relays returns
702
- the configured servers.
703
-
704
- _Source: `packages/core/src/network/relay-socket.ts` (`createRelaySocket`, `RelayStatus`), `packages/core/src/network/rendezvous.ts` (`createRendezvous`, `HELLO_MS`, `release`), `packages/core/src/network/relay-nostr.ts`, `packages/core/src/network/rtc-transport.ts` (`GATHER_MS`), `packages/core/src/network/ws-transport.ts`, `packages/core/src/network/local-transport.ts` (`createLocalHub`), `packages/core/src/node/carrier.ts` (`carry`), `packages/core/src/network/mesh.ts` (`CONNECT_TIMEOUT_MS`, `closeIfIdle`, `iceServers`, `ICE_REFRESH_MS`, `ICE_WAIT_MS`), `packages/core/src/network/introductions.ts` (`createSeenSignals`), `packages/core/src/network/rtc-transport.ts` (`DEFAULT_ICE_SERVERS`), `packages/core/src/node/space-keys.ts` (`nameRelays`), `packages/core/src/node/node.ts` (`iceServers`), `packages/cli/src/serve.ts` (`onPeer`). Tests: `packages/core/tests/relay-socket.test.ts`, `packages/core/tests/rendezvous.test.ts`, `packages/core/tests/relay-nostr.test.ts`, `packages/core/tests/introductions.test.ts`, `packages/core/tests/space-relays.test.ts`, `packages/core/tests/ws-transport.test.ts`, `packages/core/tests/carrier.test.ts`; the client-side ICE refresh is untested._
639
+ How this node uses relays, always-on nodes and WebRTC. Another
640
+ implementation may pick other numbers and still talk to this one
641
+ ([spec 04](https://github.com/leifriksheim/minca/blob/main/spec/04-network.md)).
642
+
643
+ ### Relays
644
+
645
+ Network settings can mix kinds of relay:
646
+
647
+ ```ts
648
+ import type { NodeNetworkConfig } from '@minca/core';
649
+
650
+ const network: NodeNetworkConfig = {
651
+ relays: ['wss://relay.minca.social', 'nostr+wss://relay.damus.io'],
652
+ };
653
+ ```
654
+
655
+ A relay of a kind the library doesn't speak is left out of
656
+ `network.status()`. On a Nostr relay, each event is signed with a throwaway
657
+ key.
658
+
659
+ When a relay drops, the node redials after 1, 2, 4, 8 and 16 seconds, then
660
+ every 30, each ±25% so peers that dropped together don't return together. It
661
+ never stops until `disconnect`. It tries at once when the page becomes
662
+ visible, when the browser reports `online`, and on `reconnect()`. A
663
+ successful open resets the count.
664
+
665
+ A socket can die without closing, as it does when the device sleeps. So the
666
+ node checks the clock every 5 seconds, and a gap over 30 seconds means it
667
+ slept: it drops the socket and dials again. A socket to a Minca relay that
668
+ has heard nothing for 30 seconds sends `ping`. Once the relay has answered
669
+ one, two unanswered pings end the socket ("The relay stopped answering.").
670
+
671
+ Each relay's state is a [`RelayStatus`](https://minca.dev/api/core/interfaces/RelayStatus/):
672
+ connecting, open, waiting to try again (with when and why), or stopped.
673
+
674
+ A socket opened only for a space's own relays closes once no space needs it.
675
+ A node that may change a space's relays (`/space/relays`), in a space that
676
+ names none, names its own relays there, up to 8.
677
+
678
+ ### Meeting peers
679
+
680
+ A node says hello in each space's room when it joins, on each relay as it
681
+ opens, and every 2 minutes.
682
+
683
+ - It says hello back at most once every 10 seconds, to everyone who said
684
+ hello meanwhile.
685
+ - It remembers, per room, the hellos it acted on from each peer in the last 2
686
+ minutes (up to 256 a peer), and failed tries for the last 512 peers.
687
+ - Each socket sends at most 20 messages a second, in bursts of 40, and queues
688
+ the rest.
689
+ - A connection attempt that times out is tried again at the peer's next
690
+ hello.
691
+ - Each WebRTC offer or answer waits up to 2 seconds for ICE gathering.
692
+
693
+ ### Connections
694
+
695
+ - A connection no room takes up within 10 seconds is closed.
696
+ - An attempt gets 20 seconds, doubling with each failure at the same peer, up
697
+ to 5 minutes.
698
+ - The node remembers the last 512 signals it relayed, by their signatures.
699
+ - A node that must prove read access but holds no read key fails the
700
+ handshake, and the room times out.
701
+
702
+ ### Always-on nodes
703
+
704
+ `network.nodes` lists nodes to dial, one socket per node per space. After an
705
+ unexpected close the node redials forever, waiting `min(1 s · 2ⁿ, 30 s)`,
706
+ ±25%, like a relay. A deliberate close is never redialled. The node's `/peer`
707
+ endpoint waits 10 seconds for the hello.
708
+
709
+ ### In-process links
710
+
711
+ `createLocalHub()` links every transport made from it, delivering bytes on a
712
+ later task, copied, as on a real wire. There is no handshake. A carrier uses
713
+ it to keep its copy of a space level with the copy in the person's pod folder.
714
+
715
+ ### ICE servers
716
+
717
+ The default ICE servers are STUN only, `stun:stun.l.google.com:19302` and
718
+ `stun:stun1.l.google.com:19302`. `network.iceServers` replaces them. Each new
719
+ WebRTC connection also uses the TURN servers relays offered, while they
720
+ haven't expired.
721
+
722
+ `node.iceServers()` returns the same list, for your own connections. If a
723
+ relay is connected and the TURN passwords are missing or expire within 10
724
+ minutes, it first asks each relay that can, at most once every 10 minutes,
725
+ and waits up to 1.5 seconds. With no relays, it returns the configured
726
+ servers.
705
727
 
706
728
  ## A node acting as an agent
707
729
 
708
- `node.asAgent({ keys, note })` returns the same node acting as an agent. It
709
- throws unless the note verifies, grants records only (its command is under
710
- `/record`), is made out to `keys`, and was issued by `node.did`. The agent:
711
-
712
- - signs with its own key, under its note, so what it writes is `recordsOnly`;
713
- - reaches only spaces its note names (`noteSpaces`: its subject, or a policy
714
- on `.space`), or every space for a note about the whole account;
715
- events for other spaces are filtered out;
716
- - refuses, locally, everything that needs a person: making, inviting, joining
717
- or leaving spaces; changing members, roles, invites or revocations; changing
718
- a space's key, relays or keepers; defining
719
- or deleting collections; live messages (`send`, which a person's devices
720
- would take as theirs); renaming or revoking at the account level; adding or
721
- removing carriers; notifications; hosting; changing, blocking, asking or
722
- accepting contacts; everything about the inbox (it has none);
723
- `delegate`; `asAgent`;
724
- - sees the contact list only if the contacts space is within its note.
725
-
726
- Closing the agent leaves the underlying node running. A node used across a
727
- port (`remoteNode`) starts no agent: the agent's keys would have to cross, so
728
- an agent is started on the node itself.
729
-
730
- An agent granted `scope: account` gets a records-only note for every space
731
- (`/record`, about the whole account) and the account key in its
732
- grant ([spec 06 §2.8](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)), so the contact list is within its note to read. A home never
733
- gives a records-only key the contact key: with it, it could open the
734
- account's knocks, in shared spaces and in its inbox ([inbox.md](inbox.md)).
735
-
736
- Which of these each method of the node is — passed through, held to the note's spaces, or refused — is one table, `API` in `packages/core/src/node/api.ts`; a new method does not type-check until it is decided there. The same table lists what `remoteNode` forwards.
737
-
738
- _Source: `packages/core/src/node/node-records.ts` (`startAgent`), `packages/core/src/node/api.ts` (`API`). Tests: `packages/core/tests/records-only.test.ts` ("an agent acting for a person"), `packages/core/tests/remote.test.ts` ("no agent is started across the port…")._
730
+ An agent writes for a person, but only records, and only where it was let in.
731
+ `node.asAgent({ keys, note })` gives you the same node acting as one:
732
+
733
+ ```ts
734
+ import type { Delegation } from '@minca/core';
735
+ declare const keys: CryptoKeyPair;
736
+ declare const note: Delegation;
737
+ // ---cut---
738
+ const agent = await node.asAgent({ keys, note });
739
+ await agent.records.put(space.id, 'app.note', { text: 'Written by the agent' });
740
+ ```
741
+
742
+ It throws unless the note verifies, grants records only (under `/record`), is
743
+ made out to `keys`, and was issued by `node.did`. The agent:
744
+
745
+ - signs with its own key under its note, so what it writes is `recordsOnly`;
746
+ - reaches only the spaces its note names, or every space for a note about
747
+ the whole account, and hears no events from others;
748
+ - sees the contact list only if its note covers the contacts space.
749
+
750
+ It refuses everything that needs a person: making, inviting, joining or
751
+ leaving spaces; changing members, roles, invites, revokes, keys, relays or
752
+ keepers; defining or deleting collections; live messages, which a person's
753
+ devices would take as theirs; renaming or revoking at the account level;
754
+ carriers, notifications and hosting; contacts and the inbox; `delegate` and
755
+ `asAgent`.
756
+
757
+ Closing the agent leaves the node running. A node used across a port
758
+ (`remoteNode`) starts no agent, since the agent's keys would have to cross.
759
+
760
+ An agent granted `scope: account` gets a records-only note for every space,
761
+ and the account key, so it can read the contact list. A home never gives a
762
+ records-only key the contact key, which would open the account's knocks
763
+ ([the inbox](inbox.md)).
764
+
765
+ One table in the library says which methods an agent passes through, limits
766
+ to its spaces or refuses, and what `remoteNode` forwards. A new method
767
+ doesn't type-check until it's listed there.
768
+ [Spec 06 §2.8](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md).
739
769
 
740
770
  ## The app-side client
741
771
 
742
- What an app and an account home send each other, and what each checks, is
743
- protocol ([spec 06 §2](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)). The reference app side:
744
-
745
- **The app's key.** `appKey(name = 'default')` makes the app's P-256 key once
746
- and keeps it, non-extractable, in the IndexedDB database `minca-app-key`,
747
- object store `keys`, under `name`. `forgetAppKey` deletes it; the next
748
- connection makes a new one.
749
-
750
- **An app's node outside the page.** The desktop app (`apps/desktop`) runs its
751
- app's node in a process of its own, `minca app-node`, so it keeps running with
752
- the window closed; the window uses it over a port, as a page uses its worker,
753
- carried on a WebSocket to the shell's own server at the app's origin, which
754
- opens only for the app's window, with a token made for it.
755
- That process holds the key, so the window and the menu bar are one node: two
756
- signing with one key would fork its lines, and a lock on the folder keeps a
757
- second from starting. Its key and grant can't stay in a page there, so they
758
- rest in its folder, sealed under a key the shell keeps in the system's
759
- keychain and hands to it on stdin: `key.sealed` and `grant.sealed` as
760
- `sealValue` envelopes (labels `minca/desktop-app-key/v1` and
761
- `minca/desktop-grant/v1`, each bound to `{ file }`), and the stores with their
762
- registry sealed as an account's is (spec 05 §15), one folder of stores per
763
- account: connecting as another account deletes the last one's, so its
764
- spaces never reach the new one's registry. Copied without the keychain, the
765
- folder yields no key, grant or private body, only what a carrier sees; a
766
- program running as the person can ask the keychain, as it can read a
767
- browser profile. Renewing keeps the key (a page's app asks with a new one each time, below).
768
- The key changes only when the app leaves an account: disconnecting, from the
769
- app or at the home, forgets it (`forgetAppKey` in a page), so a revoked key
770
- stays revoked. A home that answers as another account than the one connected
771
- is not used: the app leaves the last account, dropping what it wrote there
772
- that no peer had taken yet, and asks to be connected again with a new key,
773
- so one key never holds two accounts' notes. A folder that doesn't open with the keychain's
774
- key is moved aside, and the node starts again unconnected. The window is shown the grant
775
- without its account, contact or member keys. It asks the home for a 30-day
776
- note, where a page asks for the home's default.
777
-
778
- _Source: `packages/cli/src/app-node.ts` (`runAppNode`), `apps/desktop/src/bun/app-node.ts` (`createAppNode`, `keychainKey`), `apps/desktop/src/bun/node-link.ts` (`createNodeLink`), `apps/example/src/desktop.ts` (`desktopConnection`). Tests: `packages/cli/tests/app-node.test.ts`, `apps/desktop/tests/app-node.test.ts`, `apps/desktop/tests/bridge.test.ts` ("only the app’s own window gets a node token…"), `apps/desktop/tests/node-link.test.ts`._
779
-
780
- **The home's address.** `homeAddress(input)` turns what a person typed into the
781
- home's connect page:
782
-
783
- - no scheme → `https://`, or `http://` for `localhost`, `127.0.0.1`, `[::1]`;
784
- - the host must be a loopback name or a domain name with a TLD of two or more
785
- letters;
786
- - the scheme must be `https:`, or `http:` on loopback;
787
- - a path of `/` or empty becomes `/connect`; query and fragment are dropped.
788
-
789
- Example: `minca.example.com` → `https://minca.example.com/connect`.
790
-
791
- **Asking the home.** `connectToHome` (and `proposeToHome`, for a proposal)
792
- opens the home in a popup named `minca-home` with features
793
- `popup,width=460,height=720`, listens from that moment, answers a hello once its
794
- request is made and sends the request again every 500 ms, to the home's origin
795
- only, until the home answers, polls every 500 ms to see whether the person
796
- closed it, and gives up after 10 minutes by default.
797
-
798
- **Starting the node.** `startConnectedNode({ grant, key?, network?, stores?, cache? })`
799
- starts a node with:
800
-
801
- - `signer = grantSigner(grant)` ([renewing the session note](#renewing-the-session-note)):
802
- `did` = `grant.did`;
803
- - `sessionKey` = the app's key;
804
- - stores `indexedDBStores('minca-app:<grant.did>')` unless given;
805
- - `cache: {}` unless `cache: false` ([holding part of a space](#holding-part-of-a-space));
806
- - `accountKey`, `contactKey`, `contactsSpace` from the grant when present (never `contactKey` under a records-only note), and
807
- relays = the app's relays ∪ `grant.relays` (`nodeOptionsFromGrant`).
808
-
809
- It then joins each granted space it does not hold yet, passing its `memberKey`
810
- (`joinGranted`). The desktop app's node (`minca app-node`) and the agent on a
811
- computer start theirs from a grant the same way, from their own folders.
812
-
813
- **The connection.** `createMincaConnection({ home, request, network?, storage?, stores?, worker?, keys?, account? })`
814
- is the app's twin of [sign-in](sign-in.md): statuses `starting`, `disconnected`,
815
- `connecting`, `ready`, `expired`. With `worker`, it runs the node there
816
- (`startNodeInWorker`); a worker that reports a load error, or does not say the
817
- node started within 30 s (`WorkerNotStarted`), is given up on and the node
818
- runs in the page. A worker that started and refused passes its reason on.
819
- It switches to `expired` at `expiresAt` (`watchGrant`). When the node sees its
820
- own note revoked in a space it emits `revoked` ([events](#events)), and the
821
- connection forgets that account's grant and key. `propose(automations)` sends
822
- a proposal to the grant's home
823
- ([spec 06 §2.11](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)).
824
-
825
- **Several accounts.** The connection keeps a grant for every account the
826
- person connects, and acts for one at a time; `state.accounts` lists them
827
- (`did`, the `name` the home gave, `expiresAt`), in the order they were first
828
- connected. Each grant is made out to a key of its own, named
829
- `account-<uuid>` in `appKey`'s store (or `keys`, given), so peers never see
830
- one key act for two accounts. They are kept in `localStorage` under
831
- `minca.grants` (`[{ grant, keyName }]`), the account acted for last under
832
- `minca.account`, and the person's chosen home under `minca.home` (`home` in
833
- the config is only a default). A grant of another format (`v` other than
834
- `GRANT_VERSION`, 2) is dropped when read; one that ran out stays, and opens
835
- as `expired`.
836
-
837
- - `start()` acts for the account `account(accounts)` names, else the one used
772
+ An app connects to an account home with `createMincaConnection`
773
+ ([building an app](building-an-app.md)). These are the pieces underneath.
774
+ [Spec 06 §2](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)
775
+ says what the app and the home send each other.
776
+
777
+ ### The app's key
778
+
779
+ `appKey(name = 'default')` makes the app's P-256 key once and keeps it,
780
+ non-extractable, in the IndexedDB database `minca-app-key`, store `keys`,
781
+ under `name`. `forgetAppKey` deletes it, and the next connection makes a new
782
+ one.
783
+
784
+ ### An app's node outside the page
785
+
786
+ The desktop app runs its app's node in a process of its own,
787
+ `minca app-node`, so it keeps running with the window closed. The window
788
+ talks to it over a WebSocket to the shell's server, which opens only for the
789
+ app's window, with a token made for it. One process holds the key, so the
790
+ window and the menu bar share one node. A lock on the folder stops a second
791
+ one, since two nodes signing with one key would fork its lines.
792
+
793
+ Its key and grant rest in its folder as `key.sealed` and `grant.sealed`
794
+ (labels `minca/desktop-app-key/v1` and `minca/desktop-grant/v1`, bound to
795
+ `{ file }`), sealed under a key the shell keeps in the system keychain. Its
796
+ registry is sealed as an account's is. Copied without the keychain, the
797
+ folder gives up no key, grant or private body. A program running as the
798
+ person can still ask the keychain, as it could read a browser profile. A
799
+ folder that doesn't open with the keychain's key is moved aside, and the node
800
+ starts again unconnected.
801
+
802
+ - There's one folder of stores per account. Connecting as another account
803
+ deletes the last one's.
804
+ - Renewing keeps the key. Disconnecting, from the app or the home, forgets it,
805
+ so a revoked key stays revoked.
806
+ - If the home answers as a different account, the app leaves the last one,
807
+ dropping what no peer had taken yet, and asks again with a new key. One key
808
+ never holds two accounts' notes.
809
+ - The window sees the grant without its account, contact or member keys.
810
+ - It asks the home for a 30-day note, where a page asks for the home's
811
+ default.
812
+
813
+ ### The home's address
814
+
815
+ `homeAddress(input)` turns what a person typed into the home's connect page:
816
+
817
+ ```ts
818
+ import { homeAddress } from '@minca/core/session';
819
+
820
+ homeAddress('minca.example.com'); // 'https://minca.example.com/connect'
821
+ ```
822
+
823
+ - With no scheme it adds `https://`, or `http://` for `localhost`,
824
+ `127.0.0.1` and `[::1]`.
825
+ - The host must be a loopback name, or a domain with a TLD of two letters or
826
+ more.
827
+ - The scheme must be `https:`, or `http:` on loopback.
828
+ - An empty path or `/` becomes `/connect`. Query and fragment are dropped.
829
+
830
+ ### Asking the home
831
+
832
+ `connectToHome`, and `proposeToHome` for a proposal, open the home in a popup
833
+ named `minca-home` (`popup,width=460,height=720`). They send the request to
834
+ the home's origin only, every 500 ms, until the home answers. They check every
835
+ 500 ms whether the person closed the popup, and give up after 10 minutes by
836
+ default.
837
+
838
+ ### Starting the node
839
+
840
+ [`startConnectedNode`](https://minca.dev/api/session/functions/startConnectedNode/) starts a
841
+ node with:
842
+
843
+ - `signer`: `grantSigner(grant)`, so `did` is `grant.did`;
844
+ - `sessionKey`: the app's key;
845
+ - stores: `indexedDBStores('minca-app:<grant.did>')` unless given;
846
+ - `cache: {}` unless `cache: false`;
847
+ - `accountKey`, `contactKey` and `contactsSpace` from the grant when there,
848
+ never `contactKey` under a records-only note;
849
+ - relays: the app's plus `grant.relays`.
850
+
851
+ It then joins each granted space it doesn't hold yet, with its `memberKey`.
852
+ The desktop app's node and the agent on a computer start the same way, from
853
+ their own folders.
854
+
855
+ ### The connection
856
+
857
+ `createMincaConnection(config)` is the app's version of [sign-in](sign-in.md).
858
+ It takes a [`MincaConnectionConfig`](https://minca.dev/api/session/interfaces/MincaConnectionConfig/),
859
+ and its status is a [`ConnectionStatus`](https://minca.dev/api/session/type-aliases/ConnectionStatus/).
860
+
861
+ - With `worker`, the node runs in a worker. If the worker fails to load or
862
+ doesn't start the node within 30 seconds (`WorkerNotStarted`), the node runs
863
+ in the page instead. A worker that started and refused passes its reason on.
864
+ - It turns `expired` when the grant's `expiresAt` passes.
865
+ - When the node sees its note revoked (`revoked`), the connection forgets that
866
+ account's grant and key.
867
+ - `propose(automations)` sends a proposal to the grant's home.
868
+
869
+ ### Several accounts
870
+
871
+ A person can connect more than one account. The connection keeps a grant for
872
+ each and acts for one at a time. `state.accounts` lists them as
873
+ [`ConnectedAccount`](https://minca.dev/api/session/interfaces/ConnectedAccount/)s, in the order
874
+ first connected.
875
+
876
+ - `start()` acts for the account `account(accounts)` picks, else the one used
838
877
  last, else the first.
839
- - `use(did)` acts for another connected account. Its grant is here, so the
840
- home is not asked; the node acting for the last one closes, and one for
841
- this one starts, with its own stores.
842
- - `connect(home?)` asks with a new key, and acts for whichever account the
843
- person chooses at the home: a new one, or one connected already, whose grant
844
- it renews. A key that asked once may hold a note from whatever account the
845
- home was signed in as, so no key is asked with twice. An account connected
846
- again gets the new key and the app forgets the old one; the home revokes
847
- nothing, and what the old key wrote stands
848
- ([spec 06 §2.10](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)).
849
- While it waits, an app acting for an account stays `ready`; a grant whose
850
- node won't start is kept, and the connection says `disconnected` with why.
851
- - `disconnect(did?)` forgets an account's grant and key (default the one
852
- acted for) and acts for the next connected account, or none. Disconnected
853
- at the home instead, it acts for none, with `error` saying why, rather than
854
- another account the person didn't choose.
855
-
856
- Another tab's changes reach `state.accounts` by `storage` events; each tab
857
- acts for its own account. A tab whose account another tab connected again
858
- goes on with its key until it starts again, then takes the newer grant; one
859
- whose key is revoked takes up a newer grant rather than forgetting it. A
860
- shared worker runs a node per key, not only per account, so tabs on two keys
861
- never share one. Switching again before a node has started closes it.
862
-
863
- **Showing notifications.** The app shows its own notifications.
864
- `watchNotifications(node, { origin?, onNotify })` needs the account key (an
865
- app with `scope: account`): it reads the account's own automations naming the
866
- app's origin from the registry and hands the app each record that arrives
867
- matching one, as `{ automation, record }`, with the body in hand
868
- (`matchesRecord`): not paused, the collection, one of the spaces, created at
869
- or after `since` and within the last 24 hours, by another account when
870
- `others`, and for which its `where` holds, with `$me` the account. What the
871
- node held before it started is never news, and neither is what a collection
872
- held the first time an automation made it look there; anything arriving after that
873
- is, even while the account or the list of spaces changes. How the app shows a match is its own
874
- to decide; a "Notify me" button is where a proposal usually starts.
875
-
876
- _Source: `packages/core/src/session/connect.ts` (`appKey`, `forgetAppKey`, `homeAddress`, `connectToHome`, `proposeToHome`, `startConnectedNode`, `nodeOptionsFromGrant`, `joinGranted`, `grantSigner`, `usableGrant`, `watchGrant`, `grantStore`), `packages/cli/src/app-node.ts` (`startDesktopNode`), `packages/core/src/session/connection.ts`, `packages/core/src/node/watch-notifications.ts`, `packages/core/src/space/own-automations.ts` (`matchesRecord`). Tests: `packages/core/tests/connect.test.ts` ("an account home typed by a person", "watching a grant", "an app connected to several accounts", "an app showing its own notifications"), `packages/core/tests/topics.test.ts` ("an automation of the account’s own: its where"), `packages/core/tests/watch-notifications.test.ts`._
878
+ - `use(did)` switches to another connected account without asking the home.
879
+ The old node closes, and one for this account starts, with its own stores.
880
+ - `connect(home?)` asks with a new key, for whichever account the person
881
+ picks at the home: a new one, or one already connected, whose grant it
882
+ renews. No key is ever used to ask twice, since a key that asked once may
883
+ hold a note from any account the home was signed in as. The renewed account
884
+ gets the new key and the old one is forgotten. The home revokes nothing, and
885
+ what the old key wrote stands.
886
+ - While `connect` waits, an app acting for an account stays `ready`. A grant
887
+ whose node won't start is kept, and the status is `disconnected` with why.
888
+ - `disconnect(did?)` forgets an account's grant and key, by default the
889
+ current one, and acts for the next account, or none. Disconnected at the
890
+ home instead, it acts for none, with `error` saying why.
891
+
892
+ Each grant is made out to a key of its own, `account-<uuid>` in `appKey`'s
893
+ store (or `keys`), so peers never see one key act for two accounts. Grants
894
+ live in `localStorage` under `minca.grants` (`[{ grant, keyName }]`), the
895
+ current account under `minca.account`, and the chosen home under `minca.home`
896
+ (the config's `home` is only a default). A grant whose `v` isn't
897
+ `GRANT_VERSION` (2) is dropped. An expired one stays, and opens as `expired`.
898
+
899
+ Each tab acts for its own account, and sees other tabs' changes to
900
+ `state.accounts`. A tab whose account was connected again elsewhere keeps
901
+ its key until it restarts, then takes the newer grant. One whose key was
902
+ revoked takes up a newer grant rather than forgetting it. A shared worker
903
+ runs a node per key. Switching again before a node has started closes it.
904
+ [Spec 06 §2.10](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md).
905
+
906
+ ### Showing notifications
907
+
908
+ An app shows its own notifications with
909
+ `watchNotifications(node, { origin?, onNotify })`. It needs the account key,
910
+ so an app with `scope: account`. It reads the account's automations for the
911
+ app's origin, and calls `onNotify({ automation, record })` for each record
912
+ that arrives matching one.
913
+
914
+ A record matches when the automation isn't paused, and the record is in its
915
+ collection and one of its spaces, created after `since` and within the last
916
+ 24 hours, by another account when `others` is set, and its `where` holds,
917
+ with `$me` the account. What the node held before it started is never news,
918
+ and nor is what a collection held when an automation first looked there.
919
+
920
+ How to show a match is up to the app. A "Notify me" button is usually where a
921
+ proposal starts.
877
922
 
878
923
  ## Carriers, hosting and notifications
879
924
 
880
- What goes into a carry space, what a carrier checks and the host's HTTP API
881
- are protocol ([spec 06 §4](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)). The reference node's side:
882
-
883
- **Carriers.** `node.carriers.add({ did, name })` (needs the account key)
884
- derives the carry space, writes the `sys.carrier` record (name trimmed to 80,
885
- default `Carrier`), fills the carry space, and returns `{ space, invite }` for
886
- the carrier to join with; for a carrier it already has, by `did`, it returns
887
- that one's. Carry spaces are never kept in the node's own list: each is
888
- derived again from its record. A node that starts, or hears the registry change,
889
- refills every carrier's carry space in the background: it opens every space
890
- the account holds, which from a data folder is slow, and signing in doesn't
891
- wait for it. Adding an automation doesn't either (adding a carrier writes that
892
- carrier's passes before it returns):
893
- `node.carriers.settled(waitMs)` waits up to `waitMs` for the refill under way
894
- and says whether it finished, for a window about to close. `node.carriers.reached(carrySpace, waitMs)`
895
- waits up to `waitMs` for the node to be level with the carrier in the carry
896
- space and then the account registry, and says whether it was: a node about to
897
- close (the home's window, once it has answered) waits on it, so what it wrote
898
- for the carrier is not left with nobody (spec 06 §4.3). `node.carriers.remove(carrySpace)`
899
- writes `carry:closed` and marks the record removed; the node keeps the carry
900
- space open until it closes, so the carrier hears it.
901
-
902
- **A space made just now.** Until a carrier opens it from its pass and syncs
903
- it, a new space is only on the device that made it: an invite handed out and
904
- the device closed can't be used. `node.spaces.carried(spaceId, { waitMs? })`
905
- is a short loading step: when a carrier of the account is connected now, it
906
- names it a keeper, writes its pass at once, and waits up to `waitMs`
907
- (default 3 s) until it is level with this node in the space, so it holds the
908
- genesis and any invite opened before the call. It says whether it was: false
909
- at once when no carrier is connected. `contacts.ask` and `inbox.knock` wait on it before the knock goes
910
- out, and pass what it said on as `carried`, for the app to tell the person.
911
-
912
- `node.spaces.reached(spaceId, peer, waitMs)` is the same wait for one peer
913
- named by its key, such as an app's key from the request it connected with:
914
- true once that peer holds all this node does of the space, false when
915
- `waitMs` (at most a minute) passed first or the peer never came. For a node about to close,
916
- like a connect page waiting for the app to have what it wrote.
917
-
918
- _Source: `packages/core/src/node/node.ts` (`spaces.carried`, `spaces.reached`), `packages/core/src/node/node-contacts.ts` (`makePair`). Tests: `packages/core/tests/carrier.test.ts` ("a space made just now, carried before its invite goes out…", "carried is false at once with no carrier…"), `packages/core/tests/usernames.test.ts` ("spaces.reached is true once a peer holds the space…")._
919
-
920
- **The account's own automations.** `node.automations` (needs the account
921
- key) lists, adds, updates (`name`, `paused`) and removes the account's own
922
- automations, kept in its registry ([automations](automations.md#the-accounts-own)),
923
- and copies a wake for each into every carry space. The reference home adds
924
- them when a person keeps an app's proposal, and lists them by app for the
925
- person to pause or remove ([sign-in](sign-in.md#the-account-homes-side)).
926
-
927
- **A carrier's matches.** `CarrierNode` reports a version that wakes one of
928
- the account's wakes through a `wake` event, with only the wake, the space and
929
- the record's key, collection and `createdAt`; `wakes()` lists the wakes it
930
- holds. The desktop app shows them as notifications (`apps/desktop/src/bun/notify.ts`); the browser extension shows none yet.
931
-
932
- **Hosting.** `node.hosting`:
933
-
934
- | Call | Does |
935
- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
936
- | `use(url)` | Reads the host's description, makes the subscription key and writes the `sys.hosting` record. |
937
- | `list()` | Asks each host for its status and hands over the carry space when paid and not carrying, making the carrier first if needed (named after the host's address). At most once a minute per host; a second look waits for a handover in flight. |
938
- | `pay(url, { amount, method, monthly? })` | Adds to the account's balance at the host (dollars, by `checkout` or `request`, monthly by card, as its `HostingView.fund` says): a pay answer, `checkout` (a page to open in a new tab with no opener) or `request` (a payment for a wallet, shown by the app). Call `list()` until the balance moves. |
939
- | `remind(url, email)` | Asks the host to email a reminder before paid time runs out; it mails a link to confirm first. |
940
- | `stop(url)` | Sends `DELETE …/carry` (ignoring failure), removes the carrier and deletes the `sys.hosting` record. |
941
- | `space(id)` | The hosts a space names in `std.host`, each asked how the space's own subscription stands, with how its fund is paid into (below). |
942
- | `over(id)` | The account's hosts whose last status says the space is over their free line, each `{ url, name, over }` (`over.until`, `over.reasons`), from the receipts in `sys.hosting`: asks no host. An agent may call it for a space it was given. |
943
- | `payForSpace(id, url, { amount, method, monthly? })`, `remindForSpace(id, url, email)` | Adds to a space's fund at a host it names (dollars, by `checkout` or `request`, monthly by card), and asks for reminders before it runs out. Anyone in it may. `space(id)` gives each host's `fund` offer, and in its status the `balance`, `daily` spend and `bots`. |
944
- | `startBot(id, url, { name, role? })` | Asks a host the space names to run a bot there ([spec 08 §3](https://github.com/leifriksheim/minca/blob/main/spec/08-hosting.md)): makes an invite for `role` (by default as `spaces.invite` picks one) and hands it over. The host holds the bot's keys, so an app says so first. |
945
- | `stopForSpace(id, url)` | Stops a space using a host it names: deletes its `std.host` record, removes the host's bots and changes the key (below). |
946
-
947
- Every device runs `list()` after each reconciliation ([following the account](#following-the-account)).
948
- A device reaches a host at the socket its description names (`peer`,
949
- [spec 08 §1](https://github.com/leifriksheim/minca/blob/main/spec/08-hosting.md)): every
950
- open space holds one to each host in `sys.hosting`, and to each host the space
951
- names in `std.host`, and follows as those change. `network.hosts` names hosts
952
- to look for the account registry at before the account says which it uses, so
953
- an app built with a default host restores an account from its recovery code
954
- alone. `network.nodes` still adds sockets of its own, to every space.
955
-
956
- A device waits 15 seconds for a host to answer any call, and a minute for
957
- `startBot`. A host that gives no answer, or none in time, is a `HostError`
958
- with status 0 whose message names the address (`describeHost(url, timeoutMs?)`
959
- takes another limit). `list()` and `space(id)` do not throw it: they return
960
- that host's view with `error` set, so one host that is down does not hide the
961
- others, and an app can say so and offer to ask again or to stop using it.
962
-
963
- The reference host (`minca host`, `packages/cli/src/host.ts`) keeps a lapsed
964
- subscription for `graceDays` (default 30) after `paidUntil`, and drops lapsed
965
- ones in a sweep every hour (`sweepMs`). It measures each carried space's
966
- folder at most every ten minutes, and each status gives the sum as `bytes`,
967
- with `quotaBytes` as `quota` (`MINCA_HOST_QUOTA_GB`, none unless set, at a
968
- host without limits). At its quota, an account's carry space takes no new space
969
- (`full`, in `createCarryCore`): what it carries stays and keeps syncing, and a
970
- space that waited is taken once a later measure finds room. All of this is the
971
- host's own policy.
972
-
973
- With `limits` ([spec 08 §1.1](https://github.com/leifriksheim/minca/blob/main/spec/08-hosting.md),
974
- `MINCA_HOST_FREE_GB`), an account's subscription is active with nothing paid,
975
- its `plan` `free` until it pays, and its quota by plan; a device hands such a
976
- host its carry space as it would a free one. A space its own fund pays for
977
- takes none of its members' room. The host counts each carried space's writers
978
- as versions arrive (`onArrived`, in `createCarryCore`) and its readers as
979
- sockets prove themselves (`onPeer`, `packages/cli/src/serve.ts`), and once an
980
- hour (`evaluate`) holds each to the free line. Past a space's `until`, every
981
- account's carry space stops carrying it (`skip`, in `createCarryCore`), while
982
- its own subscription still may. Each change is a line in the host's log.
983
-
984
- _Source: `packages/core/src/node/node-carriers.ts` (`carriers`), `packages/core/src/node/node-hosting.ts` (`hosting`), `packages/core/src/node/carrier.ts` (`arrived`, `skip`, `onArrived`), `packages/core/src/node/host.ts` (`evaluate`), `packages/core/src/session/hosting.ts`, `packages/cli/src/host.ts`. Tests: `packages/core/tests/carrier.test.ts`, `packages/core/tests/host-limits.test.ts`, `packages/cli/tests/host.test.ts`._
925
+ A carrier is an always-on node that keeps the account's spaces online while
926
+ its devices are off. A host runs carriers for you, for a fee or for free.
927
+ [Spec 06 §4](https://github.com/leifriksheim/minca/blob/main/spec/06-nodes-and-sessions.md)
928
+ and [spec 08](https://github.com/leifriksheim/minca/blob/main/spec/08-hosting.md)
929
+ cover what goes over the wire.
930
+
931
+ ### Carriers
932
+
933
+ `node.carriers.add({ did, name })` needs the account key. It derives the
934
+ carry space, writes the `sys.carrier` record, fills the carry space, and
935
+ returns `{ space, invite }` for the carrier to join with. The name is trimmed
936
+ to 80 characters, `Carrier` by default. Adding a carrier it already has
937
+ returns that one.
938
+
939
+ Carry spaces aren't kept in the node's list. Each is derived again from its
940
+ record. When the node starts, or the registry changes, it refills every carry
941
+ space in the background. That opens every space the account holds, which is
942
+ slow from a data folder, so signing in doesn't wait for it, and nor does
943
+ adding an automation. Adding a carrier writes its passes before it returns.
944
+
945
+ - `carriers.settled(waitMs)` waits for the refill under way, and says whether
946
+ it finished. Use it before a window closes.
947
+ - `carriers.reached(carrySpace, waitMs)` waits until the node is level with
948
+ the carrier in the carry space and the account registry. A node about to
949
+ close waits on it, so what it wrote for the carrier isn't lost.
950
+ - `carriers.remove(carrySpace)` writes `carry:closed` and marks the record
951
+ removed. The carry space stays open until the node closes, so the carrier
952
+ hears it.
953
+
954
+ ### A space made just now
955
+
956
+ A new space lives only on the device that made it until a carrier syncs it.
957
+ An invite handed out before then, with the device closed, can't be used.
958
+
959
+ `node.spaces.carried(spaceId, { waitMs? })` is a short loading step for that.
960
+ If a carrier of the account is connected, it names it a keeper, writes its
961
+ pass, and waits up to `waitMs` (default 3 seconds) for it to be level. It
962
+ says whether it was, and is `false` at once with no carrier connected.
963
+ `contacts.ask` and `inbox.knock` wait on it, and return what it said as
964
+ `carried`, so the app can tell the person.
965
+
966
+ `node.spaces.reached(spaceId, peer, waitMs)` waits the same way for one peer,
967
+ named by its key, such as an app's key. It is `true` once that peer holds
968
+ everything this node does, and `false` when `waitMs` (at most a minute)
969
+ passed first. A connect page uses it to wait for the app to have what it
970
+ wrote.
971
+
972
+ ### The account's own automations
973
+
974
+ `node.automations` needs the account key. It lists, adds, updates (`name`,
975
+ `paused`) and removes the account's own
976
+ [automations](automations.md#the-accounts-own), kept in its registry, and
977
+ copies a wake for each into every carry space. The reference home adds them
978
+ when a person keeps an app's proposal, and lists them by app to pause or
979
+ remove ([the account home's side](sign-in.md#the-account-homes-side)).
980
+
981
+ ### A carrier's matches
982
+
983
+ When a version wakes one of the account's wakes, a `CarrierNode` sends a
984
+ `wake` event with only the wake, the space, and the record's key, collection
985
+ and `createdAt`. `wakes()` lists the wakes it holds. The desktop app shows
986
+ these as notifications. The browser
987
+ extension doesn't yet.
988
+
989
+ ### Hosting
990
+
991
+ `node.hosting` pays a host and hands it the account's spaces. Its calls are
992
+ on [`NodeHosting`](https://minca.dev/api/core/interfaces/NodeHosting/): start and stop using a
993
+ host, pay into the account's balance or a space's own fund, ask for reminders,
994
+ see how each host stands, and start a bot.
995
+
996
+ A few details:
997
+
998
+ - `list()` makes the carrier first if needed, named after the host's address.
999
+ A second call waits for a handover already in flight. Every device runs it
1000
+ after each [reconcile](#following-the-account).
1001
+ - `pay` and `payForSpace` take `method` `checkout` or `request`, and
1002
+ `monthly` by card, as the host's `HostingView.fund` offers. They answer
1003
+ with `checkout`, a page to open in a new tab with no opener, or `request`,
1004
+ a payment for a wallet that the app shows. Call `list()` until the balance
1005
+ moves.
1006
+ - `remind` mails a link to confirm first.
1007
+ - `stop` sends `DELETE …/carry`, ignoring failure, removes the carrier and
1008
+ deletes the `sys.hosting` record.
1009
+ - `over(id)` returns `{ url, name, over }` with `over.until` and
1010
+ `over.reasons`, read from the receipts in `sys.hosting`. It asks no host.
1011
+ An agent may call it for a space it was given.
1012
+ - `startBot` makes an invite for `role` (by default as `spaces.invite` picks)
1013
+ and hands it over. The host holds the bot's keys, so tell the person first.
1014
+ [Spec 08 §3](https://github.com/leifriksheim/minca/blob/main/spec/08-hosting.md).
1015
+
1016
+ ### Reaching hosts
1017
+
1018
+ A device reaches a host at the socket its description names (`peer`). Every
1019
+ open space holds a socket to each host in `sys.hosting`, and to each host the
1020
+ space names in `std.host`, and follows as those change. `network.nodes` adds
1021
+ sockets of its own, to every space.
1022
+
1023
+ `network.hosts` names hosts to look for the account registry at, before the
1024
+ account says which it uses. An app with a default host can then restore an
1025
+ account from its recovery code alone.
1026
+
1027
+ `network.reach(address)` decides whether the node may connect to an address
1028
+ it found rather than was given: a host or node a record or invite names, a
1029
+ relay a space or invite names, a short link's place, a host it asks to
1030
+ describe itself. Its own `relays`, `nodes` and `hosts` are always allowed,
1031
+ and without `reach`, so is everything. A refused host isn't asked, so
1032
+ `hosting` calls fail. A refused node or relay isn't dialled. Use it for a node
1033
+ a server runs for someone else, such as the MCP service's: what that node
1034
+ reads isn't the server's to trust, and must not make it connect inside its
1035
+ own network.
1036
+
1037
+ A device waits 15 seconds for a host to answer, and a minute for `startBot`.
1038
+ No answer in time is a `HostError` with status 0, whose message names the
1039
+ address. `describeHost(url, timeoutMs?)` takes another limit. `list()` and
1040
+ `space(id)` don't throw it. They return that host's view with `error` set,
1041
+ so one host that is down doesn't hide the others.
1042
+
1043
+ ### The reference host
1044
+
1045
+ `minca host` makes these choices of its own:
1046
+
1047
+ - A lapsed subscription is kept for `graceDays` (default 30) after
1048
+ `paidUntil`, and swept out hourly (`sweepMs`).
1049
+ - It measures each carried space's folder at most every ten minutes. Each
1050
+ status gives the total as `bytes`, and `quota` from `MINCA_HOST_QUOTA_GB`
1051
+ (none unless set).
1052
+ - At its quota, an account's carry space takes no new space (`full`). What it
1053
+ carries stays and keeps syncing, and a space that waited is taken once
1054
+ there's room.
1055
+
1056
+ With `limits` (`MINCA_HOST_FREE_GB`), a subscription is active with nothing
1057
+ paid, on the `free` plan until it pays, with its quota by plan. A device
1058
+ hands such a host its carry space as it would a free one. A space paid for by
1059
+ its own fund takes none of its members' room. The host counts each space's
1060
+ writers as versions arrive (`onArrived`) and its readers as sockets prove
1061
+ themselves (`onPeer`), and once an hour (`evaluate`) holds each space to the
1062
+ free line. Past a space's `until`, every account's carry space stops carrying
1063
+ it (`skip`), while the space's own subscription still may. Each change is a
1064
+ line in the host's log.
1065
+ [Spec 08 §1.1](https://github.com/leifriksheim/minca/blob/main/spec/08-hosting.md).
985
1066
 
986
1067
  ### A space paying for itself
987
1068
 
988
- A space names the hosts it pays in `std.host` records ([standard library](standard-library.md)),
989
- which only members granted it may write: the `community` template leaves
990
- `std.host` to admins and moderators (`STAFF_COLLECTIONS`). The host keeps the
991
- space for the space itself: its own subscription, `space:<id>`, with a fund
992
- anyone adds to, which pays for keeping it online and for its bots
993
- ([spec 08 §2](https://github.com/leifriksheim/minca/blob/main/spec/08-hosting.md)).
994
-
995
- Every device holding the space's key (not one whose note lacks
996
- `/account/write`, such as an agent's, nor a carrier) looks at the hosts its space names when it takes a role there and
997
- on changes after that: at once when the list of hosts changed, else at most
998
- every ten minutes. For each, it reads the description, refuses a host whose
999
- key is not the one the record names, asks for the status, and hands over the
1000
- space's pass when the host is paid (or free and not lapsed) and either does
1001
- not carry the space or carries it with an older read key. It looks only where
1002
- the space defines `std.host`, so a space held in part is not made to hold it.
1003
-
1004
- `node.hosting.space(id)` does the same at once and returns each host's view:
1005
- its name, key, status (with the fund's `balance`, its `daily` spend, and
1006
- the `bots` running), whether it is `free`, and `fund`, how money goes in,
1007
- which an app shows anyone who wants to chip in, paying with `payForSpace`.
1008
- A host with neither `free` nor a `fund` takes no communities. A host that
1009
- could not be asked has `error` and no status. An agent may call `space` for
1010
- a space it was given; paying is a person's.
1011
-
1012
- `node.hosting.stopForSpace(id, url)` stops a space using a host it names, with
1013
- what the space can do by itself. It asks the host which bots it runs there,
1014
- then deletes the `std.host` record first, so no device hands the host what
1015
- follows, removes those bots from the space, and gives a private space a new
1016
- key when the host was handed it (or can't be asked). Removing a bot changes
1017
- the key by itself; with none removed, `changeKey` is called. It answers
1018
- `{ bots, newKey }`. A bot is removed only where the account may invoke
1019
- `/member/remove` on it, and the key changed only with `/key/change`: without
1020
- either, only the record goes, and the answer is `{ bots: [], newKey: false }`. A host named and never
1021
- handed the space costs no key change. No call asks the host to drop what it
1022
- has, so it keeps that, unreadable, for as long as the space's subscription is
1023
- paid, and what is in the fund stays there
1069
+ A community can pay for its own hosting. It names its hosts in `std.host`
1070
+ records ([standard library](standard-library.md)), which only members granted
1071
+ it may write. The `community` template leaves `std.host` to admins and
1072
+ moderators (`STAFF_COLLECTIONS`). The host then keeps the space under a
1073
+ subscription of its own, `space:<id>`, with a fund anyone can add to. The
1074
+ fund pays for keeping it online and for its bots.
1075
+
1076
+ Every device holding the space's key looks at the hosts the space names: when
1077
+ it takes a role there, at once when the hosts change, and otherwise at most
1078
+ every ten minutes. Agents and carriers don't. For each host it reads the
1079
+ description, refuses one whose key isn't the one the record names, asks for
1080
+ the status, and hands over the space's pass when the host is paid (or free
1081
+ and not lapsed) and doesn't carry the space yet, or carries it with an older
1082
+ read key. It looks only where the space defines `std.host`, so a space held
1083
+ in part isn't made to hold it.
1084
+
1085
+ `node.hosting.space(id)` does the same at once, and returns each host's view:
1086
+ its name, key, status (the fund's `balance`, its `daily` spend and the `bots`
1087
+ running), whether it is `free`, and `fund`, how money goes in. Show `fund` to
1088
+ anyone who wants to chip in, and pay with `payForSpace`. A host with neither
1089
+ `free` nor `fund` takes no communities. A host that couldn't be asked has
1090
+ `error` and no status. An agent may call `space` for a space it was given,
1091
+ but paying is a person's.
1092
+
1093
+ `node.hosting.stopForSpace(id, url)` stops a space using a host. It asks the
1094
+ host which bots it runs there, deletes the `std.host` record first so no
1095
+ device hands the host anything new, removes those bots, and gives a private
1096
+ space a new key if the host had it, or can't be asked. Removing a bot
1097
+ changes the key by itself. With no bot removed, it calls `changeKey`. It
1098
+ answers `{ bots, newKey }`.
1099
+
1100
+ It removes a bot only where the account may run `/member/remove` on it, and
1101
+ changes the key only with `/key/change`. Without either, only the record
1102
+ goes, and the answer is `{ bots: [], newKey: false }`. A host that was named
1103
+ but never handed the space costs no key change.
1104
+
1105
+ No call asks the host to drop what it has. It keeps the space, unreadable,
1106
+ for as long as the space's subscription is paid, and the fund keeps its money
1024
1107
  ([#220](https://github.com/leifriksheim/minca/issues/220)).
1025
1108
 
1026
- _Source: `packages/core/src/node/node-hosting.ts` (`keepSpaceHosts`, `askSpaceHost`, `hosting.space`), `packages/core/src/session/hosting.ts` (`describeHost`, `HostError`). Tests: `packages/cli/tests/host.test.ts` ("a space paying for itself", "an address that is not a host, or one that is down", "bots a host runs": the two on stopping a space's host)._
1027
-
1028
1109
  ## The inbox
1029
1110
 
1030
- `node.inbox` ([inbox.md](inbox.md), [spec 07](https://github.com/leifriksheim/minca/blob/main/spec/07-inbox.md)):
1031
-
1032
- | Call | Does |
1033
- | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1034
- | `get()` | Your inbox, or null until opened: `{ gen, name?, key, sign, places, code, username?, usernameUntil?, updatedAt }`. `code` is signed afresh each time; what it says stays the same |
1035
- | `open({ places?, name? })` | Opens your inbox, or changes where its knocks wait and the name it gives. Places default to the current ones, else this node's relays (up to 3); name to the current one, else the account's |
1036
- | `rotate()` | Clears the inbox and replaces it with `gen + 1`: the old code leads nowhere |
1037
- | `clear()` | Purges every knock waiting, from every mailbox it names |
1038
- | `claim(username)` | Claims a username for your inbox on its domain's name service ([usernames.md](usernames.md)), opening the inbox if need be; one at a time. It follows the inbox: `rotate` and `open` point it at the new code, and `knocks` renews it a month before it lapses |
1039
- | `release()` | Gives the username up: it leads nowhere |
1040
- | `knock(code, { note? })` | by a code, a link or a username: [the exchange](inbox.md#the-exchange), returns `{ space, carried }` |
1041
- | `knocks()` | Fetches the inbox's topic from every mailbox it names, opens and checks ([spec 07 §6](https://github.com/leifriksheim/minca/blob/main/spec/07-inbox.md); opened results are cached by id), settles sent knocks; returns `{ id, from, name, note?, pairSpace, at }`, newest first |
1042
- | `sent()` | Your knocks nobody has joined yet: `{ space, name, username?, at }` |
1043
- | `accept(id)` | [the exchange](inbox.md#the-exchange), returns the new `ContactView` |
1044
- | `dismiss(id)` | Purges one knock |
1111
+ The inbox is where strangers knock to start a conversation, using a code, a
1112
+ link or a username. `node.inbox` needs the contact key
1113
+ ([inbox](inbox.md), [spec 07](https://github.com/leifriksheim/minca/blob/main/spec/07-inbox.md)).
1114
+
1115
+ Its calls are on [`NodeInbox`](https://minca.dev/api/core/interfaces/NodeInbox/): open,
1116
+ rotate and clear the inbox, claim a username, knock, and list, accept or
1117
+ dismiss the knocks that arrive. `get()` returns an
1118
+ [`InboxView`](https://minca.dev/api/core/interfaces/InboxView/), with the code to hand out.
1119
+
1120
+ A username follows the inbox. `rotate` and `open` point it at the new code,
1121
+ and `knocks` renews it a month before it lapses. You hold one at a time.
1122
+
1123
+ `knocks()` fetches the inbox from every mailbox it names, opens and checks
1124
+ each knock (caching the results by id), and settles knocks you sent. Each is
1125
+ a [`KnockView`](https://minca.dev/api/core/interfaces/KnockView/). Knocking and accepting both follow
1126
+ [the exchange](inbox.md#the-exchange), and need whole-account access.
1127
+ [Spec 07 §6](https://github.com/leifriksheim/minca/blob/main/spec/07-inbox.md).
1045
1128
 
1046
1129
  ## Client conveniences
1047
1130
 
1048
- These are not protocol; another client may draw sign-in and [calls](../../calls/README.md) however it
1049
- likes.
1050
-
1051
- - **`<minca-auth>`** draws the flow of [sign-in](sign-in.md) into its own light DOM (so password
1052
- managers find its forms). Attributes: `app-name`, `relays` and `nodes`
1053
- (comma-separated). It fires `minca-session` (`detail: { session }`, `null` when
1054
- signed out), bubbling and composed. A page can hand it its own flow with
1055
- `element.auth = createMincaAuth(…)`. It sizes to its container, so it fits a
1056
- page, a modal or a side panel, and draws nothing once someone is in. Colours,
1057
- font and radius are custom properties (`--minca-accent`, `--minca-font`, …).
1058
- - **React** (`@minca/react`): `MincaProvider`, `useMinca`,
1059
- `useAuth`, `useSession`, `useConnection`, `useAccount`, `useNode`,
1060
- `<MincaAuth>`, `useQuery`, `useLive`, `useSpaces`,
1061
- `useHoldSpace` (holds a space while mounted, releasing it a few seconds late),
1062
- `useRecord`, `useLinked`, `useCollections`, `useProfiles`, `useAccess`,
1063
- `useSpaceStatus`, `useCan`. Calls' `CallsProvider` and `useCalls` are in
1064
- `@minca/calls/react`.
1065
-
1066
- _Source: `packages/core/src/elements/minca-auth.ts`, `packages/react/src/`. Tests: none._
1131
+ These aren't protocol. Another client may draw sign-in and
1132
+ [calls](../../calls/README.md) however it likes.
1133
+
1134
+ `<minca-auth>` draws the [sign-in](sign-in.md) flow into its own light DOM,
1135
+ so password managers find its forms.
1136
+
1137
+ ```html
1138
+ <minca-auth app-name="Todo" relays="wss://relay.minca.social"></minca-auth>
1139
+ ```
1140
+
1141
+ - Attributes: `app-name`, and `relays` and `nodes`, comma-separated.
1142
+ - It fires `minca-session` with `detail: { session }`, or `null` when signed
1143
+ out. The event bubbles and is composed.
1144
+ - A page can give it its own flow with `element.auth = createMincaAuth(…)`.
1145
+ - It sizes to its container, so it fits a page, a modal or a side panel, and
1146
+ draws nothing once someone is in.
1147
+ - Colours, font and radius are custom properties (`--minca-accent`,
1148
+ `--minca-font`, …).
1149
+
1150
+ ## React
1151
+
1152
+ `@minca/react` follows sign-in or the connection, and keeps what you read
1153
+ live. `MincaProvider` goes at the top, given an `auth` or a `connection`;
1154
+ `useMinca`, `useAuth`, `useSession`, `useConnection` and `useAccount` read
1155
+ it, and `<MincaAuth>` draws the sign-in. Below it, hooks such as `useNode`,
1156
+ `useSpaces`, `useQuery`, `useRecord` and `useCan` read and keep current what
1157
+ you show, with `useLive` and `useWatched` for anything else. Each one, and what
1158
+ it gives, is in the [React reference](https://minca.dev/api/react/).
1159
+
1160
+ `result.complete` is false while an app that holds only part of a space is
1161
+ still fetching a collection. Show "Loading…", not "Nothing here".
1162
+
1163
+ An app given the whole account sees every space in it. `useSpaces({ having: [todos] })`
1164
+ lists only the spaces that define those collections.
1165
+
1166
+ Calls have their own, `CallsProvider` and `useCalls`, in `@minca/calls/react`.