@941design/marmot 0.0.0-stage → 0.2.0-alpha.1

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 (206) hide show
  1. package/CHANGELOG.md +739 -0
  2. package/LICENSE +21 -0
  3. package/README.md +33 -2
  4. package/dist/account/admin.d.ts +72 -0
  5. package/dist/account/admin.js +209 -0
  6. package/dist/account/device-deps.d.ts +379 -0
  7. package/dist/account/device-deps.js +36 -0
  8. package/dist/account/device-lineage.d.ts +199 -0
  9. package/dist/account/device-lineage.js +390 -0
  10. package/dist/account/device-registry.d.ts +93 -0
  11. package/dist/account/device-registry.js +1290 -0
  12. package/dist/account/device-rotation.d.ts +61 -0
  13. package/dist/account/device-rotation.js +827 -0
  14. package/dist/account/enrolment.d.ts +339 -0
  15. package/dist/account/enrolment.js +1247 -0
  16. package/dist/account/identity-proof.d.ts +79 -0
  17. package/dist/account/identity-proof.js +264 -0
  18. package/dist/account/index.d.ts +17 -0
  19. package/dist/account/index.js +16 -0
  20. package/dist/account/restore-rotation.d.ts +21 -0
  21. package/dist/account/restore-rotation.js +22 -0
  22. package/dist/account/same-account-authorization.d.ts +86 -0
  23. package/dist/account/same-account-authorization.js +180 -0
  24. package/dist/account/teardown.d.ts +190 -0
  25. package/dist/account/teardown.js +878 -0
  26. package/dist/client/admission-cleanup.d.ts +197 -0
  27. package/dist/client/admission-cleanup.js +635 -0
  28. package/dist/client/adoption-proof.d.ts +39 -0
  29. package/dist/client/adoption-proof.js +102 -0
  30. package/dist/client/before-create-group.d.ts +18 -0
  31. package/dist/client/before-create-group.js +65 -0
  32. package/dist/client/before-publish-hooks.d.ts +121 -0
  33. package/dist/client/before-publish-hooks.js +182 -0
  34. package/dist/client/client-config.d.ts +42 -0
  35. package/dist/client/client-config.js +13 -0
  36. package/dist/client/commit-redrive.d.ts +92 -0
  37. package/dist/client/commit-redrive.js +274 -0
  38. package/dist/client/component-update.d.ts +43 -0
  39. package/dist/client/component-update.js +53 -0
  40. package/dist/client/confirm-hooks.d.ts +55 -0
  41. package/dist/client/confirm-hooks.js +74 -0
  42. package/dist/client/create-client.d.ts +1126 -0
  43. package/dist/client/create-client.js +1232 -0
  44. package/dist/client/group-availability.d.ts +182 -0
  45. package/dist/client/group-availability.js +301 -0
  46. package/dist/client/group-disband.d.ts +28 -0
  47. package/dist/client/group-disband.js +64 -0
  48. package/dist/client/group-history.d.ts +461 -0
  49. package/dist/client/group-history.js +1365 -0
  50. package/dist/client/group-profile.d.ts +31 -0
  51. package/dist/client/group-profile.js +62 -0
  52. package/dist/client/group-records.d.ts +522 -0
  53. package/dist/client/group-records.js +1117 -0
  54. package/dist/client/group-removal.d.ts +36 -0
  55. package/dist/client/group-removal.js +127 -0
  56. package/dist/client/group-remove-member.d.ts +49 -0
  57. package/dist/client/group-remove-member.js +163 -0
  58. package/dist/client/group-runtime.d.ts +415 -0
  59. package/dist/client/group-runtime.js +2811 -0
  60. package/dist/client/group-snapshot.d.ts +104 -0
  61. package/dist/client/group-snapshot.js +474 -0
  62. package/dist/client/history-pages.d.ts +107 -0
  63. package/dist/client/history-pages.js +194 -0
  64. package/dist/client/inbox-send.d.ts +19 -0
  65. package/dist/client/inbox-send.js +71 -0
  66. package/dist/client/index.d.ts +24 -0
  67. package/dist/client/index.js +13 -0
  68. package/dist/client/ingest.d.ts +82 -0
  69. package/dist/client/ingest.js +1584 -0
  70. package/dist/client/invitation-outcomes.d.ts +50 -0
  71. package/dist/client/invitation-outcomes.js +135 -0
  72. package/dist/client/lifecycle-events.d.ts +63 -0
  73. package/dist/client/lifecycle-events.js +35 -0
  74. package/dist/client/opaque-candidates.d.ts +82 -0
  75. package/dist/client/opaque-candidates.js +170 -0
  76. package/dist/client/own-change-outbox.d.ts +66 -0
  77. package/dist/client/own-change-outbox.js +158 -0
  78. package/dist/client/pending-leaf.d.ts +116 -0
  79. package/dist/client/pending-leaf.js +378 -0
  80. package/dist/client/permissions.d.ts +9 -0
  81. package/dist/client/permissions.js +12 -0
  82. package/dist/client/pipeline.d.ts +583 -0
  83. package/dist/client/pipeline.js +3666 -0
  84. package/dist/client/reentrancy-guard.d.ts +102 -0
  85. package/dist/client/reentrancy-guard.js +159 -0
  86. package/dist/client/rekey.d.ts +58 -0
  87. package/dist/client/rekey.js +149 -0
  88. package/dist/client/transport-policy.d.ts +181 -0
  89. package/dist/client/transport-policy.js +214 -0
  90. package/dist/history/admission-lineage.d.ts +186 -0
  91. package/dist/history/admission-lineage.js +589 -0
  92. package/dist/history/equivocation.d.ts +55 -0
  93. package/dist/history/equivocation.js +113 -0
  94. package/dist/history/fencing.d.ts +66 -0
  95. package/dist/history/fencing.js +121 -0
  96. package/dist/history/hex.d.ts +3 -0
  97. package/dist/history/hex.js +10 -0
  98. package/dist/history/index.d.ts +74 -0
  99. package/dist/history/index.js +32 -0
  100. package/dist/history/notifications.d.ts +270 -0
  101. package/dist/history/notifications.js +264 -0
  102. package/dist/history/ordering-key.d.ts +24 -0
  103. package/dist/history/ordering-key.js +101 -0
  104. package/dist/history/own-change-fork.d.ts +112 -0
  105. package/dist/history/own-change-fork.js +196 -0
  106. package/dist/history/own-change.d.ts +118 -0
  107. package/dist/history/own-change.js +146 -0
  108. package/dist/history/policy.d.ts +48 -0
  109. package/dist/history/policy.js +52 -0
  110. package/dist/history/retained-window.d.ts +215 -0
  111. package/dist/history/retained-window.js +565 -0
  112. package/dist/inbox/demux.d.ts +90 -0
  113. package/dist/inbox/demux.js +78 -0
  114. package/dist/inbox/handler-registry.d.ts +42 -0
  115. package/dist/inbox/handler-registry.js +37 -0
  116. package/dist/inbox/index.d.ts +11 -0
  117. package/dist/inbox/index.js +10 -0
  118. package/dist/inbox/seen-set.d.ts +82 -0
  119. package/dist/inbox/seen-set.js +202 -0
  120. package/dist/inbox/subscription.d.ts +236 -0
  121. package/dist/inbox/subscription.js +644 -0
  122. package/dist/index.d.ts +10 -0
  123. package/dist/index.js +9 -0
  124. package/dist/invitations/competing-welcome.d.ts +223 -0
  125. package/dist/invitations/competing-welcome.js +128 -0
  126. package/dist/invitations/decline.d.ts +67 -0
  127. package/dist/invitations/decline.js +149 -0
  128. package/dist/invitations/delivery-evidence.d.ts +288 -0
  129. package/dist/invitations/delivery-evidence.js +766 -0
  130. package/dist/invitations/expect-welcome.d.ts +66 -0
  131. package/dist/invitations/expect-welcome.js +138 -0
  132. package/dist/invitations/index.d.ts +18 -0
  133. package/dist/invitations/index.js +18 -0
  134. package/dist/invitations/invitation-outcome.d.ts +110 -0
  135. package/dist/invitations/invitation-outcome.js +210 -0
  136. package/dist/invitations/invite.d.ts +358 -0
  137. package/dist/invitations/invite.js +1102 -0
  138. package/dist/invitations/offers.d.ts +79 -0
  139. package/dist/invitations/offers.js +115 -0
  140. package/dist/invitations/on-proposal.d.ts +47 -0
  141. package/dist/invitations/on-proposal.js +40 -0
  142. package/dist/invitations/pending-proposal-policy.d.ts +52 -0
  143. package/dist/invitations/pending-proposal-policy.js +139 -0
  144. package/dist/invitations/proposal-deadline.d.ts +133 -0
  145. package/dist/invitations/proposal-deadline.js +164 -0
  146. package/dist/invitations/relay-planes.d.ts +43 -0
  147. package/dist/invitations/relay-planes.js +70 -0
  148. package/dist/invitations/welcome-processor.d.ts +272 -0
  149. package/dist/invitations/welcome-processor.js +1241 -0
  150. package/dist/key-packages/device-key.d.ts +131 -0
  151. package/dist/key-packages/device-key.js +272 -0
  152. package/dist/key-packages/device-rotation-records.d.ts +83 -0
  153. package/dist/key-packages/device-rotation-records.js +173 -0
  154. package/dist/key-packages/group-refs.d.ts +40 -0
  155. package/dist/key-packages/group-refs.js +79 -0
  156. package/dist/key-packages/index.d.ts +18 -0
  157. package/dist/key-packages/index.js +18 -0
  158. package/dist/key-packages/key-package-ref.d.ts +16 -0
  159. package/dist/key-packages/key-package-ref.js +21 -0
  160. package/dist/key-packages/observation-stream.d.ts +4 -0
  161. package/dist/key-packages/observation-stream.js +120 -0
  162. package/dist/key-packages/offer-rumor.d.ts +26 -0
  163. package/dist/key-packages/offer-rumor.js +69 -0
  164. package/dist/key-packages/publisher.d.ts +174 -0
  165. package/dist/key-packages/publisher.js +1247 -0
  166. package/dist/key-packages/select-key-package.d.ts +24 -0
  167. package/dist/key-packages/select-key-package.js +90 -0
  168. package/dist/key-packages/slot-manager.d.ts +167 -0
  169. package/dist/key-packages/slot-manager.js +327 -0
  170. package/dist/key-packages/validate-key-package-event.d.ts +3 -0
  171. package/dist/key-packages/validate-key-package-event.js +49 -0
  172. package/dist/media/cache.d.ts +14 -0
  173. package/dist/media/cache.js +10 -0
  174. package/dist/media/index.d.ts +52 -0
  175. package/dist/media/index.js +71 -0
  176. package/dist/mls.d.ts +15 -0
  177. package/dist/mls.js +15 -0
  178. package/dist/shared/account-pubkey.d.ts +4 -0
  179. package/dist/shared/account-pubkey.js +10 -0
  180. package/dist/shared/errors.d.ts +28 -0
  181. package/dist/shared/errors.js +96 -0
  182. package/dist/shared/hex.d.ts +4 -0
  183. package/dist/shared/hex.js +13 -0
  184. package/dist/shared/index.d.ts +14 -0
  185. package/dist/shared/index.js +14 -0
  186. package/dist/shared/kinds.d.ts +8 -0
  187. package/dist/shared/kinds.js +28 -0
  188. package/dist/shared/publish-classification.d.ts +26 -0
  189. package/dist/shared/publish-classification.js +31 -0
  190. package/dist/storage/envelope.d.ts +39 -0
  191. package/dist/storage/envelope.js +201 -0
  192. package/dist/storage/index.d.ts +237 -0
  193. package/dist/storage/index.js +491 -0
  194. package/dist/storage/indexeddb/idb-types.d.ts +68 -0
  195. package/dist/storage/indexeddb/idb-types.js +1 -0
  196. package/dist/storage/indexeddb/index.d.ts +17 -0
  197. package/dist/storage/indexeddb/index.js +141 -0
  198. package/dist/storage/lease.d.ts +54 -0
  199. package/dist/storage/lease.js +168 -0
  200. package/dist/storage/memory/deterministic-signer.d.ts +27 -0
  201. package/dist/storage/memory/deterministic-signer.js +65 -0
  202. package/dist/storage/memory/index.d.ts +32 -0
  203. package/dist/storage/memory/index.js +87 -0
  204. package/dist/storage/memory/lock-manager.d.ts +8 -0
  205. package/dist/storage/memory/lock-manager.js +71 -0
  206. package/package.json +66 -3
@@ -0,0 +1,390 @@
1
+ import { MarmotError } from '../shared/index.js';
2
+ import { isLeafKeyHex, readAllDeviceKeyLinks, writeDeviceKeyLink } from '../key-packages/index.js';
3
+ import { DEVICE_REGISTRY_ARTIFACT } from './device-deps.js';
4
+ /** Most links one head resolution follows (AC-LIN-1). */
5
+ export const MAX_LINEAGE_DEPTH = 64;
6
+ /**
7
+ * The keys `target` descends from: those from which it is reached along `edges` (the primary links and the alternate
8
+ * evidence alike), `target` itself excluded. THE directed-ancestry rule: not the lineage component, because two live
9
+ * installations that share an origin key are one component but two devices, and the other installation's keys are not this
10
+ * device's to retire, re-key from, refuse or recognise. Pure and total (a cycle ends at the closure).
11
+ */
12
+ export function directedAncestors(target, edges) {
13
+ const all = [...edges];
14
+ const out = new Set([target]);
15
+ for (let grew = true; grew;) {
16
+ grew = false;
17
+ for (const [from, to] of all) {
18
+ if (out.has(to) && !out.has(from)) {
19
+ out.add(from);
20
+ grew = true;
21
+ }
22
+ }
23
+ }
24
+ out.delete(target);
25
+ return out;
26
+ }
27
+ /**
28
+ * Resolution over `edges`. For a key with several edges the first one given is the primary successor ({@link
29
+ * DeviceLineage.headOf} follows it); the others are alternate evidence: they still join their keys into the device
30
+ * ({@link DeviceLineage.sameDevice}, {@link DeviceLineage.keysOf}). All edges are the local account's own
31
+ * successions (signed under the old key), so a withdrawn rotation followed by a different one leaves ONE device.
32
+ * Pure, total and independent of the order edges arrive in apart from which duplicate is primary.
33
+ */
34
+ export function createDeviceLineage(edges, live) {
35
+ const next = new Map();
36
+ const all = [];
37
+ for (const [from, to] of edges) {
38
+ if (from === to)
39
+ continue;
40
+ all.push([from, to]);
41
+ if (!next.has(from))
42
+ next.set(from, to);
43
+ }
44
+ const resolve = (key) => {
45
+ let current = key;
46
+ const seen = new Set([key]);
47
+ for (let steps = 0; steps < MAX_LINEAGE_DEPTH; steps++) {
48
+ const successor = next.get(current);
49
+ if (successor === undefined)
50
+ return { head: current, steps };
51
+ if (seen.has(successor))
52
+ return { head: successor, steps: steps + 1 };
53
+ seen.add(successor);
54
+ current = successor;
55
+ }
56
+ return { head: current, steps: MAX_LINEAGE_DEPTH };
57
+ };
58
+ // Components over every edge (union-find).
59
+ const parent = new Map();
60
+ const find = (key) => {
61
+ let root = key;
62
+ while (parent.has(root) && parent.get(root) !== root)
63
+ root = parent.get(root);
64
+ let walk = key;
65
+ while (parent.has(walk) && parent.get(walk) !== root) {
66
+ const up = parent.get(walk);
67
+ parent.set(walk, root);
68
+ walk = up;
69
+ }
70
+ return root;
71
+ };
72
+ for (const [from, to] of all) {
73
+ if (!parent.has(from))
74
+ parent.set(from, from);
75
+ if (!parent.has(to))
76
+ parent.set(to, to);
77
+ const a = find(from);
78
+ const b = find(to);
79
+ if (a !== b)
80
+ parent.set(a < b ? b : a, a < b ? a : b);
81
+ }
82
+ let components;
83
+ const componentsByRoot = () => {
84
+ if (components !== undefined)
85
+ return components;
86
+ const byRoot = new Map();
87
+ const depth = new Map();
88
+ for (const key of parent.keys()) {
89
+ depth.set(key, resolve(key).steps);
90
+ const root = find(key);
91
+ const list = byRoot.get(root) ?? [];
92
+ list.push(key);
93
+ byRoot.set(root, list);
94
+ }
95
+ for (const list of byRoot.values())
96
+ list.sort((x, y) => (depth.get(y) ?? 0) - (depth.get(x) ?? 0) || (x < y ? -1 : x > y ? 1 : 0));
97
+ components = byRoot;
98
+ return byRoot;
99
+ };
100
+ let retired;
101
+ const retiredSet = () => (retired ??= new Set([...next.keys()].filter((key) => resolve(key).head !== key)));
102
+ // Directed structure, for the contested case.
103
+ const out = new Map();
104
+ const into = new Map();
105
+ for (const [from, to] of all) {
106
+ out.set(from, [...(out.get(from) ?? []), to]);
107
+ into.set(to, [...(into.get(to) ?? []), from]);
108
+ }
109
+ const reach = (start, adjacency) => {
110
+ const seen = new Set([start]);
111
+ const stack = [start];
112
+ while (stack.length > 0) {
113
+ for (const n of adjacency.get(stack.pop()) ?? [])
114
+ if (!seen.has(n))
115
+ (seen.add(n), stack.push(n));
116
+ }
117
+ return seen;
118
+ };
119
+ const liveSinksOf = new Map();
120
+ const liveSinksReached = (key) => {
121
+ let cached = liveSinksOf.get(key);
122
+ if (cached === undefined) {
123
+ cached = live === undefined ? [] : [...reach(key, out)].filter((k) => !out.has(k) && live.has(k)).sort();
124
+ liveSinksOf.set(key, cached);
125
+ }
126
+ return cached;
127
+ };
128
+ const contestedRoots = new Map();
129
+ const contested = (key) => {
130
+ if (live === undefined || !parent.has(key))
131
+ return false;
132
+ const root = find(key);
133
+ let c = contestedRoots.get(root);
134
+ if (c === undefined) {
135
+ c = componentsByRoot().get(root).filter((k) => !out.has(k) && live.has(k)).length >= 2;
136
+ contestedRoots.set(root, c);
137
+ }
138
+ return c;
139
+ };
140
+ const byAge = (keys) => [...keys].sort((x, y) => resolve(y).steps - resolve(x).steps || (x < y ? -1 : x > y ? 1 : 0));
141
+ const component = (key) => Object.freeze([...componentsByRoot().get(find(key))]);
142
+ const keysOf = (key) => {
143
+ if (!parent.has(key))
144
+ return Object.freeze([key]);
145
+ if (contested(key)) {
146
+ const reached = liveSinksReached(key);
147
+ if (reached.length === 1)
148
+ return Object.freeze(byAge(reach(reached[0], into)));
149
+ if (reached.length === 0)
150
+ return Object.freeze(byAge(reach(key, into)));
151
+ }
152
+ return component(key);
153
+ };
154
+ const headOf = (key) => resolve(key).head;
155
+ const deviceHeadOf = (key) => {
156
+ if (contested(key)) {
157
+ const reached = liveSinksReached(key);
158
+ if (reached.length === 1)
159
+ return reached[0];
160
+ }
161
+ return headOf(keysOf(key)[0]);
162
+ };
163
+ return {
164
+ headOf,
165
+ deviceHeadOf,
166
+ headsOf: (key) => {
167
+ if (contested(key)) {
168
+ const reached = liveSinksReached(key);
169
+ if (reached.length === 1)
170
+ return Object.freeze([...reached]);
171
+ }
172
+ return Object.freeze([...new Set(keysOf(key).map(headOf))].sort());
173
+ },
174
+ keysOf,
175
+ entryKeysOf: (key) => (live === undefined && parent.has(key) && [...componentsByRoot().get(find(key))].filter((k) => !out.has(k)).length > 1 ? Object.freeze([key]) : keysOf(key)),
176
+ displayHeadsOf: (key) => {
177
+ if (contested(key)) {
178
+ const reached = liveSinksReached(key);
179
+ if (reached.length >= 1)
180
+ return Object.freeze([...reached]);
181
+ }
182
+ if (live !== undefined && parent.has(key)) {
183
+ const held = keysOf(key).filter((k) => !out.has(k) && live.has(k));
184
+ if (held.length > 0)
185
+ return Object.freeze(held.sort());
186
+ }
187
+ return Object.freeze([deviceHeadOf(key)]);
188
+ },
189
+ apartFrom: (key) => {
190
+ if (!contested(key))
191
+ return Object.freeze([]);
192
+ const mine = new Set(keysOf(key));
193
+ return Object.freeze(component(key).filter((k) => !mine.has(k)));
194
+ },
195
+ sameDevice: (a, b) => {
196
+ if (a === b)
197
+ return true;
198
+ if (!parent.has(a) || !parent.has(b) || find(a) !== find(b))
199
+ return false;
200
+ if (!contested(a))
201
+ return true;
202
+ const ra = liveSinksReached(a);
203
+ const rb = liveSinksReached(b);
204
+ if (ra.some((k) => rb.includes(k)))
205
+ return true;
206
+ return (ra.length === 0 || rb.length === 0) && keysOf(a).includes(b);
207
+ },
208
+ ancestorsOf: (key) => Object.freeze([...directedAncestors(key, all)].sort()),
209
+ retiredKeys: () => Object.freeze(new Set(retiredSet())),
210
+ isRetired: (key) => retiredSet().has(key),
211
+ };
212
+ }
213
+ // ---------------------------------------------------------------------------
214
+ // Where the edges come from: ONE rule
215
+ // ---------------------------------------------------------------------------
216
+ /** Prefix of an alternate-evidence row: `rotated-alt:<fromKey>:<toKey>` (kept apart from `rotated:` so the link codec is untouched). */
217
+ export const ROTATED_ALT_PREFIX = 'rotated-alt:';
218
+ const altKey = (from, to) => `${ROTATED_ALT_PREFIX}${from}:${to}`;
219
+ async function readAlternateEdges(view) {
220
+ const out = [];
221
+ for (const key of await view.keys()) {
222
+ if (!key.startsWith(ROTATED_ALT_PREFIX))
223
+ continue;
224
+ const [from, to, ...rest] = key.slice(ROTATED_ALT_PREFIX.length).split(':');
225
+ const raw = (await view.get(key));
226
+ if (rest.length > 0 || from === undefined || to === undefined || !isLeafKeyHex(from) || !isLeafKeyHex(to) || raw?.v !== 1 || typeof raw.at !== 'number') {
227
+ throw malformedRegistryRecord(key);
228
+ }
229
+ out.push([from, to]);
230
+ }
231
+ return out;
232
+ }
233
+ const accountCache = new WeakMap();
234
+ /** The local account's pubkey, asked of the signer once per signer (a rejection is not cached). */
235
+ export function localAccountOf(signer) {
236
+ const known = accountCache.get(signer);
237
+ if (known !== undefined)
238
+ return known;
239
+ const asked = Promise.resolve(signer.getPublicKey());
240
+ accountCache.set(signer, asked);
241
+ asked.catch(() => accountCache.delete(signer));
242
+ return asked;
243
+ }
244
+ /**
245
+ * The lineage edges a set of group views report for the local account — the one place a view's `successions` are read.
246
+ * The signer is asked for the account only when some view actually reports successions, so a port that reports none
247
+ * never needs the (possibly remote, possibly locked) signer. Another account's succession is never one (AC-LIN-3).
248
+ */
249
+ export async function viewSuccessionEdges(signer, views) {
250
+ const reporting = [...views].filter((v) => (v?.successions?.length ?? 0) > 0);
251
+ if (reporting.length === 0)
252
+ return [];
253
+ const account = await localAccountOf(signer);
254
+ return reporting.flatMap((v) => v.successions.filter((s) => s.account === account).map((s) => [s.fromLeafKey, s.toLeafKey]));
255
+ }
256
+ /**
257
+ * THE lineage rule: the registry's recorded links, then `extra` edges (the successions groups' views report), then the
258
+ * recorded alternates. A reader that goes on to WRITE must first {@link persistSuccessionEdges} the view edges in the same
259
+ * transaction, so a write is never keyed by a lineage the registry does not hold.
260
+ */
261
+ export async function loadDeviceLineage(view, extra = [], live) {
262
+ const links = await readAllDeviceKeyLinks(view);
263
+ return createDeviceLineage([...[...links].map(([from, link]) => [from, link.to]), ...extra, ...(await readAlternateEdges(view))], live);
264
+ }
265
+ /**
266
+ * The closure of `seed` over `edges` without entering `apart` (the other installations of a contested component): how a
267
+ * forget's chain grows as successions are recorded, without ever pulling in a live device it was not asked to forget.
268
+ */
269
+ export function chainClosure(seed, edges, apart = []) {
270
+ const blocked = new Set(apart);
271
+ const adjacency = new Map();
272
+ for (const [from, to] of edges) {
273
+ adjacency.set(from, [...(adjacency.get(from) ?? []), to]);
274
+ adjacency.set(to, [...(adjacency.get(to) ?? []), from]);
275
+ }
276
+ const seen = new Set();
277
+ const stack = [...seed].filter((k) => !blocked.has(k));
278
+ for (const k of stack)
279
+ seen.add(k);
280
+ while (stack.length > 0) {
281
+ for (const n of adjacency.get(stack.pop()) ?? [])
282
+ if (!seen.has(n) && !blocked.has(n))
283
+ (seen.add(n), stack.push(n));
284
+ }
285
+ return seen;
286
+ }
287
+ /** Every recorded edge: the links, then the alternates (strict decode). */
288
+ export async function readRegistryEdges(view) {
289
+ const links = await readAllDeviceKeyLinks(view);
290
+ return [...[...links].map(([from, link]) => [from, link.to]), ...(await readAlternateEdges(view))];
291
+ }
292
+ /** Records every edge (idempotent, see {@link recordSuccession}) so the registry holds what a view showed before a write relies on it; returns whether it wrote. */
293
+ export async function persistSuccessionEdges(tx, edges, now, live) {
294
+ let wrote = false;
295
+ for (const [from, to] of edges)
296
+ if ((await recordSuccession(tx, { from, to, groupId: '', commitDigest: '', at: now(), ...(live === undefined ? {} : { live }) })) === 'recorded')
297
+ wrote = true;
298
+ return wrote;
299
+ }
300
+ export function malformedRegistryRecord(key) {
301
+ return new MarmotError('store-failed', `deviceRegistry/${key}: malformed record`, { details: { key, malformed: true } });
302
+ }
303
+ export async function readRegistryEntry(view, leafKey) {
304
+ const raw = await view.get(leafKey);
305
+ if (raw === undefined)
306
+ return undefined;
307
+ const r = raw;
308
+ if (r.v !== 1 || r.leafKey !== leafKey || typeof r.label !== 'string' || typeof r.enrolledAt !== 'number')
309
+ throw malformedRegistryRecord(leafKey);
310
+ return r;
311
+ }
312
+ /**
313
+ * `moved`'s facts folded into `target` (which stays under its own key): the target's non-empty `label` wins, it takes the
314
+ * moved `enrolledAt` when its own is 0 and the moved `leafIndex` when it has none, and a moved tombstone follows the
315
+ * device (when both have one, the later `at`).
316
+ */
317
+ export function mergeRegistryEntries(target, moved) {
318
+ const tombstone = target.tombstone === undefined ? moved.tombstone : moved.tombstone === undefined ? target.tombstone : moved.tombstone.at > target.tombstone.at ? moved.tombstone : target.tombstone;
319
+ const leafIndex = target.leafIndex ?? moved.leafIndex;
320
+ return {
321
+ v: 1,
322
+ leafKey: target.leafKey,
323
+ label: target.label !== '' ? target.label : moved.label,
324
+ enrolledAt: target.enrolledAt === 0 ? moved.enrolledAt : target.enrolledAt,
325
+ ...(leafIndex === undefined ? {} : { leafIndex }),
326
+ ...(tombstone === undefined ? {} : { tombstone }),
327
+ };
328
+ }
329
+ /**
330
+ * Moves every entry stored under an older key of `head`'s chain to `head` (merging, see {@link mergeRegistryEntries};
331
+ * nearest the head first) and deletes the old rows. Returns the entry at `head` afterwards and whether anything moved.
332
+ * Writes nothing when no older key has an entry.
333
+ */
334
+ export async function consolidateRegistryEntries(view, lineage, head) {
335
+ let entry = await readRegistryEntry(view, head);
336
+ let moved = false;
337
+ for (const key of [...lineage.entryKeysOf(head)].reverse()) {
338
+ if (key === head)
339
+ continue;
340
+ const older = await readRegistryEntry(view, key);
341
+ if (older === undefined)
342
+ continue;
343
+ entry = entry === undefined ? { ...older, leafKey: head } : mergeRegistryEntries(entry, older);
344
+ await view.delete(key);
345
+ moved = true;
346
+ }
347
+ if (moved)
348
+ await view.put(head, entry);
349
+ return { entry, moved };
350
+ }
351
+ /**
352
+ * Records "`from` was succeeded by `to`" and, in the same transaction, moves the registry entries of the whole device to
353
+ * its entry key ({@link DeviceLineage.deviceHeadOf}). Idempotent and independent of arrival order. A `fromKey` that
354
+ * already has a link to a DIFFERENT key keeps it (the first is primary); the new one is persisted as alternate evidence
355
+ * (`rotated-alt:<from>:<to>`) unless both keys are already one device — the old key signed both successions, so the
356
+ * device is one (a rotation withdrawn by a fork, then a different one). The caller decides that the succession belongs
357
+ * to the local account (AC-LIN-3): this writes whatever it is given.
358
+ */
359
+ export async function recordSuccession(tx, input) {
360
+ const { from, to } = input;
361
+ if (from === to || !isLeafKeyHex(from) || !isLeafKeyHex(to))
362
+ return 'ignored';
363
+ const view = tx.artifact(DEVICE_REGISTRY_ARTIFACT);
364
+ const links = await readAllDeviceKeyLinks(view);
365
+ const edges = () => [...links].map(([f, l]) => [f, l.to]);
366
+ const existing = links.get(from);
367
+ let wrote = false;
368
+ if (existing === undefined) {
369
+ // `from` has no primary link: `to` already leading back to it along the primary links would close a cycle.
370
+ let cursor = to;
371
+ for (let i = 0; i < MAX_LINEAGE_DEPTH && cursor !== undefined; i++) {
372
+ if (cursor === from)
373
+ return 'ignored';
374
+ cursor = links.get(cursor)?.to;
375
+ }
376
+ await writeDeviceKeyLink(view, from, { v: 1, to, at: input.at, source: input.source ?? 'observed' });
377
+ links.set(from, { v: 1, to, at: input.at, source: input.source ?? 'observed' });
378
+ wrote = true;
379
+ }
380
+ else if (existing.to !== to) {
381
+ const known = await loadDeviceLineage(view);
382
+ if (!known.sameDevice(from, to)) {
383
+ await view.put(altKey(from, to), { v: 1, at: input.at });
384
+ wrote = true;
385
+ }
386
+ }
387
+ const lineage = await loadDeviceLineage(view, [], input.live);
388
+ const { moved } = await consolidateRegistryEntries(view, lineage, lineage.deviceHeadOf(from));
389
+ return wrote || moved ? 'recorded' : 'unchanged';
390
+ }
@@ -0,0 +1,93 @@
1
+ import { type DispatchContext, type RumorDisposition } from '../inbox/index.js';
2
+ import { DEVICE_KEY_ENTRY } from '../key-packages/index.js';
3
+ import type { AccountStoreTx } from '../storage/index.js';
4
+ import { type DeviceServiceDeps, type EnrolmentPrompt } from './device-deps.js';
5
+ import { type DeviceLineage, type DeviceTombstone } from './device-lineage.js';
6
+ import { type DeviceKeyRotationOutcome } from './device-rotation.js';
7
+ import { handleEnrolmentRumor, type EnrolmentApprovalOutcome, type EnrolmentRequestHandle, type RegistryBinding } from './enrolment.js';
8
+ export type { DeviceTombstone };
9
+ /**
10
+ * One device of the account, as `devices.list()` reports it (AC-DEV-10): a lineage of leaf keys (a device that rotated
11
+ * its signing key is still one device), reported under its newest key.
12
+ */
13
+ export interface DeviceInfo {
14
+ /** The device's current (newest) leaf key: the head of its lineage. */
15
+ readonly leafKey: string;
16
+ /** Its leaf index in the first held group (by group id) holding any key of its lineage; -1 when no held group does. */
17
+ readonly leafIndex: number;
18
+ /** The label bound to `leafKey` in this client's registry; '' when none. */
19
+ readonly label: string;
20
+ /** Client clock (ms) when this client learned of the device; 0 when unknown. */
21
+ readonly enrolledAt: number;
22
+ readonly tombstone?: DeviceTombstone;
23
+ /** The device's older leaf keys, oldest first; empty when it never rotated. */
24
+ readonly previousLeafKeys: readonly string[];
25
+ /** Whether this is the local device (the lineage containing `deviceRegistry/self`). */
26
+ readonly self: boolean;
27
+ }
28
+ /** A group's outcome in a forget: `pending`, `removed` (the leaf is gone) or `timed-out` (given up; the group may still hold it). */
29
+ export type DeviceForgetGroupOutcome = 'removed' | 'timed-out' | 'pending';
30
+ /** `devices.forget(leafKey)`'s result (the DeviceForgetOutcome seam S9 extends for the own leaf). */
31
+ export interface DeviceForgetOutcome {
32
+ readonly leafKey: string;
33
+ /** Every group that held the leaf when the forget started. */
34
+ readonly perGroupOutcome: Readonly<Record<string, DeviceForgetGroupOutcome>>;
35
+ /** The tombstone is recorded: every group's outcome is terminal. */
36
+ readonly tombstoneRecorded: boolean;
37
+ }
38
+ /** S9 seam: the per-group `leave()` `devices.forget(ownLeafKey)` runs on every held group (AC-ADMIN-10), implemented by `teardown.ts`. */
39
+ export interface OwnLeafLeave {
40
+ /** Records (or joins) the group's leave; resolves with its request id. Never waits for the leave itself. */
41
+ startLeave(groupId: string): Promise<string>;
42
+ leaveOutcome(requestId: string): Promise<'pending' | 'removed' | 'timed-out'>;
43
+ }
44
+ export declare const registryBinding: RegistryBinding;
45
+ /**
46
+ * The own device's re-admission (a Welcome adopted under an enrolment manifest this device recorded at `recordedAt`, ms),
47
+ * run in the account transaction that fulfils the manifest: "until enrolled again" (AC-ROT-5), the counterpart of
48
+ * `supersedeDeparture` on the approving sibling's store. Every own forget record that is SETTLED (`forgotten`) or given up
49
+ * and whose own departure time (`forgetDepartureTime`) is at or before `recordedAt` ends, and so does the tombstone its
50
+ * settlement wrote on the device's entry when its own time (`tombstoneDepartureTime`) is also at or before `recordedAt`.
51
+ * A record whose kind-5 deletion is still unsettled is marked `superseded` instead of deleted, so the deletion is
52
+ * finished by the background pass, which then deletes the record. Never touched: an OPEN own forget (leaving beats
53
+ * re-keying, and its intent still needs the record), a forget that started after the request, and any row that does
54
+ * not read (rows are read loosely and a malformed one stays in place: a corrupt row must not abort the join).
55
+ */
56
+ export declare function supersedeOwnForget(tx: AccountStoreTx, recordedAt: number): Promise<void>;
57
+ export interface DeviceService {
58
+ list(): Promise<readonly DeviceInfo[]>;
59
+ /**
60
+ * The device lineage of the registry's recorded links (a synchronous query surface: `headOf`, `keysOf`, `sameDevice`,
61
+ * `isRetired`, `retiredKeys()` — a set that is cheap to snapshot before a group transaction). Rejects `store-failed`
62
+ * with `details.malformed` on a malformed `rotated:` row. Compare keys with `sameDevice`, never by `headOf` equality:
63
+ * `headOf` follows the FIRST-recorded successor of each key (alternate evidence of a second successor, a restore, joins
64
+ * the device without changing it), and a chain of more than 64 links resolves its oldest keys short of the real head.
65
+ * Built from the registry alone, it cannot tell live installations apart: it treats a component as one device.
66
+ */
67
+ lineage(): Promise<DeviceLineage>;
68
+ label(leafKey: unknown, label: unknown): Promise<void>;
69
+ forget(leafKey: unknown): Promise<DeviceForgetOutcome>;
70
+ /**
71
+ * Epic marmot-device-key-rotation (S7): re-keys the local device (AC-ROT-1..11). Resolves after the prepare transaction
72
+ * committed and one pass drove every held group; a rotation already open is returned (no second key).
73
+ */
74
+ rotateKey(): Promise<DeviceKeyRotationOutcome>;
75
+ /** The open rotation, else the last one; `undefined` when the device never rotated. */
76
+ rotation(): Promise<DeviceKeyRotationOutcome | undefined>;
77
+ requestEnrolment(options: unknown): Promise<EnrolmentRequestHandle>;
78
+ pendingEnrolments(): Promise<readonly EnrolmentPrompt[]>;
79
+ approveEnrolment(requestId: unknown): Promise<EnrolmentApprovalOutcome>;
80
+ /** The `RUMOR_KINDS.ENROLMENT_REQUEST` native inbox handler (S7 demux slot). */
81
+ handleEnrolmentRumor(rumor: Parameters<typeof handleEnrolmentRumor>[2], ctx: DispatchContext): Promise<RumorDisposition>;
82
+ /**
83
+ * Starts one background pass over every unfinished device intent (approvals,
84
+ * forgets, unsent requests) on the service queue — never awaited by the
85
+ * caller, never on the inbox queue. A pass that leaves work schedules the next.
86
+ */
87
+ resumeInBackground(): void;
88
+ dispose(): void;
89
+ }
90
+ export declare function createDeviceService(deps: DeviceServiceDeps, seams?: {
91
+ readonly ownLeaf?: OwnLeafLeave;
92
+ }): DeviceService;
93
+ export { DEVICE_KEY_ENTRY };