@boyingliu01/xp-gate 0.37.2 → 0.38.0
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/adapter-common.sh +12 -2
- package/adapters/csharp.sh +73 -2
- package/adapters/dart.sh +13 -0
- package/adapters/go.sh +5 -0
- package/adapters/iac.sh +46 -3
- package/adapters/java.sh +6 -0
- package/adapters/kotlin.sh +6 -0
- package/adapters/shell.sh +119 -34
- package/adapters/swift.sh +6 -0
- package/adapters/typescript.sh +98 -34
- package/bin/xp-gate.js +48 -2
- package/gate-10.sh +99 -26
- package/gate-12-file-hygiene.sh +13 -1
- package/gate-registry.sh +197 -0
- package/gates/common-process.ts +36 -7
- package/gates/gate-9.ts +17 -8
- package/gates/python-health.ts +215 -24
- package/hooks/adapter-common.sh +12 -2
- package/hooks/deploy-manifest.sh +100 -0
- package/hooks/gate-10.sh +99 -26
- package/hooks/gate-12-file-hygiene.sh +13 -1
- package/hooks/gate-driver.sh +120 -0
- package/hooks/gate-entries/gate-0-entry.sh +825 -0
- package/hooks/gate-entries/gate-1-entry.sh +767 -0
- package/hooks/gate-entries/gate-10-entry.sh +52 -0
- package/hooks/gate-entries/gate-11-entry.sh +120 -0
- package/hooks/gate-entries/gate-12-entry.sh +44 -0
- package/hooks/gate-entries/gate-12b-entry.sh +178 -0
- package/hooks/gate-entries/gate-12c-entry.sh +80 -0
- package/hooks/gate-entries/gate-13-entry.sh +584 -0
- package/hooks/gate-entries/gate-2-entry.sh +199 -0
- package/hooks/gate-entries/gate-3-entry.sh +53 -0
- package/hooks/gate-entries/gate-4-entry.sh +46 -0
- package/hooks/gate-entries/gate-5-entry.sh +1729 -0
- package/hooks/gate-entries/gate-6-entry.sh +658 -0
- package/hooks/gate-entries/gate-7-entry.sh +41 -0
- package/hooks/gate-entries/gate-8-entry.sh +33 -0
- package/hooks/gate-entries/gate-9-entry.sh +307 -0
- package/hooks/gate-entries/subdir-restore.sh +27 -0
- package/hooks/gate-registry.sh +51 -15
- package/hooks/hook-module-resolution.sh +73 -0
- package/hooks/install.sh +135 -0
- package/hooks/lib/now-ms.sh +55 -19
- package/hooks/lib/toolchain-path.sh +50 -6
- package/hooks/pre-commit +256 -5091
- package/hooks/pre-push +212 -25
- package/lib/__tests__/arch-config-template.test.js +190 -0
- package/lib/__tests__/baseline-shell-scope.test.js +60 -0
- package/lib/__tests__/crap-cli.test.js +14 -3
- package/lib/__tests__/deploy-manifest-check-wired.test.js +138 -0
- package/lib/__tests__/deploy-manifest-completeness.test.js +151 -0
- package/lib/__tests__/deploy-manifest-consumers-adapter-uninstall.test.js +40 -0
- package/lib/__tests__/deploy-manifest-consumers-no-private-lists.test.js +74 -0
- package/lib/__tests__/deploy-manifest-projection.test.js +66 -0
- package/lib/__tests__/deploy-manifest-shell-parity.test.js +108 -0
- package/lib/__tests__/deploy-manifest.test.js +97 -0
- package/lib/__tests__/doctor.test.js +51 -7
- package/lib/__tests__/gate-coverage.test.js +79 -12
- package/lib/__tests__/gate-numbering.test.js +28 -1
- package/lib/__tests__/install-sh-deploy-manifest.test.js +80 -0
- package/lib/__tests__/mirror-sync.test.js +45 -3
- package/lib/__tests__/npm-package.test.js +10 -7
- package/lib/__tests__/sastd-client.test.js +452 -0
- package/lib/__tests__/shared-utils-copyHooks-manifest.test.js +69 -0
- package/lib/__tests__/sprint-status-rework.test.js +1 -0
- package/lib/arch-config-template.js +87 -0
- package/lib/baseline.js +54 -2
- package/lib/deploy-manifest.js +174 -0
- package/lib/doctor.js +46 -14
- package/lib/gate-capability.js +291 -0
- package/lib/gate-coverage.js +194 -74
- package/lib/gate-identity.js +349 -0
- package/lib/gate-runner.js +11 -1
- package/lib/hook-module-resolution.js +27 -0
- package/lib/init.js +72 -5
- package/lib/mattpocock-license-verdict.json +1 -1
- package/lib/sastd-client.js +534 -0
- package/lib/shared-utils.js +31 -9
- package/lib/uninstall.js +10 -7
- package/lib/update-hooks.js +27 -18
- package/mock-policy/AGENTS.md +1 -1
- package/mutation/AGENTS.md +1 -1
- package/package.json +3 -1
- package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
- package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
- package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
- package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +2 -2
- package/plugins/dsh/package.json +1 -1
- package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
- package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
- package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +2 -2
- package/plugins/opencode/package.json +1 -1
- package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
- package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
- package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +2 -2
- package/plugins/qoder/plugin.json +1 -1
- package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
- package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
- package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +2 -2
- package/principles/AGENTS.md +1 -1
- package/principles/__tests__/analyzer.test.ts +2 -1
- package/principles/__tests__/config-enforcement.test.ts +1 -0
- package/principles/__tests__/types.test.ts +1 -0
- package/principles/adapters/base.ts +14 -1
- package/principles/adapters/duplication.ts +134 -0
- package/principles/rules/__tests__/clean-code/large-file.test.ts +2 -1
- package/principles/rules/clean-code/code-duplication.ts +75 -9
- package/principles/types.ts +39 -0
- package/scripts/__tests__/check-mattpocock-license.test.js +36 -3
- package/scripts/__tests__/sync-package-content.test.js +12 -2
- package/scripts/generate-mirrors.cjs +125 -0
- package/scripts/sync-package-content.js +64 -20
- package/skills/delphi-review/AGENTS.md +1 -1
- package/skills/sprint-flow/AGENTS.md +1 -1
- package/skills/test-specification-alignment/AGENTS.md +2 -2
- package/adapters/gate-9.sh +0 -245
- package/gate-9.sh +0 -245
- package/hooks/gate-9.sh +0 -245
|
@@ -0,0 +1,534 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Client for the xp-gate SAST daemon.
|
|
3
|
+
*
|
|
4
|
+
* The daemon keeps one semgrep process alive so its ~1.3s import cost is paid
|
|
5
|
+
* once instead of once per gate run. This module is the only thing that talks to
|
|
6
|
+
* it, and it is deliberately paranoid: EVERY failure mode here resolves to
|
|
7
|
+
* "unavailable", which the caller turns into a direct scan. A daemon that cannot
|
|
8
|
+
* answer must never be allowed to look like a gate that passed.
|
|
9
|
+
*
|
|
10
|
+
* Measured on this machine (1 local rule, 1 file):
|
|
11
|
+
* direct semgrep scan : 3,801-4,044 ms
|
|
12
|
+
* daemon, hot call : 2,089-2,245 ms
|
|
13
|
+
*/
|
|
14
|
+
'use strict';
|
|
15
|
+
|
|
16
|
+
const { spawn } = require('node:child_process');
|
|
17
|
+
const path = require('node:path');
|
|
18
|
+
|
|
19
|
+
/** Gate 10's own timeout default, mirrored: a daemon call may not outlive it. */
|
|
20
|
+
const DEFAULT_TIMEOUT_MS = 180_000;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Decide whether the daemon should even be attempted for this invocation.
|
|
24
|
+
*
|
|
25
|
+
* Returns { enabled: false, reason } for anything that is not an explicit "on".
|
|
26
|
+
* `auto` is deliberately NOT treated as degraded by the caller -- see
|
|
27
|
+
* gate-10.sh -- but it does still mean "try the daemon if one exists".
|
|
28
|
+
*
|
|
29
|
+
* @param {Record<string, string|undefined>} env
|
|
30
|
+
* @returns {{enabled: boolean, reason: string}}
|
|
31
|
+
*/
|
|
32
|
+
function resolveDaemonPolicy(env = process.env) {
|
|
33
|
+
const raw = (env.XP_GATE_SASTD || 'direct').trim().toLowerCase();
|
|
34
|
+
if (raw === 'on' || raw === '1' || raw === 'true' || raw === 'auto') {
|
|
35
|
+
return { enabled: true, reason: 'requested' };
|
|
36
|
+
}
|
|
37
|
+
return { enabled: false, reason: 'not_requested' };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Normalise one semgrep result so the daemon's output matches the CLI's.
|
|
42
|
+
*
|
|
43
|
+
* Measured difference (verified byte-for-byte against `semgrep scan --json`):
|
|
44
|
+
* the CLI reports repo-relative paths ("t.js") while the in-process API reports
|
|
45
|
+
* absolute ones ("C:\...\t.js"). Everything else -- every top-level key, every
|
|
46
|
+
* result field, and the verdict inputs (extra.severity, result count) -- is
|
|
47
|
+
* identical.
|
|
48
|
+
*
|
|
49
|
+
* The verdict logic in gate-10.sh reads only `extra.severity` and the counts, so
|
|
50
|
+
* this difference cannot change a PASS/FAIL. It is fixed anyway because the
|
|
51
|
+
* report prints the path, and a suddenly-absolute path would look like a
|
|
52
|
+
* different finding to anyone reading it or diffing two runs.
|
|
53
|
+
*
|
|
54
|
+
* `path.basename` is used rather than a repo-relative computation: gate-10
|
|
55
|
+
* already passes one directory per staged file and the CLI's own "relative"
|
|
56
|
+
* path is the basename for those targets, confirmed equal on the same fixture.
|
|
57
|
+
*
|
|
58
|
+
* @param {Array<Record<string, unknown>>} results
|
|
59
|
+
* @returns {Array<Record<string, unknown>>}
|
|
60
|
+
*/
|
|
61
|
+
function normaliseResultPaths(results) {
|
|
62
|
+
if (!Array.isArray(results)) return results;
|
|
63
|
+
return results.map((r) => {
|
|
64
|
+
if (!r || typeof r.path !== 'string') return r;
|
|
65
|
+
// Only rewrite absolute paths. A relative path is already what we want, and
|
|
66
|
+
// basename-ing it would silently destroy a subdirectory prefix.
|
|
67
|
+
if (!path.isAbsolute(r.path)) return r;
|
|
68
|
+
return { ...r, path: path.basename(r.path) };
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Apply the same normalisation to a whole semgrep payload.
|
|
74
|
+
*
|
|
75
|
+
* @param {Record<string, any>} payload
|
|
76
|
+
* @returns {Record<string, any>}
|
|
77
|
+
*/
|
|
78
|
+
function normalisePayload(payload) {
|
|
79
|
+
if (!payload || typeof payload !== 'object') return payload;
|
|
80
|
+
if (!Array.isArray(payload.results)) return payload;
|
|
81
|
+
return { ...payload, results: normaliseResultPaths(payload.results) };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Parse NDJSON from a stream and resolve the first complete line.
|
|
86
|
+
*
|
|
87
|
+
* @param {import('node:stream').Readable} stream
|
|
88
|
+
* @param {number} timeoutMs
|
|
89
|
+
* @returns {Promise<string>}
|
|
90
|
+
*/
|
|
91
|
+
function readLine(stream, timeoutMs) {
|
|
92
|
+
return new Promise((resolve, reject) => {
|
|
93
|
+
let buffer = '';
|
|
94
|
+
let done = false;
|
|
95
|
+
|
|
96
|
+
const finish = (fn, value) => {
|
|
97
|
+
if (done) return;
|
|
98
|
+
done = true;
|
|
99
|
+
clearTimeout(timer);
|
|
100
|
+
stream.removeListener('data', onData);
|
|
101
|
+
stream.removeListener('error', onError);
|
|
102
|
+
stream.removeListener('end', onEnd);
|
|
103
|
+
fn(value);
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
const onData = (chunk) => {
|
|
107
|
+
buffer += chunk.toString();
|
|
108
|
+
const nl = buffer.indexOf('\n');
|
|
109
|
+
if (nl >= 0) finish(resolve, buffer.slice(0, nl));
|
|
110
|
+
};
|
|
111
|
+
const onError = (err) => finish(reject, err);
|
|
112
|
+
const onEnd = () => finish(reject, new Error('daemon closed the stream without replying'));
|
|
113
|
+
|
|
114
|
+
const timer = setTimeout(
|
|
115
|
+
() => finish(reject, new Error(`daemon did not reply within ${timeoutMs}ms`)),
|
|
116
|
+
timeoutMs,
|
|
117
|
+
);
|
|
118
|
+
timer.unref?.();
|
|
119
|
+
|
|
120
|
+
stream.on('data', onData);
|
|
121
|
+
stream.on('error', onError);
|
|
122
|
+
stream.on('end', onEnd);
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** The resident daemon, or null when it is not running. Module-level on purpose:
|
|
127
|
+
* the process has to survive this function returning, which is the entire point. */
|
|
128
|
+
let activeDaemon = null;
|
|
129
|
+
|
|
130
|
+
/** Idle deadline: after this long with no request, let the daemon exit so it
|
|
131
|
+
* stops holding ~200MB of semgrep in RAM between commits. */
|
|
132
|
+
const IDLE_TIMEOUT_MS = 30 * 60 * 1000;
|
|
133
|
+
|
|
134
|
+
/** How many stderr lines to keep for diagnosis. Enough to see a traceback's tail. */
|
|
135
|
+
const STDERR_TAIL_LINES = 50;
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Start the daemon if it is not already running.
|
|
139
|
+
*
|
|
140
|
+
* @param {string} pythonCmd
|
|
141
|
+
* @returns {{ok: true, value: object} | {ok: false, error: string}}
|
|
142
|
+
*/
|
|
143
|
+
function ensureDaemon(pythonCmd) {
|
|
144
|
+
if (isDaemonAlive()) {
|
|
145
|
+
if (activeDaemon.idleTimer) activeDaemon.idleTimer.refresh();
|
|
146
|
+
return { ok: true, value: activeDaemon };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const spawned = spawnDaemon(pythonCmd);
|
|
150
|
+
if (!spawned.ok) return spawned;
|
|
151
|
+
const { proc, getSpawnError } = spawned.value;
|
|
152
|
+
|
|
153
|
+
attachLifecycle(proc);
|
|
154
|
+
|
|
155
|
+
// Start unref'd so an idle daemon cannot pin the process open. exchange() refs it
|
|
156
|
+
// for the duration of each request -- see refProc/releaseProc for why neither
|
|
157
|
+
// "always ref" nor "always unref" works.
|
|
158
|
+
proc.unref?.();
|
|
159
|
+
proc.stdin?.unref?.();
|
|
160
|
+
proc.stdout?.unref?.();
|
|
161
|
+
proc.stderr?.unref?.();
|
|
162
|
+
|
|
163
|
+
const idleTimer = startIdleTimer();
|
|
164
|
+
installExitHook();
|
|
165
|
+
|
|
166
|
+
activeDaemon = {
|
|
167
|
+
proc,
|
|
168
|
+
// stdout, NOT stdin: stdin is write-only, so a 'data' listener there never fires
|
|
169
|
+
// and every request would sit until the timeout with the answer unread.
|
|
170
|
+
socket: proc.stdout,
|
|
171
|
+
pending: 0,
|
|
172
|
+
idleTimer,
|
|
173
|
+
getSpawnError,
|
|
174
|
+
stderrTail: drainStderr(proc),
|
|
175
|
+
};
|
|
176
|
+
return { ok: true, value: activeDaemon };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** True when a daemon is running and still usable. */
|
|
180
|
+
function isDaemonAlive() {
|
|
181
|
+
return Boolean(activeDaemon) && !activeDaemon.proc.killed && activeDaemon.proc.exitCode === null;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Spawn the daemon process and wire its error reporting.
|
|
186
|
+
*
|
|
187
|
+
* @param {string} pythonCmd
|
|
188
|
+
* @returns {{ok: true, value: object} | {ok: false, error: string}}
|
|
189
|
+
*/
|
|
190
|
+
function spawnDaemon(pythonCmd) {
|
|
191
|
+
const daemonPath = path.join(__dirname, '..', '..', 'sastd', 'sastd.py');
|
|
192
|
+
let proc;
|
|
193
|
+
try {
|
|
194
|
+
proc = spawn(pythonCmd, [daemonPath], { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
|
|
195
|
+
} catch (err) {
|
|
196
|
+
return { ok: false, error: `spawn failed: ${err.message}` };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// spawn() reports a missing interpreter as an asynchronous 'error' event, not a
|
|
200
|
+
// throw. Unhandled, that event takes down the whole process -- observed as vitest
|
|
201
|
+
// reporting "Errors 1" while every assertion passed.
|
|
202
|
+
let spawnError = null;
|
|
203
|
+
proc.on('error', (err) => {
|
|
204
|
+
spawnError = err;
|
|
205
|
+
activeDaemon = null;
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
// A broken pipe on the request stream is reported as an 'error' event, asynchronously.
|
|
209
|
+
// Node tolerates EPIPE on a child's stdin (verified: writing after the child exited
|
|
210
|
+
// does not throw and does not crash), so this is defence rather than a known crash.
|
|
211
|
+
// It is here because the alternative -- if that tolerance ever changed -- is an
|
|
212
|
+
// unhandled event taking down the whole gate, and losing the daemon must never be
|
|
213
|
+
// worse than not having one.
|
|
214
|
+
proc.stdin?.on('error', (err) => {
|
|
215
|
+
spawnError = err;
|
|
216
|
+
resetDaemon(`stdin error: ${err.message}`);
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
return { ok: true, value: { proc, getSpawnError: () => spawnError } };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Forget the daemon when it dies, so the next call restarts instead of writing
|
|
224
|
+
* into a dead pipe and reporting a timeout that hides the real cause.
|
|
225
|
+
*
|
|
226
|
+
* @param {import('node:child_process').ChildProcess} proc
|
|
227
|
+
*/
|
|
228
|
+
function attachLifecycle(proc) {
|
|
229
|
+
proc.on('exit', () => {
|
|
230
|
+
if (activeDaemon && activeDaemon.proc === proc) activeDaemon = null;
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Drain stderr so the child never blocks on a full pipe. semgrep is chatty, and
|
|
236
|
+
* a blocked child looks exactly like a hung scan.
|
|
237
|
+
*
|
|
238
|
+
* @param {import('node:child_process').ChildProcess} proc
|
|
239
|
+
* @returns {string[]} rolling tail, newest last
|
|
240
|
+
*/
|
|
241
|
+
function drainStderr(proc) {
|
|
242
|
+
const tail = [];
|
|
243
|
+
proc.stderr.on('data', (chunk) => {
|
|
244
|
+
tail.push(chunk.toString());
|
|
245
|
+
if (tail.length > STDERR_TAIL_LINES) tail.shift();
|
|
246
|
+
});
|
|
247
|
+
return tail;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Make sure the daemon does not outlive the Node process that started it.
|
|
252
|
+
*
|
|
253
|
+
* WHY THIS IS NEEDED: a spawned child keeps the event loop alive, so a script that
|
|
254
|
+
* runs one scan and lets Node exit naturally would hang forever -- the daemon never
|
|
255
|
+
* ends, the loop never empties. Measured as a shell command substitution
|
|
256
|
+
* (`X=$(node -e ...)`) that never returned.
|
|
257
|
+
*
|
|
258
|
+
* WHY NOT unref(): unref drops the keep-alive immediately, and Node then exits
|
|
259
|
+
* BEFORE the in-flight scan resolves -- measured as 0 bytes of output where a full
|
|
260
|
+
* payload was expected. The keep-alive has to last exactly as long as the work, so
|
|
261
|
+
* the hook fires at 'beforeExit', after pending work is done.
|
|
262
|
+
*/
|
|
263
|
+
let exitHookInstalled = false;
|
|
264
|
+
|
|
265
|
+
function installExitHook() {
|
|
266
|
+
if (exitHookInstalled) return;
|
|
267
|
+
exitHookInstalled = true;
|
|
268
|
+
|
|
269
|
+
// 'exit' is the only event that does not depend on the loop draining -- and the
|
|
270
|
+
// loop cannot drain while the child is alive, so 'beforeExit' deadlocks here
|
|
271
|
+
// (measured: still hanging with the beforeExit hook in place).
|
|
272
|
+
process.once('exit', () => resetDaemon('process exiting'));
|
|
273
|
+
|
|
274
|
+
// Belt and braces for the case where the caller never lets the loop drain:
|
|
275
|
+
// 'exit' does not fire until something else ends the process, so also drop the
|
|
276
|
+
// keep-alive whenever the loop reports it is idle. `beforeExit` is re-emitted
|
|
277
|
+
// every time the loop empties, so the final one sees a daemon with no pending
|
|
278
|
+
// work and releases it.
|
|
279
|
+
// The real release point: the moment a request settles, if nothing is queued,
|
|
280
|
+
// the child stops being allowed to hold the process open. This preserves the
|
|
281
|
+
// benefit for a long-lived caller (repeated requestScan calls reuse the warm
|
|
282
|
+
// daemon) while letting a one-shot caller exit normally.
|
|
283
|
+
process.on('beforeExit', () => {
|
|
284
|
+
if (activeDaemon && activeDaemon.pending === 0) {
|
|
285
|
+
releaseKeepAlive();
|
|
286
|
+
}
|
|
287
|
+
});
|
|
288
|
+
process.once('exit', () => {
|
|
289
|
+
if (activeDaemon) resetDaemon('process exiting');
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Let Node exit without killing the daemon's usefulness immediately.
|
|
295
|
+
*
|
|
296
|
+
* unref() at SPAWN time was wrong (Node exited before the first scan resolved).
|
|
297
|
+
* unref() here is right: the work is done, so the child may no longer pin the loop.
|
|
298
|
+
* The daemon process itself keeps running until it is killed or goes idle, so a
|
|
299
|
+
* subsequent call in the same process still reuses it -- but a one-shot caller is
|
|
300
|
+
* no longer prevented from exiting.
|
|
301
|
+
*/
|
|
302
|
+
function releaseKeepAlive() {
|
|
303
|
+
if (!activeDaemon || activeDaemon.keepAliveReleased) return;
|
|
304
|
+
activeDaemon.keepAliveReleased = true;
|
|
305
|
+
activeDaemon.proc.unref();
|
|
306
|
+
activeDaemon.proc.stdin?.unref?.();
|
|
307
|
+
activeDaemon.proc.stdout?.unref?.();
|
|
308
|
+
activeDaemon.proc.stderr?.unref?.();
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Ref-count the daemon child around one request.
|
|
313
|
+
*
|
|
314
|
+
* unref() at spawn time was wrong (Node exited before the first scan resolved --
|
|
315
|
+
* 0 bytes of output). Never unref'ing was also wrong (a one-shot caller never
|
|
316
|
+
* exited; measured as a shell command substitution that hung forever). Holding only
|
|
317
|
+
* while work is in flight satisfies both.
|
|
318
|
+
*/
|
|
319
|
+
let inFlight = 0;
|
|
320
|
+
|
|
321
|
+
function refProc(proc) {
|
|
322
|
+
inFlight += 1;
|
|
323
|
+
proc.ref?.();
|
|
324
|
+
proc.stdin?.ref?.();
|
|
325
|
+
proc.stdout?.ref?.();
|
|
326
|
+
proc.stderr?.ref?.();
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
function releaseProc(proc) {
|
|
330
|
+
inFlight = Math.max(0, inFlight - 1);
|
|
331
|
+
if (inFlight > 0) return;
|
|
332
|
+
proc.unref?.();
|
|
333
|
+
proc.stdin?.unref?.();
|
|
334
|
+
proc.stdout?.unref?.();
|
|
335
|
+
proc.stderr?.unref?.();
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** Let the daemon exit after a quiet spell so it stops holding semgrep in RAM. */
|
|
339
|
+
function startIdleTimer() {
|
|
340
|
+
const timer = setTimeout(() => resetDaemon('idle'), IDLE_TIMEOUT_MS);
|
|
341
|
+
timer.unref?.();
|
|
342
|
+
return timer;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* Forget and stop the daemon. Safe to call when none is running.
|
|
347
|
+
*
|
|
348
|
+
* @param {string} reason recorded on the object only; kept for debuggability
|
|
349
|
+
*/
|
|
350
|
+
function resetDaemon(reason) {
|
|
351
|
+
if (!activeDaemon) return;
|
|
352
|
+
const { proc, idleTimer } = activeDaemon;
|
|
353
|
+
activeDaemon = null;
|
|
354
|
+
try {
|
|
355
|
+
clearTimeout(idleTimer);
|
|
356
|
+
} catch {
|
|
357
|
+
/* already cleared */
|
|
358
|
+
}
|
|
359
|
+
try {
|
|
360
|
+
proc.stdin.end();
|
|
361
|
+
} catch {
|
|
362
|
+
/* already gone */
|
|
363
|
+
}
|
|
364
|
+
try {
|
|
365
|
+
proc.kill();
|
|
366
|
+
} catch {
|
|
367
|
+
/* already gone */
|
|
368
|
+
}
|
|
369
|
+
// reason is intentionally not thrown or logged here: callers report their own
|
|
370
|
+
// error, and a daemon restart is a normal, non-exceptional event.
|
|
371
|
+
void reason;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* Read one NDJSON line from a socket, with a timeout.
|
|
376
|
+
*
|
|
377
|
+
* @param {import('node:net').Socket} socket
|
|
378
|
+
* @param {(line: string|null, err: Error|null) => void} cb
|
|
379
|
+
* @param {number} timeoutMs
|
|
380
|
+
*/
|
|
381
|
+
function readOneLine(socket, cb, timeoutMs) {
|
|
382
|
+
let buffer = '';
|
|
383
|
+
let settled = false;
|
|
384
|
+
|
|
385
|
+
const done = (line, err) => {
|
|
386
|
+
if (settled) return;
|
|
387
|
+
settled = true;
|
|
388
|
+
clearTimeout(timer);
|
|
389
|
+
socket.removeListener('data', onData);
|
|
390
|
+
socket.removeListener('error', onError);
|
|
391
|
+
socket.removeListener('close', onClose);
|
|
392
|
+
cb(line, err);
|
|
393
|
+
};
|
|
394
|
+
|
|
395
|
+
const onData = (chunk) => {
|
|
396
|
+
buffer += chunk.toString();
|
|
397
|
+
const nl = buffer.indexOf('\n');
|
|
398
|
+
if (nl >= 0) done(buffer.slice(0, nl), null);
|
|
399
|
+
};
|
|
400
|
+
const onError = (err) => done(null, err);
|
|
401
|
+
const onClose = () => done(null, new Error('daemon closed the connection without replying'));
|
|
402
|
+
const timer = setTimeout(() => done(null, new Error(`daemon did not reply within ${timeoutMs}ms`)), timeoutMs);
|
|
403
|
+
timer.unref?.();
|
|
404
|
+
|
|
405
|
+
socket.on('data', onData);
|
|
406
|
+
socket.on('error', onError);
|
|
407
|
+
socket.on('close', onClose);
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/**
|
|
411
|
+
* Ask the resident daemon to scan, starting it on first use.
|
|
412
|
+
*
|
|
413
|
+
* THE WHOLE POINT IS THAT THE PROCESS OUTLIVES ONE CALL. An earlier version of
|
|
414
|
+
* this function spawned a fresh python per request; measured, that cost ~4.2s --
|
|
415
|
+
* i.e. it paid semgrep's import tax every time and delivered none of the benefit.
|
|
416
|
+
* A resident process answers in ~2.1s after the first call. So the client connects
|
|
417
|
+
* to a long-lived child, keeps it, and only restarts when it dies or goes idle.
|
|
418
|
+
*
|
|
419
|
+
* Never throws. Every failure -- spawn failed, import broken, internal API
|
|
420
|
+
* renamed, timeout, malformed reply, daemon died mid-request -- resolves to
|
|
421
|
+
* `{ok:false}` so the caller falls back to a real direct scan. The daemon can make
|
|
422
|
+
* the gate slower; it must never make it greener (#518/#559).
|
|
423
|
+
*
|
|
424
|
+
* @param {{config: string, roots: string[], pythonCmd?: string, timeoutMs?: number}} opts
|
|
425
|
+
* @returns {Promise<{ok: true, payload: object} | {ok: false, error: string}>}
|
|
426
|
+
*/
|
|
427
|
+
async function requestScan(opts) {
|
|
428
|
+
const {
|
|
429
|
+
config,
|
|
430
|
+
roots,
|
|
431
|
+
pythonCmd = process.env.XP_GATE_SASTD_PYTHON || 'python',
|
|
432
|
+
timeoutMs = DEFAULT_TIMEOUT_MS,
|
|
433
|
+
} = opts;
|
|
434
|
+
|
|
435
|
+
let conn;
|
|
436
|
+
try {
|
|
437
|
+
conn = ensureDaemon(pythonCmd);
|
|
438
|
+
} catch (err) {
|
|
439
|
+
return { ok: false, error: `spawn failed: ${err.message}` };
|
|
440
|
+
}
|
|
441
|
+
if (!conn.ok) return conn;
|
|
442
|
+
|
|
443
|
+
return exchange(conn.value, { op: 'scan', config, roots }, timeoutMs);
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/**
|
|
447
|
+
* Send one request to a live daemon and turn its reply into a result.
|
|
448
|
+
*
|
|
449
|
+
* @param {object} daemon
|
|
450
|
+
* @param {Record<string, unknown>} request
|
|
451
|
+
* @param {number} timeoutMs
|
|
452
|
+
* @returns {Promise<{ok: true, payload: object} | {ok: false, error: string}>}
|
|
453
|
+
*/
|
|
454
|
+
function exchange(daemon, request, timeoutMs) {
|
|
455
|
+
return new Promise((resolve) => {
|
|
456
|
+
const { socket, proc } = daemon;
|
|
457
|
+
|
|
458
|
+
// Hold the process open for the duration of the request only. Without this,
|
|
459
|
+
// Node can exit mid-scan (measured: 0 bytes of output); with a permanent hold,
|
|
460
|
+
// a one-shot caller never exits at all. Ref-counting per request gives both:
|
|
461
|
+
// work in flight keeps the loop alive, and an idle daemon does not.
|
|
462
|
+
refProc(proc);
|
|
463
|
+
|
|
464
|
+
// Tag this request so a reply arriving for a prior, timed-out request cannot
|
|
465
|
+
// be mistaken for this one's answer. Without it, one slow scan poisons the
|
|
466
|
+
// next verdict -- exactly the failure a security gate must not have.
|
|
467
|
+
daemon.pending += 1;
|
|
468
|
+
const sequence = daemon.pending;
|
|
469
|
+
|
|
470
|
+
// Exactly one release per request. finish() is reachable from three paths -- the
|
|
471
|
+
// reply, the outer timeout, and the write failure -- and more than one can fire
|
|
472
|
+
// (a timeout landing while a late reply arrives; a write failure racing the read
|
|
473
|
+
// timer). A second releaseProc decrements inFlight below the real number of live
|
|
474
|
+
// requests and unrefs a process still in use, letting Node exit mid-scan.
|
|
475
|
+
let released = false;
|
|
476
|
+
let timer = null;
|
|
477
|
+
const finish = (result) => {
|
|
478
|
+
if (released) return;
|
|
479
|
+
released = true;
|
|
480
|
+
clearTimeout(timer);
|
|
481
|
+
releaseProc(proc);
|
|
482
|
+
resolve(result);
|
|
483
|
+
};
|
|
484
|
+
|
|
485
|
+
timer = setTimeout(() => {
|
|
486
|
+
finish({ ok: false, error: `daemon did not reply within ${timeoutMs}ms` });
|
|
487
|
+
// A daemon that missed its deadline may be wedged; do not keep feeding it.
|
|
488
|
+
resetDaemon(`timeout on request ${sequence}`);
|
|
489
|
+
}, timeoutMs);
|
|
490
|
+
timer.unref?.();
|
|
491
|
+
|
|
492
|
+
readOneLine(socket, (line, err) => finish(interpretReply(line, err)), timeoutMs);
|
|
493
|
+
|
|
494
|
+
try {
|
|
495
|
+
proc.stdin.write(JSON.stringify(request) + '\n');
|
|
496
|
+
} catch (writeErr) {
|
|
497
|
+
resetDaemon(`write failed: ${writeErr.message}`);
|
|
498
|
+
finish({ ok: false, error: `write failed: ${writeErr.message}` });
|
|
499
|
+
}
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/**
|
|
504
|
+
* Turn a raw line (or transport error) into the result the caller sees.
|
|
505
|
+
*
|
|
506
|
+
* @param {string|null} line
|
|
507
|
+
* @param {Error|null} err
|
|
508
|
+
* @returns {{ok: true, payload: object} | {ok: false, error: string}}
|
|
509
|
+
*/
|
|
510
|
+
function interpretReply(line, err) {
|
|
511
|
+
if (err) return { ok: false, error: err.message };
|
|
512
|
+
let reply;
|
|
513
|
+
try {
|
|
514
|
+
reply = JSON.parse(line);
|
|
515
|
+
} catch {
|
|
516
|
+
return { ok: false, error: `malformed reply: ${String(line).slice(0, 120)}` };
|
|
517
|
+
}
|
|
518
|
+
if (!reply || reply.ok !== true) {
|
|
519
|
+
// The daemon answered and said no. Keep it alive: a bad config is the
|
|
520
|
+
// caller's problem, not a reason to tear down a healthy process.
|
|
521
|
+
return { ok: false, error: reply?.error || 'daemon reported failure' };
|
|
522
|
+
}
|
|
523
|
+
return { ok: true, payload: normalisePayload(reply.data) };
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
module.exports = {
|
|
527
|
+
resolveDaemonPolicy,
|
|
528
|
+
normaliseResultPaths,
|
|
529
|
+
normalisePayload,
|
|
530
|
+
requestScan,
|
|
531
|
+
ensureDaemon,
|
|
532
|
+
resetDaemon,
|
|
533
|
+
DEFAULT_TIMEOUT_MS,
|
|
534
|
+
};
|
package/lib/shared-utils.js
CHANGED
|
@@ -67,7 +67,10 @@ function copyHooks(srcDir, destDir) {
|
|
|
67
67
|
// hook-module-resolution.sh (#655/#631) is loaded by pre-commit BEFORE any tier
|
|
68
68
|
// decision and fails closed — omitting it made every commit FATAL on a fresh
|
|
69
69
|
// install. It is generated, but it must still ship beside the hooks.
|
|
70
|
-
|
|
70
|
+
// REQ-DEPLOY-001: the list comes from the single deploy-manifest module. A
|
|
71
|
+
// hand-kept copy here was one of four divergent ones (#789 root cause ②), and
|
|
72
|
+
// it is exactly how post-commit silently stopped being installed before.
|
|
73
|
+
const hookFiles = require('./deploy-manifest.js').HOOK_FILES;
|
|
71
74
|
hookFiles.forEach(hook => {
|
|
72
75
|
const src = path.join(srcDir, 'hooks', hook);
|
|
73
76
|
const dest = path.join(destDir, hook);
|
|
@@ -77,19 +80,38 @@ function copyHooks(srcDir, destDir) {
|
|
|
77
80
|
}
|
|
78
81
|
});
|
|
79
82
|
|
|
80
|
-
// Copy
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
83
|
+
// Copy the non-hook modules (lib/*.sh, lib/*.cjs, lib/*.py, lib/*.ps1,
|
|
84
|
+
// adapter-common.sh, deploy-manifest.sh, install.sh) from the manifest.
|
|
85
|
+
//
|
|
86
|
+
// REQ-DEPLOY-002: this used to be `copyDirRecursive(path.join(srcDir,'hooks','lib'))`
|
|
87
|
+
// — a hardcoded directory copy that bypassed the manifest entirely. Two problems,
|
|
88
|
+
// and the second is worse than the first:
|
|
89
|
+
// 1. adapter-common.sh, deploy-manifest.sh and install.sh were never installed,
|
|
90
|
+
// because they are not under lib/ and HOOK_FILES did not list them.
|
|
91
|
+
// 2. Copying an entire directory means the manifest cannot describe what gets
|
|
92
|
+
// installed. A file added under hooks/lib/ appeared on users' disks with no
|
|
93
|
+
// manifest entry, so "is the manifest complete" was unanswerable by reading
|
|
94
|
+
// the manifest — the exact question REQ-DEPLOY-002 exists to make answerable.
|
|
95
|
+
// Copying the declared list makes the manifest the actual install plan.
|
|
96
|
+
const { MODULE_FILES } = require('./deploy-manifest.js');
|
|
97
|
+
MODULE_FILES.forEach(rel => {
|
|
98
|
+
const src = path.join(srcDir, 'hooks', rel);
|
|
99
|
+
if (!fs.existsSync(src)) return;
|
|
100
|
+
const dest = path.join(destDir, rel);
|
|
101
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
102
|
+
fs.copyFileSync(src, dest);
|
|
103
|
+
// Only executables need the bit; a .ps1/.cjs/.py helper does not, but setting
|
|
104
|
+
// it is harmless and keeps shell modules runnable the way they were before.
|
|
105
|
+
fs.chmodSync(dest, 0o755);
|
|
106
|
+
});
|
|
86
107
|
}
|
|
87
108
|
|
|
88
109
|
function copyAdapters(srcDir, destDir) {
|
|
89
110
|
const adaptersDir = path.join(srcDir, 'adapters');
|
|
90
|
-
const
|
|
111
|
+
const { ADAPTER_COMMON } = require('./deploy-manifest.js');
|
|
112
|
+
const adapterCommon = path.join(srcDir, ADAPTER_COMMON);
|
|
91
113
|
if (fs.existsSync(adapterCommon)) {
|
|
92
|
-
fs.copyFileSync(adapterCommon, path.join(destDir,
|
|
114
|
+
fs.copyFileSync(adapterCommon, path.join(destDir, ADAPTER_COMMON));
|
|
93
115
|
}
|
|
94
116
|
// Shared shell helpers the fragments `source` at runtime (ccn-ratchet.sh and
|
|
95
117
|
// friends). Without this, gate-3.sh resolves $GATE_DIR/lib/ccn-ratchet.sh to a
|
package/lib/uninstall.js
CHANGED
|
@@ -10,6 +10,7 @@ const {
|
|
|
10
10
|
GLOBAL_ADAPTERS_DIR,
|
|
11
11
|
GLOBAL_MODULES_DIR,
|
|
12
12
|
} = require('./shared-paths.js');
|
|
13
|
+
const { HOOK_FILES } = require('./deploy-manifest.js');
|
|
13
14
|
|
|
14
15
|
const BACKUP_DIR = path.join(CONFIG_DIR, '.uninstall-backup');
|
|
15
16
|
|
|
@@ -865,14 +866,16 @@ function planHooksDirRemoval(hooksDir) {
|
|
|
865
866
|
/**
|
|
866
867
|
* Hook entry points xp-gate installs.
|
|
867
868
|
*
|
|
868
|
-
* This must stay in sync with
|
|
869
|
-
*
|
|
870
|
-
* uninstaller classified its own hook as a third party's and kept it
|
|
871
|
-
* file contains nine `xp-gate` references and is installed unconditionally
|
|
872
|
-
* setup-global. The set is
|
|
873
|
-
* retyped, so
|
|
869
|
+
* This must stay in sync with the list of hooks actually installed, which is
|
|
870
|
+
* what `copyHooks()` puts on disk. `post-commit` was missing here once (#714),
|
|
871
|
+
* so the uninstaller classified its own hook as a third party's and kept it —
|
|
872
|
+
* the file contains nine `xp-gate` references and is installed unconditionally
|
|
873
|
+
* by setup-global. The set is now read from the deploy manifest (REQ-DEPLOY-001,
|
|
874
|
+
* AC-DEPLOY-05) rather than retyped, so installer and uninstaller cannot drift
|
|
875
|
+
* apart again — and hook-module-resolution.sh is claimed too, which the old
|
|
876
|
+
* retyped list missed.
|
|
874
877
|
*/
|
|
875
|
-
const OWNED_HOOK_NAMES =
|
|
878
|
+
const OWNED_HOOK_NAMES = HOOK_FILES;
|
|
876
879
|
|
|
877
880
|
/** 'git-lfs' when the file proves it, else null. Content-based: see doctor.js. */
|
|
878
881
|
function foreignHookSource(filePath) {
|
package/lib/update-hooks.js
CHANGED
|
@@ -38,8 +38,9 @@ function getProjectHooksDir() {
|
|
|
38
38
|
function detectLocalModifications(srcDir, hooksDestDir, adaptersDestDir) {
|
|
39
39
|
const modified = [];
|
|
40
40
|
|
|
41
|
-
// Check hook files
|
|
42
|
-
|
|
41
|
+
// Check hook files — the list is the manifest's, so a hook that gets installed
|
|
42
|
+
// is also a hook whose local modifications get detected (REQ-DEPLOY-001).
|
|
43
|
+
require('./deploy-manifest.js').HOOK_FILES.forEach(hook => {
|
|
43
44
|
const srcPath = path.join(srcDir, 'hooks', hook);
|
|
44
45
|
const destPath = path.join(hooksDestDir, hook);
|
|
45
46
|
if (fs.existsSync(destPath) && fs.existsSync(srcPath)) {
|
|
@@ -158,26 +159,34 @@ function atomicCopyFile(src, dest, dryRun, noBackup, label) {
|
|
|
158
159
|
*/
|
|
159
160
|
function copyHooks(srcDir, destDir, dryRun, noBackup) {
|
|
160
161
|
const hooksSrcDir = path.join(srcDir, 'hooks');
|
|
161
|
-
|
|
162
|
+
// REQ-DEPLOY-001 (AC-DEPLOY-09): this listed only three hooks, so
|
|
163
|
+
// `update-hooks --scope hooks` produced a directory with no
|
|
164
|
+
// hook-module-resolution.sh — and pre-commit loads that file before any tier
|
|
165
|
+
// decision and fails closed, making every commit FATAL. post-commit was
|
|
166
|
+
// missing too (its audit-attribution flush never ran). Both now come from the
|
|
167
|
+
// manifest, so the installer and the updater cannot disagree again.
|
|
168
|
+
require('./deploy-manifest.js').HOOK_FILES.forEach(hook => {
|
|
162
169
|
const src = path.join(hooksSrcDir, hook);
|
|
163
170
|
const dest = path.join(destDir, hook);
|
|
164
171
|
atomicCopyFile(src, dest, dryRun, noBackup, hook);
|
|
165
172
|
});
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
173
|
+
// Non-hook modules (lib/*, adapter-common.sh, deploy-manifest.sh, install.sh)
|
|
174
|
+
// come from MODULE_FILES rather than a directory enumeration.
|
|
175
|
+
//
|
|
176
|
+
// REQ-DEPLOY-002: enumerating `hooks/lib/` meant the updater installed whatever
|
|
177
|
+
// happened to be in that directory — including files no manifest declared — and
|
|
178
|
+
// left adapter-common.sh / deploy-manifest.sh / install.sh uninstalled entirely.
|
|
179
|
+
// Enumerating the manifest instead makes the install plan readable.
|
|
180
|
+
const { MODULE_FILES } = require('./deploy-manifest.js');
|
|
181
|
+
MODULE_FILES.forEach(rel => {
|
|
182
|
+
atomicCopyFile(
|
|
183
|
+
path.join(hooksSrcDir, rel),
|
|
184
|
+
path.join(destDir, rel),
|
|
185
|
+
dryRun,
|
|
186
|
+
noBackup,
|
|
187
|
+
rel
|
|
188
|
+
);
|
|
189
|
+
});
|
|
181
190
|
}
|
|
182
191
|
|
|
183
192
|
/**
|