worktrust 0.10.24 → 0.10.25
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.
- package/README.md +7 -0
- package/SECURITY.md +24 -4
- package/engine-release.json +1 -1
- package/log-session.mjs +19 -84
- package/package-integrity.mjs +83 -6
- package/package-release.json +1 -1
- package/package.json +1 -1
- package/preserve-lines.mjs +2 -1
- package/preserve.mjs +7 -9
- package/runtime-install.mjs +48 -6
- package/setup-mcp.mjs +20 -18
- package/worktrust-launch.mjs +90 -8
- package/worktrust.mjs +45 -35
package/README.md
CHANGED
|
@@ -510,3 +510,10 @@ claim eligibility remains the server publication gate's responsibility.
|
|
|
510
510
|
Revoking a computer key stops new submissions, not the validity of every historical publication.
|
|
511
511
|
Passport withdrawal is a separate audited operation. Neither operation automatically erases the
|
|
512
512
|
person's prior data. Release signing keys, computer keys and passport signing keys are separate.
|
|
513
|
+
|
|
514
|
+
In 0.10.25, hooks and helper processes from the official launcher stay inside the checked
|
|
515
|
+
release. The old loose `~/.worktrust/count-behaviour.mjs` and individual-script download
|
|
516
|
+
fallbacks are no longer executed. Persistent Python hooks use the host Python to check the
|
|
517
|
+
copied Node runtime before starting it, even after the temporary uvx/pipx cache is removed.
|
|
518
|
+
Keep that host Python installed. Updating preserves credentials, pending uploads and archives;
|
|
519
|
+
it does not approve held history or publish a passport automatically.
|
package/SECURITY.md
CHANGED
|
@@ -9,11 +9,11 @@ private transcripts or account data in a public issue.
|
|
|
9
9
|
|
|
10
10
|
- Setup changes client configuration and local coupling files; preservation can change retention
|
|
11
11
|
settings and create or append archives. See the README for the paths and individual options.
|
|
12
|
-
|
|
13
|
-
|
|
12
|
+
The complete official release is required. Individual script download fallbacks are removed;
|
|
13
|
+
interactive commands may check for a newer release.
|
|
14
14
|
- Submissions go to the configured WorkTrust MCP endpoint. Interactive commands can also contact
|
|
15
|
-
the npm registry for a version notice.
|
|
16
|
-
modules, but installation and
|
|
15
|
+
the npm registry for a version notice. Release notices never execute a different version. The npm package bundles its runtime
|
|
16
|
+
modules, but package-manager installation and explicit upgrades still use the network. `preserve` itself is local.
|
|
17
17
|
A custom `--origin`, URL or registry override changes whom you trust.
|
|
18
18
|
- The key it receives is a WorkTrust coupling for this computer: it can submit work metadata to your
|
|
19
19
|
record and cannot read your record back. Revoke it in WorkTrust at any time.
|
|
@@ -131,3 +131,23 @@ selection and consent. It is not an automatic SDK upload or an MCP submission. D
|
|
|
131
131
|
recording does not erase a separately imported copy; delete that copy through the private app.
|
|
132
132
|
See the service [privacy policy](https://worktrust.io/privacy) and
|
|
133
133
|
[support](https://worktrust.io/support) for account data requests.
|
|
134
|
+
|
|
135
|
+
## Execution boundary in 0.10.25
|
|
136
|
+
|
|
137
|
+
The official launcher starts helpers from its checked release, never a loose counter, hook or
|
|
138
|
+
reader in `~/.worktrust`. Its helper processes re-enter the launcher and its manifest check.
|
|
139
|
+
A missing or changed release is refused with an instruction to reinstall; it is not repaired
|
|
140
|
+
by downloading individual scripts. Earlier loose files may remain for recovery but are not
|
|
141
|
+
used as executable fallbacks.
|
|
142
|
+
|
|
143
|
+
Python's persistent installation now starts with the package manager's host Python in isolated
|
|
144
|
+
mode. A standard-library bootstrap checks the copied Node binary and engine before Node
|
|
145
|
+
executes, against hashes authenticated during installation. It does not trust a rewritten local
|
|
146
|
+
`runtime.json` or `installation.json` to authorize changes. The initial Python package still
|
|
147
|
+
verifies its publisher signature before installation. The host Python must remain available.
|
|
148
|
+
|
|
149
|
+
Bootstrap files, host interpreters, client configuration and processes running as the owner
|
|
150
|
+
remain trust boundaries. Replacing the bootstrap or racing file changes after a check cannot
|
|
151
|
+
be prevented by self-verification on an owner-controlled computer. Generated Claude/OpenCode
|
|
152
|
+
client plugins and user transcript/SDK inputs are not remote attestation. Server claim and
|
|
153
|
+
publication gates remain necessary; a matching client hash never proves truthful activity.
|
package/engine-release.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"chat-exports.mjs":"04eafe333940ec03d5058d8d51062124aa12ab882bf04db03bcda5613ec69298","claude-mod.mjs":"02d86b0cdddf39879efc5194c0a5be6b41456faedec28963dc123a4e88dc3942","config-edits.mjs":"0eba2f176ef6f7afba071d6e00de0ff19ba2b283180a801dfd957aa38c1edd94","count-behaviour.mjs":"1beaec2a4d0aead76d166f89cc52441a9cf48f2e69da9888ca2091dd3a10a37b","history-outbox.mjs":"1bdca17b807c76e4a8e7bf42c6f07e12e8ae8e4466417cafdd26b1f58bf178a5","log-session.mjs":"
|
|
1
|
+
{"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"chat-exports.mjs":"04eafe333940ec03d5058d8d51062124aa12ab882bf04db03bcda5613ec69298","claude-mod.mjs":"02d86b0cdddf39879efc5194c0a5be6b41456faedec28963dc123a4e88dc3942","config-edits.mjs":"0eba2f176ef6f7afba071d6e00de0ff19ba2b283180a801dfd957aa38c1edd94","count-behaviour.mjs":"1beaec2a4d0aead76d166f89cc52441a9cf48f2e69da9888ca2091dd3a10a37b","history-outbox.mjs":"1bdca17b807c76e4a8e7bf42c6f07e12e8ae8e4466417cafdd26b1f58bf178a5","log-session.mjs":"c5e6e4d44a85768f21c25945b8630f31306ec2665193886870c1010ef6bf3c26","orchestration-contract.mjs":"ec08f303a166365b99e70b675de4cfe76c6156c2567e14b5569f6d992f0231b7","orchestration-evidence.mjs":"d0d06cecf0eb08e5c6e653c62a4f45b1eddf2119c2acb8341056b34f488d214a","orchestration-report.mjs":"d4e0a9ad8e4a01b462d22c6b1866aac291565c533ff476085d3367cb6d59bc1b","package-integrity.mjs":"a8210c9494a56bfb9a5ea3d10064c7a269f0b6330c0af7c0700e706c3c0224e3","preserve-lines.mjs":"2df64a69687aa51219bf7b86b88d175cc50990fa29574b31897e41a9ebeecf43","preserve-summary.mjs":"137f781ed7021596a3f0ea67afcf2ab8616ac293f833dbb8f176e838e0ed8321","preserve.mjs":"9add279352750be94d94873738145e379819d793c20c6c6503219969608e2c2f","runtime-install.mjs":"aab47b52c79d726ef428a24f982c648fa3f1c2dc2b574f633611d02924864e5f","session-databases.mjs":"543fd3b82d28d96d789be0a1dc9186c5fafa783e98b87e5b3b17b211542e2b4d","setup-mcp.mjs":"6ecfbf44f001dd433512b26736031ebc855b154e2bb0a401e2512b43623cd9cd","stack-rules.mjs":"b23c56e72ec56ba02b17ed895f869172d988c468a697e8d6026b0e268f61e489","stretch-evidence.mjs":"5b31a6f29b785d277e92257532f3c7cee366a79759decc7a75cfbaec2686ee13","transcript-readers.mjs":"413948644a74dc0bf1b49548be193bf596bcf82ac7eae668f624345a18e189e7","worktrust-launch.mjs":"84801bd29d472d48188c126b9ebe3989a3132b54e13cc4fe534ff7c383a294ee","worktrust.mjs":"bd208923c08a16ed640f25417ae381d0c3e3dda02e56aad4aee66497cdd494b9"},"format":"worktrust-package/1","kind":"engine","version":"0.10.25"},"signature":"3nt9U84E4YOoRtRh-5jp8WJcJVzCafdMYgFiI0WPhK2_OGYHnFAlD2mJYYYuO_8_Utrwh_41AQKHqYbNqJ7BAQ"}
|
package/log-session.mjs
CHANGED
|
@@ -60,12 +60,14 @@
|
|
|
60
60
|
* honoured here too, matched against the transcript's project directory, before a file is read.
|
|
61
61
|
*/
|
|
62
62
|
import { execFileSync, spawn, spawnSync } from "node:child_process";
|
|
63
|
-
import {
|
|
63
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync, lstatSync, openSync, closeSync, fsyncSync, linkSync, unlinkSync, constants } from "node:fs";
|
|
64
64
|
import { homedir } from "node:os";
|
|
65
65
|
import { dirname, join, resolve, sep } from "node:path";
|
|
66
66
|
import { fileURLToPath } from "node:url";
|
|
67
67
|
import { createHash, createPrivateKey, createPublicKey, randomBytes, sign as cryptoSign } from "node:crypto";
|
|
68
68
|
|
|
69
|
+
import { moduleArgs, moduleExecutable } from "./package-integrity.mjs";
|
|
70
|
+
|
|
69
71
|
async function main() {
|
|
70
72
|
const args = process.argv.slice(2), NODE_FLAGS = process.versions.node === "26.5.0" ? ["--no-concurrent-sparkplug"] : [];
|
|
71
73
|
const flag = (name) => args.includes(`--${name}`), value = (name) => { const i = args.indexOf(`--${name}`); return i >= 0 ? args[i + 1] : undefined; }, DRY = flag("dry-run");
|
|
@@ -83,32 +85,13 @@ const exitFlushed = (code) => new Promise((resolve) => process.stdout.write("",
|
|
|
83
85
|
* may stage, only the owner may count — and a hook that could send counts by itself would put an
|
|
84
86
|
* automatic writer on the one surface that describes how a person thinks.
|
|
85
87
|
*/
|
|
86
|
-
const
|
|
87
|
-
|
|
88
|
+
const RELEASE_DIR = dirname(fileURLToPath(import.meta.url));
|
|
89
|
+
const COUNTER = join(RELEASE_DIR, "count-behaviour.mjs");
|
|
90
|
+
/** Legacy marker, used only when the person explicitly purges the old installation. */
|
|
88
91
|
const PINNED = join(homedir(), ".worktrust", "pinned");
|
|
89
92
|
/** A hook command is ours when it runs this file, or the `worktrust hook` wrapper that hands it the key from the key file. */
|
|
90
|
-
const ours = (command) => /log-session|worktrust
|
|
93
|
+
const ours = (command) => /log-session|worktrust(?:-launch)?\.(?:mjs|py)" (?:hook|--internal-module)|worktrust(?:-launch)?\.(?:mjs|py) hook/.test(String(command ?? ""));
|
|
91
94
|
const COUNTER_EVERY_MS = 24 * 3600_000;
|
|
92
|
-
/**
|
|
93
|
-
* Counter compatibility is pinned by the verified release.
|
|
94
|
-
*/
|
|
95
|
-
const versionOf = (text) => /export const ANALYZER_VERSION = "counter@(\d+)\.(\d+)\.(\d+)"/.exec(text ?? "")?.slice(1, 4).map(Number) ?? null;
|
|
96
|
-
const newer = (a, b) => { if (!a || !b) return false; for (let i = 0; i < 3; i += 1) { if (a[i] === b[i]) continue; return a[i] > b[i]; } return false; };
|
|
97
|
-
async function refreshCounter(origin, announce) {
|
|
98
|
-
if (!origin || !existsSync(COUNTER) || existsSync(PINNED)) return false;
|
|
99
|
-
try {
|
|
100
|
-
const response = await fetch(`${origin}/counter/count-behaviour.mjs`);
|
|
101
|
-
if (!response.ok) return false;
|
|
102
|
-
const remote = await response.text();
|
|
103
|
-
const have = versionOf(readFileSync(COUNTER, "utf8")), theirs = versionOf(remote);
|
|
104
|
-
if (!newer(theirs, have)) return false;
|
|
105
|
-
writeFileSync(COUNTER, remote);
|
|
106
|
-
await installReaders(origin, true);
|
|
107
|
-
announce?.(`counter: updated to counter@${theirs.join(".")} (was counter@${have?.join(".") ?? "?"}) — the next reading counts under the new rubric`);
|
|
108
|
-
return true;
|
|
109
|
-
} catch { return false; }
|
|
110
|
-
}
|
|
111
|
-
|
|
112
95
|
/**
|
|
113
96
|
* The live door refuses stretches older than two days; older work uses the history door.
|
|
114
97
|
*
|
|
@@ -254,20 +237,6 @@ const EXPORT_PATHS = []; for (let i = 0; i < args.length; i += 1) if (args[i] ==
|
|
|
254
237
|
const DATABASE_CLIENTS = ["hermes", "goose", "opencode", "openclaw", "cursor", "copilot"]; // the registry's keys, the name each line carries
|
|
255
238
|
const LIVE_SOURCE = new RegExp(`^(codex|antigravity|${DATABASE_CLIENTS.join("|")}):`); // a sweep entry's id → the client it names (every database client, 0.6.16)
|
|
256
239
|
const READER_FILES = ["history-outbox.mjs", "transcript-readers.mjs", "session-databases.mjs", "stretch-evidence.mjs", "chat-exports.mjs", "stack-rules.mjs", "claude-mod.mjs"]; // 0.7.4: the derived record travels with the hook; 0.10.10: the export reader; 0.10.11: the stack rules; 0.10.15: the mod
|
|
257
|
-
/** The readers go where the hook and the counter run: copied from beside this file, else (or for a newer counter) from the deployment. */
|
|
258
|
-
async function installReaders(origin, fromNetwork = false) {
|
|
259
|
-
let installed = true;
|
|
260
|
-
for (const name of READER_FILES) { // Hermes, Goose, OpenCode and OpenClaw are read by session-databases.mjs
|
|
261
|
-
const here = join(dirname(fileURLToPath(import.meta.url)), name), home = join(homedir(), ".worktrust", name);
|
|
262
|
-
try {
|
|
263
|
-
if (!fromNetwork && existsSync(here)) { mkdirSync(dirname(home), { recursive: true }); if (here !== home) copyFileSync(here, home); continue; }
|
|
264
|
-
const response = origin ? await fetch(`${origin}/counter/${name}`) : null;
|
|
265
|
-
if (response?.ok) writeFileSync(home, await response.text()); else installed = false;
|
|
266
|
-
} catch { installed = false; }
|
|
267
|
-
}
|
|
268
|
-
return installed;
|
|
269
|
-
}
|
|
270
|
-
|
|
271
240
|
/** The roots this machine's transcripts live under; a test names its own. */
|
|
272
241
|
const claudeRoot = () => value("transcript-root") ?? join(homedir(), ".claude", "projects");
|
|
273
242
|
const codexRoot = () => { const given = value("codex-root"); if (given) return given.replace(/^~(?=\/|$)/, homedir()); return value("transcript-root") ? null : join(homedir(), ".codex", "sessions"); };
|
|
@@ -1070,7 +1039,7 @@ if (flag("uninstall")) {
|
|
|
1070
1039
|
}
|
|
1071
1040
|
const removed = before !== JSON.stringify(HOOK_EVENTS.map((event) => settings.hooks?.[event] ?? []));
|
|
1072
1041
|
if (removed) writeFileSync(file, JSON.stringify(settings, null, 2));
|
|
1073
|
-
if (flag("purge")) for (const path of [
|
|
1042
|
+
if (flag("purge")) for (const path of [join(homedir(), ".worktrust", "count-behaviour.mjs"), PINNED, join(homedir(), ".worktrust", "log-session.mjs"), STATE, ...READER_FILES.map((name) => join(homedir(), ".worktrust", name)), join(homedir(), ".worktrust", "antigravity.json")]) { try { rmSync(path); } catch { /* already gone */ } }
|
|
1074
1043
|
console.log(`${removed ? "removed" : "nothing wired"}: ${file}${flag("purge") ? "\n purged ~/.worktrust" : ""}`);
|
|
1075
1044
|
console.log("the coupling itself still exists: end it in the app (Sources → the computer's row → end this coupling)");
|
|
1076
1045
|
return await exitFlushed(0);
|
|
@@ -1085,32 +1054,17 @@ if (flag("install")) {
|
|
|
1085
1054
|
if (value("history-floor") === "now") floors.__historyFloor = now;
|
|
1086
1055
|
writeState(floors);
|
|
1087
1056
|
}
|
|
1088
|
-
//
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
// from a person who stopped working. So install copies itself to ~/.worktrust and wires that.
|
|
1095
|
-
const home = join(homedir(), ".worktrust", "log-session.mjs");
|
|
1096
|
-
const self = process.argv[1];
|
|
1097
|
-
// The copy that runs is refreshed from the file you ran — and SAYS so, because "already installed —
|
|
1098
|
-
// nothing changed" after a newer download read as "your hook is old" to the person who had just updated it.
|
|
1099
|
-
let hookRefreshed = false;
|
|
1100
|
-
if (self !== home) {
|
|
1101
|
-
const next = readFileSync(self, "utf8");
|
|
1102
|
-
const current = existsSync(home) ? readFileSync(home, "utf8") : null;
|
|
1103
|
-
mkdirSync(dirname(home), { recursive: true });
|
|
1104
|
-
if (current !== next) { writeFileSync(home, next); hookRefreshed = current !== null; }
|
|
1057
|
+
// Only complete, verified releases may be installed. Old loose scripts are never copied or fetched.
|
|
1058
|
+
const home = join(RELEASE_DIR, "log-session.mjs");
|
|
1059
|
+
let via = value("via");
|
|
1060
|
+
if (!via) {
|
|
1061
|
+
const { installSignedPackage } = await import("./package-integrity.mjs");
|
|
1062
|
+
via = installSignedPackage(RELEASE_DIR, join(homedir(), ".worktrust"));
|
|
1105
1063
|
}
|
|
1106
|
-
// A counter handed over by the package (`--counter <path>`) is copied and pinned: nothing below fetches one.
|
|
1107
|
-
const given = args.indexOf("--counter") >= 0 ? args[args.indexOf("--counter") + 1] : null;
|
|
1108
|
-
if (given) { mkdirSync(dirname(COUNTER), { recursive: true }); writeFileSync(COUNTER, readFileSync(given, "utf8")); writeFileSync(PINNED, "the counter comes with the worktrust package; it is not refreshed from the network\n"); console.log(`counter: ${COUNTER} — from the package, pinned`); }
|
|
1109
1064
|
const file = join(homedir(), ".claude", "settings.json");
|
|
1110
1065
|
const settings = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
|
|
1111
|
-
|
|
1112
|
-
const
|
|
1113
|
-
const command = `"${process.env.WORKTRUST_NODE || process.execPath}" "${via ?? home}"${via ? " hook" : ""}`;
|
|
1066
|
+
const direct = flag("direct");
|
|
1067
|
+
const command = `"${process.env.WORKTRUST_NODE || process.execPath}"${process.env.WORKTRUST_NODE_ARGS === '["-I"]' ? " -I" : ""} "${via}"${direct ? " --internal-module log-session.mjs" : " hook"}`;
|
|
1114
1068
|
settings.hooks ??= {};
|
|
1115
1069
|
for (const event of HOOK_EVENTS) settings.hooks[event] ??= [];
|
|
1116
1070
|
// A WIRING THAT POINTS SOMEWHERE ELSE IS REPAIRED, NOT LEFT. An earlier install wired whatever
|
|
@@ -1135,24 +1089,7 @@ if (flag("install")) {
|
|
|
1135
1089
|
// how a person ends up certain that a thing works which does not.
|
|
1136
1090
|
const added = HOOK_EVENTS.filter((event) => !wired.has(event));
|
|
1137
1091
|
const already = added.length === 0;
|
|
1138
|
-
|
|
1139
|
-
// says plainly that it could not — a half nobody knows is missing is the worse outcome.
|
|
1140
|
-
const counterOrigin = coupling()?.url ? new URL(coupling().url).origin : null;
|
|
1141
|
-
if (!(await installReaders(counterOrigin))) console.log("readers: transcript-readers.mjs or session-databases.mjs not found beside this file nor at the deployment; the clients they read are not read until they are");
|
|
1142
|
-
if (existsSync(COUNTER)) await refreshCounter(counterOrigin, (line) => console.log(line));
|
|
1143
|
-
if (!existsSync(COUNTER)) {
|
|
1144
|
-
const origin = counterOrigin;
|
|
1145
|
-
if (!origin) console.log("counter: not installed — no coupling found to name the deployment; fetch /counter/count-behaviour.mjs yourself");
|
|
1146
|
-
else {
|
|
1147
|
-
try {
|
|
1148
|
-
const response = await fetch(`${origin}/counter/count-behaviour.mjs`);
|
|
1149
|
-
if (!response.ok) throw new Error(String(response.status));
|
|
1150
|
-
writeFileSync(COUNTER, await response.text());
|
|
1151
|
-
console.log(`counter: ${COUNTER} — it runs once a day from this hook and STAGES its reading; nothing counts until you click Import in the app`);
|
|
1152
|
-
} catch (error) { console.log(`counter: could not fetch it (${error.message}) — the hook works without it; fetch /counter/count-behaviour.mjs later`); }
|
|
1153
|
-
}
|
|
1154
|
-
}
|
|
1155
|
-
if (already && !repaired) { console.log(hookRefreshed ? `hook updated: ${home} now runs the version you downloaded; the wiring was already right (${command})` : `already installed — nothing changed (${command})`); return await exitFlushed(0); }
|
|
1092
|
+
if (already && !repaired) { console.log(`already installed — nothing changed (${command})`); return await exitFlushed(0); }
|
|
1156
1093
|
for (const event of added) settings.hooks[event].push({ hooks: [{ type: "command", command }] });
|
|
1157
1094
|
mkdirSync(dirname(file), { recursive: true });
|
|
1158
1095
|
writeFileSync(file, JSON.stringify(settings, null, 2));
|
|
@@ -1234,7 +1171,7 @@ if (flag("history") && flag("from-archive")) {
|
|
|
1234
1171
|
// archive must still verify whole, and only stretches no longer in any AI app here travel.
|
|
1235
1172
|
let ownKey = null;
|
|
1236
1173
|
try { ownKey = pem ? createPublicKey(createPrivateKey(pem)).export({ format: "jwk" }).x : null; } catch { ownKey = null; }
|
|
1237
|
-
const verified = spawnSync(
|
|
1174
|
+
const verified = spawnSync(moduleExecutable(RELEASE_DIR), [...moduleArgs(RELEASE_DIR, "preserve.mjs", ["--verify", dir])], { encoding: "utf8" });
|
|
1238
1175
|
if (verified.status !== 0) { say(`The archive in ${dir} does not verify, so nothing was sent: ${(verified.stdout || verified.stderr || "").trim().split("\n").pop()}`); return await exitFlushed(1); }
|
|
1239
1176
|
const { archiveEntries = null } = (await import("./preserve-lines.mjs").catch(() => null)) ?? {};
|
|
1240
1177
|
if (!archiveEntries) { say("preserve-lines.mjs is not beside this file. Nothing was sent."); return await exitFlushed(1); }
|
|
@@ -1360,12 +1297,10 @@ if (!DRY && (sent > 0 || filed > 0)) writeState(state);
|
|
|
1360
1297
|
// `--send`: staging is idempotent on the reading's own digest, so a day that changed nothing
|
|
1361
1298
|
// leaves nothing behind.
|
|
1362
1299
|
if (!DRY && existsSync(COUNTER)) {
|
|
1363
|
-
// Before the day's count: the deployment's counter, if it is newer than the one on this machine.
|
|
1364
|
-
await refreshCounter(door?.url ? new URL(door.url).origin : null, (line) => console.log(line));
|
|
1365
1300
|
const last = state.__counter?.at ? Date.parse(state.__counter.at) : 0;
|
|
1366
1301
|
if (Date.now() - last > COUNTER_EVERY_MS) {
|
|
1367
1302
|
try {
|
|
1368
|
-
const child = spawn(
|
|
1303
|
+
const child = spawn(moduleExecutable(RELEASE_DIR), moduleArgs(RELEASE_DIR, "count-behaviour.mjs", ["--stage"]), { detached: true, stdio: ["ignore", "ignore", "inherit"] });
|
|
1369
1304
|
child.unref();
|
|
1370
1305
|
state.__counter = { at: new Date().toISOString() };
|
|
1371
1306
|
writeState(state);
|
package/package-integrity.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** Official launcher verification. Pinned keys are generated from reviewed release configuration. */
|
|
2
2
|
import { createHash, createPublicKey, verify, randomBytes } from 'node:crypto';
|
|
3
|
-
import { existsSync, lstatSync, readFileSync, readdirSync, mkdirSync, writeFileSync, renameSync, rmSync } from 'node:fs';
|
|
4
|
-
import { join, dirname } from 'node:path';
|
|
3
|
+
import { existsSync, lstatSync, readFileSync, readdirSync, mkdirSync, writeFileSync, renameSync, rmSync, constants, openSync, closeSync, fstatSync, fchmodSync, readSync, fsyncSync } from 'node:fs';
|
|
4
|
+
import { join, dirname, basename, isAbsolute } from 'node:path';
|
|
5
5
|
|
|
6
6
|
export const RELEASE_KEYS = {"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5":"-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAxe/h8yLe+e4iKYSx/2lzS7MgHIgzM+mi1XjofW1VKo4=\n-----END PUBLIC KEY-----\n"}; // GENERATED_RELEASE_KEYS
|
|
7
7
|
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
|
|
@@ -16,7 +16,7 @@ const exact = (value, keys) => value && Object.keys(value).sort().join(',') ===
|
|
|
16
16
|
const safe = name => {
|
|
17
17
|
if (typeof name !== 'string' || name.length > 240) return false;
|
|
18
18
|
const parts = name.split('/');
|
|
19
|
-
return parts.every((p, i) => (/^[A-Za-z0-
|
|
19
|
+
return parts.every((p, i) => (/^[A-Za-z0-9_][A-Za-z0-9._-]*$/.test(p) && p !== '..')
|
|
20
20
|
|| (p === '.claude-plugin' && i > 0 && i < parts.length - 1 && parts[i - 1] === 'agent'));
|
|
21
21
|
};
|
|
22
22
|
function regular(path) {
|
|
@@ -44,7 +44,7 @@ export function verifyPackage(root, kind = 'npm') {
|
|
|
44
44
|
|| !verify(null, Buffer.from('worktrust:package:1\n' + canonical(signed.payload)), key, Buffer.from(signed.signature, 'base64url'))) throw Error('PACKAGE_UNTRUSTED_SIGNATURE');
|
|
45
45
|
const m = signed.payload;
|
|
46
46
|
if (!exact(m, ['format', 'kind', 'version', 'files']) || m.format !== 'worktrust-package/1' || m.kind !== kind || !/^\d+\.\d+\.\d+$/.test(m.version)
|
|
47
|
-
|| !m.files || Array.isArray(m.files) || typeof m.files !== 'object' || Object.keys(m.files).length > 2000 || !Object.hasOwn(m.files, 'worktrust.mjs')) throw Error('PACKAGE_INVALID_MANIFEST');
|
|
47
|
+
|| !m.files || Array.isArray(m.files) || typeof m.files !== 'object' || Object.keys(m.files).length > 2000 || !Object.hasOwn(m.files, kind === 'python' ? 'bundle/worktrust.mjs' : 'worktrust.mjs')) throw Error('PACKAGE_INVALID_MANIFEST');
|
|
48
48
|
const expected = Object.keys(m.files).sort();
|
|
49
49
|
for (const name of expected) {
|
|
50
50
|
if (!safe(name) || name === signatureName || !/^[a-f0-9]{64}$/.test(m.files[name])) throw Error('PACKAGE_INVALID_MANIFEST');
|
|
@@ -53,9 +53,9 @@ export function verifyPackage(root, kind = 'npm') {
|
|
|
53
53
|
const file = join(root, name);
|
|
54
54
|
if (regular(file).size > 128 * 1024 * 1024 || hash(readFileSync(file)) !== m.files[name]) throw Error('PACKAGE_FILE_CHANGED');
|
|
55
55
|
}
|
|
56
|
-
const found = filesIn(root).filter(name => name !== signatureName && (kind !== 'engine' || name.endsWith('.mjs'))).sort();
|
|
56
|
+
const found = filesIn(root).filter(name => (kind !== 'python' || !name.split('/').includes('__pycache__')) && name !== signatureName && (kind !== 'engine' || name.endsWith('.mjs'))).sort();
|
|
57
57
|
if (JSON.stringify(found) !== JSON.stringify(expected)) throw Error('PACKAGE_FILE_LIST_CHANGED');
|
|
58
|
-
if (/const CLI_VERSION = "([^"]+)";/.exec(readFileSync(join(root, 'worktrust.mjs'), 'utf8'))?.[1] !== m.version) throw Error('PACKAGE_VERSION_MISMATCH');
|
|
58
|
+
if (/const CLI_VERSION = "([^"]+)";/.exec(readFileSync(join(root, kind === 'python' ? 'bundle/worktrust.mjs' : 'worktrust.mjs'), 'utf8'))?.[1] !== m.version) throw Error('PACKAGE_VERSION_MISMATCH');
|
|
59
59
|
return { manifest: m, identity: hash(readFileSync(path)), signatureName };
|
|
60
60
|
}
|
|
61
61
|
export function installSignedPackage(source, home) {
|
|
@@ -80,3 +80,80 @@ export function installSignedPackage(source, home) {
|
|
|
80
80
|
} finally { rmSync(pending, { recursive: true, force: true }); }
|
|
81
81
|
return join(target, 'worktrust-launch.mjs');
|
|
82
82
|
}
|
|
83
|
+
|
|
84
|
+
/** Child processes of the official launcher re-enter verification, including long-lived MCP bridges.
|
|
85
|
+
* Raw source test harnesses retain direct entry; they are not authenticated release launches.
|
|
86
|
+
*/
|
|
87
|
+
function persistentPython(root) {
|
|
88
|
+
return globalThis[Symbol.for("worktrust.verifiedReleaseRoot")] === root
|
|
89
|
+
&& basename(root) === "engine" && /^[a-f0-9]{64}$/.test(basename(dirname(root)))
|
|
90
|
+
&& basename(dirname(dirname(root))) === "installations"
|
|
91
|
+
&& typeof process.env.WORKTRUST_BUNDLED_PYTHON === "string" && isAbsolute(process.env.WORKTRUST_BUNDLED_PYTHON)
|
|
92
|
+
&& process.env.WORKTRUST_INSTALLED_LAUNCHER === join(dirname(root), "worktrust-launch.py")
|
|
93
|
+
&& process.env.WORKTRUST_BUNDLED_PYTHON;
|
|
94
|
+
}
|
|
95
|
+
export function moduleExecutable(root) { return persistentPython(root) || process.execPath; }
|
|
96
|
+
export function moduleArgs(root, name, args = []) {
|
|
97
|
+
if (!["worktrust.mjs", "setup-mcp.mjs", "log-session.mjs", "count-behaviour.mjs", "preserve.mjs"].includes(name)) throw Error("PACKAGE_INVALID_ENTRY");
|
|
98
|
+
if (persistentPython(root)) return ["-I", process.env.WORKTRUST_INSTALLED_LAUNCHER, "--internal-module", name, ...args];
|
|
99
|
+
const flags = process.versions.node === "26.5.0" ? ["--no-concurrent-sparkplug"] : [];
|
|
100
|
+
return globalThis[Symbol.for("worktrust.verifiedReleaseRoot")] === root
|
|
101
|
+
? [...flags, join(root, "worktrust-launch.mjs"), "--internal-module", name, ...args]
|
|
102
|
+
: [...flags, join(root, name), ...args];
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Credentials stay outside the immutable release. File hygiene reduces cross-user theft;
|
|
106
|
+
// it does not attest the machine owner or the truth of data they choose to sign.
|
|
107
|
+
function privateDirectory(path, create) {
|
|
108
|
+
if (create) mkdirSync(path, { recursive: true, mode: 0o700 });
|
|
109
|
+
const before = lstatSync(path);
|
|
110
|
+
if (!before.isDirectory() || before.isSymbolicLink() || (process.getuid && before.uid !== process.getuid())) throw Error('KEY_FILE_UNSAFE');
|
|
111
|
+
// Windows ACLs remain the responsibility of the user's private profile directory.
|
|
112
|
+
if (process.platform !== 'win32') {
|
|
113
|
+
const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
114
|
+
try { const current = fstatSync(fd); if (current.ino !== before.ino || current.dev !== before.dev) throw Error('KEY_FILE_UNSAFE'); fchmodSync(fd, 0o700); }
|
|
115
|
+
finally { closeSync(fd); }
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
function privateStat(stat) {
|
|
119
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > 65536 || (process.getuid && stat.uid !== process.getuid())) throw Error('KEY_FILE_UNSAFE');
|
|
120
|
+
}
|
|
121
|
+
/** Bounded descriptor read; never follow a linked credential, pipe, device or directory. */
|
|
122
|
+
export function readPrivateFile(file) {
|
|
123
|
+
let fd;
|
|
124
|
+
try {
|
|
125
|
+
privateDirectory(dirname(file), false);
|
|
126
|
+
const before = lstatSync(file); privateStat(before);
|
|
127
|
+
fd = openSync(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
|
|
128
|
+
const current = fstatSync(fd); privateStat(current);
|
|
129
|
+
if (current.ino !== before.ino || current.dev !== before.dev) throw Error('KEY_FILE_UNSAFE');
|
|
130
|
+
if (process.platform !== 'win32') fchmodSync(fd, 0o600);
|
|
131
|
+
const bytes = Buffer.alloc(65537); let size = 0, next;
|
|
132
|
+
while (size < bytes.length && (next = readSync(fd, bytes, size, bytes.length - size, null)) > 0) size += next;
|
|
133
|
+
if (size > 65536) throw Error('KEY_FILE_UNSAFE');
|
|
134
|
+
return bytes.subarray(0, size).toString('utf8');
|
|
135
|
+
} catch (error) {
|
|
136
|
+
if (error.code === 'ENOENT') return null;
|
|
137
|
+
throw Error('KEY_FILE_UNSAFE');
|
|
138
|
+
} finally { if (fd !== undefined) closeSync(fd); }
|
|
139
|
+
}
|
|
140
|
+
/** Exclusive random temp, flush, atomic replace. Existing credentials survive a failed write. */
|
|
141
|
+
export function writePrivateFile(file, bytes) {
|
|
142
|
+
if (Buffer.byteLength(bytes) > 65536) throw Error('KEY_FILE_UNSAFE');
|
|
143
|
+
privateDirectory(dirname(file), true);
|
|
144
|
+
try { privateStat(lstatSync(file)); } catch (error) { if (error.code !== 'ENOENT') throw Error('KEY_FILE_UNSAFE'); }
|
|
145
|
+
const temporary = file + '.' + randomBytes(16).toString('hex') + '.tmp'; let fd;
|
|
146
|
+
try {
|
|
147
|
+
fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600);
|
|
148
|
+
writeFileSync(fd, bytes); fsyncSync(fd); closeSync(fd); fd = undefined;
|
|
149
|
+
renameSync(temporary, file);
|
|
150
|
+
} finally { if (fd !== undefined) closeSync(fd); rmSync(temporary, { force: true }); }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** First creation only, used by offline archive secrets; never overwrite an existing key. */
|
|
154
|
+
export function createPrivateFile(file, bytes) {
|
|
155
|
+
if (Buffer.byteLength(bytes) > 65536) throw Error('KEY_FILE_UNSAFE');
|
|
156
|
+
privateDirectory(dirname(file), true);
|
|
157
|
+
const fd = openSync(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600);
|
|
158
|
+
try { writeFileSync(fd, bytes); fsyncSync(fd); } finally { closeSync(fd); }
|
|
159
|
+
}
|
package/package-release.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"AGENTS.md":"d1db152d88338df23b5900beed6a69bedc2900b6f53fef3f036b46dd7a07b841","CLAUDE.md":"5933504f93e5a40369a4790e96dd5dad791d849d3178b1833eb64088e456aaeb","LICENSE":"3096ed1693974a90e1f4f59bf01c9559d94a7941d933e36fb81d3995a97f25c1","README.md":"
|
|
1
|
+
{"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"AGENTS.md":"d1db152d88338df23b5900beed6a69bedc2900b6f53fef3f036b46dd7a07b841","CLAUDE.md":"5933504f93e5a40369a4790e96dd5dad791d849d3178b1833eb64088e456aaeb","LICENSE":"3096ed1693974a90e1f4f59bf01c9559d94a7941d933e36fb81d3995a97f25c1","README.md":"0677478b03ee480c869121f3243cb510b45990d18849df64643982d621913088","SECURITY.md":"02c049a69fb6104813c1ff223b312e1e91ec70cfe776f1c2853f7952e818c09b","chat-exports.mjs":"04eafe333940ec03d5058d8d51062124aa12ab882bf04db03bcda5613ec69298","claude-mod.mjs":"02d86b0cdddf39879efc5194c0a5be6b41456faedec28963dc123a4e88dc3942","config-edits.mjs":"0eba2f176ef6f7afba071d6e00de0ff19ba2b283180a801dfd957aa38c1edd94","count-behaviour.mjs":"1beaec2a4d0aead76d166f89cc52441a9cf48f2e69da9888ca2091dd3a10a37b","engine-release.json":"514abde48bf6206e489387f3819d92c3d3de2c6a1f9f71a1b171013683ec3677","history-outbox.mjs":"1bdca17b807c76e4a8e7bf42c6f07e12e8ae8e4466417cafdd26b1f58bf178a5","log-session.mjs":"c5e6e4d44a85768f21c25945b8630f31306ec2665193886870c1010ef6bf3c26","orchestration-contract.mjs":"ec08f303a166365b99e70b675de4cfe76c6156c2567e14b5569f6d992f0231b7","orchestration-evidence.mjs":"d0d06cecf0eb08e5c6e653c62a4f45b1eddf2119c2acb8341056b34f488d214a","orchestration-report.mjs":"d4e0a9ad8e4a01b462d22c6b1866aac291565c533ff476085d3367cb6d59bc1b","package-integrity.mjs":"a8210c9494a56bfb9a5ea3d10064c7a269f0b6330c0af7c0700e706c3c0224e3","package.json":"6d47c91ff4672cd6f5f7ed72971dd11e2951f73b25b6f83b157255f69193733b","preserve-lines.mjs":"2df64a69687aa51219bf7b86b88d175cc50990fa29574b31897e41a9ebeecf43","preserve-summary.mjs":"137f781ed7021596a3f0ea67afcf2ab8616ac293f833dbb8f176e838e0ed8321","preserve.mjs":"9add279352750be94d94873738145e379819d793c20c6c6503219969608e2c2f","runtime-install.mjs":"aab47b52c79d726ef428a24f982c648fa3f1c2dc2b574f633611d02924864e5f","session-databases.mjs":"543fd3b82d28d96d789be0a1dc9186c5fafa783e98b87e5b3b17b211542e2b4d","setup-mcp.mjs":"6ecfbf44f001dd433512b26736031ebc855b154e2bb0a401e2512b43623cd9cd","stack-rules.mjs":"b23c56e72ec56ba02b17ed895f869172d988c468a697e8d6026b0e268f61e489","stretch-evidence.mjs":"5b31a6f29b785d277e92257532f3c7cee366a79759decc7a75cfbaec2686ee13","transcript-readers.mjs":"413948644a74dc0bf1b49548be193bf596bcf82ac7eae668f624345a18e189e7","worktrust-launch.mjs":"84801bd29d472d48188c126b9ebe3989a3132b54e13cc4fe534ff7c383a294ee","worktrust.mjs":"bd208923c08a16ed640f25417ae381d0c3e3dda02e56aad4aee66497cdd494b9"},"format":"worktrust-package/1","kind":"npm","version":"0.10.25"},"signature":"CS95agn012vWfW2TtV68C9Fe30xdxSmmaeWNJfi3k6STlWASh9caZvuYvMrh5m53vImITnKY9oVbt9Re8jqAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "worktrust",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.25",
|
|
4
4
|
"description": "Couple this computer to WorkTrust: approve a code in your browser, and every AI app here reports what you built. Metadata only, no dependencies.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
package/preserve-lines.mjs
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
* and the behaviour signals joined on `stretch_ref`. A key not named here never reaches the archive. The capability
|
|
4
4
|
* tranches (docs/CAPABILITY-EVIDENCE-ROADMAP.md) add their fields here, each with its own check.
|
|
5
5
|
*/
|
|
6
|
+
import { moduleArgs, moduleExecutable } from "./package-integrity.mjs";
|
|
6
7
|
import { spawnSync } from "node:child_process";
|
|
7
8
|
import { createHash, createHmac } from "node:crypto";
|
|
8
9
|
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
|
@@ -25,7 +26,7 @@ const WORD = /^[a-z][A-Za-z]{1,31}$/;
|
|
|
25
26
|
export function stretchSignals(here, say) {
|
|
26
27
|
const counter = join(here, "count-behaviour.mjs");
|
|
27
28
|
if (!existsSync(counter)) return null;
|
|
28
|
-
const run = spawnSync(
|
|
29
|
+
const run = spawnSync(moduleExecutable(here), moduleArgs(here, "count-behaviour.mjs", ["--stretch-signals", "--months", "120"]), { encoding: "utf8", maxBuffer: 1 << 29, env: { ...process.env, WORKTRUST_MCP_URL: "", WORKTRUST_MCP_TOKEN: "" } });
|
|
29
30
|
const rows = (run.stdout ?? "").split("\n").filter((text) => text.startsWith("{")).map((text) => { try { return JSON.parse(text); } catch { return null; } });
|
|
30
31
|
const end = rows.at(-1)?.stretch_signals_end;
|
|
31
32
|
if (run.status !== 0 || !Number.isInteger(end) || end !== rows.length - 1) { say(" The behaviour counter did not answer whole, so these lines carry no signals; the next run adds them to new lines."); return null; }
|
package/preserve.mjs
CHANGED
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
* (`prev`, `hash`), appended and never rewritten; each day has proofs/<day>.json, its root, signed with the device key
|
|
24
24
|
* (~/.worktrust/key.json) when there is one. Today waits for the next run. Nothing leaves this computer.
|
|
25
25
|
*/
|
|
26
|
+
import { moduleArgs, moduleExecutable, readPrivateFile, createPrivateFile } from "./package-integrity.mjs";
|
|
26
27
|
import { execFileSync, spawnSync } from "node:child_process";
|
|
27
28
|
import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes, sign, verify } from "node:crypto";
|
|
28
29
|
import { appendFileSync, chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
|
|
@@ -185,13 +186,13 @@ function computerIds() {
|
|
|
185
186
|
/** This computer's own secret for the archive's project hashes (0.8.6): made once, readable by its owner alone, never archived. */
|
|
186
187
|
function archiveSalt() {
|
|
187
188
|
const file = home(".worktrust", "archive-salt");
|
|
188
|
-
try { const kept =
|
|
189
|
-
try {
|
|
189
|
+
try { const kept = readPrivateFile(file)?.trim(); if (/^[0-9a-f]{64}$/.test(kept)) return kept; } catch { /* first run */ }
|
|
190
|
+
try { const made = randomBytes(32).toString("hex"); createPrivateFile(file, `${made}\n`); return made; } catch { try { return readPrivateFile(file)?.trim() ?? null; } catch { return null; } }
|
|
190
191
|
}
|
|
191
192
|
/** The device key, when this computer is coupled: its private half signs, its public half goes into the proof. */
|
|
192
193
|
function deviceKey() {
|
|
193
194
|
try {
|
|
194
|
-
const key = JSON.parse(Buffer.from(
|
|
195
|
+
const key = JSON.parse(Buffer.from(readPrivateFile(home(".worktrust", "key.json")), "base64").toString("utf8"));
|
|
195
196
|
const privateKey = createPrivateKey(key.device);
|
|
196
197
|
return { privateKey, publicX: createPublicKey(privateKey).export({ format: "jwk" }).x, kind: "device" };
|
|
197
198
|
} catch { return null; }
|
|
@@ -207,7 +208,7 @@ function deviceKey() {
|
|
|
207
208
|
const ARCHIVE_KEY_FILE = home(".worktrust", "archive-key.json");
|
|
208
209
|
function archiveKey(create = false) {
|
|
209
210
|
try {
|
|
210
|
-
const kept = JSON.parse(
|
|
211
|
+
const kept = JSON.parse(readPrivateFile(ARCHIVE_KEY_FILE));
|
|
211
212
|
const privateKey = createPrivateKey(kept.private);
|
|
212
213
|
return { privateKey, publicX: createPublicKey(privateKey).export({ format: "jwk" }).x, kind: "archive", made: false };
|
|
213
214
|
} catch { /* none yet, or unreadable */ }
|
|
@@ -215,10 +216,7 @@ function archiveKey(create = false) {
|
|
|
215
216
|
try {
|
|
216
217
|
const pair = generateKeyPairSync("ed25519");
|
|
217
218
|
const privatePem = pair.privateKey.export({ format: "pem", type: "pkcs8" }), publicX = pair.publicKey.export({ format: "jwk" }).x;
|
|
218
|
-
|
|
219
|
-
try { chmodSync(home(".worktrust"), 0o700); } catch { /* Windows */ }
|
|
220
|
-
writeFileSync(ARCHIVE_KEY_FILE, `${JSON.stringify({ format: "worktrust-archive-key/1", public: publicX, private: privatePem, created: new Date().toISOString() }, null, 1)}\n`, { mode: 0o600, flag: "wx" });
|
|
221
|
-
try { chmodSync(ARCHIVE_KEY_FILE, 0o600); } catch { /* Windows */ }
|
|
219
|
+
createPrivateFile(ARCHIVE_KEY_FILE, `${JSON.stringify({ format: "worktrust-archive-key/1", public: publicX, private: privatePem, created: new Date().toISOString() }, null, 1)}\n`);
|
|
222
220
|
return { privateKey: pair.privateKey, publicX, kind: "archive", made: true };
|
|
223
221
|
} catch { return archiveKey(false); }
|
|
224
222
|
}
|
|
@@ -289,7 +287,7 @@ function archive(dir) {
|
|
|
289
287
|
IDS = computerIds();
|
|
290
288
|
const existing = existsSync(join(dir, "manifest.json")) || readArchive(dir).length > 0 ? check(dir) : { lines: [], manifest: null };
|
|
291
289
|
if (existing.broken) { say(` The archive in ${dir} does not verify, so nothing was added: ${existing.broken}`); process.exit(1); }
|
|
292
|
-
const hook = spawnSync(
|
|
290
|
+
const hook = spawnSync(moduleExecutable(HERE), moduleArgs(HERE, "log-session.mjs", ["--archive-lines"]), { encoding: "utf8", maxBuffer: 1 << 29, env: { ...process.env, WORKTRUST_MCP_URL: "", WORKTRUST_MCP_TOKEN: "", WORKTRUST_HOOK_INPUT: "" } });
|
|
293
291
|
if (hook.status !== 0) { say(` The session hook could not read this computer's sessions: ${(hook.stderr || "").trim().split("\n").pop()}`); process.exit(1); }
|
|
294
292
|
// A WHOLE ANSWER OR NOTHING: the hook ends with its own count; one line missing or cut is a read to refuse, never part of an archive.
|
|
295
293
|
const rows = hook.stdout.split("\n").filter(Boolean), end = (() => { try { return JSON.parse(rows.at(-1) ?? "").archive_end; } catch { return undefined; } })();
|
package/runtime-install.mjs
CHANGED
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
* Called only after the person's connect/update confirmation. No network, credentials or measurement logic.
|
|
3
3
|
*/
|
|
4
4
|
import { createHash, randomBytes } from "node:crypto";
|
|
5
|
-
import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
6
|
-
import { join } from "node:path";
|
|
5
|
+
import { existsSync, realpathSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { join, dirname, resolve, isAbsolute } from "node:path";
|
|
7
|
+
import { verifyPackage } from "./package-integrity.mjs";
|
|
7
8
|
|
|
8
9
|
const hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
|
9
10
|
const regular = (path) => { const stat = lstatSync(path); if (!stat.isFile() || stat.isSymbolicLink()) throw Error("bundled installation requires regular files"); };
|
|
@@ -12,6 +13,13 @@ const checkedBytes = (path) => { regular(path); return readFileSync(path); };
|
|
|
12
13
|
|
|
13
14
|
export function installRuntime(runtime, engine, home, moduleNames) {
|
|
14
15
|
directory(runtime); directory(engine); directory(home);
|
|
16
|
+
const python = process.env.WORKTRUST_BUNDLED_PYTHON;
|
|
17
|
+
if (!python || !isAbsolute(python) || !existsSync(python)) throw Error("trusted Python interpreter required");
|
|
18
|
+
// The Python entry authenticates this package before Node starts; check again before persisting it.
|
|
19
|
+
const packageRoot = dirname(realpathSync(engine));
|
|
20
|
+
if (realpathSync(runtime) !== join(resolve(packageRoot), "runtime") || realpathSync(engine) !== join(resolve(packageRoot), "bundle")) throw Error("bundled distribution layout mismatch");
|
|
21
|
+
verifyPackage(packageRoot, "python");
|
|
22
|
+
verifyPackage(engine, "engine");
|
|
15
23
|
const descriptor = checkedBytes(join(runtime, "runtime.json"));
|
|
16
24
|
const manifest = JSON.parse(descriptor);
|
|
17
25
|
const executable = process.platform === "win32" ? "node.exe" : "node";
|
|
@@ -32,19 +40,53 @@ export function installRuntime(runtime, engine, home, moduleNames) {
|
|
|
32
40
|
}
|
|
33
41
|
if (existsSync(join(engine, "engine-release.json"))) contents.set("engine/engine-release.json", checkedBytes(join(engine, "engine-release.json")));
|
|
34
42
|
const identities = Object.fromEntries([...contents].map(([name, bytes]) => [name, hash(bytes)]));
|
|
35
|
-
const identity = Buffer.from(JSON.stringify(identities));
|
|
36
|
-
|
|
43
|
+
const identity = Buffer.from(JSON.stringify({ format: "worktrust-installation/2", files: identities }));
|
|
44
|
+
// The external, package-manager Python starts BEFORE the copied Node executable. This bootstrap
|
|
45
|
+
// pins the hashes authenticated above; it never trusts a locally rewritten descriptor to bless code.
|
|
46
|
+
const bootstrap = Buffer.from(`import hashlib, json, os, pathlib, subprocess, sys
|
|
47
|
+
EXPECTED = json.loads(${JSON.stringify(JSON.stringify(identities))})
|
|
48
|
+
IDENTITY = ${JSON.stringify(identity.toString())}
|
|
49
|
+
root = pathlib.Path(__file__).absolute().parent.resolve()
|
|
50
|
+
try:
|
|
51
|
+
if not sys.flags.isolated or root.is_symlink(): raise ValueError("PACKAGE_BOOTSTRAP_REQUIRED")
|
|
52
|
+
if set(p.name for p in root.iterdir()) != {"engine", "runtime", "installation.json", "worktrust-launch.py"}: raise ValueError("PACKAGE_FILE_LIST_CHANGED")
|
|
53
|
+
for group in ("engine", "runtime"):
|
|
54
|
+
folder = root / group
|
|
55
|
+
if folder.is_symlink() or not folder.is_dir(): raise ValueError("PACKAGE_NON_REGULAR_DIRECTORY")
|
|
56
|
+
if set(p.name for p in folder.iterdir()) != {name.split("/", 1)[1] for name in EXPECTED if name.startswith(group + "/")}: raise ValueError("PACKAGE_FILE_LIST_CHANGED")
|
|
57
|
+
marker = root / "installation.json"
|
|
58
|
+
if marker.is_symlink() or marker.read_text() != IDENTITY: raise ValueError("PACKAGE_INSTALLATION_IDENTITY_MISMATCH")
|
|
59
|
+
for name, digest in EXPECTED.items():
|
|
60
|
+
file = root / name
|
|
61
|
+
if file.is_symlink() or not file.is_file() or file.stat().st_size > 128 * 1024 * 1024 or hashlib.sha256(file.read_bytes()).hexdigest() != digest: raise ValueError("PACKAGE_FILE_CHANGED")
|
|
62
|
+
except (OSError, ValueError):
|
|
63
|
+
print("worktrust: PACKAGE_VERIFICATION_FAILED. Execution stopped; reinstall an official WorkTrust release.", file=sys.stderr)
|
|
64
|
+
sys.exit(1)
|
|
65
|
+
node = root / "runtime" / ${JSON.stringify(executable)}
|
|
66
|
+
entry = root / "engine" / "worktrust-launch.mjs"
|
|
67
|
+
env = dict(os.environ)
|
|
68
|
+
env["WORKTRUST_BUNDLED_PYTHON"] = sys.executable
|
|
69
|
+
env["WORKTRUST_INSTALLED_LAUNCHER"] = str(root / "worktrust-launch.py")
|
|
70
|
+
for key in ("NODE_OPTIONS", "NODE_PATH", "WORKTRUST_BUNDLED_RUNTIME_DIR"):
|
|
71
|
+
env.pop(key, None)
|
|
72
|
+
argv = [str(node), str(entry), *sys.argv[1:]]
|
|
73
|
+
if os.name != "nt": os.execve(node, argv, env)
|
|
74
|
+
sys.exit(subprocess.call(argv, env=env))
|
|
75
|
+
`);
|
|
76
|
+
contents.set("worktrust-launch.py", bootstrap);
|
|
77
|
+
const installations = join(home, "installations"), installed = join(installations, hash(Buffer.concat([identity, bootstrap])));
|
|
37
78
|
if (!existsSync(installations)) mkdirSync(installations, { mode: 0o700 });
|
|
38
79
|
directory(installations);
|
|
39
80
|
const verify = (place) => {
|
|
40
81
|
directory(place);
|
|
41
|
-
if (JSON.stringify(readdirSync(place).sort()) !== JSON.stringify(["engine", "installation.json", "runtime"])) throw Error("installed bundle file list mismatch");
|
|
82
|
+
if (JSON.stringify(readdirSync(place).sort()) !== JSON.stringify(["engine", "installation.json", "runtime", "worktrust-launch.py"])) throw Error("installed bundle file list mismatch");
|
|
42
83
|
if (!checkedBytes(join(place, "installation.json")).equals(identity)) throw Error("installed bundle identity mismatch");
|
|
43
84
|
for (const group of ["engine", "runtime"]) {
|
|
44
85
|
directory(join(place, group));
|
|
45
86
|
const expected = [...contents.keys()].filter(name => name.startsWith(`${group}/`)).map(name => name.slice(group.length + 1)).sort();
|
|
46
87
|
if (JSON.stringify(readdirSync(join(place, group)).sort()) !== JSON.stringify(expected)) throw Error("installed bundle file list mismatch");
|
|
47
88
|
}
|
|
89
|
+
if (!checkedBytes(join(place, "worktrust-launch.py")).equals(bootstrap)) throw Error("installed bootstrap integrity check failed");
|
|
48
90
|
for (const [name, digest] of Object.entries(identities)) if (hash(checkedBytes(join(place, name))) !== digest) throw Error("installed bundle integrity check failed");
|
|
49
91
|
};
|
|
50
92
|
if (existsSync(installed)) verify(installed);
|
|
@@ -61,5 +103,5 @@ export function installRuntime(runtime, engine, home, moduleNames) {
|
|
|
61
103
|
} finally { rmSync(temporary, { recursive: true, force: true }); }
|
|
62
104
|
}
|
|
63
105
|
// Existing immutable directories are never replaced, including executables used by Windows processes.
|
|
64
|
-
return { executable:
|
|
106
|
+
return { executable: python, args: ["-I"], bridge: join(installed, "worktrust-launch.py") };
|
|
65
107
|
}
|
package/setup-mcp.mjs
CHANGED
|
@@ -33,6 +33,8 @@ const NAME = value("name") ?? "worktrust";
|
|
|
33
33
|
*/
|
|
34
34
|
const BRIDGE = value("bridge");
|
|
35
35
|
const NODE = process.env.WORKTRUST_NODE || process.execPath;
|
|
36
|
+
const NODE_ARGS = process.env.WORKTRUST_NODE_ARGS === '["-I"]' ? ["-I"] : [];
|
|
37
|
+
const NODE_COMMAND = `"${NODE}"${NODE_ARGS.length ? " -I" : ""}`;
|
|
36
38
|
|
|
37
39
|
/** The coupling: given, or the one Claude Code already holds (the counter reads it the same way). */
|
|
38
40
|
function fromClaude() {
|
|
@@ -65,7 +67,7 @@ const URL_ = value("url") ?? process.env.WORKTRUST_MCP_URL ?? discovered?.url;
|
|
|
65
67
|
const TOKEN = value("token") ?? process.env.WORKTRUST_MCP_TOKEN ?? discovered?.token;
|
|
66
68
|
if (!URL_ || (!TOKEN && !BRIDGE)) { console.error("no coupling: pass --url and --token (from Sources → Claude (MCP) → Add coupling), or couple Claude Code first"); process.exit(1); }
|
|
67
69
|
const masked = BRIDGE ? "kept in ~/.worktrust/key.json, not in these files" : `${TOKEN.slice(0, 6)}…${TOKEN.slice(-4)}`;
|
|
68
|
-
const stdio = { command: NODE, args: [BRIDGE ?? "", "mcp"] };
|
|
70
|
+
const stdio = { command: NODE, args: [...NODE_ARGS, BRIDGE ?? "", "mcp"] };
|
|
69
71
|
const home = homedir();
|
|
70
72
|
/** Whether Claude Code's own command is on this machine: asked of the shell, never guessed from a file. */
|
|
71
73
|
/**
|
|
@@ -98,8 +100,8 @@ const hermesHomes = () => {
|
|
|
98
100
|
try { for (const name of readdirSync(join(HERMES_BASE, "profiles")).sort()) homes.add(join(HERMES_BASE, "profiles", name)); } catch { /* no profiles */ }
|
|
99
101
|
return [...homes].filter((dir) => existsSync(dir));
|
|
100
102
|
};
|
|
101
|
-
const HERMES_HOOK =
|
|
102
|
-
const ours = (text) => text.includes(URL_) || /worktrust
|
|
103
|
+
const HERMES_HOOK = `${NODE_COMMAND} "${BRIDGE ?? ""}" hook --hermes`;
|
|
104
|
+
const ours = (text) => text.includes(URL_) || /worktrust(?:-launch)?\.(?:mjs|py)/.test(text);
|
|
103
105
|
/** A YAML client's file with our entry (and hook) taken out and, unless removing, put back in; null when it cannot be. */
|
|
104
106
|
function yamlConfig(client, text, remove) {
|
|
105
107
|
const lines = text.trim() === "" ? [] : text.replace(/\n$/, "").split("\n");
|
|
@@ -112,7 +114,7 @@ function yamlConfig(client, text, remove) {
|
|
|
112
114
|
return lines.length ? `${lines.join("\n")}\n` : "";
|
|
113
115
|
}
|
|
114
116
|
const bridgeOrUrl = (local, remote) => (BRIDGE ? local : remote);
|
|
115
|
-
const HERMES_SERVER = bridgeOrUrl([`${NAME}:`, ` command: ${JSON.stringify(NODE)}`, ` args: [${JSON.stringify(
|
|
117
|
+
const HERMES_SERVER = bridgeOrUrl([`${NAME}:`, ` command: ${JSON.stringify(NODE)}`, ` args: [${[...NODE_ARGS, BRIDGE, "mcp"].map(arg => JSON.stringify(arg)).join(", ")}]`], [`${NAME}:`, ` url: ${JSON.stringify(URL_)}`, " headers:", ` Authorization: ${JSON.stringify(`Bearer ${TOKEN}`)}`]);
|
|
116
118
|
/**
|
|
117
119
|
* GOOSE (2026-10-05, aaif-goose/goose: crates/goose/src/config/extensions.rs, agents/extension.rs; documentation
|
|
118
120
|
* guides/config-files.md): `extensions` in config.yaml (~/.config/goose, %APPDATA%\\Block\\goose\\config on Windows,
|
|
@@ -121,12 +123,12 @@ const HERMES_SERVER = bridgeOrUrl([`${NAME}:`, ` command: ${JSON.stringify(NODE
|
|
|
121
123
|
* guides/context-engineering/hooks.md); with the bridge one plugin named worktrust runs the session hook on SessionEnd.
|
|
122
124
|
*/
|
|
123
125
|
const GOOSE_SERVER = bridgeOrUrl(
|
|
124
|
-
[`${NAME}:`, " type: stdio", ` name: ${NAME}`, " enabled: true", ` cmd: ${JSON.stringify(NODE)}`, ` args: [${JSON.stringify(
|
|
126
|
+
[`${NAME}:`, " type: stdio", ` name: ${NAME}`, " enabled: true", ` cmd: ${JSON.stringify(NODE)}`, ` args: [${[...NODE_ARGS, BRIDGE, "mcp"].map(arg => JSON.stringify(arg)).join(", ")}]`, " envs: {}", " timeout: 300"],
|
|
125
127
|
[`${NAME}:`, " type: streamable_http", ` name: ${NAME}`, " enabled: true", ` uri: ${JSON.stringify(URL_)}`, " headers:", ` Authorization: ${JSON.stringify(`Bearer ${TOKEN}`)}`, " envs: {}", " timeout: 300"],
|
|
126
128
|
);
|
|
127
129
|
const gooseDirs = () => [...new Set([...(process.env.GOOSE_PATH_ROOT ? [join(process.env.GOOSE_PATH_ROOT, "config")] : []), join(home, ".config", "goose"), ...(platform() === "win32" && process.env.APPDATA ? [join(process.env.APPDATA, "Block", "goose", "config")] : [])])].filter((dir) => existsSync(dir));
|
|
128
130
|
const GOOSE_PLUGIN = join(process.env.GOOSE_PATH_ROOT || home, ".agents", "plugins", NAME);
|
|
129
|
-
const GOOSE_HOOKS = { hooks: { SessionEnd: [{ hooks: [{ type: "command", command:
|
|
131
|
+
const GOOSE_HOOKS = { hooks: { SessionEnd: [{ hooks: [{ type: "command", command: `${NODE_COMMAND} "${BRIDGE ?? ""}" hook --goose`, timeout: 30 }] }] } };
|
|
130
132
|
const goosePluginStands = () => { try { return JSON.stringify(JSON.parse(readFileSync(join(GOOSE_PLUGIN, "hooks", "hooks.json"), "utf8"))) === JSON.stringify(GOOSE_HOOKS); } catch { return false; } };
|
|
131
133
|
/** Our plugin folder in, or out; another plugin is never touched, and a folder of that name that is not ours stays. */
|
|
132
134
|
function goosePlugin(remove) {
|
|
@@ -157,7 +159,7 @@ export const WorkTrust = async () => ({
|
|
|
157
159
|
event: async ({ event }) => {
|
|
158
160
|
if (event?.type !== "session.idle" || Date.now() - last < 30_000) return;
|
|
159
161
|
last = Date.now();
|
|
160
|
-
try { spawn(${JSON.stringify(NODE)},
|
|
162
|
+
try { spawn(${JSON.stringify(NODE)}, ${JSON.stringify([...NODE_ARGS, BRIDGE ?? "", "hook"])}, { detached: true, stdio: "ignore" }).unref(); } catch { /* the next run sweeps it */ }
|
|
161
163
|
},
|
|
162
164
|
});
|
|
163
165
|
`;
|
|
@@ -179,25 +181,25 @@ const opencodePluginStands = () => { try { return readFileSync(OPENCODE_PLUGIN,
|
|
|
179
181
|
* sessions are read whenever another client's hook runs.
|
|
180
182
|
*/
|
|
181
183
|
const OPENCLAW_FILE = process.env.OPENCLAW_CONFIG_PATH || join(process.env.OPENCLAW_STATE_DIR || join(home, ".openclaw"), "openclaw.json");
|
|
182
|
-
const OPENCLAW_ENTRY = BRIDGE ? { command: NODE, args: [BRIDGE, "mcp"] } : { url: URL_, transport: "streamable-http", headers: { Authorization: `Bearer ${TOKEN}` } };
|
|
184
|
+
const OPENCLAW_ENTRY = BRIDGE ? { command: NODE, args: [...NODE_ARGS, BRIDGE, "mcp"] } : { url: URL_, transport: "streamable-http", headers: { Authorization: `Bearer ${TOKEN}` } };
|
|
183
185
|
|
|
184
186
|
/** Each client: where it lives, how it says "an HTTP MCP server with a header". */
|
|
185
187
|
const CLIENTS = [
|
|
186
188
|
{ key: "cursor", label: "Cursor", present: () => existsSync(join(home, ".cursor")), file: join(home, ".cursor", "mcp.json"), shape: "json", root: "mcpServers", entry: BRIDGE ? stdio : { url: URL_, headers: { Authorization: `Bearer ${TOKEN}` } } },
|
|
187
|
-
{ key: "codex", label: "Codex CLI", present: () => existsSync(join(home, ".codex")), file: join(home, ".codex", "config.toml"), shape: "toml", block: BRIDGE ? `\n[mcp_servers.${NAME}]\ncommand = ${JSON.stringify(NODE)}\nargs = [${JSON.stringify(
|
|
189
|
+
{ key: "codex", label: "Codex CLI", present: () => existsSync(join(home, ".codex")), file: join(home, ".codex", "config.toml"), shape: "toml", block: BRIDGE ? `\n[mcp_servers.${NAME}]\ncommand = ${JSON.stringify(NODE)}\nargs = [${[...NODE_ARGS, BRIDGE, "mcp"].map(arg => JSON.stringify(arg)).join(", ")}]\n` : `\n[mcp_servers.${NAME}]\nurl = "${URL_}"\nhttp_headers = { Authorization = "Bearer ${TOKEN}" }\n` },
|
|
188
190
|
{ key: "gemini", label: "Gemini CLI", present: () => existsSync(join(home, ".gemini")), file: join(home, ".gemini", "settings.json"), shape: "json", root: "mcpServers", entry: BRIDGE ? stdio : { httpUrl: URL_, headers: { Authorization: `Bearer ${TOKEN}` } } },
|
|
189
191
|
{ key: "copilot", label: "VS Code (Copilot agent mode)", present: () => existsSync(vscodeUser), file: join(vscodeUser, "mcp.json"), shape: "json", root: "servers", entry: BRIDGE ? { type: "stdio", ...stdio } : { type: "http", url: URL_, headers: { Authorization: `Bearer ${TOKEN}` } } },
|
|
190
192
|
{ key: "windsurf", label: "Windsurf", present: () => existsSync(join(home, ".codeium", "windsurf")), file: join(home, ".codeium", "windsurf", "mcp_config.json"), shape: "json", root: "mcpServers", entry: BRIDGE ? stdio : { serverUrl: URL_, headers: { Authorization: `Bearer ${TOKEN}` } } },
|
|
191
193
|
// MISTRAL VIBE (2026-10-04, docs.mistral.ai/vibe/code/cli/mcp-servers): `[[mcp_servers]]` tables in
|
|
192
194
|
// ~/.vibe/config.toml (or $VIBE_HOME), each with a name, a transport and a url or a command.
|
|
193
|
-
{ key: "vibe", label: "Mistral Vibe", present: () => existsSync(VIBE_DIR), file: join(VIBE_DIR, "config.toml"), shape: "vibe", block: BRIDGE ? `\n[[mcp_servers]]\nname = "${NAME}"\ntransport = "stdio"\ncommand = ${JSON.stringify(NODE)}\nargs = [${JSON.stringify(
|
|
195
|
+
{ key: "vibe", label: "Mistral Vibe", present: () => existsSync(VIBE_DIR), file: join(VIBE_DIR, "config.toml"), shape: "vibe", block: BRIDGE ? `\n[[mcp_servers]]\nname = "${NAME}"\ntransport = "stdio"\ncommand = ${JSON.stringify(NODE)}\nargs = [${[...NODE_ARGS, BRIDGE, "mcp"].map(arg => JSON.stringify(arg)).join(", ")}]\n` : `\n[[mcp_servers]]\nname = "${NAME}"\ntransport = "streamable-http"\nurl = "${URL_}"\nheaders = { "Authorization" = "Bearer ${TOKEN}" }\n` },
|
|
194
196
|
// GOOGLE ANTIGRAVITY (2026-10-04, antigravity.google/docs/mcp/): the 2.0 app, the `agy` CLI and the IDE read
|
|
195
197
|
// ~/.gemini/config/mcp_config.json; a remote server is `serverUrl` with headers (`url` and `httpUrl` are not
|
|
196
198
|
// read), a local one `command` and `args`. Present when its config folder or one of its data folders is here.
|
|
197
199
|
{ key: "antigravity", label: "Antigravity", present: () => existsSync(join(home, ".gemini", "config")) || (() => { try { return readdirSync(join(home, ".gemini")).some((name) => /^antigravity/.test(name)); } catch { return false; } })(), file: join(home, ".gemini", "config", "mcp_config.json"), shape: "json", root: "mcpServers", entry: BRIDGE ? stdio : { serverUrl: URL_, headers: { Authorization: `Bearer ${TOKEN}` } } },
|
|
198
200
|
// GROK BUILD (2026-10-04, docs.x.ai/build/settings/reference): `[mcp_servers.<name>]` in ~/.grok/config.toml (or
|
|
199
201
|
// $GROK_HOME), `url` and `headers` for a remote server, `command` and `args` for a local one.
|
|
200
|
-
{ key: "grok", label: "Grok Build", present: () => existsSync(GROK_DIR), file: join(GROK_DIR, "config.toml"), shape: "toml", block: BRIDGE ? `\n[mcp_servers.${NAME}]\ncommand = ${JSON.stringify(NODE)}\nargs = [${JSON.stringify(
|
|
202
|
+
{ key: "grok", label: "Grok Build", present: () => existsSync(GROK_DIR), file: join(GROK_DIR, "config.toml"), shape: "toml", block: BRIDGE ? `\n[mcp_servers.${NAME}]\ncommand = ${JSON.stringify(NODE)}\nargs = [${[...NODE_ARGS, BRIDGE, "mcp"].map(arg => JSON.stringify(arg)).join(", ")}]\n` : `\n[mcp_servers.${NAME}]\nurl = "${URL_}"\nheaders = { Authorization = "Bearer ${TOKEN}" }\n` },
|
|
201
203
|
// ZED (zed.dev/docs/ai/mcp): `context_servers` in its settings.json, `url` and `headers` for a remote server.
|
|
202
204
|
{ key: "zed", label: "Zed", present: () => existsSync(ZED_DIR), file: join(ZED_DIR, "settings.json"), shape: "json", root: "context_servers", entry: BRIDGE ? { ...stdio, env: {} } : { url: URL_, headers: { Authorization: `Bearer ${TOKEN}` } } },
|
|
203
205
|
// CLINE (docs.cline.bot/mcp): `mcpServers` in the extension's cline_mcp_settings.json; `type` must be
|
|
@@ -205,7 +207,7 @@ const CLIENTS = [
|
|
|
205
207
|
{ key: "cline", label: "Cline (VS Code)", present: () => existsSync(CLINE_DIR), file: join(CLINE_DIR, "cline_mcp_settings.json"), shape: "json", root: "mcpServers", entry: BRIDGE ? { ...stdio, disabled: false } : { type: "streamableHttp", url: URL_, headers: { Authorization: `Bearer ${TOKEN}` }, disabled: false } },
|
|
206
208
|
...hermesHomes().map((dir) => ({ key: "hermes", label: dir === HERMES_BASE ? "Hermes Agent" : `Hermes Agent (${dir.split(/[\\/]/).pop()})`, present: () => true, file: join(dir, "config.yaml"), shape: "yaml", root: "mcp_servers", server: HERMES_SERVER, hook: { path: ["hooks", "on_session_end"], unit: [`- command: ${JSON.stringify(HERMES_HOOK)}`, " timeout: 30"], note: "an on_session_end hook (Hermes asks once before it runs it)" } })),
|
|
207
209
|
...gooseDirs().map((dir) => ({ key: "goose", label: "Goose", present: () => true, file: join(dir, "config.yaml"), shape: "yaml", root: "extensions", server: GOOSE_SERVER, plugin: true })),
|
|
208
|
-
{ key: "opencode", label: "OpenCode", present: () => existsSync(OPENCODE_DIR), file: OPENCODE_FILE, shape: "json", root: "mcp", entry: BRIDGE ? { type: "local", command: [NODE, BRIDGE, "mcp"], enabled: true } : { type: "remote", url: URL_, headers: { Authorization: `Bearer ${TOKEN}` }, enabled: true }, plugin: "opencode" },
|
|
210
|
+
{ key: "opencode", label: "OpenCode", present: () => existsSync(OPENCODE_DIR), file: OPENCODE_FILE, shape: "json", root: "mcp", entry: BRIDGE ? { type: "local", command: [NODE, ...NODE_ARGS, BRIDGE, "mcp"], enabled: true } : { type: "remote", url: URL_, headers: { Authorization: `Bearer ${TOKEN}` }, enabled: true }, plugin: "opencode" },
|
|
209
211
|
{ key: "openclaw", label: "OpenClaw", present: () => existsSync(dirname(OPENCLAW_FILE)) || onPath("openclaw"), file: OPENCLAW_FILE, shape: "openclaw" },
|
|
210
212
|
{ key: "claude", label: "Claude Code", present: () => existsSync(join(home, ".claude.json")), file: join(home, ".claude.json"), shape: "claude" },
|
|
211
213
|
];
|
|
@@ -233,8 +235,8 @@ for (const client of CLIENTS) {
|
|
|
233
235
|
// the verb when the `claude` command is on this machine (2026-09-28; before, the line was only
|
|
234
236
|
// printed, and a person who had just run one command was handed a second to type), and prints
|
|
235
237
|
// it when the command is not. User scope, so the coupling holds in every folder on this machine.
|
|
236
|
-
const claudeArgs = REMOVE ? ["mcp", "remove", "-s", "user", NAME] : BRIDGE ? ["mcp", "add", "-s", "user", NAME, "--", NODE, BRIDGE, "mcp"] : ["mcp", "add", "--transport", "http", "-s", "user", NAME, URL_, "-H", `Authorization: Bearer ${TOKEN}`];
|
|
237
|
-
const shown = REMOVE ? `claude mcp remove -s user ${NAME}` : BRIDGE ? `claude mcp add -s user ${NAME} --
|
|
238
|
+
const claudeArgs = REMOVE ? ["mcp", "remove", "-s", "user", NAME] : BRIDGE ? ["mcp", "add", "-s", "user", NAME, "--", NODE, ...NODE_ARGS, BRIDGE, "mcp"] : ["mcp", "add", "--transport", "http", "-s", "user", NAME, URL_, "-H", `Authorization: Bearer ${TOKEN}`];
|
|
239
|
+
const shown = REMOVE ? `claude mcp remove -s user ${NAME}` : BRIDGE ? `claude mcp add -s user ${NAME} -- ${NODE_COMMAND} "${BRIDGE}" mcp` : `claude mcp add --transport http -s user ${NAME} "${URL_}" -H "Authorization: Bearer <token>"`;
|
|
238
240
|
const direct = directClaudeEntries();
|
|
239
241
|
if (!REMOVE && (BRIDGE ? direct.bridged && direct.entries.length === 0 : discovered)) { console.log(` ✓ ${client.label}: already coupled`); standing += 1; continue; }
|
|
240
242
|
// A direct entry under any name is replaced by the bridge, and every one goes on removal.
|
|
@@ -255,7 +257,7 @@ for (const client of CLIENTS) {
|
|
|
255
257
|
}
|
|
256
258
|
const text = existsSync(client.file) ? readFileSync(client.file, "utf8") : "";
|
|
257
259
|
// With the bridge, coupled means the bridge is in AND no entry with a key in it is left beside it.
|
|
258
|
-
const already = client.shape === "yaml" && !REMOVE ? (BRIDGE !== undefined ? text.includes(JSON.stringify(BRIDGE)) && (!client.plugin || goosePluginStands()) : text.includes(URL_)) && yamlConfig(client, text, false) === text : REMOVE ? text.includes(URL_) || /worktrust
|
|
260
|
+
const already = client.shape === "yaml" && !REMOVE ? (BRIDGE !== undefined ? text.includes(JSON.stringify(BRIDGE)) && (!client.plugin || goosePluginStands()) : text.includes(URL_)) && yamlConfig(client, text, false) === text : REMOVE ? text.includes(URL_) || /worktrust(?:-launch)?\.(?:mjs|py)/.test(text) : BRIDGE !== undefined ? text.includes(JSON.stringify(BRIDGE).slice(1, -1)) && !text.includes(URL_) : text.includes(URL_);
|
|
259
261
|
// THE WAY OUT, ON THE MACHINE. Uncoupling in the app ends the TOKEN; the config that names the
|
|
260
262
|
// door stays behind on every client here, so the next person to read this file believes the
|
|
261
263
|
// machine is coupled. `--remove` takes the entry out; the account side is a separate act and
|
|
@@ -268,7 +270,7 @@ for (const client of CLIENTS) {
|
|
|
268
270
|
try { config = JSON.parse(readFileSync(client.file, "utf8")); } catch { console.log(` ! ${client.label}: ${client.file} is not plain JSON; take the "${NAME}" entry out by hand`); continue; }
|
|
269
271
|
const root = config[client.root] ?? {};
|
|
270
272
|
for (const [key, entry] of Object.entries(root)) {
|
|
271
|
-
const named = JSON.stringify(entry ?? {}).includes(URL_) || /worktrust
|
|
273
|
+
const named = JSON.stringify(entry ?? {}).includes(URL_) || /worktrust(?:-launch)?\.(?:mjs|py)/.test(JSON.stringify(entry ?? {}));
|
|
272
274
|
if (key === NAME || named) delete root[key];
|
|
273
275
|
}
|
|
274
276
|
config[client.root] = root;
|
|
@@ -282,7 +284,7 @@ for (const client of CLIENTS) {
|
|
|
282
284
|
// Vibe's servers are an ARRAY of tables, so a block is found by what it says, not by its header: every
|
|
283
285
|
// `[[mcp_servers]]` that names ours, the door, or the bridge goes, up to the next header at a line start.
|
|
284
286
|
const text = readFileSync(client.file, "utf8");
|
|
285
|
-
const stripped = text.replace(/\n?\[\[mcp_servers\]\][\s\S]*?(?=\n\[|$)/g, (block) => (block.includes(`name = "${NAME}"`) || block.includes(URL_) || /worktrust
|
|
287
|
+
const stripped = text.replace(/\n?\[\[mcp_servers\]\][\s\S]*?(?=\n\[|$)/g, (block) => (block.includes(`name = "${NAME}"`) || block.includes(URL_) || /worktrust(?:-launch)?\.(?:mjs|py)/.test(block) ? "" : block));
|
|
286
288
|
console.log(` − ${client.label}: ${WRITE ? "removed from" : "would remove from"} ${client.file}`);
|
|
287
289
|
if (WRITE) writeFileSync(client.file, stripped);
|
|
288
290
|
} else if (client.shape === "toml") {
|
|
@@ -291,7 +293,7 @@ for (const client of CLIENTS) {
|
|
|
291
293
|
// Every block that names the door, under any name (a hand-made one too, 2026-10-04), or ours.
|
|
292
294
|
// A block runs to the next table header at the START of a line, never to the next "[" — the
|
|
293
295
|
// bridge's own `args = ["…", "mcp"]` holds one, and cutting there left half a block behind.
|
|
294
|
-
const stripped = text.replace(/\n?\[mcp_servers\.("?)([A-Za-z0-9_.-]+)\1\][\s\S]*?(?=\n\[|$)/g, (block, _q, name) => (name === NAME || block.includes(URL_) || /worktrust
|
|
296
|
+
const stripped = text.replace(/\n?\[mcp_servers\.("?)([A-Za-z0-9_.-]+)\1\][\s\S]*?(?=\n\[|$)/g, (block, _q, name) => (name === NAME || block.includes(URL_) || /worktrust(?:-launch)?\.(?:mjs|py)/.test(block) ? "" : block));
|
|
295
297
|
console.log(` − ${client.label}: ${WRITE ? "removed from" : "would remove from"} ${client.file}`);
|
|
296
298
|
if (WRITE) writeFileSync(client.file, stripped);
|
|
297
299
|
}
|
package/worktrust-launch.mjs
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
// GENERATED by scripts/build-cli-launchers.mjs; verify before importing any local module.
|
|
3
3
|
/** Official launcher verification. Pinned keys are generated from reviewed release configuration. */
|
|
4
4
|
import { createHash, createPublicKey, verify, randomBytes } from 'node:crypto';
|
|
5
|
-
import { existsSync, lstatSync, readFileSync, readdirSync, mkdirSync, writeFileSync, renameSync, rmSync } from 'node:fs';
|
|
6
|
-
import { join, dirname } from 'node:path';
|
|
5
|
+
import { existsSync, lstatSync, readFileSync, readdirSync, mkdirSync, writeFileSync, renameSync, rmSync, constants, openSync, closeSync, fstatSync, fchmodSync, readSync, fsyncSync } from 'node:fs';
|
|
6
|
+
import { join, dirname, basename, isAbsolute } from 'node:path';
|
|
7
7
|
|
|
8
8
|
const RELEASE_KEYS = {"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5":"-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAxe/h8yLe+e4iKYSx/2lzS7MgHIgzM+mi1XjofW1VKo4=\n-----END PUBLIC KEY-----\n"}; // GENERATED_RELEASE_KEYS
|
|
9
9
|
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
|
|
@@ -18,7 +18,7 @@ const exact = (value, keys) => value && Object.keys(value).sort().join(',') ===
|
|
|
18
18
|
const safe = name => {
|
|
19
19
|
if (typeof name !== 'string' || name.length > 240) return false;
|
|
20
20
|
const parts = name.split('/');
|
|
21
|
-
return parts.every((p, i) => (/^[A-Za-z0-
|
|
21
|
+
return parts.every((p, i) => (/^[A-Za-z0-9_][A-Za-z0-9._-]*$/.test(p) && p !== '..')
|
|
22
22
|
|| (p === '.claude-plugin' && i > 0 && i < parts.length - 1 && parts[i - 1] === 'agent'));
|
|
23
23
|
};
|
|
24
24
|
function regular(path) {
|
|
@@ -46,7 +46,7 @@ function verifyPackage(root, kind = 'npm') {
|
|
|
46
46
|
|| !verify(null, Buffer.from('worktrust:package:1\n' + canonical(signed.payload)), key, Buffer.from(signed.signature, 'base64url'))) throw Error('PACKAGE_UNTRUSTED_SIGNATURE');
|
|
47
47
|
const m = signed.payload;
|
|
48
48
|
if (!exact(m, ['format', 'kind', 'version', 'files']) || m.format !== 'worktrust-package/1' || m.kind !== kind || !/^\d+\.\d+\.\d+$/.test(m.version)
|
|
49
|
-
|| !m.files || Array.isArray(m.files) || typeof m.files !== 'object' || Object.keys(m.files).length > 2000 || !Object.hasOwn(m.files, 'worktrust.mjs')) throw Error('PACKAGE_INVALID_MANIFEST');
|
|
49
|
+
|| !m.files || Array.isArray(m.files) || typeof m.files !== 'object' || Object.keys(m.files).length > 2000 || !Object.hasOwn(m.files, kind === 'python' ? 'bundle/worktrust.mjs' : 'worktrust.mjs')) throw Error('PACKAGE_INVALID_MANIFEST');
|
|
50
50
|
const expected = Object.keys(m.files).sort();
|
|
51
51
|
for (const name of expected) {
|
|
52
52
|
if (!safe(name) || name === signatureName || !/^[a-f0-9]{64}$/.test(m.files[name])) throw Error('PACKAGE_INVALID_MANIFEST');
|
|
@@ -55,9 +55,9 @@ function verifyPackage(root, kind = 'npm') {
|
|
|
55
55
|
const file = join(root, name);
|
|
56
56
|
if (regular(file).size > 128 * 1024 * 1024 || hash(readFileSync(file)) !== m.files[name]) throw Error('PACKAGE_FILE_CHANGED');
|
|
57
57
|
}
|
|
58
|
-
const found = filesIn(root).filter(name => name !== signatureName && (kind !== 'engine' || name.endsWith('.mjs'))).sort();
|
|
58
|
+
const found = filesIn(root).filter(name => (kind !== 'python' || !name.split('/').includes('__pycache__')) && name !== signatureName && (kind !== 'engine' || name.endsWith('.mjs'))).sort();
|
|
59
59
|
if (JSON.stringify(found) !== JSON.stringify(expected)) throw Error('PACKAGE_FILE_LIST_CHANGED');
|
|
60
|
-
if (/const CLI_VERSION = "([^"]+)";/.exec(readFileSync(join(root, 'worktrust.mjs'), 'utf8'))?.[1] !== m.version) throw Error('PACKAGE_VERSION_MISMATCH');
|
|
60
|
+
if (/const CLI_VERSION = "([^"]+)";/.exec(readFileSync(join(root, kind === 'python' ? 'bundle/worktrust.mjs' : 'worktrust.mjs'), 'utf8'))?.[1] !== m.version) throw Error('PACKAGE_VERSION_MISMATCH');
|
|
61
61
|
return { manifest: m, identity: hash(readFileSync(path)), signatureName };
|
|
62
62
|
}
|
|
63
63
|
function installSignedPackage(source, home) {
|
|
@@ -83,12 +83,94 @@ function installSignedPackage(source, home) {
|
|
|
83
83
|
return join(target, 'worktrust-launch.mjs');
|
|
84
84
|
}
|
|
85
85
|
|
|
86
|
+
/** Child processes of the official launcher re-enter verification, including long-lived MCP bridges.
|
|
87
|
+
* Raw source test harnesses retain direct entry; they are not authenticated release launches.
|
|
88
|
+
*/
|
|
89
|
+
function persistentPython(root) {
|
|
90
|
+
return globalThis[Symbol.for("worktrust.verifiedReleaseRoot")] === root
|
|
91
|
+
&& basename(root) === "engine" && /^[a-f0-9]{64}$/.test(basename(dirname(root)))
|
|
92
|
+
&& basename(dirname(dirname(root))) === "installations"
|
|
93
|
+
&& typeof process.env.WORKTRUST_BUNDLED_PYTHON === "string" && isAbsolute(process.env.WORKTRUST_BUNDLED_PYTHON)
|
|
94
|
+
&& process.env.WORKTRUST_INSTALLED_LAUNCHER === join(dirname(root), "worktrust-launch.py")
|
|
95
|
+
&& process.env.WORKTRUST_BUNDLED_PYTHON;
|
|
96
|
+
}
|
|
97
|
+
function moduleExecutable(root) { return persistentPython(root) || process.execPath; }
|
|
98
|
+
function moduleArgs(root, name, args = []) {
|
|
99
|
+
if (!["worktrust.mjs", "setup-mcp.mjs", "log-session.mjs", "count-behaviour.mjs", "preserve.mjs"].includes(name)) throw Error("PACKAGE_INVALID_ENTRY");
|
|
100
|
+
if (persistentPython(root)) return ["-I", process.env.WORKTRUST_INSTALLED_LAUNCHER, "--internal-module", name, ...args];
|
|
101
|
+
const flags = process.versions.node === "26.5.0" ? ["--no-concurrent-sparkplug"] : [];
|
|
102
|
+
return globalThis[Symbol.for("worktrust.verifiedReleaseRoot")] === root
|
|
103
|
+
? [...flags, join(root, "worktrust-launch.mjs"), "--internal-module", name, ...args]
|
|
104
|
+
: [...flags, join(root, name), ...args];
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Credentials stay outside the immutable release. File hygiene reduces cross-user theft;
|
|
108
|
+
// it does not attest the machine owner or the truth of data they choose to sign.
|
|
109
|
+
function privateDirectory(path, create) {
|
|
110
|
+
if (create) mkdirSync(path, { recursive: true, mode: 0o700 });
|
|
111
|
+
const before = lstatSync(path);
|
|
112
|
+
if (!before.isDirectory() || before.isSymbolicLink() || (process.getuid && before.uid !== process.getuid())) throw Error('KEY_FILE_UNSAFE');
|
|
113
|
+
// Windows ACLs remain the responsibility of the user's private profile directory.
|
|
114
|
+
if (process.platform !== 'win32') {
|
|
115
|
+
const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
116
|
+
try { const current = fstatSync(fd); if (current.ino !== before.ino || current.dev !== before.dev) throw Error('KEY_FILE_UNSAFE'); fchmodSync(fd, 0o700); }
|
|
117
|
+
finally { closeSync(fd); }
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
function privateStat(stat) {
|
|
121
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > 65536 || (process.getuid && stat.uid !== process.getuid())) throw Error('KEY_FILE_UNSAFE');
|
|
122
|
+
}
|
|
123
|
+
/** Bounded descriptor read; never follow a linked credential, pipe, device or directory. */
|
|
124
|
+
function readPrivateFile(file) {
|
|
125
|
+
let fd;
|
|
126
|
+
try {
|
|
127
|
+
privateDirectory(dirname(file), false);
|
|
128
|
+
const before = lstatSync(file); privateStat(before);
|
|
129
|
+
fd = openSync(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
|
|
130
|
+
const current = fstatSync(fd); privateStat(current);
|
|
131
|
+
if (current.ino !== before.ino || current.dev !== before.dev) throw Error('KEY_FILE_UNSAFE');
|
|
132
|
+
if (process.platform !== 'win32') fchmodSync(fd, 0o600);
|
|
133
|
+
const bytes = Buffer.alloc(65537); let size = 0, next;
|
|
134
|
+
while (size < bytes.length && (next = readSync(fd, bytes, size, bytes.length - size, null)) > 0) size += next;
|
|
135
|
+
if (size > 65536) throw Error('KEY_FILE_UNSAFE');
|
|
136
|
+
return bytes.subarray(0, size).toString('utf8');
|
|
137
|
+
} catch (error) {
|
|
138
|
+
if (error.code === 'ENOENT') return null;
|
|
139
|
+
throw Error('KEY_FILE_UNSAFE');
|
|
140
|
+
} finally { if (fd !== undefined) closeSync(fd); }
|
|
141
|
+
}
|
|
142
|
+
/** Exclusive random temp, flush, atomic replace. Existing credentials survive a failed write. */
|
|
143
|
+
function writePrivateFile(file, bytes) {
|
|
144
|
+
if (Buffer.byteLength(bytes) > 65536) throw Error('KEY_FILE_UNSAFE');
|
|
145
|
+
privateDirectory(dirname(file), true);
|
|
146
|
+
try { privateStat(lstatSync(file)); } catch (error) { if (error.code !== 'ENOENT') throw Error('KEY_FILE_UNSAFE'); }
|
|
147
|
+
const temporary = file + '.' + randomBytes(16).toString('hex') + '.tmp'; let fd;
|
|
148
|
+
try {
|
|
149
|
+
fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600);
|
|
150
|
+
writeFileSync(fd, bytes); fsyncSync(fd); closeSync(fd); fd = undefined;
|
|
151
|
+
renameSync(temporary, file);
|
|
152
|
+
} finally { if (fd !== undefined) closeSync(fd); rmSync(temporary, { force: true }); }
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** First creation only, used by offline archive secrets; never overwrite an existing key. */
|
|
156
|
+
function createPrivateFile(file, bytes) {
|
|
157
|
+
if (Buffer.byteLength(bytes) > 65536) throw Error('KEY_FILE_UNSAFE');
|
|
158
|
+
privateDirectory(dirname(file), true);
|
|
159
|
+
const fd = openSync(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600);
|
|
160
|
+
try { writeFileSync(fd, bytes); fsyncSync(fd); } finally { closeSync(fd); }
|
|
161
|
+
}
|
|
162
|
+
|
|
86
163
|
import { fileURLToPath } from 'node:url';
|
|
87
164
|
const root = dirname(fileURLToPath(import.meta.url));
|
|
88
165
|
try {
|
|
89
166
|
verifyPackage(root, existsSync(join(root, 'package.json')) ? 'npm' : 'engine');
|
|
90
|
-
|
|
91
|
-
|
|
167
|
+
Object.defineProperty(globalThis, Symbol.for('worktrust.verifiedReleaseRoot'), { value: root });
|
|
168
|
+
const internal = process.argv[2] === '--internal-module';
|
|
169
|
+
const entry = internal ? process.argv[3] : 'worktrust.mjs';
|
|
170
|
+
if (!['worktrust.mjs', 'setup-mcp.mjs', 'log-session.mjs', 'count-behaviour.mjs', 'preserve.mjs'].includes(entry)) throw Error('PACKAGE_INVALID_ENTRY');
|
|
171
|
+
if (internal) process.argv.splice(2, 2);
|
|
172
|
+
process.argv[1] = join(root, entry);
|
|
173
|
+
await import('./' + entry);
|
|
92
174
|
} catch (error) {
|
|
93
175
|
const category = /^PACKAGE_[A-Z_]+$/.test(error.message) ? error.message : 'PACKAGE_VERIFICATION_FAILED';
|
|
94
176
|
process.stderr.write(`worktrust: ${category}. Execution stopped; reinstall an official WorkTrust release.\n`);
|
package/worktrust.mjs
CHANGED
|
@@ -32,9 +32,7 @@
|
|
|
32
32
|
* WHAT RUNS. From the npm package, everything that runs is in the package: this file,
|
|
33
33
|
* `setup-mcp.mjs` (gives every AI app here the WorkTrust door), `log-session.mjs` (the session hook)
|
|
34
34
|
* and `count-behaviour.mjs` (the local counter, pinned: never replaced from the network), with
|
|
35
|
-
* `transcript-readers.mjs` (how Codex and Antigravity logs are read, imported by the last two).
|
|
36
|
-
* is downloaded. Run as a single file from WorkTrust's site instead, it fetches those from that
|
|
37
|
-
* same site, and says so before it asks.
|
|
35
|
+
* `transcript-readers.mjs` (how Codex and Antigravity logs are read, imported by the last two). Individual support scripts are never downloaded or executed outside the complete release.
|
|
38
36
|
* HOW THE ACCOUNT IS DECIDED. By default this terminal listens on 127.0.0.1 for one answer and holds
|
|
39
37
|
* a PKCE secret. Your browser opens WorkTrust, you approve this computer there (signed in, second
|
|
40
38
|
* factor), and the browser is sent back to 127.0.0.1 with a one-time code that only this terminal,
|
|
@@ -67,18 +65,20 @@ import { createHash, createPublicKey, generateKeyPairSync, randomBytes, sign } f
|
|
|
67
65
|
import { createServer } from "node:http";
|
|
68
66
|
import { chmodSync, closeSync, copyFileSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
|
|
69
67
|
import { homedir, hostname, platform } from "node:os";
|
|
70
|
-
import { dirname, join } from "node:path";
|
|
68
|
+
import { dirname, join, basename } from "node:path";
|
|
71
69
|
import { createInterface } from "node:readline/promises";
|
|
72
70
|
import { createInterface as lines } from "node:readline";
|
|
73
71
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
74
72
|
|
|
73
|
+
const { moduleArgs, moduleExecutable, readPrivateFile, writePrivateFile } = await import("./package-integrity.mjs").catch(() => ({}));
|
|
74
|
+
|
|
75
75
|
const args = process.argv.slice(2);
|
|
76
76
|
const VALUED = ["--name", "--origin", "--url", "--export", "--from-folder"];
|
|
77
77
|
const command = args.includes("--help") ? "help" : args.includes("--version") ? "version" : args.find((arg, at) => !arg.startsWith("--") && !(at > 0 && VALUED.includes(args[at - 1]))) ?? "default";
|
|
78
78
|
const flag = (name) => { const at = args.indexOf(`--${name}`); return at >= 0 ? args[at + 1] : undefined; };
|
|
79
79
|
const has = (name) => args.includes(`--${name}`);
|
|
80
80
|
/** This CLI's version, said to the door so the app can tell which computer runs an old one (check-cli-package holds it equal to package.json). */
|
|
81
|
-
const CLI_VERSION = "0.10.
|
|
81
|
+
const CLI_VERSION = "0.10.25";
|
|
82
82
|
const ORIGIN = (flag("origin") ?? process.env.WORKTRUST_ORIGIN ?? "https://app.worktrust.io").replace(/\/$/, "");
|
|
83
83
|
const MCP = flag("url") ?? process.env.WORKTRUST_MCP_URL ?? `${ORIGIN}/api/mcp`;
|
|
84
84
|
const HOME_DIR = join(homedir(), ".worktrust");
|
|
@@ -125,7 +125,7 @@ async function post(path, body) {
|
|
|
125
125
|
return { status: response.status, json: await response.json().catch(() => ({})) };
|
|
126
126
|
}
|
|
127
127
|
|
|
128
|
-
/**
|
|
128
|
+
/** Every helper belongs to this complete release. No loose-file download fallback. */
|
|
129
129
|
async function scripts() {
|
|
130
130
|
if (BUNDLED) return Object.fromEntries(SCRIPTS.map((name) => [name, join(HERE, name)]));
|
|
131
131
|
fail("Use the complete official npm/Python package or preservation kit. Individual scripts are not downloaded or executed without release verification.");
|
|
@@ -142,7 +142,7 @@ function historyQueueScope(token) {
|
|
|
142
142
|
/** Run a script; its output is shown, or collected for the plan. The key travels in the environment only. */
|
|
143
143
|
function run(path, scriptArgs, token, collect = false, extraEnv = {}) {
|
|
144
144
|
return new Promise((resolve) => {
|
|
145
|
-
const child = spawn(
|
|
145
|
+
const child = spawn(moduleExecutable(HERE), [...moduleArgs(HERE, basename(path), scriptArgs)], { stdio: collect ? ["ignore", "pipe", "pipe"] : "inherit", env: { ...process.env, WORKTRUST_MCP_URL: MCP, WORKTRUST_MCP_TOKEN: token, WORKTRUST_NODE: NODE, WORKTRUST_NODE_ARGS: JSON.stringify(NODE_ARGS), WORKTRUST_CLI_VERSION: CLI_VERSION, WORKTRUST_HISTORY_SCOPE: historyQueueScope(token), ...extraEnv } });
|
|
146
146
|
let out = "";
|
|
147
147
|
child.stdout?.on("data", (chunk) => { out += chunk; });
|
|
148
148
|
child.stderr?.on("data", (chunk) => { out += chunk; });
|
|
@@ -272,7 +272,7 @@ async function pairByCode(host, extra) {
|
|
|
272
272
|
let NODE = process.env.WORKTRUST_BUNDLED_RUNTIME_DIR ? process.execPath : (process.env.PATH ?? "").split(OS === "windows" ? ";" : ":").map((dir) => join(dir, OS === "windows" ? "node.exe" : "node")).find((path) => existsSync(path)) ?? process.execPath;
|
|
273
273
|
const KEY_FILE = join(HOME_DIR, "key.json");
|
|
274
274
|
const STABLE_FILE = join(HOME_DIR, "worktrust.mjs");
|
|
275
|
-
let STABLE =
|
|
275
|
+
let STABLE = join(HERE, "worktrust-launch.mjs"), runtimePrepared = false, NODE_ARGS = [];
|
|
276
276
|
const RENEW_EVERY_MS = 7 * 24 * 3600_000;
|
|
277
277
|
const KEY_PLACE = "~/.worktrust/key.json (only you can read it)";
|
|
278
278
|
const ensureHome = () => { mkdirSync(HOME_DIR, { recursive: true, mode: 0o700 }); try { chmodSync(HOME_DIR, 0o700); } catch { /* Windows */ } };
|
|
@@ -280,6 +280,10 @@ const ensureHome = () => { mkdirSync(HOME_DIR, { recursive: true, mode: 0o700 })
|
|
|
280
280
|
/** A tool-runner cache is disposable. Install the whole verified runtime/engine before changing wiring. */
|
|
281
281
|
async function prepareBundledRuntime() {
|
|
282
282
|
if (runtimePrepared) return;
|
|
283
|
+
const installedLauncher = join(dirname(HERE), "worktrust-launch.py");
|
|
284
|
+
if (moduleExecutable(HERE) !== process.execPath) {
|
|
285
|
+
NODE = process.env.WORKTRUST_BUNDLED_PYTHON; NODE_ARGS = ["-I"]; STABLE = installedLauncher; runtimePrepared = true; return;
|
|
286
|
+
}
|
|
283
287
|
if (!process.env.WORKTRUST_BUNDLED_RUNTIME_DIR) {
|
|
284
288
|
if (existsSync(join(HERE, "package-release.json"))) {
|
|
285
289
|
if (existsSync(HOME_DIR) && (!lstatSync(HOME_DIR).isDirectory() || lstatSync(HOME_DIR).isSymbolicLink())) fail("the WorkTrust directory must be a directory, not a symlink.");
|
|
@@ -291,11 +295,11 @@ async function prepareBundledRuntime() {
|
|
|
291
295
|
if (existsSync(HOME_DIR) && (!lstatSync(HOME_DIR).isDirectory() || lstatSync(HOME_DIR).isSymbolicLink())) fail("the WorkTrust directory must be a directory, not a symlink.");
|
|
292
296
|
ensureHome();
|
|
293
297
|
const installed = installRuntime(process.env.WORKTRUST_BUNDLED_RUNTIME_DIR, HERE, HOME_DIR, ["worktrust.mjs", ...SCRIPTS, "preserve.mjs", "preserve-lines.mjs", "preserve-summary.mjs"]);
|
|
294
|
-
NODE = installed.executable; STABLE = installed.bridge; runtimePrepared = true;
|
|
298
|
+
NODE = installed.executable; NODE_ARGS = installed.args; STABLE = installed.bridge; runtimePrepared = true;
|
|
295
299
|
}
|
|
296
300
|
function saveStableEntry() {
|
|
297
|
-
const temporary = `${
|
|
298
|
-
try { writeFileSync(temporary,
|
|
301
|
+
const target = join(HOME_DIR, "installed-release.json"), temporary = `${target}.${randomBytes(8).toString("hex")}.tmp`;
|
|
302
|
+
try { writeFileSync(temporary, JSON.stringify({ version: CLI_VERSION }), { flag: "wx", mode: 0o600 }); renameSync(temporary, target); }
|
|
299
303
|
finally { try { rmSync(temporary); } catch { /* already renamed */ } }
|
|
300
304
|
}
|
|
301
305
|
|
|
@@ -309,14 +313,16 @@ function saveStableEntry() {
|
|
|
309
313
|
const keyStore = {
|
|
310
314
|
/** Written whole or not at all: a temporary file renamed over the old one. */
|
|
311
315
|
save(entry) {
|
|
312
|
-
|
|
313
|
-
const temporary = `${KEY_FILE}.${process.pid}.tmp`;
|
|
314
|
-
writeFileSync(temporary, Buffer.from(JSON.stringify(entry)).toString("base64"), { mode: 0o600 });
|
|
315
|
-
try { chmodSync(temporary, 0o600); } catch { /* Windows */ }
|
|
316
|
-
renameSync(temporary, KEY_FILE);
|
|
316
|
+
writePrivateFile(KEY_FILE, Buffer.from(JSON.stringify(entry)).toString("base64"));
|
|
317
317
|
},
|
|
318
318
|
load() {
|
|
319
|
-
|
|
319
|
+
const bytes = readPrivateFile(KEY_FILE);
|
|
320
|
+
if (bytes === null) return null;
|
|
321
|
+
try {
|
|
322
|
+
const entry = JSON.parse(Buffer.from(bytes, "base64").toString("utf8"));
|
|
323
|
+
if (!entry || Array.isArray(entry) || typeof entry !== "object" || typeof entry.token !== "string" || !entry.token) throw Error();
|
|
324
|
+
return entry;
|
|
325
|
+
} catch { throw Error("KEY_FILE_INVALID"); }
|
|
320
326
|
},
|
|
321
327
|
erase() { try { rmSync(KEY_FILE); } catch { /* gone */ } },
|
|
322
328
|
};
|
|
@@ -467,7 +473,7 @@ function sweepAtMostHourly() {
|
|
|
467
473
|
const stamp = join(HOME_DIR, "bridge-swept-at");
|
|
468
474
|
try { if (Date.now() - Number(readFileSync(stamp, "utf8")) < 3_600_000) return; } catch { /* never swept here */ }
|
|
469
475
|
try { mkdirSync(HOME_DIR, { recursive: true }); writeFileSync(stamp, String(Date.now())); } catch { return; }
|
|
470
|
-
try { spawn(
|
|
476
|
+
try { spawn(moduleExecutable(HERE), [...moduleArgs(HERE, "worktrust.mjs", ["hook"])], { detached: true, stdio: "ignore" }).unref(); } catch { /* the next start sweeps */ }
|
|
471
477
|
}
|
|
472
478
|
|
|
473
479
|
async function bridge() {
|
|
@@ -510,7 +516,7 @@ async function hook() {
|
|
|
510
516
|
if (has("hermes") || has("goose")) return sessionEnd();
|
|
511
517
|
const key = await freshKey();
|
|
512
518
|
if (!key) return;
|
|
513
|
-
const child = spawn(
|
|
519
|
+
const child = spawn(moduleExecutable(HERE), [...moduleArgs(HERE, "log-session.mjs", args.filter((arg) => arg !== "hook"))], { stdio: "inherit", env: { ...process.env, WORKTRUST_MCP_URL: key.url, WORKTRUST_MCP_TOKEN: key.token, WORKTRUST_CLI_VERSION: CLI_VERSION, WORKTRUST_HISTORY_SCOPE: historyQueueScope(key.token), ...(key.device ? { WORKTRUST_DEVICE_KEY: key.device } : {}) } }); // 0.10.20: the hook names the version that started it, beside each line
|
|
514
520
|
process.exitCode = await new Promise((resolve, reject) => { child.on("error", reject); child.on("close", (code) => resolve(code ?? 1)); });
|
|
515
521
|
}
|
|
516
522
|
|
|
@@ -533,7 +539,7 @@ async function antigravityStop() {
|
|
|
533
539
|
process.stdin.on("end", () => { clearTimeout(timer); resolve(text); });
|
|
534
540
|
process.stdin.on("error", () => { clearTimeout(timer); resolve(text); });
|
|
535
541
|
});
|
|
536
|
-
try { spawn(
|
|
542
|
+
try { spawn(moduleExecutable(HERE), [...moduleArgs(HERE, "worktrust.mjs", ["hook", "--antigravity"])], { detached: true, stdio: "ignore", env: { ...process.env, WORKTRUST_HOOK_INPUT: input.slice(0, 65536) } }).unref(); } catch { /* the next run sweeps it */ }
|
|
537
543
|
process.stdin.pause(); return;
|
|
538
544
|
}
|
|
539
545
|
|
|
@@ -547,7 +553,7 @@ async function antigravityStop() {
|
|
|
547
553
|
async function sessionEnd() {
|
|
548
554
|
writeSync(1, "{}\n");
|
|
549
555
|
if (!process.stdin.isTTY) await new Promise((resolve) => { const timer = setTimeout(resolve, 2000); process.stdin.on("data", () => {}); process.stdin.on("end", () => { clearTimeout(timer); resolve(); }); process.stdin.on("error", () => { clearTimeout(timer); resolve(); }); });
|
|
550
|
-
try { spawn(
|
|
556
|
+
try { spawn(moduleExecutable(HERE), [...moduleArgs(HERE, "worktrust.mjs", ["hook"])], { detached: true, stdio: "ignore" }).unref(); } catch { /* the next run sweeps it */ }
|
|
551
557
|
process.stdin.pause(); return;
|
|
552
558
|
}
|
|
553
559
|
|
|
@@ -583,7 +589,7 @@ async function update() {
|
|
|
583
589
|
// Out first, then in: an app that held a key of its own (a hand-made entry) moves onto the bridge.
|
|
584
590
|
await run(paths["setup-mcp.mjs"], ["--remove", "--write"], key.token, true);
|
|
585
591
|
if ((await run(paths["setup-mcp.mjs"], ["--write", "--bridge", STABLE], key.token)).code !== 0) fail("coupling the AI apps failed; the output above says where.");
|
|
586
|
-
const hookArgs = ["--install",
|
|
592
|
+
const hookArgs = ["--install", "--via", STABLE];
|
|
587
593
|
if ((await run(paths["log-session.mjs"], hookArgs, key.token, false)).code !== 0) fail("installing the session hook failed; the output above says where.");
|
|
588
594
|
// Codex installed since, or a No said at connect: the one question, asked again (or "already set").
|
|
589
595
|
await offerCodex();
|
|
@@ -611,7 +617,6 @@ async function connect() {
|
|
|
611
617
|
if (!has("replace") && !(await ask("Couple it again?", false))) { say(" Stopped. Nothing was changed: this computer stays coupled as it is."); return; }
|
|
612
618
|
say();
|
|
613
619
|
}
|
|
614
|
-
if (!BUNDLED) say(` The three scripts that do the work are downloaded from ${ORIGIN} first. From npm they come in the package.\n`);
|
|
615
620
|
const paths = await scripts();
|
|
616
621
|
const direct = has("direct");
|
|
617
622
|
const plan = await run(paths["setup-mcp.mjs"], direct ? [] : ["--bridge", STABLE], PLACEHOLDER, true);
|
|
@@ -623,7 +628,7 @@ async function connect() {
|
|
|
623
628
|
if (foundApps.length === 0) say(" (no AI app found here yet; run connect again after installing one)");
|
|
624
629
|
if (!direct) say(` 3. The key is kept in ${KEY_PLACE}, works only on this computer (every call is signed) and is renewed every week.`);
|
|
625
630
|
say(` ${direct ? 3 : 4}. The session hook is installed:`);
|
|
626
|
-
say(
|
|
631
|
+
say(" + The hook and counter from the checked release, retained outside the package-manager cache");
|
|
627
632
|
say(` + ${join(homedir(), ".claude", "settings.json")} → SessionStart, SessionEnd and PreCompact run it`);
|
|
628
633
|
say();
|
|
629
634
|
say(" Sent to WorkTrust afterwards: durations, token counts, model names, a layer keyword, counts,");
|
|
@@ -661,7 +666,7 @@ async function connect() {
|
|
|
661
666
|
// A NEW COUPLING SENDS NOTHING FROM BEFORE IT (log-session THE FLOORS): `--from-now` for a first coupling and a change
|
|
662
667
|
// of account; the same account coupled again keeps its watermarks. A change of account also closes the history offer.
|
|
663
668
|
const floors = !previous || switched ? ["--from-now", ...(switched ? ["--history-floor", "now"] : [])] : [];
|
|
664
|
-
const hookArgs = ["--install", ...floors,
|
|
669
|
+
const hookArgs = ["--install", ...floors, "--via", STABLE, ...(direct ? ["--direct"] : [])];
|
|
665
670
|
if ((await run(paths["log-session.mjs"], hookArgs, token, false, { WORKTRUST_CODEX_OFFER: "1" })).code !== 0) fail("installing the session hook failed; the output above says where.");
|
|
666
671
|
await offerCodex();
|
|
667
672
|
await offerAntigravity();
|
|
@@ -720,7 +725,7 @@ async function offerHistory(paths, token, devicePem, url = MCP, rebuild = false)
|
|
|
720
725
|
}
|
|
721
726
|
|
|
722
727
|
/** The version stamped in the stable copy in ~/.worktrust, the CLI this computer ran before an update; null without one. */
|
|
723
|
-
const stableVersion = () => { try { return /const CLI_VERSION = "([^"]+)";/.exec(readFileSync(STABLE_FILE, "utf8"))?.[1] ?? null; } catch { return null; } };
|
|
728
|
+
const stableVersion = () => { try { const installed = JSON.parse(readFileSync(join(HOME_DIR, "installed-release.json"), "utf8")); if (/^\d+\.\d+\.\d+$/.test(installed.version)) return installed.version; } catch { /* older registration */ } try { return /const CLI_VERSION = "([^"]+)";/.exec(readFileSync(STABLE_FILE, "utf8"))?.[1] ?? null; } catch { return null; } };
|
|
724
729
|
|
|
725
730
|
/**
|
|
726
731
|
* OFFERED ONCE, BY `update`, IN PLAIN WORDS (owner, 2026-10-07): when the computer's earlier lines were made by an earlier CLI
|
|
@@ -937,9 +942,9 @@ function writeCodex(rows) {
|
|
|
937
942
|
async function offerCodex() {
|
|
938
943
|
if (!existsSync(join(homedir(), ".codex"))) { if (command === "codex") say(" Codex is not on this computer (no ~/.codex)."); return; }
|
|
939
944
|
const viaBridge = existsSync(STABLE);
|
|
940
|
-
const hookFile =
|
|
945
|
+
const hookFile = STABLE;
|
|
941
946
|
if (!existsSync(hookFile)) { say(" Couple this computer first: npx worktrust"); return; }
|
|
942
|
-
const desired = () => `notify = [${(viaBridge ? [NODE, STABLE, "hook", "--codex-notify"] : [NODE, hookFile, "--codex-notify"]).map((part) => JSON.stringify(part)).join(", ")}]`;
|
|
947
|
+
const desired = () => `notify = [${(viaBridge ? [NODE, ...NODE_ARGS, STABLE, "hook", "--codex-notify"] : [NODE, ...NODE_ARGS, hookFile, "--codex-notify"]).map((part) => JSON.stringify(part)).join(", ")}]`;
|
|
943
948
|
let want = desired();
|
|
944
949
|
const found = codexNotify();
|
|
945
950
|
say();
|
|
@@ -986,7 +991,7 @@ function writeAgyHooks(hooks) {
|
|
|
986
991
|
async function offerAntigravity() {
|
|
987
992
|
if (!antigravityHere()) { if (command === "antigravity") say(" Antigravity is not on this computer (no ~/.gemini/config or ~/.gemini/antigravity*)."); return; }
|
|
988
993
|
if (!existsSync(STABLE)) { say(" Couple this computer first: npx worktrust"); return; }
|
|
989
|
-
const desired = () => ({ enabled: true, Stop: [{ type: "command", command: `"${NODE}" "${STABLE}" hook --antigravity-stop`, timeout: 10 }] });
|
|
994
|
+
const desired = () => ({ enabled: true, Stop: [{ type: "command", command: `"${NODE}" ${NODE_ARGS.map(arg => JSON.stringify(arg)).join(" ")}${NODE_ARGS.length ? " " : ""}"${STABLE}" hook --antigravity-stop`, timeout: 10 }] });
|
|
990
995
|
let want = desired();
|
|
991
996
|
const hooks = agyHooks();
|
|
992
997
|
say();
|
|
@@ -1042,7 +1047,7 @@ async function disconnect() {
|
|
|
1042
1047
|
previousNote.save(keyStore.load());
|
|
1043
1048
|
keyStore.erase();
|
|
1044
1049
|
// Everything of ours on this computer goes; the folder too, when nothing else is left in it.
|
|
1045
|
-
for (const name of [
|
|
1050
|
+
for (const name of [STABLE_FILE, ...SCRIPTS.map((script) => join(HOME_DIR, downloaded(script))), join(HOME_DIR, "pinned")]) { try { rmSync(name); } catch { /* gone */ } }
|
|
1046
1051
|
try { rmSync(HOME_DIR, { recursive: false }); } catch { /* not empty, or gone */ }
|
|
1047
1052
|
say();
|
|
1048
1053
|
say(" Done. Revoke the key in WorkTrust to finish.");
|
|
@@ -1102,12 +1107,12 @@ async function status() {
|
|
|
1102
1107
|
say(key ? ` Key: in ${KEY_PLACE}, ${key.device ? "bound to this computer, " : ""}last renewed ${String(key.renewedAt ?? "").slice(0, 10) || "never"}` : " Key: not on this computer (or written into the apps' settings with --direct)");
|
|
1103
1108
|
if (key) say(key.account ? ` Account: ${key.account}${key.coupledAt ? `, coupled ${String(key.coupledAt).slice(0, 10)}` : ""}` : " Account: not recorded (coupled by an older version; `npx worktrust connect` records it)");
|
|
1104
1109
|
let hook = false;
|
|
1105
|
-
try { hook = /log-session|worktrust
|
|
1110
|
+
try { hook = /log-session|worktrust(?:-launch)?\.(?:mjs|py)\\?" hook/.test(readFileSync(join(homedir(), ".claude", "settings.json"), "utf8")); } catch { /* none */ }
|
|
1106
1111
|
say(hook ? " Session hook: installed" : " Session hook: not installed");
|
|
1107
1112
|
if (existsSync(join(homedir(), ".codex"))) { const notify = codexNotify().text ?? ""; say(isOurNotify(notify) ? " Codex: wakes the session hook" : " Codex: does not wake the session hook (npx worktrust update asks)"); }
|
|
1108
|
-
if (existsSync(join(homedir(), ".hermes"))) { let text = ""; try { text = readFileSync(join(homedir(), ".hermes", "config.yaml"), "utf8"); } catch { /* none */ } say(/worktrust
|
|
1113
|
+
if (existsSync(join(homedir(), ".hermes"))) { let text = ""; try { text = readFileSync(join(homedir(), ".hermes", "config.yaml"), "utf8"); } catch { /* none */ } say(/worktrust(?:-launch)?\.(?:mjs|py)\\?" hook --hermes/.test(text) ? " Hermes Agent: wakes the session hook" : " Hermes Agent: does not wake the session hook (npx worktrust update writes it)"); }
|
|
1109
1114
|
if (antigravityHere()) say(agyHooks()?.worktrust ? " Antigravity: wakes the session hook" : " Antigravity: does not wake the session hook (npx worktrust update asks)");
|
|
1110
|
-
say(
|
|
1115
|
+
say(" Counter: from this release, checked by the official launcher");
|
|
1111
1116
|
await measuredHere();
|
|
1112
1117
|
}
|
|
1113
1118
|
|
|
@@ -1116,7 +1121,7 @@ async function status() {
|
|
|
1116
1121
|
* with each stretch (kinds and counts, never text). Read here by the hook beside this file; nothing is sent to show it.
|
|
1117
1122
|
*/
|
|
1118
1123
|
async function measuredHere() {
|
|
1119
|
-
const hook =
|
|
1124
|
+
const hook = join(HERE, "log-session.mjs");
|
|
1120
1125
|
if (!hook) return;
|
|
1121
1126
|
// Through the CLI's one way of starting a script (never a synchronous child: check-computer-pairing), with no door to send to.
|
|
1122
1127
|
const read = await run(hook, ["--evidence-summary"], "", true, { WORKTRUST_MCP_URL: "", WORKTRUST_HOOK_INPUT: "" });
|
|
@@ -1150,7 +1155,7 @@ function claudeKeepsDays() {
|
|
|
1150
1155
|
async function preserve() {
|
|
1151
1156
|
const script = join(HERE, "preserve.mjs");
|
|
1152
1157
|
if (!existsSync(script)) fail("preserve runs from the package: npx worktrust@latest preserve");
|
|
1153
|
-
const child = spawn(
|
|
1158
|
+
const child = spawn(moduleExecutable(HERE), [...moduleArgs(HERE, "preserve.mjs", args.filter((arg) => arg !== "preserve"))], { stdio: "inherit", env: { ...process.env, WORKTRUST_COLLECTOR: `worktrust-cli/${CLI_VERSION}` } });
|
|
1154
1159
|
process.exitCode = await new Promise((resolve) => child.on("exit", (code) => resolve(code ?? 1)));
|
|
1155
1160
|
}
|
|
1156
1161
|
|
|
@@ -1201,6 +1206,7 @@ function help() {
|
|
|
1201
1206
|
// before anything is read or written, --yes included. The hook and the MCP bridge are started by the agent's client
|
|
1202
1207
|
// itself and stay as they are; `status` only reads.
|
|
1203
1208
|
async function main() {
|
|
1209
|
+
if (!moduleArgs || !moduleExecutable) fail("Use the complete WorkTrust package from npm/PyPI or the signed preservation kit; individual scripts cannot run.");
|
|
1204
1210
|
if (Number(process.versions.node.split(".")[0]) < 18) fail("needs Node 18 or later (fetch is built in from 18).");
|
|
1205
1211
|
const AGENT_ENV = ["CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "CODEX_SANDBOX", "CODEX_CI", "GEMINI_CLI", "CURSOR_AGENT", "OPENCODE", "CLINE_ACTIVE", "AIDER_CHAT", "ANTIGRAVITY_AGENT", "WINDSURF_AGENT"];
|
|
1206
1212
|
const PERSON_ONLY = new Set(["default", "connect", "update", "history", "disconnect", "preserve", "codex", "antigravity", "sources", "web", "import", "orchestration", "mod"]);
|
|
@@ -1235,6 +1241,10 @@ async function relayToNewest() {
|
|
|
1235
1241
|
}
|
|
1236
1242
|
if (await relayToNewest()) return;
|
|
1237
1243
|
|
|
1244
|
+
if (!["version", "help", "preserve"].includes(command)) {
|
|
1245
|
+
try { keyStore.load(); }
|
|
1246
|
+
catch { fail("The local WorkTrust key file is unsafe or damaged. Upload stopped. Restore the private key file from your own backup, or reconnect using an official release."); }
|
|
1247
|
+
}
|
|
1238
1248
|
if (command === "version") say(CLI_VERSION);
|
|
1239
1249
|
else if (command === "default") { if (keyStore.load()) await again(); else await connect(); }
|
|
1240
1250
|
else if (command === "mcp") await bridge();
|