tryharness 0.7.83 → 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 (215) 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 +191 -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 +52 -0
  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 +2426 -338
  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 +1 -1
  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/originals.mjs +216 -0
  107. package/lib/outsideEvents.mjs +383 -0
  108. package/lib/outsideRuns.mjs +230 -0
  109. package/lib/ownMachines.mjs +674 -256
  110. package/lib/pain.mjs +215 -0
  111. package/lib/pairing.mjs +91 -11
  112. package/lib/paths.mjs +42 -3
  113. package/lib/peerProcess.mjs +21 -7
  114. package/lib/peopleLink.mjs +268 -0
  115. package/lib/personNotices.mjs +3 -2
  116. package/lib/phones.mjs +252 -542
  117. package/lib/placeCards.mjs +282 -0
  118. package/lib/placeChecks.mjs +95 -0
  119. package/lib/placeCommands.mjs +8 -17
  120. package/lib/placeRequests.mjs +152 -0
  121. package/lib/placeStore.mjs +295 -0
  122. package/lib/placeTool.d.ts +12 -0
  123. package/lib/placeTool.js +40 -0
  124. package/lib/places.mjs +63 -14
  125. package/lib/plans.mjs +53 -8
  126. package/lib/presence.mjs +270 -0
  127. package/lib/privateNetwork.d.ts +2 -0
  128. package/lib/privateNetwork.js +93 -0
  129. package/lib/proposals.mjs +300 -0
  130. package/lib/publicFetch.d.ts +32 -0
  131. package/lib/publicFetch.js +248 -0
  132. package/lib/reach.mjs +128 -0
  133. package/lib/rebuildable.mjs +72 -0
  134. package/lib/recall.mjs +216 -0
  135. package/lib/record.mjs +13 -0
  136. package/lib/reflexes.mjs +392 -0
  137. package/lib/relayLimits.mjs +31 -2
  138. package/lib/releaseNotice.mjs +198 -0
  139. package/lib/removeHarness.mjs +15 -4
  140. package/lib/repoLinks.mjs +204 -35
  141. package/lib/runAuthority.mjs +102 -39
  142. package/lib/runBrief.mjs +93 -40
  143. package/lib/runRequests.mjs +52 -14
  144. package/lib/runUsage.mjs +31 -0
  145. package/lib/runWorker.mjs +74 -25
  146. package/lib/runner.mjs +289 -45
  147. package/lib/runtime-install.mjs +37 -8
  148. package/lib/schedules.mjs +171 -47
  149. package/lib/screenWatches.mjs +221 -0
  150. package/lib/sealed.mjs +12 -30
  151. package/lib/sealedThreads.mjs +198 -392
  152. package/lib/secretStore.mjs +178 -0
  153. package/lib/secrets.mjs +11 -0
  154. package/lib/seen.mjs +3 -9
  155. package/lib/selfUpdate.mjs +51 -15
  156. package/lib/senseCall.mjs +1514 -0
  157. package/lib/senseHook.mjs +114 -0
  158. package/lib/senseTools.mjs +1298 -0
  159. package/lib/sessionBriefs.mjs +87 -0
  160. package/lib/sessionControl.mjs +63 -13
  161. package/lib/sessionFiles.mjs +85 -0
  162. package/lib/setupChoices.mjs +12 -3
  163. package/lib/setupMode.mjs +70 -25
  164. package/lib/sharedKeys.mjs +166 -0
  165. package/lib/sleep.mjs +396 -0
  166. package/lib/sources.mjs +306 -0
  167. package/lib/speech.mjs +166 -411
  168. package/lib/spoken.mjs +210 -0
  169. package/lib/steerHook.mjs +3 -1
  170. package/lib/steerQueue.mjs +40 -11
  171. package/lib/store.mjs +323 -130
  172. package/lib/stuck.mjs +85 -7
  173. package/lib/swarm.mjs +157 -49
  174. package/lib/swarmDevices.mjs +25 -85
  175. package/lib/swarmMemory.mjs +93 -9
  176. package/lib/t3.mjs +73 -3
  177. package/lib/taskCommands.mjs +51 -60
  178. package/lib/taskRooms.mjs +30 -4
  179. package/lib/taskRules.json +29 -0
  180. package/lib/taskRules.mjs +21 -0
  181. package/lib/taskRuns.mjs +74 -11
  182. package/lib/team.mjs +2 -1
  183. package/lib/threadActions.mjs +37 -9
  184. package/lib/threadAuthority.mjs +4 -4
  185. package/lib/threadBriefs.mjs +173 -43
  186. package/lib/threadNotes.mjs +320 -0
  187. package/lib/threadRecord.mjs +491 -0
  188. package/lib/threadRuns.mjs +216 -108
  189. package/lib/threadView.mjs +27 -30
  190. package/lib/threadWatches.mjs +1962 -0
  191. package/lib/timeSense.mjs +839 -0
  192. package/lib/tripwires.mjs +454 -0
  193. package/lib/ui.mjs +1 -1
  194. package/lib/vault.mjs +560 -45
  195. package/lib/vaultCommands.mjs +5 -3
  196. package/lib/vaultPeers.mjs +165 -0
  197. package/lib/vaultTools.d.ts +4 -1
  198. package/lib/vaultTools.js +22 -1
  199. package/lib/verdicts.mjs +12 -26
  200. package/lib/versions.mjs +117 -0
  201. package/lib/waitTool.mjs +278 -0
  202. package/lib/wakePicture.mjs +268 -0
  203. package/lib/wakeQueue.mjs +108 -0
  204. package/lib/watchResponses.mjs +533 -0
  205. package/lib/watches.mjs +290 -145
  206. package/lib/windowAsks.mjs +80 -17
  207. package/lib/worktrees.mjs +159 -9
  208. package/npm-shrinkwrap.json +138 -631
  209. package/package.json +7 -6
  210. package/release.json +211 -129
  211. package/lib/callSessions.mjs +0 -51
  212. package/lib/directLink.mjs +0 -349
  213. package/lib/peopleBoard.mjs +0 -131
  214. package/lib/projects.mjs +0 -2917
  215. package/lib/roomChannels.mjs +0 -667
@@ -0,0 +1,82 @@
1
+ import { cleanRemote, pushAddress, remoteName } from "./jamGit.mjs";
2
+ import {
3
+ accessTo,
4
+ levelThrough,
5
+ parseRepoLink,
6
+ signInHint,
7
+ } from "./repoLinks.mjs";
8
+
9
+ // Who may start or join a jam on a repository: only someone whose own git sign-ins can read and push to it. Someone
10
+ // who can only read would have their agents' work stranded at the first push, so read-only access is refused the same
11
+ // as none. The remote is the one authority on this: Harness keeps no access list and can't ask ahead of time, because a
12
+ // swarm name isn't a GitHub username.
13
+
14
+ const REFUSED_LEVELS = ["none", "read"];
15
+
16
+ const shortName = (name) => String(name).split("/").slice(-2).join("/");
17
+
18
+ /** What a refused person reads under Join. */
19
+ function refusalWords({ level, repo }) {
20
+ const name = shortName(repo.name);
21
+ if (level === "read")
22
+ return `You can read ${name} but can't push to it, and a jam needs both. Press Join again once you have write access.`;
23
+ const host = parseRepoLink(repo.remote)?.host;
24
+ const signIn = host ? ` ${signInHint(host)}` : "";
25
+ return `You don't have access to ${name} from this computer, so you can't join yet. If another account has access, sign in with it and press Join again.${signIn}`;
26
+ }
27
+
28
+ export function createJamAccess() {
29
+ return {
30
+ /**
31
+ * Whether this person may join a jam on its repository, asked of the remote before anything is copied. `{ address }`
32
+ * when they can read and push, the address that can; otherwise the refusal to answer with.
33
+ */
34
+ check: async ({ repo }) => {
35
+ const access = await accessTo(repo.remote);
36
+ if (access.level === "write") return { address: access.address };
37
+ const refusal = REFUSED_LEVELS.includes(access.level)
38
+ ? refusalWords({ level: access.level, repo })
39
+ : `Harness couldn't reach ${shortName(repo.name)} to check your access (${access.said}). Try again when this computer can reach it.`;
40
+ return { refusal: { ok: false, code: "no_access", error: refusal } };
41
+ },
42
+
43
+ /**
44
+ * Why this person can't start a jam on their copy, or null: a jam nobody can push from strands every agent's work
45
+ * at its first push. Only the remote's own no refuses; a remote that doesn't answer leaves the choice with them.
46
+ */
47
+ startRefusal: async ({ folder, repo }) => {
48
+ const access = await accessTo(repo.remote);
49
+ const name = shortName(repo.name);
50
+ if (access.level === "read")
51
+ return `You can read ${name} but can't push to it, and a jam needs both. Get write access, then start the jam again.`;
52
+ if (access.level === "none")
53
+ return `You don't have access to ${name} from this computer, so you can't start a jam on it. If another account has access, sign in with it, then start the jam again.`;
54
+ if (access.level !== "write") return null;
55
+ const origin = pushAddress(folder);
56
+ if (!origin || origin === access.address) return null;
57
+ if (remoteName(origin) !== remoteName(repo.remote)) return null;
58
+ const { level } = await levelThrough(origin);
59
+ return REFUSED_LEVELS.includes(level)
60
+ ? `Your copy in ${folder} pushes through ${cleanRemote(origin)}, which can't write to ${name}, but ${access.address} can. Run git remote set-url origin ${access.address} there, then start the jam again.`
61
+ : null;
62
+ },
63
+
64
+ /**
65
+ * A refusal when the person's existing copy can't push through its own origin, though another address can: their
66
+ * agents' work would go nowhere. It is theirs to fix.
67
+ */
68
+ checkCopy: async ({ folder, repo, address }) => {
69
+ const origin = pushAddress(folder);
70
+ if (!origin || origin === address) return null;
71
+ // A copy whose origin is some other repository is the person's own arrangement, a fork for instance.
72
+ if (remoteName(origin) !== remoteName(repo.remote)) return null;
73
+ const { level } = await levelThrough(origin);
74
+ if (!REFUSED_LEVELS.includes(level)) return null;
75
+ return {
76
+ ok: false,
77
+ code: "no_access",
78
+ error: `Your copy in ${folder} pushes through ${cleanRemote(origin)}, which can't write to ${shortName(repo.name)}, but ${address} can. Run git remote set-url origin ${address} there, then press Join again.`,
79
+ };
80
+ },
81
+ };
82
+ }
@@ -1,6 +1,6 @@
1
- // A shared project's board: the one board every person in the project and their agents see, built on each computer
2
- // from the project's record (projects.mjs), so every copy shows the same cards. It holds:
3
- // - the project's pieces and the work agents said they are doing (plan_work) as cards, their column, title and holder
1
+ // A jam's board: the one board every person in the jam and their agents see, built on each computer from the jam's
2
+ // record (jams.mjs), so every copy shows the same cards. It holds:
3
+ // - the jam's pieces and the work agents said they are doing (plan_work) as cards, their column, title and holder
4
4
  // following the record: an open piece is To do, one held or work under way In progress, work done Review, merged
5
5
  // Done; work that clashes is blocked;
6
6
  // - the cards agents and people add (update_board, a task handed out in the room): a `card` entry made by the side
@@ -11,6 +11,7 @@
11
11
  import { oneLine } from "./oneLine.mjs";
12
12
 
13
13
  export const BOARD_KINDS = ["card", "card-edit"];
14
+
14
15
  const FIELDS = ["title", "column", "agent", "note", "blocked", "needsYou"];
15
16
  // A card from the record is moved by the record: these of its fields are never set on the board.
16
17
  const RECORD_FIELDS = new Set(["title", "column", "agent"]);
@@ -28,7 +29,7 @@ const WORK_COLUMNS = {
28
29
  /** The one entry a side keeps for its changes to one card; an entry under another id is not that side's. */
29
30
  export const editIdOf = (cardId, side) => `card-edit:${cardId}:${side}`;
30
31
 
31
- export function createProjectBoard({ items, write, local, shared, pieces }) {
32
+ export function createJamBoard({ items, write, local, shared, pieces }) {
32
33
  const now = () => new Date().toISOString();
33
34
  const named = (p, field, value, toShared) =>
34
35
  field === "agent" && value
@@ -1,16 +1,15 @@
1
1
  import fs from "node:fs";
2
- import os from "node:os";
3
2
  import path from "node:path";
4
3
  import { spawn, spawnSync } from "node:child_process";
5
4
 
6
- // The git half of a shared project. The repository is named by hashes, the same on every computer that has it: its
7
- // first commit says which repository it is, and the shared remote's canon branch says where work starts and ends.
8
- // Each agent works on a branch of its own, in a worktree of the person's checkout made from canon's head; code moves
9
- // between the two people only through the remote.
5
+ // The git half of a jam. The repository is named by hashes, the same on every computer that has it: its first commit
6
+ // says which repository it is (and identifies the jam), and the shared remote's canon branch says where work starts and
7
+ // ends. Each agent works on a branch of its own, in a worktree of the person's checkout made from canon's head; code
8
+ // moves between people only through the remote.
10
9
 
11
10
  // Hooks and the file-system monitor off for every call Harness makes itself: a repository the other person also writes
12
11
  // to can set core.hooksPath to a tracked folder, and its scripts would run here, outside any agent's sandbox.
13
- const IDENTITY = [
12
+ export const IDENTITY = [
14
13
  "-c",
15
14
  "user.name=Harness",
16
15
  "-c",
@@ -60,6 +59,24 @@ function gitLater(cwd, args) {
60
59
  });
61
60
  }
62
61
 
62
+ // Lines in git's error output that never say what went wrong: progress and warnings.
63
+ const NOT_THE_ERROR =
64
+ /^(?:Cloning into |warning:|remote: (?:Enumerating|Counting|Compressing|Total)|Receiving objects|Resolving deltas)/i;
65
+
66
+ /**
67
+ * The line of git's error output that says what went wrong, without its "fatal:" label. It is an early line: the last
68
+ * ones are boilerplate ("Please make sure you have the correct access rights / and the repository exists.").
69
+ */
70
+ export const gitSaid = (err) =>
71
+ (
72
+ String(err || "")
73
+ .split(/\r?\n/)
74
+ .map((line) => line.trim())
75
+ .find((line) => line && !NOT_THE_ERROR.test(line)) ?? ""
76
+ )
77
+ .replace(/^(?:remote|fatal|error):\s*/i, "")
78
+ .replace(/\.$/, "");
79
+
63
80
  /** A remote's address without credentials in it, so it can be shown and shared. */
64
81
  export const cleanRemote = (remote) =>
65
82
  String(remote || "").replace(/\/\/[^@/]+@/, "//");
@@ -117,7 +134,9 @@ export function anchorOf(folder) {
117
134
  : null;
118
135
  if (!first)
119
136
  return { ok: false, error: "That repository has no commits yet." };
120
- const remote = git(root, ["remote", "get-url", "origin"]);
137
+ // As the person's repository names it, not rewritten by their own git settings: a url.insteadOf for a private mirror would
138
+ // send the invited person a path on this computer.
139
+ const remote = git(root, ["config", "--get", "remote.origin.url"]);
121
140
  if (!remote.ok || !remote.out)
122
141
  return {
123
142
  ok: false,
@@ -173,26 +192,45 @@ export function findCheckout(folders, first) {
173
192
  return null;
174
193
  }
175
194
 
176
- /** A new checkout of the shared remote in the home folder, named for the repository, next to nothing already there. */
177
- export async function cloneInto(remote, name) {
195
+ /**
196
+ * A new checkout of the shared remote in `parent` (the folder the person chose), named for the repository, next to
197
+ * nothing already there.
198
+ */
199
+ export async function cloneInto(remote, name, parent) {
178
200
  if (!validRemote(remote))
179
201
  return {
180
202
  ok: false,
181
203
  error: "That repository's address isn't one Harness copies from.",
182
204
  };
183
- const base = path.basename(String(name || "project")) || "project";
184
- let target = path.join(os.homedir(), base);
205
+ const where = String(parent || "");
206
+ if (
207
+ !path.isAbsolute(where) ||
208
+ !fs.existsSync(where) ||
209
+ !fs.statSync(where).isDirectory()
210
+ )
211
+ return { ok: false, error: "Pick a folder that is on this computer." };
212
+ const base = path.basename(String(name || "jam")) || "jam";
213
+ let target = path.join(where, base);
185
214
  for (let n = 2; fs.existsSync(target); n += 1)
186
- target = path.join(os.homedir(), `${base}-${n}`);
187
- const cloned = await gitLater(os.homedir(), ["clone", "--", remote, target]);
215
+ target = path.join(where, `${base}-${n}`);
216
+ const cloned = await gitLater(where, ["clone", "--", remote, target]);
188
217
  if (!cloned.ok)
189
218
  return {
190
219
  ok: false,
191
- error: `Could not copy the repository from ${remote}: ${cloned.err.split("\n").at(-1)}`,
220
+ error: `Could not copy the repository from ${remote}: ${gitSaid(cloned.err)}`,
192
221
  };
193
222
  return { ok: true, folder: target };
194
223
  }
195
224
 
225
+ /** The address a checkout's pushes go to, as its config writes it. */
226
+ export function pushAddress(folder) {
227
+ const read = (key) => git(folder, ["config", "--get", key]);
228
+ const pushUrl = read("remote.origin.pushurl");
229
+ if (pushUrl.ok && pushUrl.out) return pushUrl.out;
230
+ const url = read("remote.origin.url");
231
+ return url.ok && url.out ? url.out : null;
232
+ }
233
+
196
234
  /** Canon's newest commit on the remote, fetched now; null when the remote could not be reached. */
197
235
  export async function fetchCanon(folder, canon) {
198
236
  if (!validBranch(canon)) return null;
@@ -350,7 +388,7 @@ export async function pushLane(where, branch) {
350
388
  ]);
351
389
  return pushed.ok
352
390
  ? { ok: true }
353
- : { ok: false, error: pushed.err.split("\n").at(-1) || "git push failed" };
391
+ : { ok: false, error: gitSaid(pushed.err) || "git push failed" };
354
392
  }
355
393
 
356
394
  export function removeLane(checkout, where) {
package/lib/jamKey.mjs ADDED
@@ -0,0 +1,274 @@
1
+ import { webcrypto } from "node:crypto";
2
+ import { openSealedBytes, sealBytes } from "./deviceSeal.mjs";
3
+ import {
4
+ openBound,
5
+ openBytes,
6
+ sealBound,
7
+ sealBytes as sealRaw,
8
+ } from "./sealed.mjs";
9
+
10
+ // The jam's keys and signatures (docs/jam-plan.md J3). Harness keeps a jam's events and cannot read them:
11
+ //
12
+ // - Each epoch has a random 32-byte key. It reaches each member wrapped to their computer's sealing key
13
+ // (deviceSeal.mjs: an ephemeral P-256 key, ECDH, AES-GCM), so Harness carries it unread.
14
+ // - An event is sealed under its epoch's key, bound to `jam|<id>|<epoch>|<author>|<seq>` (sealed.mjs sealBound): one
15
+ // moved to another jam, epoch, author or place does not open.
16
+ // - Everyone in the jam holds the same key, so the key alone cannot say who wrote what. Every event, and every wrapped
17
+ // key, is signed by the computer that made it (ECDSA P-256, deviceIdentity.mjs), and checked against that member's
18
+ // card: their keys, signed by the jam's owner, whose own key each member pinned as their friend. Without the
19
+ // signature on a wrapped key, Harness could hand members a key of its own making and read what follows.
20
+
21
+ const { subtle } = webcrypto;
22
+ const SIGNING = { name: "ECDSA", namedCurve: "P-256" };
23
+ const SIGNATURE = { name: "ECDSA", hash: "SHA-256" };
24
+ const encoder = new TextEncoder();
25
+ const KEY_BYTES = 32;
26
+
27
+ const toBase64 = (bytes) => Buffer.from(bytes).toString("base64");
28
+ const fromBase64 = (text) =>
29
+ new Uint8Array(Buffer.from(String(text), "base64"));
30
+ // A computer's sealing key travels base64url (sealed.mjs); deviceSeal.mjs takes it as standard base64.
31
+ const standardBase64 = (key) =>
32
+ Buffer.from(String(key), "base64url").toString("base64");
33
+
34
+ export const eventBinding = ({ jamId, epoch, author, seq }) =>
35
+ `jam|${jamId}|${epoch}|${author}|${seq}`;
36
+ const keyBinding = ({ jamId, epoch, to }) => `jam-key|${jamId}|${epoch}|${to}`;
37
+ const cardBinding = ({ jamId, handle, sealingKey, signingKey }) =>
38
+ `jam-card|${jamId}|${handle}|${sealingKey}|${signingKey}`;
39
+
40
+ async function sign(privateKey, text) {
41
+ const signature = await subtle.sign(
42
+ SIGNATURE,
43
+ privateKey,
44
+ encoder.encode(text)
45
+ );
46
+ return toBase64(new Uint8Array(signature));
47
+ }
48
+
49
+ async function verify(publicKey, signature, text) {
50
+ if (typeof signature !== "string" || !signature) return false;
51
+ try {
52
+ const key = await subtle.importKey(
53
+ "raw",
54
+ fromBase64(publicKey),
55
+ SIGNING,
56
+ false,
57
+ ["verify"]
58
+ );
59
+ return await subtle.verify(
60
+ SIGNATURE,
61
+ key,
62
+ fromBase64(signature),
63
+ encoder.encode(text)
64
+ );
65
+ } catch {
66
+ return false;
67
+ }
68
+ }
69
+
70
+ const aesKey = (bytes) =>
71
+ subtle.importKey("raw", bytes, { name: "AES-GCM" }, false, [
72
+ "encrypt",
73
+ "decrypt",
74
+ ]);
75
+
76
+ /** A new epoch's key: 32 random bytes. */
77
+ export const newJamKey = () =>
78
+ webcrypto.getRandomValues(new Uint8Array(KEY_BYTES));
79
+
80
+ /**
81
+ * A member's card: their handle and computer keys, signed by the jam's owner. `signer` is the owner's signing private
82
+ * key (their own card included).
83
+ */
84
+ export async function signCard(
85
+ { jamId, handle, sealingKey, signingKey },
86
+ signer
87
+ ) {
88
+ const card = { handle, sealingKey, signingKey };
89
+ return { ...card, sig: await sign(signer, cardBinding({ jamId, ...card })) };
90
+ }
91
+
92
+ /** Whether a card is the owner's word for this jam. `ownerSigningKey`: the owner's key as this computer pinned it. */
93
+ export const cardHolds = (card, jamId, ownerSigningKey) =>
94
+ verify(ownerSigningKey, card?.sig, cardBinding({ jamId, ...card }));
95
+
96
+ /**
97
+ * An epoch's key for one member, sealed to their computer's sealing key and signed by the computer wrapping it.
98
+ * `to`: { handle, sealingKey }; `by`: { handle, signingPrivateKey }.
99
+ */
100
+ export async function wrapKey({ jamId, epoch, key, to, by }) {
101
+ const sealed = await sealBytes(key, standardBase64(to.sealingKey));
102
+ const text = `${keyBinding({ jamId, epoch, to: to.handle })}|${sealed}`;
103
+ return { sealed, by: by.handle, sig: await sign(by.signingPrivateKey, text) };
104
+ }
105
+
106
+ /**
107
+ * This member's copy of an epoch's key. Throws unless it was wrapped for `me` (handle) by the computer whose signing
108
+ * key is `wrapperSigningKey`, and opens with this computer's sealing private key.
109
+ */
110
+ export async function unwrapKey({
111
+ jamId,
112
+ epoch,
113
+ wrapped,
114
+ me,
115
+ sealingPrivateKey,
116
+ wrapperSigningKey,
117
+ }) {
118
+ const text = `${keyBinding({ jamId, epoch, to: me })}|${wrapped?.sealed}`;
119
+ if (!(await verify(wrapperSigningKey, wrapped?.sig, text)))
120
+ throw new Error(`the key for epoch ${epoch} is not signed by a member`);
121
+ const key = await openSealedBytes(wrapped.sealed, sealingPrivateKey);
122
+ if (key.length !== KEY_BYTES)
123
+ throw new Error(`the key for epoch ${epoch} is not a jam key`);
124
+ return key;
125
+ }
126
+
127
+ /** One event, sealed under its epoch's key and signed by its author's computer. */
128
+ export async function sealEvent({
129
+ jamId,
130
+ epoch,
131
+ seq,
132
+ author,
133
+ key,
134
+ body,
135
+ signingPrivateKey,
136
+ }) {
137
+ const binding = eventBinding({ jamId, epoch, author, seq });
138
+ const { iv, ct } = await sealBound(await aesKey(key), binding, body);
139
+ return {
140
+ iv,
141
+ ct,
142
+ sig: await sign(signingPrivateKey, `${binding}|${iv}|${ct}`),
143
+ };
144
+ }
145
+
146
+ /**
147
+ * One event's body. Throws when it is unsigned, signed by anyone but its author (`authorSigningKey`, from their card),
148
+ * changed, or moved to another jam, epoch, author or place in the order.
149
+ */
150
+ export async function openEvent({
151
+ jamId,
152
+ epoch,
153
+ seq,
154
+ author,
155
+ key,
156
+ sealed,
157
+ authorSigningKey,
158
+ }) {
159
+ const binding = eventBinding({ jamId, epoch, author, seq });
160
+ if (!sealed?.sig) throw new Error("the event is not signed");
161
+ if (
162
+ !(await verify(
163
+ authorSigningKey,
164
+ sealed.sig,
165
+ `${binding}|${sealed.iv}|${sealed.ct}`
166
+ ))
167
+ )
168
+ throw new Error(`the event is not signed by ${author}`);
169
+ try {
170
+ return await openBound(await aesKey(key), binding, sealed);
171
+ } catch {
172
+ throw new Error("the event does not open under its epoch's key");
173
+ }
174
+ }
175
+
176
+ const fileBinding = ({ jamId, epoch, author, fileId }) =>
177
+ `jam-file|${jamId}|${epoch}|${author}|${fileId}`;
178
+
179
+ /**
180
+ * A file's bytes for the jam (docs/jam-plan.md J4.9): sealed as they are under its epoch's key, bound to the jam, epoch,
181
+ * author and file id, and signed by its author's computer like an event.
182
+ */
183
+ export async function sealFile({
184
+ jamId,
185
+ epoch,
186
+ author,
187
+ fileId,
188
+ key,
189
+ bytes,
190
+ signingPrivateKey,
191
+ }) {
192
+ const binding = fileBinding({ jamId, epoch, author, fileId });
193
+ const { iv, ct } = await sealRaw(await aesKey(key), binding, bytes);
194
+ return {
195
+ iv,
196
+ ct,
197
+ sig: await sign(signingPrivateKey, `${binding}|${iv}|${ct}`),
198
+ };
199
+ }
200
+
201
+ /** A file's bytes. Throws when it is unsigned, signed by anyone but its author, changed, or moved to another place. */
202
+ export async function openFile({
203
+ jamId,
204
+ epoch,
205
+ author,
206
+ fileId,
207
+ key,
208
+ sealed,
209
+ authorSigningKey,
210
+ }) {
211
+ const binding = fileBinding({ jamId, epoch, author, fileId });
212
+ if (
213
+ !(await verify(
214
+ authorSigningKey,
215
+ sealed?.sig,
216
+ `${binding}|${sealed?.iv}|${sealed?.ct}`
217
+ ))
218
+ )
219
+ throw new Error(`the file is not signed by ${author}`);
220
+ try {
221
+ return await openBytes(await aesKey(key), binding, sealed);
222
+ } catch {
223
+ throw new Error("the file does not open under its epoch's key");
224
+ }
225
+ }
226
+
227
+ const offerBinding = ({ jamId, epoch, to }) =>
228
+ `jam-offer|${jamId}|${epoch}|${to}`;
229
+
230
+ /**
231
+ * What an invited friend is shown before joining (docs/jam-plan.md J4): sealed under the epoch's key they were given,
232
+ * for them alone (`to`), and signed by the owner's computer, so Harness can neither read it nor show them its own.
233
+ */
234
+ export async function sealOffer({
235
+ jamId,
236
+ epoch,
237
+ to,
238
+ key,
239
+ body,
240
+ signingPrivateKey,
241
+ }) {
242
+ const binding = offerBinding({ jamId, epoch, to });
243
+ const { iv, ct } = await sealBound(await aesKey(key), binding, body);
244
+ return {
245
+ iv,
246
+ ct,
247
+ sig: await sign(signingPrivateKey, `${binding}|${iv}|${ct}`),
248
+ };
249
+ }
250
+
251
+ /** The offer an invitation carries. Throws unless the owner's computer (`ownerSigningKey`) signed it for `to`. */
252
+ export async function openOffer({
253
+ jamId,
254
+ epoch,
255
+ to,
256
+ key,
257
+ sealed,
258
+ ownerSigningKey,
259
+ }) {
260
+ const binding = offerBinding({ jamId, epoch, to });
261
+ if (
262
+ !(await verify(
263
+ ownerSigningKey,
264
+ sealed?.sig,
265
+ `${binding}|${sealed?.iv}|${sealed?.ct}`
266
+ ))
267
+ )
268
+ throw new Error("the invitation is not signed by the jam's owner");
269
+ try {
270
+ return await openBound(await aesKey(key), binding, sealed);
271
+ } catch {
272
+ throw new Error("the invitation does not open under the jam's key");
273
+ }
274
+ }