worktrust 0.10.35 → 0.10.37
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/AGENTS.md +1 -1
- package/README.md +47 -1
- package/SECURITY.md +63 -1
- package/chat-exports.mjs +281 -54
- package/config-edits.mjs +25 -0
- package/count-behaviour.mjs +8 -3
- package/engine-release.json +1 -1
- package/history-outbox.mjs +75 -16
- package/history-progress.mjs +141 -0
- package/log-session.mjs +39 -36
- package/package-release.json +1 -1
- package/package.json +4 -2
- package/preserve.mjs +4 -3
- package/self-update.mjs +274 -0
- package/setup-mcp.mjs +6 -4
- package/worktrust.mjs +309 -44
package/self-update.mjs
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* UPDATING ITSELF WHEN THE PERSON TURNS IT ON (owner, 2026-11-05; CLI 0.10.37). The ONE place this CLI installs code
|
|
3
|
+
* without a person typing a command, and only on that person's own act: turning CLI active back on for this computer in
|
|
4
|
+
* Sources (set_my_computer_measure, a resume from a pause this computer had confirmed). WorkTrust's door answer
|
|
5
|
+
* (api/cli/door) then carries a one-shot instruction `{ version, at }`: the version WorkTrust names from the published
|
|
6
|
+
* npm release, `at` the moment of that resume, which is the instruction's id. A version string alone never starts it:
|
|
7
|
+
* no instruction, no install, and the same id is never handled twice.
|
|
8
|
+
*
|
|
9
|
+
* WHAT RUNS, AND ONLY WHEN EVERYTHING HOLDS (SECURITY.md "Updating itself when you turn it on"):
|
|
10
|
+
* 1. the method: this CLI runs from the verified npm copy in ~/.worktrust/verified (the launcher checked it); Python
|
|
11
|
+
* installations and anything else update by the person's own command and report `python` / `unsupported`;
|
|
12
|
+
* 2. the version is NEWER than this CLI (never equal, never a downgrade: `current`);
|
|
13
|
+
* 3. npm beside the running Node (else the first on PATH) is 11.12.0 or later, the first that lists the attestations it
|
|
14
|
+
* verified (`audit signatures --include-attestations`); an older one is `unsupported` before anything is fetched;
|
|
15
|
+
* 4. THE COMPUTER'S OWN POLICY, not the server's (review M1): npm's registry record names <version> as `latest` and does
|
|
16
|
+
* not deprecate it (a version the console classes critical is deprecated on npm too: tools/worktrust-release/README);
|
|
17
|
+
* 5. `npm install --ignore-scripts` of exactly worktrust@<version> from registry.npmjs.org into a fresh staging folder
|
|
18
|
+
* (nothing of the package runs during install);
|
|
19
|
+
* 6. `npm audit signatures` there: the registry signature and the Sigstore attestations, verified BY NPM against its own
|
|
20
|
+
* trust roots and relayed here; the SLSA provenance's certificate must name
|
|
21
|
+
* github.com/fhomey/worktrust-cli/.github/workflows/publish.yml at tag v<version> and carry GitHub Actions' OIDC
|
|
22
|
+
* issuer in Fulcio's extension 1.3.6.1.4.1.57264.1.8, its DSSE signature verify under it, its subject be this exact
|
|
23
|
+
* tarball (sha512 of the lockfile);
|
|
24
|
+
* 7. WorkTrust's own release signature (package-release.json) under the key pinned in THIS CLI, naming <version>: the
|
|
25
|
+
* binding root, which needs neither npm's word nor WorkTrust's server;
|
|
26
|
+
* 8. only then: the verified copy is installed beside the current one, and the NEW launcher (which verifies itself
|
|
27
|
+
* again) runs `update --yes`: what was agreed before is refreshed, nothing new is coupled, no history is sent.
|
|
28
|
+
* A failed check leaves the running CLI as it is and reports a code (`unverified` or `failed`), never content, on the
|
|
29
|
+
* next door call. It runs detached from the hook, under a lock, and logs to ~/.worktrust/update.log on this computer only.
|
|
30
|
+
*/
|
|
31
|
+
import { spawn } from "node:child_process";
|
|
32
|
+
import { X509Certificate, verify as verifySignature } from "node:crypto";
|
|
33
|
+
import { appendFileSync, closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
34
|
+
import { delimiter, dirname, isAbsolute, join } from "node:path";
|
|
35
|
+
|
|
36
|
+
/** The closed list of outcomes reported back as `worktrust-update/<code>.<id>` (mcp_identify knows the same list). */
|
|
37
|
+
export const UPDATE_RESULTS = ["installed", "current", "python", "unsupported", "unverified", "failed"];
|
|
38
|
+
export const REGISTRY = "https://registry.npmjs.org/";
|
|
39
|
+
export const REPOSITORY = "https://github.com/fhomey/worktrust-cli";
|
|
40
|
+
export const WORKFLOW = ".github/workflows/publish.yml";
|
|
41
|
+
export const OIDC_ISSUER = "https://token.actions.githubusercontent.com";
|
|
42
|
+
const SLSA = "https://slsa.dev/provenance/v1";
|
|
43
|
+
const VERSION = /^\d{1,4}\.\d{1,4}\.\d{1,4}$/;
|
|
44
|
+
/** An attempt that has not finished in half an hour died (a closed lid, a killed process): it counts as failed, once. */
|
|
45
|
+
const STALE_MS = 30 * 60_000;
|
|
46
|
+
/** The first npm whose `audit signatures --include-attestations` lists the bundles it verified (review M2). */
|
|
47
|
+
export const NPM_SINCE = "11.12.0";
|
|
48
|
+
|
|
49
|
+
/** Fulcio's OIDC issuer extension, 1.3.6.1.4.1.57264.1.8, as its DER OID bytes. */
|
|
50
|
+
const FULCIO_ISSUER_OID = Buffer.from([0x2b, 0x06, 0x01, 0x04, 0x01, 0x83, 0xbf, 0x30, 0x01, 0x08]);
|
|
51
|
+
/** One DER element at `at`: its tag, where its content starts and ends. Null when it does not fit. */
|
|
52
|
+
function der(bytes, at) {
|
|
53
|
+
if (at + 2 > bytes.length) return null;
|
|
54
|
+
const tag = bytes[at]; let length = bytes[at + 1], start = at + 2;
|
|
55
|
+
if (length & 0x80) { const count = length & 0x7f; if (count === 0 || count > 4 || start + count > bytes.length) return null; length = 0; for (let i = 0; i < count; i += 1) length = length * 256 + bytes[start + i]; start += count; }
|
|
56
|
+
return start + length > bytes.length ? null : { tag, start, end: start + length };
|
|
57
|
+
}
|
|
58
|
+
function children(bytes, item) { const out = []; for (let at = item.start; at < item.end;) { const child = der(bytes, at); if (!child) return null; out.push(child); at = child.end; } return out; }
|
|
59
|
+
/** The issuer Fulcio wrote into the certificate's own extension (a DER UTF8String), or null: never a byte string elsewhere. */
|
|
60
|
+
export function fulcioIssuer(raw) {
|
|
61
|
+
const certificate = der(raw, 0), tbs = certificate && children(raw, certificate)?.[0];
|
|
62
|
+
const holder = tbs && children(raw, tbs)?.find((item) => item.tag === 0xa3);
|
|
63
|
+
const list = holder && children(raw, holder)?.[0];
|
|
64
|
+
const found = [];
|
|
65
|
+
for (const extension of (list && children(raw, list)) ?? []) {
|
|
66
|
+
const parts = children(raw, extension);
|
|
67
|
+
if (!parts || parts[0]?.tag !== 0x06 || !raw.subarray(parts[0].start, parts[0].end).equals(FULCIO_ISSUER_OID)) continue;
|
|
68
|
+
const octets = parts.at(-1), value = octets?.tag === 0x04 ? der(raw, octets.start) : null;
|
|
69
|
+
found.push(value?.tag === 0x0c && value.end === octets.end ? raw.subarray(value.start, value.end).toString("utf8") : null);
|
|
70
|
+
}
|
|
71
|
+
return found.length === 1 ? found[0] : null;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function newerThan(a, b) {
|
|
75
|
+
const x = a.split(".").map(Number), y = b.split(".").map(Number);
|
|
76
|
+
for (let i = 0; i < 3; i += 1) if (x[i] !== y[i]) return x[i] > y[i];
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The instruction in a door answer, `{ id, version }`, or null: an id is the resume moment in whole seconds. */
|
|
81
|
+
export function updateOffer(update) {
|
|
82
|
+
if (!update || typeof update !== "object" || typeof update.version !== "string" || !VERSION.test(update.version) || typeof update.at !== "string") return null;
|
|
83
|
+
const id = Math.floor(Date.parse(update.at) / 1000);
|
|
84
|
+
return Number.isSafeInteger(id) && id > 0 ? { id, version: update.version } : null;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* THE ONE DECISION, given an instruction (tools/worktrust-release/update-policy.mjs `resumePolicy` says the same;
|
|
89
|
+
* scripts/test-cli-self-update.mjs holds them equal). Only the verified npm copy installs, and only a newer version.
|
|
90
|
+
*/
|
|
91
|
+
export function resumeDecision({ method, current, version }) {
|
|
92
|
+
if (!VERSION.test(version ?? "") || !VERSION.test(current ?? "")) return { install: false, outcome: "failed" };
|
|
93
|
+
if (!newerThan(version, current)) return { install: false, outcome: "current" };
|
|
94
|
+
if (method === "npm") return { install: true, outcome: null };
|
|
95
|
+
if (method === "python") return { install: false, outcome: "python" };
|
|
96
|
+
return { install: false, outcome: "unsupported" };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The outcome to report for the state kept in update.json; null while an attempt waits or runs. */
|
|
100
|
+
export function updateResult(state, now = Date.now()) {
|
|
101
|
+
if (!state || !Number.isSafeInteger(state.id)) return null;
|
|
102
|
+
if (UPDATE_RESULTS.includes(state.state)) return state.state;
|
|
103
|
+
if (["pending", "running"].includes(state.state) && !(now - Date.parse(state.at ?? "") <= STALE_MS)) return "failed";
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* WHAT NPM VERIFIED, BOUND TO OUR PUBLISHER. npm has already checked the registry signature and the attestation bundles
|
|
109
|
+
* (certificate chain to Sigstore's root, transparency log, signatures); this names whose they are. Null when everything
|
|
110
|
+
* holds, else a short reason for the local log (never sent).
|
|
111
|
+
*/
|
|
112
|
+
export function provenanceProblem({ audit, auditCode, lock, version }) {
|
|
113
|
+
if (auditCode !== 0) return "audit-exit";
|
|
114
|
+
if (!audit || !Array.isArray(audit.invalid) || !Array.isArray(audit.missing) || audit.invalid.length > 0 || audit.missing.length > 0) return "audit-invalid";
|
|
115
|
+
const packages = lock?.packages;
|
|
116
|
+
if (!packages || typeof packages !== "object" || Object.keys(packages).sort().join(",") !== ",node_modules/worktrust") return "lock-shape";
|
|
117
|
+
const entry = packages["node_modules/worktrust"];
|
|
118
|
+
if (entry?.version !== version || entry.resolved !== `${REGISTRY}worktrust/-/worktrust-${version}.tgz` || !/^sha512-[A-Za-z0-9+/]{86}==$/.test(entry.integrity ?? "")) return "lock-entry";
|
|
119
|
+
const digest = Buffer.from(entry.integrity.slice(7), "base64").toString("hex");
|
|
120
|
+
const verified = (Array.isArray(audit.verified) ? audit.verified : []).filter((one) => one?.name === "worktrust" && one.version === version && one.location === "node_modules/worktrust");
|
|
121
|
+
if (verified.length !== 1) return "not-verified";
|
|
122
|
+
const bundles = (Array.isArray(verified[0].attestationBundles) ? verified[0].attestationBundles : []).filter((one) => one?.predicateType === SLSA);
|
|
123
|
+
if (bundles.length !== 1) return "no-provenance";
|
|
124
|
+
const bundle = bundles[0].bundle;
|
|
125
|
+
const raw = bundle?.verificationMaterial?.certificate?.rawBytes ?? bundle?.verificationMaterial?.x509CertificateChain?.certificates?.[0]?.rawBytes;
|
|
126
|
+
let certificate;
|
|
127
|
+
try { certificate = new X509Certificate(Buffer.from(String(raw), "base64")); } catch { return "certificate"; }
|
|
128
|
+
if (certificate.subjectAltName !== `URI:${REPOSITORY}/${WORKFLOW}@refs/tags/v${version}`) return "identity";
|
|
129
|
+
if (fulcioIssuer(certificate.raw) !== OIDC_ISSUER) return "issuer";
|
|
130
|
+
const envelope = bundle.dsseEnvelope;
|
|
131
|
+
if (envelope?.payloadType !== "application/vnd.in-toto+json" || typeof envelope.payload !== "string" || !Array.isArray(envelope.signatures) || envelope.signatures.length !== 1) return "envelope";
|
|
132
|
+
const body = Buffer.from(envelope.payload, "base64");
|
|
133
|
+
const signedBytes = Buffer.concat([Buffer.from(`DSSEv1 ${Buffer.byteLength(envelope.payloadType)} ${envelope.payloadType} ${body.length} `), body]);
|
|
134
|
+
let signed = false;
|
|
135
|
+
try { signed = verifySignature("sha256", signedBytes, certificate.publicKey, Buffer.from(String(envelope.signatures[0].sig), "base64")); } catch { signed = false; }
|
|
136
|
+
if (!signed) return "signature";
|
|
137
|
+
let statement;
|
|
138
|
+
try { statement = JSON.parse(body.toString("utf8")); } catch { return "statement"; }
|
|
139
|
+
if (statement?.predicateType !== SLSA || !Array.isArray(statement.subject) || statement.subject.length !== 1) return "statement";
|
|
140
|
+
const [subject] = statement.subject;
|
|
141
|
+
if (subject?.name !== `pkg:npm/worktrust@${version}` || subject.digest?.sha512 !== digest) return "subject";
|
|
142
|
+
const workflow = statement.predicate?.buildDefinition?.externalParameters?.workflow;
|
|
143
|
+
if (workflow?.repository !== REPOSITORY || workflow.path !== WORKFLOW || workflow.ref !== `refs/tags/v${version}`) return "workflow";
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* npm: the one beside the running Node first (its own installation: <prefix>/lib/node_modules/npm, or on Windows
|
|
149
|
+
* <dir>/node_modules/npm), run under this Node; else the first on PATH (absolute directories only). On Windows the
|
|
150
|
+
* npm-cli.js runs under this Node: a .cmd needs a shell.
|
|
151
|
+
*/
|
|
152
|
+
export function findNpm(env = process.env, platform = process.platform, node = process.execPath) {
|
|
153
|
+
const beside = platform === "win32" ? join(dirname(node), "node_modules", "npm", "bin", "npm-cli.js") : join(dirname(node), "..", "lib", "node_modules", "npm", "bin", "npm-cli.js");
|
|
154
|
+
if (existsSync(beside)) return { command: node, prefix: [beside] };
|
|
155
|
+
for (const dir of String(env.PATH ?? env.Path ?? "").split(delimiter).filter((one) => one && isAbsolute(one))) {
|
|
156
|
+
if (platform === "win32") {
|
|
157
|
+
const cli = join(dir, "node_modules", "npm", "bin", "npm-cli.js");
|
|
158
|
+
if (existsSync(join(dir, "npm.cmd")) && existsSync(cli)) return { command: process.execPath, prefix: [cli] };
|
|
159
|
+
} else if (existsSync(join(dir, "npm"))) return { command: join(dir, "npm"), prefix: [] };
|
|
160
|
+
}
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function runProcess(command, args, { env, cwd, timeout }) {
|
|
165
|
+
return new Promise((resolve) => {
|
|
166
|
+
let out = "", err = "", settled = false;
|
|
167
|
+
const finish = (code) => { if (!settled) { settled = true; clearTimeout(timer); resolve({ code, out, err }); } };
|
|
168
|
+
let child;
|
|
169
|
+
try { child = spawn(command, args, { cwd, env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true }); } catch { resolve({ code: -1, out, err }); return; }
|
|
170
|
+
const timer = setTimeout(() => { try { child.kill("SIGKILL"); } catch { /* gone */ } }, timeout);
|
|
171
|
+
child.stdout.on("data", (chunk) => { if (out.length < 8 << 20) out += chunk; });
|
|
172
|
+
child.stderr.on("data", (chunk) => { if (err.length < 65536) err += chunk; });
|
|
173
|
+
child.on("error", () => finish(-1));
|
|
174
|
+
child.on("close", (code) => finish(code ?? -1));
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** One line per event, on this computer only: versions, codes and a short reason; never a key or a path of the person's. */
|
|
179
|
+
function logger(home) {
|
|
180
|
+
const file = join(home, "update.log");
|
|
181
|
+
return (...words) => {
|
|
182
|
+
try {
|
|
183
|
+
if (existsSync(file) && statSync(file).size > 256 * 1024) writeFileSync(file, readFileSync(file, "utf8").slice(-64 * 1024), { mode: 0o600 });
|
|
184
|
+
appendFileSync(file, `${new Date().toISOString()} ${words.join(" ").replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, 600)}\n`, { mode: 0o600 });
|
|
185
|
+
} catch { /* a log that cannot be written changes nothing */ }
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function takeLock(path) {
|
|
190
|
+
for (let tries = 0; tries < 2; tries += 1) {
|
|
191
|
+
try { closeSync(openSync(path, "wx", 0o600)); return () => rmSync(path, { force: true }); }
|
|
192
|
+
catch (error) {
|
|
193
|
+
if (error?.code !== "EEXIST") return null;
|
|
194
|
+
try { if (Date.now() - statSync(path).mtimeMs > STALE_MS) { rmSync(path, { force: true }); continue; } } catch { continue; }
|
|
195
|
+
return null;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* The detached run the hook starts (`worktrust self-update`). `options`: home (~/.worktrust), method ("npm" | "python" |
|
|
203
|
+
* "unknown"), current (this CLI's version), readState / saveState (update.json), verifyPackage / installSignedPackage
|
|
204
|
+
* (this CLI's package-integrity, its pinned release key), nodeArgs (Node flags for the new launcher), agentEnv (the agent
|
|
205
|
+
* markers left out of the update's environment), env.
|
|
206
|
+
*/
|
|
207
|
+
export async function runSelfUpdate(options) {
|
|
208
|
+
const { home } = options;
|
|
209
|
+
const release = takeLock(join(home, "update.lock"));
|
|
210
|
+
if (!release) return null;
|
|
211
|
+
const log = logger(home);
|
|
212
|
+
try {
|
|
213
|
+
const state = options.readState();
|
|
214
|
+
if (state?.state !== "pending" || !Number.isSafeInteger(state.id)) return null;
|
|
215
|
+
// COMPARE AND SET (review L4): an outcome is written only while the stored instruction is still the one that started.
|
|
216
|
+
const save = (next) => { if (options.readState()?.id === state.id) options.saveState(next); };
|
|
217
|
+
// CONSUMED BEFORE ANYTHING RUNS: whatever happens next, this instruction is never taken again.
|
|
218
|
+
save({ state: "running", at: new Date().toISOString() });
|
|
219
|
+
log("start", `id=${state.id}`, `from=${options.current}`, `to=${state.version}`, `method=${options.method}`);
|
|
220
|
+
let outcome;
|
|
221
|
+
try { outcome = await attempt(options, state.version, log); } catch (error) { log("error", String(error?.message ?? error).slice(0, 200)); outcome = "failed"; }
|
|
222
|
+
save({ state: outcome, at: new Date().toISOString() });
|
|
223
|
+
log("result", outcome);
|
|
224
|
+
return outcome;
|
|
225
|
+
} finally { release(); }
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
async function attempt(options, version, log) {
|
|
229
|
+
const decision = resumeDecision({ method: options.method, current: options.current, version });
|
|
230
|
+
if (!decision.install) return decision.outcome;
|
|
231
|
+
const env = options.env ?? process.env;
|
|
232
|
+
const npm = findNpm(env);
|
|
233
|
+
if (!npm) { log("no-npm"); return "unsupported"; }
|
|
234
|
+
const quiet = Object.fromEntries(Object.entries(env).filter(([name]) => !(options.agentEnv ?? []).includes(name)));
|
|
235
|
+
const said = await runProcess(npm.command, [...npm.prefix, "--version"], { env: quiet, cwd: options.home, timeout: 30_000 });
|
|
236
|
+
const npmVersion = /^(\d{1,4}\.\d{1,4}\.\d{1,4})/.exec(said.out.trim())?.[1] ?? null;
|
|
237
|
+
if (said.code !== 0 || !npmVersion || newerThan(NPM_SINCE, npmVersion)) { log("unsupported", "npm-old", `npm=${npmVersion ?? "unknown"}`, `needs=${NPM_SINCE}`); return "unsupported"; }
|
|
238
|
+
// THE COMPUTER'S OWN POLICY (review M1): whatever the door names, only npm's `latest`, and never a deprecated version.
|
|
239
|
+
const viewed = await runProcess(npm.command, [...npm.prefix, "view", `worktrust@${version}`, "--json", `--registry=${REGISTRY}`], { env: quiet, cwd: options.home, timeout: 60_000 });
|
|
240
|
+
if (viewed.code !== 0) { log("view", `exit=${viewed.code}`, viewed.err.slice(-200)); return "failed"; }
|
|
241
|
+
let record = null;
|
|
242
|
+
try { record = JSON.parse(viewed.out); } catch { record = null; }
|
|
243
|
+
if (record?.version !== version || record?.["dist-tags"]?.latest !== version) { log("unverified", "not-latest", `latest=${String(record?.["dist-tags"]?.latest ?? "unknown").slice(0, 20)}`); return "unverified"; }
|
|
244
|
+
if (record.deprecated) { log("unverified", "deprecated"); return "unverified"; }
|
|
245
|
+
const stages = join(options.home, "update-stage");
|
|
246
|
+
mkdirSync(stages, { recursive: true, mode: 0o700 });
|
|
247
|
+
const stage = mkdtempSync(join(stages, "run-"));
|
|
248
|
+
try {
|
|
249
|
+
writeFileSync(join(stage, "package.json"), `${JSON.stringify({ name: "worktrust-update-stage", version: "0.0.0", private: true })}\n`, { mode: 0o600 });
|
|
250
|
+
const common = ["--prefix", stage, `--registry=${REGISTRY}`];
|
|
251
|
+
const installed = await runProcess(npm.command, [...npm.prefix, "install", ...common, "--ignore-scripts", "--no-audit", "--no-fund", "--save-exact", `worktrust@${version}`], { env: quiet, cwd: stage, timeout: 180_000 });
|
|
252
|
+
if (installed.code !== 0) { log("install", `exit=${installed.code}`, installed.err.slice(-300)); return "failed"; }
|
|
253
|
+
const audited = await runProcess(npm.command, [...npm.prefix, "audit", "signatures", ...common, "--json", "--include-attestations"], { env: quiet, cwd: stage, timeout: 120_000 });
|
|
254
|
+
let audit = null, lock = null;
|
|
255
|
+
try { audit = JSON.parse(audited.out); } catch { audit = null; }
|
|
256
|
+
try { lock = JSON.parse(readFileSync(join(stage, "package-lock.json"), "utf8")); } catch { lock = null; }
|
|
257
|
+
const problem = provenanceProblem({ audit, auditCode: audited.code, lock, version });
|
|
258
|
+
if (problem) { log("unverified", problem); return "unverified"; }
|
|
259
|
+
const unpacked = join(stage, "node_modules", "worktrust");
|
|
260
|
+
let launcher;
|
|
261
|
+
try {
|
|
262
|
+
const checked = options.verifyPackage(unpacked);
|
|
263
|
+
if (checked?.manifest?.version !== version) { log("unverified", "release-version"); return "unverified"; }
|
|
264
|
+
launcher = options.installSignedPackage(unpacked, options.home);
|
|
265
|
+
} catch (error) { log("unverified", String(error?.message ?? "release-signature").slice(0, 80)); return "unverified"; }
|
|
266
|
+
// THE NEW CLI DOES THE SWITCH, as `npx worktrust update --yes` would: agreed entries refreshed, nothing new coupled.
|
|
267
|
+
const switched = await runProcess(process.execPath, [...(options.nodeArgs ?? []), launcher, "update", "--yes"], { env: { ...quiet, WORKTRUST_RELAYED: "1" }, cwd: options.home, timeout: 600_000 });
|
|
268
|
+
if (switched.code !== 0) { log("switch", `exit=${switched.code}`, switched.err.slice(-300)); return "failed"; }
|
|
269
|
+
return "installed";
|
|
270
|
+
} finally {
|
|
271
|
+
// A folder that cannot be removed now (Windows: a file still open, EBUSY) changes no outcome (review L5).
|
|
272
|
+
try { rmSync(stage, { recursive: true, force: true }); } catch (error) { log("cleanup", String(error?.code ?? "error")); }
|
|
273
|
+
}
|
|
274
|
+
}
|
package/setup-mcp.mjs
CHANGED
|
@@ -19,7 +19,7 @@ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync
|
|
|
19
19
|
import { spawnSync } from "node:child_process";
|
|
20
20
|
import { homedir, platform } from "node:os";
|
|
21
21
|
import { dirname, join } from "node:path";
|
|
22
|
-
import { isWorkTrustDoor, placeUnder, takeOut } from "./config-edits.mjs";
|
|
22
|
+
import { doorSnapshot, isWorkTrustDoor, placeUnder, putDoorsBack, takeOut } from "./config-edits.mjs";
|
|
23
23
|
|
|
24
24
|
const args = process.argv.slice(2);
|
|
25
25
|
const value = (name) => { const i = args.indexOf(`--${name}`); return i >= 0 ? args[i + 1] : undefined; };
|
|
@@ -214,9 +214,9 @@ const CLIENTS = [
|
|
|
214
214
|
{ key: "claude", label: "Claude Code", present: () => existsSync(join(home, ".claude.json")), file: join(home, ".claude.json"), shape: "claude" },
|
|
215
215
|
];
|
|
216
216
|
|
|
217
|
+
if (args.includes("--snapshot") || args.includes("--restore")) { if (args.includes("--snapshot")) console.log(JSON.stringify(doorSnapshot([...CLIENTS.filter((client) => !["claude", "openclaw"].includes(client.shape) && client.present()).map((client) => client.file), OPENCODE_PLUGIN], join(home, ".claude.json"), NAME))); else putDoorsBack(readFileSync(0, "utf8"), NAME, claudeOnPath() ? (verb) => runCommand("claude", verb).status === 0 : null); process.exit(0); } // a failed run's doors put back (security review L3; config-edits.mjs)
|
|
217
218
|
console.log(`WorkTrust MCP ${REMOVE ? "removal" : "setup"} · door ${new URL(URL_).host} · token ${masked} · ${WRITE ? "WRITING" : "dry run — add --write to write"}`);
|
|
218
|
-
let touched = 0;
|
|
219
|
-
let standing = 0;
|
|
219
|
+
let touched = 0, standing = 0;
|
|
220
220
|
for (const client of CLIENTS) {
|
|
221
221
|
if (!client.present()) { console.log(` – ${client.label}: not on this machine`); continue; }
|
|
222
222
|
if (SKIP.has(client.label)) { console.log(` · ${client.label}: left as it is (not agreed yet)`); continue; }
|
|
@@ -260,7 +260,9 @@ for (const client of CLIENTS) {
|
|
|
260
260
|
}
|
|
261
261
|
const text = existsSync(client.file) ? readFileSync(client.file, "utf8") : "";
|
|
262
262
|
// With the bridge, coupled means the bridge is in AND no entry with a key in it is left beside it.
|
|
263
|
-
|
|
263
|
+
// A TOML'S SERVER TABLES ONLY (2026-10-31): Codex's `notify` names the same launcher, and read as "already there" it left Codex doorless.
|
|
264
|
+
const doorText = client.shape === "toml" ? (text.match(/\n?\[mcp_servers\.[^\n]*\][\s\S]*?(?=\n\[|$)/g) ?? []).join("\n") : text;
|
|
265
|
+
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 ? doorText.includes(URL_) || /worktrust(?:-launch)?\.(?:mjs|py)/.test(doorText) : BRIDGE !== undefined ? doorText.includes(JSON.stringify(BRIDGE).slice(1, -1)) && !doorText.includes(URL_) : doorText.includes(URL_);
|
|
264
266
|
// THE WAY OUT, ON THE MACHINE. Uncoupling in the app ends the TOKEN; the config that names the
|
|
265
267
|
// door stays behind on every client here, so the next person to read this file believes the
|
|
266
268
|
// machine is coupled. `--remove` takes the entry out; the account side is a separate act and
|