fullcourtdefense-cli 1.26.5 → 1.26.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/commands/daemon.d.ts +14 -0
  2. package/dist/commands/daemon.js +181 -28
  3. package/dist/commands/desktopChatGuard.js +5 -4
  4. package/dist/commands/deterministicGuard.d.ts +8 -0
  5. package/dist/commands/deterministicGuard.js +6 -0
  6. package/dist/commands/doctor.d.ts +4 -0
  7. package/dist/commands/doctor.js +99 -0
  8. package/dist/commands/hook.d.ts +1 -0
  9. package/dist/commands/hook.js +25 -2
  10. package/dist/commands/installClaudeHook.d.ts +2 -0
  11. package/dist/commands/installClaudeHook.js +4 -0
  12. package/dist/commands/installCursorHook.d.ts +8 -0
  13. package/dist/commands/installCursorHook.js +5 -0
  14. package/dist/commands/mcpGateway.js +234 -43
  15. package/dist/commands/onboard.d.ts +9 -0
  16. package/dist/commands/onboard.js +7 -0
  17. package/dist/commands/watchdog.d.ts +5 -2
  18. package/dist/commands/watchdog.js +34 -4
  19. package/dist/config.js +6 -1
  20. package/dist/daemonForensics.d.ts +27 -0
  21. package/dist/daemonForensics.js +27 -0
  22. package/dist/distress.d.ts +17 -0
  23. package/dist/distress.js +17 -0
  24. package/dist/hookIo.js +1 -0
  25. package/dist/index.js +6 -0
  26. package/dist/integrity.js +8 -0
  27. package/dist/localSafetySnapshot.d.ts +9 -0
  28. package/dist/localSafetySnapshot.js +58 -2
  29. package/dist/machineIdentity.js +70 -4
  30. package/dist/runtimeConfig.d.ts +12 -0
  31. package/dist/runtimeConfig.js +181 -7
  32. package/dist/selfTest.d.ts +10 -0
  33. package/dist/selfTest.js +21 -8
  34. package/dist/selfUpdate.d.ts +19 -4
  35. package/dist/selfUpdate.js +108 -12
  36. package/dist/telemetry.js +67 -2
  37. package/dist/verdictIpc.js +76 -30
  38. package/dist/verdictIpcClient.d.ts +27 -0
  39. package/dist/verdictIpcClient.js +68 -0
  40. package/dist/version.json +1 -1
  41. package/package.json +5 -1
package/dist/telemetry.js CHANGED
@@ -135,7 +135,19 @@ function spoolEvent(event) {
135
135
  fs.appendFileSync(SPOOL_PATH, JSON.stringify(full) + '\n', { encoding: 'utf-8', mode: 0o600 });
136
136
  enforceSpoolCap();
137
137
  }
138
- catch { /* best-effort */ }
138
+ catch (error) {
139
+ // Telemetry must never break the hook — but a machine that cannot RECORD
140
+ // its decisions (disk full, ACL, AV lock) must not fail silently either:
141
+ // that machine looks identical to a quiet one in the console. The distress
142
+ // ledger is a different file/directory, so it usually still works; lazy
143
+ // require keeps the hook hot path free of the module when spooling is fine.
144
+ try {
145
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
146
+ const { reportDistress, DISTRESS } = require('./distress');
147
+ reportDistress('telemetry', DISTRESS.SPOOL_WRITE_FAILED, error?.message?.slice(0, 200));
148
+ }
149
+ catch { /* truly best-effort */ }
150
+ }
139
151
  }
140
152
  /** Drop-oldest cap so a long-offline machine never grows an unbounded spool. */
141
153
  function enforceSpoolCap() {
@@ -172,12 +184,65 @@ function rewriteSpool(remaining) {
172
184
  fs.unlinkSync(SPOOL_PATH);
173
185
  return;
174
186
  }
175
- fs.writeFileSync(SPOOL_PATH, remaining.map(e => JSON.stringify(e)).join('\n') + '\n', { encoding: 'utf-8', mode: 0o600 });
187
+ // Atomic write-temp-rename: a crash/kill mid-rewrite must never leave a
188
+ // torn spool (half a JSON line poisons readSpool's tail parsing), and a
189
+ // concurrent appendFileSync from a hook lands either before the snapshot
190
+ // or after the rename — never inside a partially written file.
191
+ const tmp = `${SPOOL_PATH}.tmp-${process.pid}`;
192
+ fs.writeFileSync(tmp, remaining.map(e => JSON.stringify(e)).join('\n') + '\n', { encoding: 'utf-8', mode: 0o600 });
193
+ fs.renameSync(tmp, SPOOL_PATH);
176
194
  }
177
195
  catch { /* best-effort */ }
178
196
  }
197
+ // ── Flush lock ───────────────────────────────────────────────────────────────
198
+ // Two flushers CAN overlap (daemon heartbeat flush + a detached critical-block
199
+ // flusher): both would read the same spool, POST the same batch, and race the
200
+ // read-filter-rewrite cycle — the loser's rewrite resurrects events the winner
201
+ // already dropped, or drops events appended in between. The lock makes flushing
202
+ // single-writer; the POST itself is idempotent on eventId so a lost lock only
203
+ // costs a duplicate upload, never data.
204
+ const FLUSH_LOCK = path.join(os.homedir(), '.fullcourtdefense-flush.lock');
205
+ /** A flush attempt is bounded by fetch timeout (≤8s) + I/O; anything older is a crashed flusher. */
206
+ const FLUSH_LOCK_STALE_MS = 2 * 60_000;
207
+ function acquireFlushLock() {
208
+ for (let attempt = 0; attempt < 2; attempt++) {
209
+ try {
210
+ fs.writeFileSync(FLUSH_LOCK, `${process.pid}:${Date.now()}`, { flag: 'wx', encoding: 'utf-8' });
211
+ return true;
212
+ }
213
+ catch {
214
+ try {
215
+ const raw = fs.readFileSync(FLUSH_LOCK, 'utf-8');
216
+ const heldAt = Number(raw.split(':')[1]);
217
+ if (Number.isFinite(heldAt) && Date.now() - heldAt < FLUSH_LOCK_STALE_MS)
218
+ return false;
219
+ fs.unlinkSync(FLUSH_LOCK); // stale holder (crashed flusher) — reclaim
220
+ }
221
+ catch {
222
+ return false; // unreadable/contended — let the other flusher win
223
+ }
224
+ }
225
+ }
226
+ return false;
227
+ }
228
+ function releaseFlushLock() {
229
+ try {
230
+ fs.unlinkSync(FLUSH_LOCK);
231
+ }
232
+ catch { /* already gone */ }
233
+ }
179
234
  /** Drain the spool to the backend in one batch (+ optional heartbeat). Returns accepted count. */
180
235
  async function flushSpool(input) {
236
+ if (!acquireFlushLock())
237
+ return null; // another flusher is draining — its batch covers these events
238
+ try {
239
+ return await flushSpoolLocked(input);
240
+ }
241
+ finally {
242
+ releaseFlushLock();
243
+ }
244
+ }
245
+ async function flushSpoolLocked(input) {
181
246
  // Piggyback on the flush cycle to re-sync terminal guard rule caches (mode flips
182
247
  // + new custom rules reach open shells within ~30s). Loaded lazily: telemetry
183
248
  // sits on the hook hot path (spoolEvent/triggerFlush) and must not drag the
@@ -128,6 +128,12 @@ function startVerdictServer(evaluate, log) {
128
128
  reply({ v: verdictIpcClient_1.VERDICT_IPC_PROTOCOL_VERSION, error: 'unauthorized' });
129
129
  return;
130
130
  }
131
+ // Liveness ping (watchdog hung-daemon check / startup pid-reuse
132
+ // check): answer immediately, never evaluate.
133
+ if (request.ping === true) {
134
+ reply({ v: verdictIpcClient_1.VERDICT_IPC_PROTOCOL_VERSION, pong: true });
135
+ return;
136
+ }
131
137
  try {
132
138
  // Attach the requesting hook's own start time to whatever this
133
139
  // evaluation spools, so fleet telemetry reports the wall time the
@@ -144,42 +150,82 @@ function startVerdictServer(evaluate, log) {
144
150
  })();
145
151
  });
146
152
  });
147
- server.on('error', (err) => {
148
- // EADDRINUSE here means another daemon already serves verdicts — leave
149
- // its token untouched. removeTokenIfOurs is a no-op unless we had already
150
- // published our own token (listen succeeded earlier).
151
- log(`Verdict IPC: server error (${err.message}) — hooks will evaluate locally.`);
152
- removeTokenIfOurs();
153
- });
154
- try {
155
- server.listen(pipePath, () => {
156
- if (process.platform !== 'win32') {
157
- try {
158
- fs.chmodSync(pipePath, 0o600);
159
- }
160
- catch { /* best-effort */ }
153
+ // EADDRINUSE recovery: a wedged predecessor (or a stale unix socket) can
154
+ // hold the endpoint at boot. Giving up permanently downgraded every hook on
155
+ // the machine to the slow local path for the daemon's whole life. Instead,
156
+ // retry on a timer — the kernel frees a Windows named pipe the moment its
157
+ // owner dies (e.g. the watchdog recycles it), and the retry takes over.
158
+ const LISTEN_RETRY_MS = Math.max(100, Number(process.env.FCD_IPC_LISTEN_RETRY_MS) || 60_000);
159
+ let closedByUs = false;
160
+ let retryTimer;
161
+ let retries = 0;
162
+ const onListening = () => {
163
+ if (process.platform !== 'win32') {
164
+ try {
165
+ fs.chmodSync(pipePath, 0o600);
161
166
  }
162
- // Publish the token only now that the pipe is actually owned by us.
167
+ catch { /* best-effort */ }
168
+ }
169
+ if (retries > 0)
170
+ log(`Verdict IPC: endpoint freed after ${retries} retr${retries === 1 ? 'y' : 'ies'} — taking over.`);
171
+ retries = 0;
172
+ // Publish the token only now that the pipe is actually owned by us.
173
+ try {
174
+ fs.mkdirSync((0, verdictIpcClient_1.verdictStateDir)(), { recursive: true });
175
+ fs.writeFileSync((0, verdictIpcClient_1.verdictTokenFile)(), token, { encoding: 'utf8', mode: 0o600 });
176
+ log(`Verdict IPC: serving hook verdicts on ${pipePath} (thin-client hooks, ms verdicts).`);
177
+ }
178
+ catch (err) {
179
+ log(`Verdict IPC: could not write token file (${err instanceof Error ? err.message : String(err)}) — hooks will evaluate locally.`);
163
180
  try {
164
- fs.mkdirSync((0, verdictIpcClient_1.verdictStateDir)(), { recursive: true });
165
- fs.writeFileSync((0, verdictIpcClient_1.verdictTokenFile)(), token, { encoding: 'utf8', mode: 0o600 });
166
- log(`Verdict IPC: serving hook verdicts on ${pipePath} (thin-client hooks, ms verdicts).`);
181
+ server.close();
167
182
  }
168
- catch (err) {
169
- log(`Verdict IPC: could not write token file (${err instanceof Error ? err.message : String(err)}) — hooks will evaluate locally.`);
170
- try {
171
- server.close();
172
- }
173
- catch { /* best-effort */ }
183
+ catch { /* best-effort */ }
184
+ }
185
+ };
186
+ const tryListen = () => {
187
+ try {
188
+ server.listen(pipePath, onListening);
189
+ }
190
+ catch (err) {
191
+ log(`Verdict IPC: listen failed (${err instanceof Error ? err.message : String(err)}) — hooks will evaluate locally.`);
192
+ }
193
+ };
194
+ server.on('error', (err) => {
195
+ // removeTokenIfOurs is a no-op unless we had already published our own
196
+ // token (listen succeeded earlier) — a live daemon's token is untouched.
197
+ removeTokenIfOurs();
198
+ const code = err.code;
199
+ if (!closedByUs && code === 'EADDRINUSE') {
200
+ if (retries === 0) {
201
+ log(`Verdict IPC: endpoint busy (${err.message}) — retrying every ${Math.round(LISTEN_RETRY_MS / 1000)}s until it frees; hooks evaluate locally meanwhile.`);
174
202
  }
175
- });
176
- }
177
- catch (err) {
178
- log(`Verdict IPC: listen failed (${err instanceof Error ? err.message : String(err)}) — hooks will evaluate locally.`);
179
- return undefined;
180
- }
203
+ retries += 1;
204
+ retryTimer = setTimeout(() => {
205
+ if (closedByUs)
206
+ return;
207
+ if (process.platform !== 'win32') {
208
+ // A crashed owner leaves the socket FILE behind; unlink so the
209
+ // retry can bind. The pid lock guarantees no healthy daemon owns it.
210
+ try {
211
+ fs.unlinkSync(pipePath);
212
+ }
213
+ catch { /* not there — fine */ }
214
+ }
215
+ tryListen();
216
+ }, LISTEN_RETRY_MS);
217
+ if (typeof retryTimer.unref === 'function')
218
+ retryTimer.unref();
219
+ return;
220
+ }
221
+ log(`Verdict IPC: server error (${err.message}) — hooks will evaluate locally.`);
222
+ });
223
+ tryListen();
181
224
  return {
182
225
  close() {
226
+ closedByUs = true;
227
+ if (retryTimer)
228
+ clearTimeout(retryTimer);
183
229
  // Remove the token FIRST so new hook processes stop trying the pipe —
184
230
  // but only if it is still ours (a newer daemon may have taken over).
185
231
  removeTokenIfOurs();
@@ -37,6 +37,13 @@ export interface VerdictRequest {
37
37
  * and an old daemon ignores it — same-machine clock, so no skew.
38
38
  */
39
39
  t0?: number;
40
+ /**
41
+ * Liveness ping (watchdog / startup pid-reuse check): the server replies
42
+ * `{ pong: true }` without evaluating anything. Watchdog and daemon always
43
+ * ship in the same build (one install, one scheduled task target), so no
44
+ * cross-version compatibility concern.
45
+ */
46
+ ping?: boolean;
40
47
  }
41
48
  export interface VerdictResponse {
42
49
  v: number;
@@ -46,6 +53,8 @@ export interface VerdictResponse {
46
53
  exitCode?: number;
47
54
  /** Present when the daemon could not evaluate — client falls back locally. */
48
55
  error?: string;
56
+ /** Reply to a liveness ping. */
57
+ pong?: boolean;
49
58
  }
50
59
  /** Result of a client attempt. Anything but 'verdict' → evaluate locally. */
51
60
  export interface VerdictClientResult {
@@ -74,3 +83,21 @@ export declare function verdictPipePath(): string;
74
83
  * still fall back to local evaluation instantly.
75
84
  */
76
85
  export declare function requestDaemonVerdict(args: Record<string, string | undefined>, stdin: string, responseTimeoutMs?: number, clientStartedAt?: number): Promise<VerdictClientResult>;
86
+ /**
87
+ * Liveness probe result for the verdict endpoint:
88
+ * - 'responsive' — something answered on the pipe (any parseable reply,
89
+ * including 'unauthorized': the server is alive).
90
+ * - 'unresponsive' — the endpoint EXISTS (connect succeeded, or the pipe is
91
+ * busy) but nothing answered within the budget. On
92
+ * Windows a named pipe is a kernel object freed when its
93
+ * owner dies, so an existing-but-silent endpoint means a
94
+ * live-but-wedged owner.
95
+ * - 'no-endpoint' — nothing is serving the pipe/socket at all.
96
+ */
97
+ export type VerdictServerProbe = 'responsive' | 'unresponsive' | 'no-endpoint';
98
+ /**
99
+ * Probe the verdict server without evaluating anything. Used by the watchdog
100
+ * (hung-daemon detection) and by daemon startup (pid-reuse detection). Never
101
+ * throws; bounded by `timeoutMs`.
102
+ */
103
+ export declare function probeVerdictServer(timeoutMs?: number): Promise<VerdictServerProbe>;
@@ -38,6 +38,7 @@ exports.verdictStateDir = verdictStateDir;
38
38
  exports.verdictTokenFile = verdictTokenFile;
39
39
  exports.verdictPipePath = verdictPipePath;
40
40
  exports.requestDaemonVerdict = requestDaemonVerdict;
41
+ exports.probeVerdictServer = probeVerdictServer;
41
42
  const fs = __importStar(require("fs"));
42
43
  const net = __importStar(require("net"));
43
44
  const os = __importStar(require("os"));
@@ -181,3 +182,70 @@ function attemptDaemonVerdict(args, stdin, responseTimeoutMs, clientStartedAt) {
181
182
  socket.on('close', () => fail('connection closed'));
182
183
  });
183
184
  }
185
+ /**
186
+ * Probe the verdict server without evaluating anything. Used by the watchdog
187
+ * (hung-daemon detection) and by daemon startup (pid-reuse detection). Never
188
+ * throws; bounded by `timeoutMs`.
189
+ */
190
+ function probeVerdictServer(timeoutMs = 1_500) {
191
+ return new Promise((resolve) => {
192
+ let settled = false;
193
+ let socket;
194
+ const finish = (result) => {
195
+ if (settled)
196
+ return;
197
+ settled = true;
198
+ clearTimeout(timer);
199
+ try {
200
+ socket.destroy();
201
+ }
202
+ catch { /* already gone */ }
203
+ resolve(result);
204
+ };
205
+ const timer = setTimeout(() => finish('unresponsive'), timeoutMs);
206
+ try {
207
+ socket = net.connect({ path: verdictPipePath() });
208
+ }
209
+ catch {
210
+ clearTimeout(timer);
211
+ resolve('no-endpoint');
212
+ return;
213
+ }
214
+ let connected = false;
215
+ socket.on('error', (err) => {
216
+ const code = err.code;
217
+ // EBUSY/EAGAIN: the pipe exists but every instance is taken — an owner
218
+ // exists. Anything else pre-connect (ENOENT, ECONNREFUSED) means no one
219
+ // is serving the endpoint.
220
+ if (code === 'EBUSY' || code === 'EAGAIN' || connected)
221
+ finish('unresponsive');
222
+ else
223
+ finish('no-endpoint');
224
+ });
225
+ socket.on('connect', () => {
226
+ connected = true;
227
+ const token = readToken() || '';
228
+ try {
229
+ socket.write(JSON.stringify({ v: exports.VERDICT_IPC_PROTOCOL_VERSION, token, ping: true, args: {}, stdin: '' }) + '\n');
230
+ }
231
+ catch {
232
+ finish('unresponsive');
233
+ }
234
+ });
235
+ let buffer = '';
236
+ socket.on('data', (chunk) => {
237
+ buffer += chunk.toString('utf8');
238
+ const nl = buffer.indexOf('\n');
239
+ if (nl === -1)
240
+ return;
241
+ try {
242
+ JSON.parse(buffer.slice(0, nl));
243
+ finish('responsive');
244
+ }
245
+ catch {
246
+ finish('unresponsive');
247
+ }
248
+ });
249
+ socket.on('close', () => finish(connected ? 'unresponsive' : 'no-endpoint'));
250
+ });
251
+ }
package/dist/version.json CHANGED
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": "1.26.5"
2
+ "version": "1.26.7"
3
3
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fullcourtdefense-cli",
3
- "version": "1.26.5",
3
+ "version": "1.26.7",
4
4
  "description": "Full Court Defense CLI — security scanning for AI agents from your terminal",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -55,6 +55,10 @@
55
55
  "test:distress-ledger": "npm run build && node scripts/test-distress-ledger.js",
56
56
  "test:poll-loop": "npm run build && node scripts/test-poll-loop-resilience.js",
57
57
  "test:slim-hook": "npm run build && node scripts/test-slim-hook.js",
58
+ "test:killswitch": "npm run build && node scripts/test-killswitch-integrity.js",
59
+ "test:restart-guarantees": "npm run build && node scripts/test-daemon-restart-guarantees.js",
60
+ "test:gateway-secrets": "npm run build && node scripts/test-mcp-gateway-secret-safety.js",
61
+ "test:updater-hold": "npm run build && node scripts/test-updater-hold-resilience.js",
58
62
  "test:deep-selftest": "npm run build && node scripts/test-deep-selftest.js",
59
63
  "test:update-loop": "npm run build && node scripts/test-update-loop-detection.js",
60
64
  "test:bricked-rescue": "npm run build && node scripts/test-bricked-machine-rescue.js",