tryharness 0.7.82 → 0.7.86

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 (216) hide show
  1. package/README.md +21 -19
  2. package/assets/dsh-plugin.mjs +75 -4
  3. package/assets/herdr-mod/harness/main.js +367 -0
  4. package/assets/herdr-mod/harness/mod.json +6 -0
  5. package/assets/opencode-plugin.js +87 -22
  6. package/assets/pi-extension.ts +81 -2
  7. package/cli.mjs +544 -208
  8. package/lib/adapters.mjs +62 -27
  9. package/lib/agentBinaries.mjs +6 -8
  10. package/lib/agentClaims.mjs +168 -0
  11. package/lib/agentReadTools.json +415 -0
  12. package/lib/agentSignIn.mjs +17 -18
  13. package/lib/agentWiring.mjs +114 -0
  14. package/lib/archetypes.js +10 -11
  15. package/lib/attention.mjs +100 -0
  16. package/lib/audit.mjs +1 -1
  17. package/lib/backupSetup.mjs +6 -28
  18. package/lib/bankrApprovals.mjs +86 -0
  19. package/lib/boardAccess.mjs +40 -66
  20. package/lib/boardBackup.mjs +86 -85
  21. package/lib/boardCommands.mjs +28 -0
  22. package/lib/boardFileCommands.mjs +29 -36
  23. package/lib/boardFiles.mjs +83 -15
  24. package/lib/boardMirror.mjs +78 -11
  25. package/lib/boardProtocol.json +193 -123
  26. package/lib/boardThreads.mjs +19 -37
  27. package/lib/boardTools.mjs +22 -15
  28. package/lib/boardWatches.mjs +43 -15
  29. package/lib/bridge.mjs +7 -3
  30. package/lib/browserAgentTools.mjs +59 -0
  31. package/lib/browserWake.mjs +0 -6
  32. package/lib/cards.mjs +57 -2
  33. package/lib/circling.mjs +189 -0
  34. package/lib/cleanup.mjs +234 -0
  35. package/lib/cloudBoot.mjs +21 -4
  36. package/lib/cloudSave.mjs +46 -5
  37. package/lib/compaction.mjs +8 -1
  38. package/lib/completion.mjs +358 -0
  39. package/lib/computerDevices.mjs +853 -0
  40. package/lib/connectionStatus.mjs +34 -0
  41. package/lib/connectors.mjs +139 -1
  42. package/lib/coordinator.mjs +108 -14
  43. package/lib/coreModels.mjs +36 -12
  44. package/lib/daemon.mjs +2435 -333
  45. package/lib/daemonLock.mjs +103 -0
  46. package/lib/deviceDoor.mjs +308 -0
  47. package/lib/deviceIdentity.mjs +114 -0
  48. package/lib/deviceList.mjs +172 -0
  49. package/lib/deviceSeal.mjs +74 -0
  50. package/lib/dispatcher.mjs +497 -26
  51. package/lib/dispatches.mjs +3 -3
  52. package/lib/environment.mjs +2 -1
  53. package/lib/environments.mjs +67 -41
  54. package/lib/events.mjs +318 -0
  55. package/lib/facts.mjs +170 -0
  56. package/lib/fileSource.mjs +540 -0
  57. package/lib/files.mjs +47 -2
  58. package/lib/gitHost.mjs +39 -1
  59. package/lib/goalCommands.mjs +12 -80
  60. package/lib/handover.mjs +21 -16
  61. package/lib/harnessOffers.mjs +140 -15
  62. package/lib/herdr.mjs +100 -15
  63. package/lib/herdrAppCall.mjs +19 -0
  64. package/lib/herdrCore.mjs +59 -0
  65. package/lib/herdrRuns.mjs +1126 -0
  66. package/lib/hookDialects.mjs +235 -50
  67. package/lib/identityLink.mjs +81 -0
  68. package/lib/inference.mjs +31 -2
  69. package/lib/jamAccess.mjs +82 -0
  70. package/lib/{projectBoard.mjs → jamBoard.mjs} +5 -4
  71. package/lib/{projectGit.mjs → jamGit.mjs} +53 -15
  72. package/lib/jamKey.mjs +274 -0
  73. package/lib/{projectPieces.mjs → jamPieces.mjs} +35 -29
  74. package/lib/{projectSettings.mjs → jamSettings.mjs} +12 -22
  75. package/lib/jamStore.mjs +973 -0
  76. package/lib/jamUpgrade.mjs +112 -0
  77. package/lib/jams.mjs +3079 -0
  78. package/lib/kanban.mjs +13 -7
  79. package/lib/landed.mjs +5 -1
  80. package/lib/library.mjs +41 -22
  81. package/lib/limits.mjs +91 -0
  82. package/lib/lineDiff.mjs +97 -0
  83. package/lib/lineup.mjs +18 -13
  84. package/lib/link.mjs +584 -0
  85. package/lib/localStack.mjs +75 -16
  86. package/lib/localmodels.mjs +58 -78
  87. package/lib/loopBackstop.mjs +2 -1
  88. package/lib/machine.mjs +544 -0
  89. package/lib/machineLink.mjs +446 -0
  90. package/lib/machineRoutes.mjs +68 -19
  91. package/lib/machineRuns.mjs +85 -4
  92. package/lib/machineSeal.mjs +6 -31
  93. package/lib/manager.mjs +134 -12
  94. package/lib/mcp-stdio.mjs +492 -215
  95. package/lib/mcpRelay.mjs +34 -35
  96. package/lib/members.json +2 -2
  97. package/lib/modelRoute.mjs +162 -0
  98. package/lib/nativeHost.mjs +81 -90
  99. package/lib/nativeSenses.mjs +258 -0
  100. package/lib/nerves.mjs +523 -0
  101. package/lib/network.mjs +117 -278
  102. package/lib/networkPlaces.mjs +578 -0
  103. package/lib/nextStep.mjs +95 -0
  104. package/lib/notify.mjs +2 -2
  105. package/lib/nudge.mjs +116 -10
  106. package/lib/onboard.mjs +6 -6
  107. package/lib/originals.mjs +216 -0
  108. package/lib/outsideEvents.mjs +383 -0
  109. package/lib/outsideRuns.mjs +230 -0
  110. package/lib/ownMachines.mjs +674 -256
  111. package/lib/pain.mjs +215 -0
  112. package/lib/pairing.mjs +91 -11
  113. package/lib/paths.mjs +42 -3
  114. package/lib/peerProcess.mjs +21 -7
  115. package/lib/peopleLink.mjs +268 -0
  116. package/lib/personNotices.mjs +3 -2
  117. package/lib/phones.mjs +252 -542
  118. package/lib/placeCards.mjs +282 -0
  119. package/lib/placeChecks.mjs +95 -0
  120. package/lib/placeCommands.mjs +8 -17
  121. package/lib/placeRequests.mjs +152 -0
  122. package/lib/placeStore.mjs +295 -0
  123. package/lib/placeTool.d.ts +12 -0
  124. package/lib/placeTool.js +40 -0
  125. package/lib/places.mjs +63 -14
  126. package/lib/plans.mjs +53 -8
  127. package/lib/presence.mjs +270 -0
  128. package/lib/privateNetwork.d.ts +2 -0
  129. package/lib/privateNetwork.js +93 -0
  130. package/lib/proposals.mjs +300 -0
  131. package/lib/publicFetch.d.ts +32 -0
  132. package/lib/publicFetch.js +248 -0
  133. package/lib/reach.mjs +128 -0
  134. package/lib/rebuildable.mjs +72 -0
  135. package/lib/recall.mjs +216 -0
  136. package/lib/record.mjs +13 -0
  137. package/lib/reflexes.mjs +392 -0
  138. package/lib/relayLimits.mjs +31 -2
  139. package/lib/releaseNotice.mjs +198 -0
  140. package/lib/removeHarness.mjs +15 -4
  141. package/lib/repoLinks.mjs +204 -35
  142. package/lib/runAuthority.mjs +102 -39
  143. package/lib/runBrief.mjs +93 -40
  144. package/lib/runRequests.mjs +52 -14
  145. package/lib/runUsage.mjs +31 -0
  146. package/lib/runWorker.mjs +74 -25
  147. package/lib/runner.mjs +289 -45
  148. package/lib/runtime-install.mjs +37 -8
  149. package/lib/schedules.mjs +171 -47
  150. package/lib/screenWatches.mjs +221 -0
  151. package/lib/sealed.mjs +12 -30
  152. package/lib/sealedThreads.mjs +198 -392
  153. package/lib/secretStore.mjs +178 -0
  154. package/lib/secrets.mjs +11 -0
  155. package/lib/seen.mjs +3 -9
  156. package/lib/selfUpdate.mjs +51 -15
  157. package/lib/senseCall.mjs +1514 -0
  158. package/lib/senseHook.mjs +114 -0
  159. package/lib/senseTools.mjs +1298 -0
  160. package/lib/sessionBriefs.mjs +87 -0
  161. package/lib/sessionControl.mjs +63 -13
  162. package/lib/sessionFiles.mjs +85 -0
  163. package/lib/setupChoices.mjs +12 -3
  164. package/lib/setupMode.mjs +70 -25
  165. package/lib/sharedKeys.mjs +166 -0
  166. package/lib/sleep.mjs +396 -0
  167. package/lib/sources.mjs +306 -0
  168. package/lib/speech.mjs +166 -411
  169. package/lib/spoken.mjs +210 -0
  170. package/lib/steerHook.mjs +3 -1
  171. package/lib/steerQueue.mjs +40 -11
  172. package/lib/store.mjs +323 -130
  173. package/lib/stuck.mjs +85 -7
  174. package/lib/swarm.mjs +157 -49
  175. package/lib/swarmDevices.mjs +25 -85
  176. package/lib/swarmMemory.mjs +93 -9
  177. package/lib/t3.mjs +73 -3
  178. package/lib/taskCommands.mjs +51 -60
  179. package/lib/taskRooms.mjs +30 -4
  180. package/lib/taskRules.json +29 -0
  181. package/lib/taskRules.mjs +21 -0
  182. package/lib/taskRuns.mjs +74 -11
  183. package/lib/team.mjs +2 -1
  184. package/lib/threadActions.mjs +37 -9
  185. package/lib/threadAuthority.mjs +4 -4
  186. package/lib/threadBriefs.mjs +173 -43
  187. package/lib/threadNotes.mjs +320 -0
  188. package/lib/threadRecord.mjs +491 -0
  189. package/lib/threadRuns.mjs +216 -108
  190. package/lib/threadView.mjs +27 -30
  191. package/lib/threadWatches.mjs +1962 -0
  192. package/lib/timeSense.mjs +839 -0
  193. package/lib/tripwires.mjs +454 -0
  194. package/lib/ui.mjs +1 -1
  195. package/lib/vault.mjs +560 -45
  196. package/lib/vaultCommands.mjs +5 -3
  197. package/lib/vaultPeers.mjs +165 -0
  198. package/lib/vaultTools.d.ts +4 -1
  199. package/lib/vaultTools.js +22 -1
  200. package/lib/verdicts.mjs +12 -26
  201. package/lib/versions.mjs +117 -0
  202. package/lib/waitTool.mjs +278 -0
  203. package/lib/wakePicture.mjs +268 -0
  204. package/lib/wakeQueue.mjs +108 -0
  205. package/lib/watchResponses.mjs +533 -0
  206. package/lib/watches.mjs +290 -145
  207. package/lib/windowAsks.mjs +80 -17
  208. package/lib/worktrees.mjs +159 -9
  209. package/npm-shrinkwrap.json +138 -631
  210. package/package.json +7 -6
  211. package/release.json +212 -130
  212. package/lib/callSessions.mjs +0 -51
  213. package/lib/directLink.mjs +0 -349
  214. package/lib/peopleBoard.mjs +0 -131
  215. package/lib/projects.mjs +0 -2917
  216. package/lib/roomChannels.mjs +0 -667
@@ -0,0 +1,853 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { readJson, writeJsonAtomic } from "./files.mjs";
3
+ import {
4
+ approvalCode,
5
+ loadDeviceIdentity,
6
+ newApprovalSecret,
7
+ revealHolds,
8
+ } from "./deviceIdentity.mjs";
9
+ import {
10
+ DeviceListError,
11
+ deviceRecordHash,
12
+ readDeviceList,
13
+ signDeviceRecord,
14
+ } from "./deviceList.mjs";
15
+ import { openSealedBytes, sealBytes } from "./deviceSeal.mjs";
16
+ import { webcrypto } from "node:crypto";
17
+ import {
18
+ createRecoveryCode,
19
+ createSharedKeys,
20
+ openIdentity,
21
+ sealWithRecoveryCode,
22
+ } from "./sharedKeys.mjs";
23
+ import { signIdentityLink } from "./identityLink.mjs";
24
+ import {
25
+ readSecretFile,
26
+ removeSecretFile,
27
+ writeSecretFile,
28
+ } from "./secretStore.mjs";
29
+
30
+ // This computer as one of the person's devices, for the daemon (device redesign 1.8f): it reads their signed device
31
+ // list (deviceList.mjs) through /api/computer/devices with its own token, signs changes onto it as itself, and approves
32
+ // another computer the way a browser does (src/main/agents/machinePairing.ts): both computers show one code made from
33
+ // their random numbers (src/shared/deviceApproval.ts), the person says it matches, and this computer signs the new one
34
+ // on and seals the person's shared keys to it. Harness gives the new computer its token only then.
35
+ //
36
+ // The shared keys stay sealed to this computer's own key, at Harness, and are never written here unsealed (owner,
37
+ // November 9). The account's keys in them are the person's identity toward other people (owner, November 14), which
38
+ // this computer uses to reach their friends: it opens them into memory as keys it cannot export, again whenever they
39
+ // change. As the person's first device it makes the shared keys, and after removing a device it changes them, the keys
40
+ // before signing the new ones (identityLink.mjs), so their friends follow. Every list read is checked against the
41
+ // newest one this computer has seen, so a list served from before it is refused.
42
+
43
+ // How long an approval waits for the new computer's answer: it answers at once on its held stream. Past this, the
44
+ // comparison is left to run out (UNANSWERED_ROUND_MS, a minute) and the person types the code again.
45
+ const ANSWER_WAIT_MS = 20_000;
46
+ const ANSWER_POLL_MS = 500;
47
+ // Comparisons this computer started and the person has not matched yet, kept for as long as a pairing lasts.
48
+ const COMPARISON_TTL_MS = 10 * 60 * 1000;
49
+
50
+ export function createComputerDevices({
51
+ paths,
52
+ origin,
53
+ token,
54
+ ask,
55
+ log = () => {},
56
+ fetchImpl = fetch,
57
+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
58
+ }) {
59
+ let identity = null;
60
+ const self = async () => (identity ??= await loadDeviceIdentity(paths));
61
+ const route = () =>
62
+ `${String(origin()).replace(/\/$/, "")}/api/computer/devices`;
63
+ const call = async (init = {}) => {
64
+ const response = await fetchImpl(route(), {
65
+ ...init,
66
+ headers: {
67
+ authorization: `Bearer ${token()}`,
68
+ ...(init.body ? { "content-type": "application/json" } : {}),
69
+ },
70
+ signal: AbortSignal.timeout(15_000),
71
+ });
72
+ const body = await response.json().catch(() => ({}));
73
+ return { status: response.status, ok: response.ok, body };
74
+ };
75
+
76
+ const seenFile = () => paths.deviceListSeen;
77
+ /** The person's list, checked: throws when the chain does not hold or is older than one this computer has seen. */
78
+ const read = async () => {
79
+ const answer = await call();
80
+ if (!answer.ok)
81
+ throw new Error(
82
+ answer.body.error ||
83
+ `Your devices could not be read (${answer.status}).`
84
+ );
85
+ const { records } = answer.body;
86
+ const list = await readDeviceList(records);
87
+ const before = readJson(seenFile(), null);
88
+ if (before?.seq > 0) {
89
+ const same = records[before.seq - 1];
90
+ if (
91
+ list.seq < before.seq ||
92
+ !same ||
93
+ (await deviceRecordHash(same)) !== before.head
94
+ )
95
+ throw new DeviceListError(
96
+ "Your device list is older than one this computer already saw."
97
+ );
98
+ }
99
+ writeJsonAtomic(seenFile(), { seq: list.seq, head: list.head });
100
+ return {
101
+ list,
102
+ records,
103
+ grant: answer.body.grant,
104
+ accountPublicKey: answer.body.accountPublicKey ?? null,
105
+ deviceId: answer.body.deviceId,
106
+ };
107
+ };
108
+
109
+ /** Signs one change as this computer and appends it; a list that moved meanwhile is read again, twice at most. */
110
+ const change = async (deviceChange) => {
111
+ const me = await self();
112
+ for (let attempt = 0; attempt < 3; attempt++) {
113
+ const { list } = await read();
114
+ const record = await signDeviceRecord(
115
+ {
116
+ seq: list.seq + 1,
117
+ prev: list.head,
118
+ at: new Date().toISOString(),
119
+ signer: me.deviceId,
120
+ change: deviceChange,
121
+ },
122
+ me.signing.privateKey
123
+ );
124
+ const answer = await call({
125
+ method: "POST",
126
+ body: JSON.stringify({ record }),
127
+ });
128
+ if (answer.status === 409) continue;
129
+ if (!answer.ok)
130
+ throw new Error(
131
+ answer.body.error ||
132
+ `Your devices were not changed (${answer.status}).`
133
+ );
134
+ return (await read()).list;
135
+ }
136
+ throw new Error("Your device list kept changing; try again.");
137
+ };
138
+
139
+ /** Signs a device on (when it is not yet) and seals the shared keys to it, opened here only for that moment. */
140
+ const signOn = async (device, kind) => {
141
+ const { list, grant } = await read();
142
+ const me = await self();
143
+ if (!list.devices.some((listed) => listed.deviceId === me.deviceId))
144
+ throw new Error("This computer is not one of your devices.");
145
+ if (!grant)
146
+ throw new Error(
147
+ "This computer does not hold your keys yet. Approve the new computer from a browser of yours."
148
+ );
149
+ if (!list.devices.some((listed) => listed.deviceId === device.deviceId))
150
+ await change({
151
+ op: "add",
152
+ deviceId: device.deviceId,
153
+ kind,
154
+ label: device.label,
155
+ signingKey: device.signingKey,
156
+ sealingKey: device.sealingKey,
157
+ });
158
+ const bundle = await openSealedBytes(grant, me.sealing.privateKey);
159
+ try {
160
+ const answer = await call({
161
+ method: "POST",
162
+ body: JSON.stringify({
163
+ grant: {
164
+ deviceId: device.deviceId,
165
+ sealedBundle: await sealBytes(bundle, device.sealingKey),
166
+ },
167
+ }),
168
+ });
169
+ if (!answer.ok)
170
+ throw new Error(answer.body.error || "Your keys were not handed over.");
171
+ } finally {
172
+ bundle.fill(0);
173
+ }
174
+ };
175
+
176
+ /**
177
+ * The person's shared backup keys (src/shared/backupKeys.ts bundle): the current one and those from before a device
178
+ * was removed, raw, newest first. Opened from this computer's sealed copy for the moment it takes; the caller drops
179
+ * them. Throws when this computer holds no copy.
180
+ */
181
+ const sharedBackupKeys = async () => {
182
+ const { grant } = await read();
183
+ if (!grant)
184
+ throw new Error(
185
+ "This computer does not hold your keys yet. Approve it from one of your devices."
186
+ );
187
+ const me = await self();
188
+ const bundle = await openSealedBytes(grant, me.sealing.privateKey);
189
+ try {
190
+ const parsed = JSON.parse(new TextDecoder().decode(bundle));
191
+ return {
192
+ current: Buffer.from(parsed.backupKey, "base64"),
193
+ previous: (parsed.previousBackupKeys ?? []).map((key) =>
194
+ Buffer.from(key, "base64")
195
+ ),
196
+ };
197
+ } finally {
198
+ bundle.fill(0);
199
+ }
200
+ };
201
+
202
+ // ---- the person's identity, which every one of their devices holds ----
203
+
204
+ let opened = null;
205
+ /**
206
+ * The person's identity as this computer holds it (sharedKeys.mjs openIdentity): their account keys, in memory and
207
+ * unexportable, with the signing key's public half and the earlier keys. Null while this computer holds no copy.
208
+ * Opened again when the keys changed.
209
+ */
210
+ const personIdentity = async () => {
211
+ const { grant, list } = await read();
212
+ if (!grant) return (opened = null);
213
+ if (opened?.grant === grant) return opened.identity;
214
+ const me = await self();
215
+ const bundle = await openSealedBytes(grant, me.sealing.privateKey);
216
+ try {
217
+ const keys = await openIdentity(bundle);
218
+ const found = { ...keys, signingKey: keys.signingKey ?? list.accountKey };
219
+ opened = { grant, identity: found };
220
+ return found;
221
+ } finally {
222
+ bundle.fill(0);
223
+ }
224
+ };
225
+
226
+ // A recovery code made here waits, sealed in this computer's keychain or 0600 file, until the person is shown it.
227
+ const keepRecoveryCode = (code) =>
228
+ writeSecretFile(
229
+ paths.recoveryCode,
230
+ JSON.stringify({ code, madeAt: new Date().toISOString() })
231
+ );
232
+ /** The recovery code this computer made and has not shown yet, forgotten once read; null when there is none. */
233
+ const takeRecoveryCode = () => {
234
+ try {
235
+ const kept = JSON.parse(readSecretFile(paths.recoveryCode));
236
+ removeSecretFile(paths.recoveryCode);
237
+ return kept;
238
+ } catch {
239
+ return null;
240
+ }
241
+ };
242
+ /** A recovery code for the keys in `bundle`, stored sealed at Harness and kept here to show the person once. */
243
+ const makeRecoveryCode = async (bundle, { onlyIfNone = false } = {}) => {
244
+ const code = createRecoveryCode();
245
+ const answer = await call({
246
+ method: "POST",
247
+ body: JSON.stringify({
248
+ recovery: {
249
+ recoverySealed: await sealWithRecoveryCode(bundle, code),
250
+ ...(onlyIfNone ? { onlyIfNone: true } : {}),
251
+ },
252
+ }),
253
+ });
254
+ if (!answer.ok || answer.body.replaced === false) return null;
255
+ keepRecoveryCode(code);
256
+ return code;
257
+ };
258
+
259
+ /**
260
+ * As the person's first device with no keys yet (they have no browser, or this computer came first), this computer
261
+ * makes the shared keys, seals them to itself, records the account's signing key on the list and makes the recovery
262
+ * code (owner, November 14: shown once where the person set up). Returns { created, recoveryCode }; created false
263
+ * when keys exist or another device made them first.
264
+ */
265
+ const ensureKeys = async () => {
266
+ const { list, grant, accountPublicKey } = await read();
267
+ const me = await self();
268
+ const mine = list.devices.find((listed) => listed.deviceId === me.deviceId);
269
+ if (grant || accountPublicKey || !mine) return { created: false };
270
+ const made = await createSharedKeys();
271
+ try {
272
+ const answer = await call({
273
+ method: "POST",
274
+ body: JSON.stringify({
275
+ create: {
276
+ deviceId: me.deviceId,
277
+ accountPublicKey: made.accountPublicKey,
278
+ accountSigningKey: made.accountSigningPublicKey,
279
+ sealedBundle: await sealBytes(made.bundle, mine.sealingKey),
280
+ },
281
+ }),
282
+ });
283
+ if (!answer.ok || !answer.body.created) return { created: false };
284
+ await change({ op: "account", signingKey: made.accountSigningPublicKey });
285
+ log("devices: made the person's keys as their first device");
286
+ const recoveryCode = await makeRecoveryCode(made.bundle, {
287
+ onlyIfNone: true,
288
+ });
289
+ return { created: true, recoveryCode };
290
+ } finally {
291
+ made.bundle.fill(0);
292
+ }
293
+ };
294
+
295
+ /**
296
+ * New shared keys after a device left the list: sealed to every device on it, read from the signed list rather than
297
+ * from Harness, with the keys before signing the new ones so the person's friends follow, and a new recovery code
298
+ * (the old one opened the old keys). Returns { rotated, recoveryCode }; rotated false when another device changed
299
+ * them first or this computer holds no copy.
300
+ */
301
+ const rotate = async () => {
302
+ const { list, grant } = await read();
303
+ if (!grant) return { rotated: false };
304
+ const me = await self();
305
+ const before = await personIdentity();
306
+ const old = await openSealedBytes(grant, me.sealing.privateKey);
307
+ let made;
308
+ try {
309
+ made = await createSharedKeys(old);
310
+ } finally {
311
+ old.fill(0);
312
+ }
313
+ try {
314
+ const link = before.signingKey
315
+ ? await signIdentityLink({
316
+ prev: {
317
+ publicKey: before.publicKey,
318
+ signingKey: before.signingKey,
319
+ },
320
+ next: {
321
+ publicKey: made.accountPublicKey,
322
+ signingKey: made.accountSigningPublicKey,
323
+ },
324
+ by: me.deviceId,
325
+ prevSigningPrivateKey: before.signingPrivateKey,
326
+ })
327
+ : null;
328
+ const grants = await Promise.all(
329
+ list.devices.map(async (listed) => ({
330
+ deviceId: listed.deviceId,
331
+ sealedBundle: await sealBytes(made.bundle, listed.sealingKey),
332
+ }))
333
+ );
334
+ const answer = await call({
335
+ method: "POST",
336
+ body: JSON.stringify({
337
+ rotate: {
338
+ expectedAccountPublicKey: before.publicKey,
339
+ accountPublicKey: made.accountPublicKey,
340
+ accountSigningKey: made.accountSigningPublicKey,
341
+ ...(link ? { link } : {}),
342
+ grants,
343
+ },
344
+ }),
345
+ });
346
+ if (!answer.ok || !answer.body.rotated) {
347
+ if (answer.body.error)
348
+ log(`devices: keys not changed: ${answer.body.error}`);
349
+ return { rotated: false };
350
+ }
351
+ await change({ op: "account", signingKey: made.accountSigningPublicKey });
352
+ opened = null;
353
+ log("devices: changed the person's keys after a device left");
354
+ return {
355
+ rotated: true,
356
+ recoveryCode: await makeRecoveryCode(made.bundle),
357
+ };
358
+ } finally {
359
+ made.bundle.fill(0);
360
+ }
361
+ };
362
+
363
+ /** The keys change when a device left the list and no device of the person's changed them since. */
364
+ const rotateIfDue = async () => {
365
+ const { list } = await read();
366
+ const me = await self();
367
+ if (
368
+ !list.rotationDue ||
369
+ !list.devices.some((d) => d.deviceId === me.deviceId)
370
+ )
371
+ return { rotated: false };
372
+ return rotate();
373
+ };
374
+
375
+ // ---- approving another computer by comparing codes ----
376
+
377
+ const comparisons = new Map();
378
+ const sweep = () => {
379
+ for (const [id, entry] of comparisons)
380
+ if (Date.now() - entry.startedAt > COMPARISON_TTL_MS)
381
+ comparisons.delete(id);
382
+ };
383
+ const pair = (claim, step, extra = {}) =>
384
+ ask("machine_pair", { ...claim, step, ...extra }).catch((error) => ({
385
+ ok: false,
386
+ error: error.message,
387
+ }));
388
+
389
+ /**
390
+ * The person typed a new computer's code here: Harness's pairing is read, this computer's challenge goes to it, and
391
+ * once it answered, the code both show. Returns { ok, id, machine, code } to show the person.
392
+ */
393
+ const startApproval = async (claim) => {
394
+ sweep();
395
+ const peeked = await pair(claim, "peek");
396
+ if (!peeked?.ok) return peeked;
397
+ const { pending } = peeked;
398
+ if (!pending?.device || !pending.commitment)
399
+ return {
400
+ ok: false,
401
+ error:
402
+ "That computer's setup is too old to approve. Run npx tryharness on it again.",
403
+ };
404
+ const challenge = newApprovalSecret();
405
+ const started = await pair(claim, "challenge", {
406
+ commitment: pending.commitment,
407
+ challenge,
408
+ });
409
+ if (!started?.ok) return started;
410
+ const keys = {
411
+ sealingKey: pending.device.sealingKey,
412
+ signingKey: pending.device.signingKey,
413
+ };
414
+ const deadline = Date.now() + ANSWER_WAIT_MS;
415
+ while (Date.now() < deadline) {
416
+ const now = await pair(claim, "peek");
417
+ const round = now?.pending?.round;
418
+ if (!now?.ok || !round || round.challenge !== challenge)
419
+ return {
420
+ ok: false,
421
+ error:
422
+ "That computer is comparing codes with another of your devices, or its setup started again.",
423
+ };
424
+ if (round.reveal) {
425
+ if (!(await revealHolds(keys, pending.commitment, round.reveal)))
426
+ return {
427
+ ok: false,
428
+ error:
429
+ "That computer's answer does not match what it showed before. Do not add it.",
430
+ };
431
+ const code = await approvalCode(keys, round.reveal, challenge);
432
+ const id = randomBytes(6).toString("hex");
433
+ comparisons.set(id, {
434
+ claim,
435
+ device: pending.device,
436
+ hostname: pending.hostname,
437
+ code,
438
+ startedAt: Date.now(),
439
+ });
440
+ log(`devices: comparing codes with ${pending.hostname}`);
441
+ return { ok: true, id, machine: pending.hostname, code };
442
+ }
443
+ await sleep(ANSWER_POLL_MS);
444
+ }
445
+ return {
446
+ ok: false,
447
+ error: "That computer did not answer. Is its setup still running?",
448
+ };
449
+ };
450
+
451
+ /**
452
+ * The person said whether the codes match. Matching: this computer signs the new one on as a computer, seals the keys
453
+ * to it, and Harness gives it its token. Returns { ok, machine } or an error.
454
+ */
455
+ const finishApproval = async (id, matches) => {
456
+ sweep();
457
+ const entry = comparisons.get(id);
458
+ comparisons.delete(id);
459
+ if (!entry)
460
+ return {
461
+ ok: false,
462
+ error: "That comparison ended. Type the computer's code again.",
463
+ };
464
+ if (!matches) return { ok: true, declined: true, machine: entry.hostname };
465
+ await signOn(entry.device, "computer");
466
+ const approved = await pair(entry.claim, "approve");
467
+ if (!approved?.ok) return approved;
468
+ return {
469
+ ok: true,
470
+ approved: approved.approved !== false,
471
+ machine: approved.hostname || entry.hostname,
472
+ };
473
+ };
474
+
475
+ // ---- approving a waiting browser or phone by comparing codes ----
476
+ //
477
+ // A new browser or phone signs in and waits until one of the person's devices approves it (src/main/backup/
478
+ // sharedKeys.ts on a browser). This computer can be that device: it reads who waits, sends its challenge, checks the
479
+ // reveal against the commitment it read before, and shows the code both show. Matching, it signs the device on and
480
+ // seals the keys to it (signOn); "Not mine" turns it down.
481
+
482
+ /** The browsers and phones waiting for approval; none while this computer does not hold the keys. */
483
+ const waiting = async () => {
484
+ const answer = await call();
485
+ if (!answer.ok) return [];
486
+ return (answer.body.waiting ?? []).map((device) => ({
487
+ deviceId: device.deviceId,
488
+ kind: device.kind === "phone" ? "phone" : "browser",
489
+ label: device.label,
490
+ createdAt: device.createdAt,
491
+ }));
492
+ };
493
+
494
+ const waitingOne = async (deviceId) => {
495
+ const answer = await call();
496
+ return (answer.body.waiting ?? []).find(
497
+ (device) => device.deviceId === deviceId
498
+ );
499
+ };
500
+
501
+ /** The person chose Compare codes for a waiting device. Returns { ok, id, label, kind, code } once it answered. */
502
+ const compareWaiting = async (deviceId) => {
503
+ sweep();
504
+ const device = await waitingOne(deviceId);
505
+ if (!device)
506
+ return { ok: false, error: "That device no longer waits for approval." };
507
+ if (!device.commitment)
508
+ return {
509
+ ok: false,
510
+ error:
511
+ "That device is not ready to compare codes yet. Keep Harness open on it and try again.",
512
+ };
513
+ const challenge = newApprovalSecret();
514
+ const started = await call({
515
+ method: "POST",
516
+ body: JSON.stringify({
517
+ challenge: { deviceId, commitment: device.commitment, challenge },
518
+ }),
519
+ });
520
+ if (!started.body.started)
521
+ return {
522
+ ok: false,
523
+ error: started.body.busy
524
+ ? "That device is comparing codes with another of yours. Use that one, or try again in a minute."
525
+ : started.body.error || "That device changed meanwhile. Try again.",
526
+ };
527
+ const keys = {
528
+ sealingKey: device.publicKey,
529
+ signingKey: device.signingKey,
530
+ };
531
+ const deadline = Date.now() + ANSWER_WAIT_MS;
532
+ while (Date.now() < deadline) {
533
+ const round = (await waitingOne(deviceId))?.round;
534
+ if (!round || round.challenge !== challenge)
535
+ return {
536
+ ok: false,
537
+ error:
538
+ "That device was approved, turned down, or started comparing with another of yours.",
539
+ };
540
+ if (round.reveal) {
541
+ if (!(await revealHolds(keys, device.commitment, round.reveal)))
542
+ return {
543
+ ok: false,
544
+ error:
545
+ "That device's answer does not match what it showed before. Do not approve it.",
546
+ };
547
+ const code = await approvalCode(keys, round.reveal, challenge);
548
+ const id = randomBytes(6).toString("hex");
549
+ comparisons.set(id, {
550
+ waiting: {
551
+ deviceId,
552
+ label: device.label,
553
+ signingKey: device.signingKey,
554
+ sealingKey: device.publicKey,
555
+ },
556
+ kind: device.kind === "phone" ? "phone" : "browser",
557
+ code,
558
+ startedAt: Date.now(),
559
+ });
560
+ log(`devices: comparing codes with a waiting ${device.kind}`);
561
+ return { ok: true, id, label: device.label, kind: device.kind, code };
562
+ }
563
+ await sleep(ANSWER_POLL_MS);
564
+ }
565
+ return {
566
+ ok: false,
567
+ error:
568
+ "That device did not answer. Keep Harness open on it and try again.",
569
+ };
570
+ };
571
+
572
+ /** Approve: the codes match, so the device is signed on and given the keys. */
573
+ const approveWaiting = async (id) => {
574
+ sweep();
575
+ const entry = comparisons.get(id);
576
+ comparisons.delete(id);
577
+ if (!entry?.waiting)
578
+ return {
579
+ ok: false,
580
+ error: "That comparison ended. Compare codes again.",
581
+ };
582
+ await signOn(entry.waiting, entry.kind);
583
+ log(`devices: approved a ${entry.kind}`);
584
+ return { ok: true, label: entry.waiting.label };
585
+ };
586
+
587
+ /** Not mine: a waiting device is turned down, and nothing is ever sealed to it. */
588
+ const declineWaiting = async (deviceId) => {
589
+ for (const [id, entry] of comparisons)
590
+ if (entry.waiting?.deviceId === deviceId) comparisons.delete(id);
591
+ const answer = await call({
592
+ method: "POST",
593
+ body: JSON.stringify({ decline: { deviceId } }),
594
+ });
595
+ if (!answer.ok)
596
+ return {
597
+ ok: false,
598
+ error: answer.body.error || "That device was not turned down.",
599
+ };
600
+ return { ok: true };
601
+ };
602
+
603
+ // ---- a browser or phone reaching this computer as one of the person's devices ----
604
+ //
605
+ // Any browser or phone on the person's list may open a sealed line to any of their computers (src/main/device/
606
+ // deviceLines.ts): its sealing key on the signed list is the key the line is made with, so there is no pairing, no
607
+ // link and nothing to allow. Read at most every LINE_LIST_MS while devices call; a removed device is refused once
608
+ // the list says so.
609
+ // A device the list read does not hold may have been added since: the list is read again then, at most every
610
+ // LINE_UNKNOWN_MS for each such device, so a browser approved a moment ago is not turned away for half a minute; a
611
+ // call sooner than that waits for that read.
612
+ const LINE_LIST_MS = 30_000;
613
+ const LINE_UNKNOWN_MS = 2_000;
614
+ let lineList = null;
615
+ let lineListAt = 0;
616
+ const unknownReadAt = new Map();
617
+ // The read a device not on the list is waiting for, shared by its calls meanwhile.
618
+ const unknownReads = new Map();
619
+ // A list that cannot be read again (Harness unreachable) leaves the one last read and checked in place: devices are
620
+ // answered by it, not by whatever happens to be kept here. Only with none read yet does the read's error stand.
621
+ const readLines = async () => {
622
+ try {
623
+ lineList = (await read()).list;
624
+ lineListAt = Date.now();
625
+ } catch (error) {
626
+ if (!lineList) throw error;
627
+ }
628
+ };
629
+ const findOnList = (deviceId) => {
630
+ if (lineList.removed.includes(deviceId)) return { removed: true };
631
+ const device = lineList.devices.find(
632
+ (listed) => listed.deviceId === deviceId
633
+ );
634
+ return device ? { device } : null;
635
+ };
636
+ /**
637
+ * The device on the person's list with this id ({ device }), one taken off it ({ removed: true }), or null for one
638
+ * not on it. Throws when no list could be read yet.
639
+ */
640
+ const deviceOnList = async (deviceId) => {
641
+ if (!lineList || Date.now() - lineListAt > LINE_LIST_MS) await readLines();
642
+ const found = findOnList(deviceId);
643
+ if (found) return found;
644
+ // Within LINE_UNKNOWN_MS of the last read for this device, the call waits for the next one rather than being turned
645
+ // away from a list known to be old: a browser asks before it is approved, and its first call after approval (a
646
+ // moment later) was refused, and a refused page drops its line until it is reloaded (sealedBridge.ts).
647
+ let next = unknownReads.get(deviceId);
648
+ if (!next) {
649
+ const wait =
650
+ (unknownReadAt.get(deviceId) ?? 0) + LINE_UNKNOWN_MS - Date.now();
651
+ next = (async () => {
652
+ if (wait > 0) await sleep(wait);
653
+ unknownReadAt.set(deviceId, Date.now());
654
+ if (unknownReadAt.size > 1000) unknownReadAt.clear();
655
+ await readLines();
656
+ })().finally(() => unknownReads.delete(deviceId));
657
+ unknownReads.set(deviceId, next);
658
+ }
659
+ await next;
660
+ return findOnList(deviceId);
661
+ };
662
+
663
+ /**
664
+ * The list read again now (Harness says a device was taken off it, or this computer has just connected): every device
665
+ * taken off it, with the kind and sealing key it had there, for the daemon to cut off (docs/one-link-plan.md L6.1).
666
+ * The list's own record of a removal is what counts, never Harness's word. Calls are answered by this read from now.
667
+ */
668
+ const removedNow = async () => {
669
+ const { list, records } = await read();
670
+ lineList = list;
671
+ lineListAt = Date.now();
672
+ const added = new Map();
673
+ for (const { change } of records)
674
+ if (change.op === "add" || change.op === "reset")
675
+ added.set(change.deviceId, change);
676
+ return list.removed.map((deviceId) => ({
677
+ deviceId,
678
+ kind: added.get(deviceId)?.kind ?? null,
679
+ sealingKey: added.get(deviceId)?.sealingKey ?? null,
680
+ }));
681
+ };
682
+
683
+ // ---- joining the swarm as one of the person's devices ----
684
+ //
685
+ // Two of the person's computers on their list trust each other's swarm keys (the relay identity ownMachines.mjs
686
+ // pins) without a code: each signs the pair of keys with its device key, and the other checks that signature against
687
+ // the device on the signed list. Harness carries both and can forge neither.
688
+
689
+ const SIGNATURE = { name: "ECDSA", hash: "SHA-256" };
690
+ const SIGNING = { name: "ECDSA", namedCurve: "P-256" };
691
+ const joinBytes = (role, keys) =>
692
+ new TextEncoder().encode(
693
+ [
694
+ "harness swarm join",
695
+ role,
696
+ keys.homeId,
697
+ keys.homeKey,
698
+ keys.workerId,
699
+ keys.workerKey,
700
+ ].join("\n")
701
+ );
702
+
703
+ /** This computer's word, as `role` ("home" or "worker"), that these swarm keys are its and its peer's. */
704
+ const swarmProof = async (role, keys) => {
705
+ const me = await self();
706
+ const signature = await webcrypto.subtle.sign(
707
+ SIGNATURE,
708
+ me.signing.privateKey,
709
+ joinBytes(role, keys)
710
+ );
711
+ return {
712
+ deviceId: me.deviceId,
713
+ signature: Buffer.from(signature).toString("base64"),
714
+ };
715
+ };
716
+
717
+ /**
718
+ * The computer on the person's list whose device signed this proof, or null: only a computer or cloud computer
719
+ * listed now, never a browser or phone, and never one removed.
720
+ */
721
+ const checkSwarmProof = async (role, keys, proof) => {
722
+ if (
723
+ typeof proof?.deviceId !== "string" ||
724
+ typeof proof?.signature !== "string"
725
+ )
726
+ return null;
727
+ const { list: current } = await read();
728
+ const device = current.devices.find(
729
+ (listed) =>
730
+ listed.deviceId === proof.deviceId &&
731
+ (listed.kind === "computer" || listed.kind === "cloud")
732
+ );
733
+ if (!device) return null;
734
+ try {
735
+ const key = await webcrypto.subtle.importKey(
736
+ "raw",
737
+ Buffer.from(device.signingKey, "base64"),
738
+ SIGNING,
739
+ false,
740
+ ["verify"]
741
+ );
742
+ const holds = await webcrypto.subtle.verify(
743
+ SIGNATURE,
744
+ key,
745
+ Buffer.from(proof.signature, "base64"),
746
+ joinBytes(role, keys)
747
+ );
748
+ return holds ? device : null;
749
+ } catch {
750
+ return null;
751
+ }
752
+ };
753
+
754
+ // ---- the person's devices, as tryharness devices shows and changes them ----
755
+
756
+ /** One device by its name or the start of its id; an error names what is wrong. */
757
+ const find = (list, named) => {
758
+ const wanted = named.trim().toLowerCase();
759
+ const matches = list.devices.filter(
760
+ (device) =>
761
+ device.label.toLowerCase() === wanted ||
762
+ (wanted.length >= 4 && device.deviceId.startsWith(wanted))
763
+ );
764
+ if (matches.length === 1) return { device: matches[0] };
765
+ return {
766
+ error: matches.length
767
+ ? `More than one device is called ${named}; use the start of its id.`
768
+ : `None of your devices is called ${named}.`,
769
+ };
770
+ };
771
+
772
+ /** The person's devices, checked, with this computer marked. */
773
+ const list = async () => {
774
+ const me = await self();
775
+ const { list: current } = await read();
776
+ return {
777
+ ok: true,
778
+ self: me.deviceId,
779
+ devices: current.devices,
780
+ removed: current.removed.length,
781
+ };
782
+ };
783
+
784
+ const rename = async (named, label) => {
785
+ const name = label.trim().slice(0, 120);
786
+ if (!name) return { ok: false, error: "Give the device a name." };
787
+ const { list: current } = await read();
788
+ const found = find(current, named);
789
+ if (found.error) return { ok: false, error: found.error };
790
+ await change({
791
+ op: "rename",
792
+ deviceId: found.device.deviceId,
793
+ label: name,
794
+ });
795
+ return { ok: true, device: { ...found.device, label: name } };
796
+ };
797
+
798
+ /**
799
+ * Takes a device off the person's list, signed by this computer, and changes their keys from here; what was sealed
800
+ * to the removed device opens nothing new. This computer itself is removed with tryharness uninstall, not here.
801
+ */
802
+ const remove = async (named) => {
803
+ const me = await self();
804
+ const { list: current } = await read();
805
+ const found = find(current, named);
806
+ if (found.error) return { ok: false, error: found.error };
807
+ if (found.device.deviceId === me.deviceId)
808
+ return {
809
+ ok: false,
810
+ error:
811
+ "That is this computer. To take it off, run tryharness uninstall here.",
812
+ };
813
+ await change({ op: "remove", deviceId: found.device.deviceId });
814
+ // The keys change at once, from here: the removed device held them (owner, November 14).
815
+ const changed = await rotate().catch((error) => {
816
+ log(`devices: keys not changed after a removal: ${error.message}`);
817
+ return { rotated: false };
818
+ });
819
+ return {
820
+ ok: true,
821
+ device: found.device,
822
+ keysChanged: changed.rotated,
823
+ ...(changed.recoveryCode ? { recoveryCode: changed.recoveryCode } : {}),
824
+ };
825
+ };
826
+
827
+ return {
828
+ list,
829
+ rename,
830
+ remove,
831
+ swarmProof,
832
+ checkSwarmProof,
833
+ sharedBackupKeys,
834
+ personIdentity,
835
+ ensureKeys,
836
+ rotate,
837
+ rotateIfDue,
838
+ takeRecoveryCode,
839
+ deviceOnList,
840
+ removedNow,
841
+ read,
842
+ change,
843
+ signOn,
844
+ startApproval,
845
+ finishApproval,
846
+ waiting,
847
+ compareWaiting,
848
+ approveWaiting,
849
+ declineWaiting,
850
+ /** The code a comparison in progress shows, for a surface that lost track of it. */
851
+ comparing: (id) => comparisons.get(id) ?? null,
852
+ };
853
+ }