@lifeaitools/clauth 2.15.3 → 2.15.4

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.
@@ -28,32 +28,31 @@ import { readBody, readRawBody } from "../request-utils.js";
28
28
 
29
29
  const LOG_FILE = path.join(os.tmpdir(), "clauth-serve.log");
30
30
 
31
- function sha256base64url(str) {
32
- return crypto.createHash("sha256").update(str).digest("base64url");
33
- }
34
-
35
- function approvalPage({ approvalId, clientName, scopes, port }) {
36
- const escapedName = String(clientName).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
37
- const scopeList = scopes.map((scope) => `<li>${scope}</li>`).join("") || "<li>mcp:tools</li>";
38
- return `<!doctype html><html><head><meta charset="utf-8"><title>CLAUTH access request</title><meta name="viewport" content="width=device-width,initial-scale=1"><style>body{font-family:system-ui;margin:3rem;max-width:42rem;color:#18251e}button{padding:.7rem 1rem;margin-right:.6rem;font:inherit;border-radius:.45rem}button[name=decision]{background:#164f35;color:white;border:0}button[value=deny]{background:white;color:#8b1d1d;border:1px solid #8b1d1d}#machine{color:#8b5b00}</style></head><body><h1>CLAUTH access request</h1><p><strong>${escapedName}</strong> is requesting access to this machine's MCP services.</p><p>Requested scopes:</p><ul>${scopeList}</ul><p id="machine">Verifying this browser is paired with the enrolled CLAUTH machine…</p><form method="post" action="/authorize/approve"><input type="hidden" name="approval_id" value="${approvalId}"><input id="attestation" type="hidden" name="attestation"><button id="approve" name="decision" value="approve" type="submit" disabled>Approve access</button><button name="decision" value="deny" type="submit">Deny</button></form><script>fetch('http://127.0.0.1:${port}/authorize/attest?approval_id=${approvalId}').then(r=>r.ok?r.json():Promise.reject()).then(x=>{document.querySelector('#attestation').value=x.attestation;document.querySelector('#approve').disabled=false;document.querySelector('#machine').textContent='This browser is paired with the enrolled CLAUTH machine.'}).catch(()=>{document.querySelector('#machine').textContent='Machine verification failed. Open this request on the machine that runs CLAUTH.'})</script></body></html>`;
39
- }
40
-
41
- function attestationFor(ctx, approvalId, nonce) {
42
- if (!ctx.machineAttestationKey) return null;
43
- return crypto.createHmac("sha256", ctx.machineAttestationKey).update(`${ctx.machineHash}:${approvalId}:${nonce}`).digest("base64url");
31
+ // Hosts that bypass OAuth entirely (fresh domains for claude.ai compatibility
32
+ // -- those domains use the tunnel URL itself as a shared secret, like
33
+ // regen-media). Dynamic Client Registration (RFC 7591) must not be reachable
34
+ // on them. This check used to live as a raw if-block in serve.js's if-chain,
35
+ // but the exact-match write-route Map (where these 3 routes now live) is
36
+ // checked BEFORE that if-chain -- so the block never actually ran once these
37
+ // routes moved to the registry, silently exposing /register, /authorize, and
38
+ // /token on the noauth hosts. Restored here, at the point the Map actually
39
+ // intercepts the request.
40
+ const NOAUTH_HOSTS = ["fs.regendevcorp.com", "clauth.regendevcorp.com", "chitchat.regendevcorp.com"];
41
+ function isNoAuthHost(req) {
42
+ const requestHost = (req.headers.host || "").split(":")[0].toLowerCase();
43
+ return NOAUTH_HOSTS.includes(requestHost);
44
44
  }
45
45
 
46
- function issueAuthorizationCode(ctx, request) {
47
- const code = crypto.randomBytes(32).toString("hex");
48
- ctx.oauthCodes.set(code, { ...request, expires: Date.now() + 300_000 });
49
- const redirect = new URL(request.redirect_uri);
50
- redirect.searchParams.set("code", code);
51
- if (request.state) redirect.searchParams.set("state", request.state);
52
- return redirect;
46
+ function sha256base64url(str) {
47
+ return crypto.createHash("sha256").update(str).digest("base64url");
53
48
  }
54
49
 
55
50
  export function registerOAuthRoutes(ctx) {
56
51
  ctx.registerWriteRoute("POST", "/register", async (req, res, url) => {
52
+ if (isNoAuthHost(req)) {
53
+ res.writeHead(404, { "Content-Type": "application/json", ...ctx.CORS });
54
+ return res.end(JSON.stringify({ error: "not_found" }));
55
+ }
57
56
  let body;
58
57
  try { body = await readBody(req); } catch {
59
58
  res.writeHead(400, { "Content-Type": "application/json", ...ctx.CORS });
@@ -78,6 +77,10 @@ export function registerOAuthRoutes(ctx) {
78
77
  return res.end(JSON.stringify(client));
79
78
  });
80
79
  ctx.registerWriteRoute("GET", "/authorize", async (req, res, url) => {
80
+ if (isNoAuthHost(req)) {
81
+ res.writeHead(404, { "Content-Type": "application/json", ...ctx.CORS });
82
+ return res.end(JSON.stringify({ error: "not_found" }));
83
+ }
81
84
  const clientId = url.searchParams.get("client_id");
82
85
  const redirectUri = url.searchParams.get("redirect_uri");
83
86
  const state = url.searchParams.get("state");
@@ -109,66 +112,29 @@ export function registerOAuthRoutes(ctx) {
109
112
  return res.end("redirect_uri mismatch");
110
113
  }
111
114
 
112
- const approvalId = crypto.randomBytes(24).toString("base64url");
113
- const scopes = (url.searchParams.get("scope") || "mcp:tools").split(/\s+/).filter(Boolean);
114
- ctx.oauthApprovals.set(approvalId, {
115
+ // Auto-approve (no user interaction — clauth is a personal vault)
116
+ const code = crypto.randomBytes(32).toString("hex");
117
+ ctx.oauthCodes.set(code, {
115
118
  client_id: clientId,
116
119
  redirect_uri: redirectUri,
117
120
  code_challenge: codeChallenge,
118
- state,
119
- scopes,
120
- machine_id: ctx.machineHash,
121
- expires: Date.now() + 300_000,
121
+ expires: Date.now() + 300_000, // 5 minutes
122
122
  });
123
- const logMsg = `[${new Date().toISOString()}] OAuth: consent requested for ${clientId}\n`;
123
+
124
+ const redirect = new URL(redirectUri);
125
+ redirect.searchParams.set("code", code);
126
+ if (state) redirect.searchParams.set("state", state);
127
+
128
+ const logMsg = `[${new Date().toISOString()}] OAuth: authorize → code for ${clientId}, redirect to ${redirect.origin}\n`;
124
129
  try { fs.appendFileSync(LOG_FILE, logMsg); } catch {}
125
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
126
- const request = ctx.oauthApprovals.get(approvalId);
127
- request.nonce = crypto.randomBytes(24).toString("base64url");
128
- return res.end(approvalPage({ approvalId, clientName: client.client_name, scopes, port: ctx.port }));
129
- });
130
- ctx.registerWriteRoute("GET", "/authorize/attest", async (req, res, url) => {
131
- const host = (req.headers.host || "").split(":")[0].toLowerCase();
132
- if (!["127.0.0.1", "localhost", "::1", "[::1]"].includes(host)) {
133
- res.writeHead(403, { "Content-Type": "application/json" });
134
- return res.end(JSON.stringify({ error: "loopback_required" }));
135
- }
136
- const approvalId = url.searchParams.get("approval_id");
137
- const request = ctx.oauthApprovals.get(approvalId);
138
- const attestation = request && request.expires > Date.now() ? attestationFor(ctx, approvalId, request.nonce) : null;
139
- if (!attestation) {
140
- res.writeHead(400, { "Content-Type": "application/json" });
141
- return res.end(JSON.stringify({ error: "invalid_or_expired_request" }));
142
- }
143
- res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store", "Access-Control-Allow-Origin": req.headers.origin || "null", "Access-Control-Allow-Private-Network": "true" });
144
- return res.end(JSON.stringify({ attestation }));
145
- });
146
- ctx.registerWriteRoute("POST", "/authorize/approve", async (req, res) => {
147
- const raw = await readRawBody(req);
148
- const body = Object.fromEntries(new URLSearchParams(raw));
149
- const request = ctx.oauthApprovals.get(body.approval_id);
150
- ctx.oauthApprovals.delete(body.approval_id);
151
- if (!request || request.expires < Date.now()) {
152
- res.writeHead(400, { "Content-Type": "text/plain" });
153
- return res.end("Authorization request expired or invalid.");
154
- }
155
- const expectedAttestation = request && attestationFor(ctx, body.approval_id, request.nonce);
156
- const presented = Buffer.from(body.attestation || "");
157
- const expected = Buffer.from(expectedAttestation || "");
158
- if (!expected.length || presented.length !== expected.length || !crypto.timingSafeEqual(presented, expected)) {
159
- res.writeHead(403, { "Content-Type": "text/plain" });
160
- return res.end("Machine verification failed.");
161
- }
162
- if (body.decision !== "approve") {
163
- res.writeHead(403, { "Content-Type": "text/plain" });
164
- return res.end("Access denied.");
165
- }
166
- const redirect = issueAuthorizationCode(ctx, request);
167
- operation("oauth.consent_approve", { client_id: request.client_id, scopes: request.scopes }, null, { ok: true });
168
- res.writeHead(302, { Location: redirect.toString(), "Cache-Control": "no-store" });
130
+ res.writeHead(302, { Location: redirect.toString(), "Cache-Control": "no-store", ...ctx.CORS });
169
131
  return res.end();
170
132
  });
171
133
  ctx.registerWriteRoute("POST", "/token", async (req, res, url) => {
134
+ if (isNoAuthHost(req)) {
135
+ res.writeHead(404, { "Content-Type": "application/json", ...ctx.CORS });
136
+ return res.end(JSON.stringify({ error: "not_found" }));
137
+ }
172
138
  let body;
173
139
  const ct = req.headers["content-type"] || "";
174
140
  try {
@@ -229,13 +195,13 @@ export function registerOAuthRoutes(ctx) {
229
195
  // All checks passed — delete code (one-time use) and issue token
230
196
  ctx.oauthCodes.delete(body.code);
231
197
  const accessToken = crypto.randomBytes(32).toString("hex");
232
- ctx.oauthTokens.set(accessToken, { scopes: stored.scopes || ["mcp:tools"], machine_id: stored.machine_id, expires: Date.now() + 86_400_000 });
198
+ ctx.oauthTokens.add(accessToken);
233
199
  ctx.saveTokens(ctx.oauthTokens);
234
200
 
235
201
  const logMsg = `[${new Date().toISOString()}] OAuth: token issued for ${stored.client_id} (token=${accessToken.slice(0,8)}…)\n`;
236
202
  try { fs.appendFileSync(LOG_FILE, logMsg); } catch {}
237
203
  operation("oauth.token_issue", { client_id: stored.client_id }, null, { ok: true });
238
204
  res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store", ...ctx.CORS });
239
- return res.end(JSON.stringify({ access_token: accessToken, token_type: "Bearer", scope: (stored.scopes || ["mcp:tools"]).join(" "), expires_in: 86400 }));
205
+ return res.end(JSON.stringify({ access_token: accessToken, token_type: "Bearer", scope: "mcp:tools", expires_in: 86400 }));
240
206
  });
241
207
  }
@@ -1,7 +1,7 @@
1
1
  // cli/http/components/supervisor-component.js
2
- // The Supervisor-write component: plugin rescan/test/promote, surface
3
- // health probe + surface actions, and tunnel-route CRUD -- all gated by
4
- // hasSupervisorWrite() (the supervisor's own
2
+ // The Supervisor-write component: plugin rescan/enable/disable/test/
3
+ // promote, surface health probe + surface actions, and tunnel-route
4
+ // CRUD -- all gated by hasSupervisorWrite() (the supervisor's own
5
5
  // write-token, a THIRD distinct guard from lockedGuard/writeGuard and
6
6
  // from the ops plane's bearer token), except /v1/surfaces/health which
7
7
  // is deliberately guard-free (read-only health sweep, run whenever the
@@ -16,6 +16,7 @@
16
16
  // every other component this session.
17
17
  import {
18
18
  discoverPlugins,
19
+ setPluginEnabled,
19
20
  runPluginAction,
20
21
  probeAllSurfaceHealth,
21
22
  runSurfaceAction,
@@ -40,17 +41,16 @@ export function registerSupervisorRoutes(ctx) {
40
41
  return ctx.ok(res, discoverPlugins());
41
42
  }
42
43
 
43
- // enable/disable were removed 2026-08-31: the flag they set was pure
44
- // metadata (no process spawn) and never implied a running process --
45
- // starting/stopping a surface always required a separate, unrelated
46
- // action (runSurfaceAction "start"/"restart"). That disconnect made the
47
- // flag actively misleading rather than a real lifecycle control.
48
- const pluginActionMatch = reqPath.match(/^\/v1\/plugins\/([^/]+)\/(test|promote)$/);
49
- if (method === "POST" && pluginActionMatch) {
44
+ const pluginEnableMatch = reqPath.match(/^\/v1\/plugins\/([^/]+)\/(enable|disable|test|promote)$/);
45
+ if (method === "POST" && pluginEnableMatch) {
50
46
  if (!ctx.hasSupervisorWrite(req)) return ctx.rejectSupervisorWrite(res);
51
- const pluginId = decodeURIComponent(pluginActionMatch[1]);
52
- const op = pluginActionMatch[2];
53
- const result = runPluginAction(pluginId, op);
47
+ const pluginId = decodeURIComponent(pluginEnableMatch[1]);
48
+ const op = pluginEnableMatch[2];
49
+ const result = op === "enable"
50
+ ? setPluginEnabled(pluginId, true)
51
+ : op === "disable"
52
+ ? setPluginEnabled(pluginId, false)
53
+ : runPluginAction(pluginId, op);
54
54
  res.writeHead(result.error ? 400 : 200, { "Content-Type": "application/json", ...ctx.CORS });
55
55
  return res.end(JSON.stringify(result));
56
56
  }
@@ -53,116 +53,6 @@ function callbackCall(pm2, method, args = []) {
53
53
  });
54
54
  }
55
55
 
56
- // PM2's own stop/restart/delete callbacks resolve once the daemon has ISSUED
57
- // the kill, not once the OS has actually reclaimed the process -- confirmed
58
- // live 2026-09-04, Windows: a `restart` on a real app left its outgoing
59
- // child alive and still holding its listen port for 1000+ cycles, and a
60
- // plain `stop` right before an `npm install -g` over that same app's
61
- // install directory still hit EBUSY because the "stopped" process was, in
62
- // fact, not. Every caller of this adapter (the ops CLI, ops HTTP surface,
63
- // and every cutover procedure built on top of it) inherits that lie unless
64
- // this file closes it once, here, rather than each caller re-discovering it
65
- // under pressure.
66
- function isAlive(pid) {
67
- if (typeof pid !== "number" || pid <= 0) return false;
68
- try {
69
- process.kill(pid, 0);
70
- return true;
71
- } catch (error) {
72
- // ESRCH: no such process -- genuinely gone. Anything else (EPERM, etc.)
73
- // means the OS still has an opinion about this pid, so it isn't safe to
74
- // call it dead.
75
- return error.code !== "ESRCH";
76
- }
77
- }
78
-
79
- // pm2's own death check on Windows is also parent-pid-only (God.processIsDead
80
- // reads pm2_env._tree_pids || [pid], and treekill's taskkill callback reports
81
- // only the pid it was given) -- so a spawned-child topology like clauth's own
82
- // next-runner fixture can have its child survive everything pm2 itself
83
- // thinks killed it. Capture _tree_pids alongside pid so this adapter isn't
84
- // blind to exactly the shape its own fixtures use.
85
- function pidsOf(processes) {
86
- return (Array.isArray(processes) ? processes : [processes])
87
- .flatMap((entry) => [entry?.pid, ...(entry?.pm2_env?._tree_pids || [])])
88
- .filter((pid) => typeof pid === "number" && pid > 0);
89
- }
90
-
91
- const DEATH_TIMEOUT_MS = 3000;
92
- const KILL_TIMEOUT_MS = 1000;
93
-
94
- // describe() resolving with [] IS the normal "no such app" case -- do not
95
- // mask that behind a try/catch that also swallows a real RPC/transport
96
- // failure. A caller that can't see whether the old process is still alive
97
- // must not silently report success; let it fail loudly instead.
98
- function pidsFor(pm2, target) {
99
- return callbackCall(pm2, "describe", [target]).then(pidsOf);
100
- }
101
-
102
- async function waitForDeath(pids, { pollMs = 150, timeoutMs = DEATH_TIMEOUT_MS } = {}) {
103
- const deadline = Date.now() + timeoutMs;
104
- let survivors = pids.filter(isAlive);
105
- while (survivors.length > 0 && Date.now() < deadline) {
106
- await new Promise((resolve) => setTimeout(resolve, pollMs));
107
- survivors = survivors.filter(isAlive);
108
- }
109
- return survivors;
110
- }
111
-
112
- // Verifies the pids captured BEFORE a stop/restart/reload/delete are
113
- // actually gone afterward, escalating to SIGKILL (TerminateProcess on
114
- // Windows, same as POSIX SIGKILL) if PM2's own signal didn't finish the job
115
- // within the timeout. Only throws if a process survives an explicit SIGKILL,
116
- // which should not happen -- if it does, the caller needs to know its
117
- // "stop" silently didn't, rather than proceed as though it did. The thrown
118
- // error carries the surviving pids as structured fields (not just in the
119
- // message) so a caller logging/job-recording the failure can act on them
120
- // even after this operation's own bookkeeping (e.g. a deleted pm2 record)
121
- // is gone.
122
- async function verifyTerminated(target, oldPids, operation) {
123
- if (oldPids.length === 0) return;
124
- const survivors = await waitForDeath(oldPids);
125
- if (survivors.length === 0) return;
126
- console.error(
127
- `[ops] pm2 ${operation} "${target}" did not stop pid(s) ${survivors.join(", ")} within ${DEATH_TIMEOUT_MS}ms -- force-killing`,
128
- );
129
- for (const pid of survivors) {
130
- try {
131
- process.kill(pid, "SIGKILL");
132
- } catch {
133
- // Already gone between the check and the kill -- fine.
134
- }
135
- }
136
- const stillAlive = await waitForDeath(survivors, { timeoutMs: KILL_TIMEOUT_MS });
137
- if (stillAlive.length > 0) {
138
- const error = new Error(
139
- `pm2 ${operation} "${target}": pid(s) ${stillAlive.join(", ")} survived SIGKILL -- refusing to report success`,
140
- );
141
- error.pids = stillAlive;
142
- error.operation = operation;
143
- error.target = target;
144
- error.reason = "survived_sigkill";
145
- throw error;
146
- }
147
- }
148
-
149
- // restart/reload spawn the replacement BEFORE the pm2 callback this adapter
150
- // awaits resolves (confirmed against pm2's own God.restartProcessId, and
151
- // reload falls through to the identical path outside cluster_mode -- which
152
- // is every app this control plane manages). So by the time verification
153
- // starts, a genuinely new process can already exist, and on Windows a freed
154
- // pid can be reallocated to it inside the same poll window this adapter is
155
- // watching. Re-describing AFTER the operation and only verifying death for
156
- // pids no longer reported as current tells the two apart: a truly orphaned
157
- // old pid is never in the fresh describe and still gets killed; a pid pm2
158
- // still reports as live is never touched, whether that's because pm2
159
- // genuinely didn't rotate it or because it now belongs to the new process.
160
- async function survivorsOf(pm2, target, oldPids) {
161
- if (oldPids.length === 0) return [];
162
- const currentPids = new Set(await pidsFor(pm2, target));
163
- return oldPids.filter((pid) => !currentPids.has(pid));
164
- }
165
-
166
56
  function normalizeProcess(process) {
167
57
  if (!process || typeof process !== "object") return process;
168
58
  return {
@@ -211,43 +101,10 @@ export function createPm2Adapter(pm2) {
211
101
  case "logs": return (await callbackCall(pm2, "describe", [missing(input.target, "target")])).map(normalizeProcess);
212
102
  case "bus": return callbackCall(pm2, "launchBus");
213
103
  case "start": return callbackCall(pm2, "start", [missing(input.script, "script"), input.options || {}]);
214
- case "stop": {
215
- const target = missing(input.target, "target");
216
- const oldPids = await pidsFor(pm2, target);
217
- const result = await callbackCall(pm2, "stop", [target]);
218
- await verifyTerminated(target, oldPids, "stop");
219
- return result;
220
- }
221
- case "restart": {
222
- const target = missing(input.target, "target");
223
- const oldPids = await pidsFor(pm2, target);
224
- const result = await callbackCall(pm2, "restart", [target, input.options || {}]);
225
- await verifyTerminated(target, await survivorsOf(pm2, target, oldPids), "restart");
226
- return result;
227
- }
228
- case "reload": {
229
- // Fork mode -- every app this control plane manages -- makes
230
- // reload identical to restart inside pm2 (God.reloadProcessId only
231
- // takes the cluster branch in cluster_mode; everything else falls
232
- // straight through to God.restartProcessId). clauth's own deploy
233
- // cutover (deployment-adapter.js) calls this operation, not
234
- // "restart" -- so this is the actual path "install then hit
235
- // restart, pm2 should pick up the new one" travels in production,
236
- // and it needs the identical guarantee, not a lighter one because
237
- // the pm2 verb sounds gentler.
238
- const target = missing(input.target, "target");
239
- const oldPids = await pidsFor(pm2, target);
240
- const result = await callbackCall(pm2, "reload", [target, input.options || {}]);
241
- await verifyTerminated(target, await survivorsOf(pm2, target, oldPids), "reload");
242
- return result;
243
- }
244
- case "delete": {
245
- const target = missing(input.target, "target");
246
- const oldPids = await pidsFor(pm2, target);
247
- const result = await callbackCall(pm2, "delete", [target]);
248
- await verifyTerminated(target, oldPids, "delete");
249
- return result;
250
- }
104
+ case "stop": return callbackCall(pm2, "stop", [missing(input.target, "target")]);
105
+ case "restart": return callbackCall(pm2, "restart", [missing(input.target, "target"), input.options || {}]);
106
+ case "reload": return callbackCall(pm2, "reload", [missing(input.target, "target"), input.options || {}]);
107
+ case "delete": return callbackCall(pm2, "delete", [missing(input.target, "target")]);
251
108
  case "scale": return callbackCall(pm2, "scale", [missing(input.target, "target"), missing(input.instances, "instances")]);
252
109
  case "reset": return callbackCall(pm2, "reset", [missing(input.target, "target")]);
253
110
  case "dump": return callbackCall(pm2, "dump");
@@ -4,7 +4,6 @@
4
4
  // git-exec.js/fs-upload-sessions.js — these are file-content concerns, not
5
5
  // mount-resolution concerns.
6
6
 
7
- import fsSync from "node:fs";
8
7
  import path from "node:path";
9
8
  import crypto from "node:crypto";
10
9
  import { mkdir, writeFile, rename, stat, readFile } from "node:fs/promises";
@@ -13,33 +12,16 @@ export function sha256Hex(value) {
13
12
  return crypto.createHash("sha256").update(value).digest("hex");
14
13
  }
15
14
 
16
- function atomicTempPath(filePath) {
17
- return path.join(
15
+ export async function atomicWriteText(filePath, content) {
16
+ await mkdir(path.dirname(filePath), { recursive: true });
17
+ const tempPath = path.join(
18
18
  path.dirname(filePath),
19
19
  `.${path.basename(filePath)}.tmp-${process.pid}-${Date.now()}-${crypto.randomBytes(4).toString("hex")}`
20
20
  );
21
- }
22
-
23
- export async function atomicWriteText(filePath, content) {
24
- await mkdir(path.dirname(filePath), { recursive: true });
25
- const tempPath = atomicTempPath(filePath);
26
21
  await writeFile(tempPath, content, "utf8");
27
22
  await rename(tempPath, filePath);
28
23
  }
29
24
 
30
- // Sync twin of atomicWriteText -- same mkdir+temp+write+rename contract, for
31
- // callers that can't be async (e.g. cli/supervisor-registry.js's mutators,
32
- // all currently synchronous). Identified as a needed pairing rather than a
33
- // fourth independent reimplementation of this pattern (also hand-rolled in
34
- // cli/ops/job-store.js and standalone/fs-mcp/lib/webdav-config.js) by a peer
35
- // review of the commit that first needed it.
36
- export function atomicWriteTextSync(filePath, content) {
37
- fsSync.mkdirSync(path.dirname(filePath), { recursive: true });
38
- const tempPath = atomicTempPath(filePath);
39
- fsSync.writeFileSync(tempPath, content, "utf8");
40
- fsSync.renameSync(tempPath, filePath);
41
- }
42
-
43
25
  export async function fileInfo(filePath, requestedPath) {
44
26
  const s = await stat(filePath);
45
27
  const info = {
@@ -1,42 +1,10 @@
1
1
  import test from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import fs from "node:fs";
4
- import os from "node:os";
5
- import path from "node:path";
6
3
 
7
- import { sha256Hex, atomicWriteTextSync } from "./file-io.js";
4
+ import { sha256Hex } from "./file-io.js";
8
5
 
9
6
  test("sha256Hex hashes deterministically", () => {
10
7
  assert.equal(sha256Hex("hello"), sha256Hex("hello"));
11
8
  assert.notEqual(sha256Hex("hello"), sha256Hex("world"));
12
9
  assert.match(sha256Hex("hello"), /^[0-9a-f]{64}$/);
13
10
  });
14
-
15
- // atomicWriteTextSync is the sync twin of atomicWriteText, added so
16
- // cli/supervisor-registry.js's (synchronous) writeJson could reuse this
17
- // module's atomic-write contract instead of hand-rolling a fourth
18
- // independent copy of it (peer-review finding, 2026-09-02).
19
- test("atomicWriteTextSync creates the target file with the given content, creating parent dirs as needed", () => {
20
- const root = fs.mkdtempSync(path.join(os.tmpdir(), "clauth-atomic-write-"));
21
- try {
22
- const target = path.join(root, "nested", "dir", "file.txt");
23
- atomicWriteTextSync(target, "hello world");
24
- assert.equal(fs.readFileSync(target, "utf8"), "hello world");
25
- } finally {
26
- fs.rmSync(root, { recursive: true, force: true });
27
- }
28
- });
29
-
30
- test("atomicWriteTextSync replaces existing content and leaves no temp file behind", () => {
31
- const root = fs.mkdtempSync(path.join(os.tmpdir(), "clauth-atomic-write-"));
32
- try {
33
- const target = path.join(root, "file.txt");
34
- atomicWriteTextSync(target, "first");
35
- atomicWriteTextSync(target, "second");
36
- assert.equal(fs.readFileSync(target, "utf8"), "second");
37
- const leftovers = fs.readdirSync(root).filter((name) => name !== "file.txt");
38
- assert.deepEqual(leftovers, [], `expected no stray temp files, found: ${JSON.stringify(leftovers)}`);
39
- } finally {
40
- fs.rmSync(root, { recursive: true, force: true });
41
- }
42
- });