@yeison.restrepo.r/code-conductor 1.48.0 → 1.50.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.
@@ -3,6 +3,7 @@
3
3
  // base commit) for credentials, and judges changed package.json scripts with the base
4
4
  // commit's own Guard 3. It reads git and writes nothing in the project: the only file
5
5
  // it creates is a temporary directory of its own, removed before it returns.
6
+ // FEAT-059: findings carry the audit's severities, and those already present at the base are printed in an owner-only block, never mixed with the ones the change introduces.
6
7
  // node: builtins only; no network call.
7
8
  import { spawnSync } from 'node:child_process';
8
9
  import { closeSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
@@ -10,18 +11,34 @@ import { tmpdir } from 'node:os';
10
11
  import { basename, join } from 'node:path';
11
12
  import { pathToFileURL } from 'node:url';
12
13
 
14
+ // FEAT-059 C15: the router refuses a base scanner from before this contract.
15
+ export const SCAN_CONTRACT = 2;
16
+
13
17
  // The generic row fires on test fixtures, so it must not block at the default threshold (C8).
18
+ // `marker` rows match a constant header, not the secret itself: a base file holding the same
19
+ // header proves nothing about the key, so their hits are never classified as pre-existing.
14
20
  export const SECRET_PATTERNS = [
15
- { name: 'private key block', severity: 'critical', re: /-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----/ },
16
- { name: 'AWS access key id', severity: 'critical', re: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/ },
17
- { name: 'GitHub token', severity: 'critical', re: /\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{22,})\b/ },
18
- { name: 'Slack token', severity: 'critical', re: /\bxox[abprs]-[A-Za-z0-9-]{10,}/ },
19
- { name: 'Stripe live key', severity: 'critical', re: /\b[sr]k_live_[A-Za-z0-9]{16,}/ },
20
- { name: 'Google API key', severity: 'critical', re: /\bAIza[0-9A-Za-z_-]{35}/ },
21
- { name: 'Anthropic API key', severity: 'critical', re: /\bsk-ant-[A-Za-z0-9_-]{20,}/ },
22
- { name: 'generic secret assignment', severity: 'moderate', re: /\b(?:password|passwd|secret|token|api[_-]?key)\b["']?\s*[:=]\s*["'][^"'\s]{12,}["']/i },
21
+ { name: 'private key block', level: 'critical', marker: true, re: /-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----/ },
22
+ { name: 'AWS access key id', level: 'critical', re: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/ },
23
+ { name: 'GitHub token', level: 'critical', re: /\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{22,})\b/ },
24
+ { name: 'Slack token', level: 'critical', re: /\bxox[abprs]-[A-Za-z0-9-]{10,}/ },
25
+ { name: 'Stripe live key', level: 'critical', re: /\b[sr]k_live_[A-Za-z0-9]{16,}/ },
26
+ { name: 'Google API key', level: 'critical', re: /\bAIza[0-9A-Za-z_-]{35}/ },
27
+ { name: 'Anthropic API key', level: 'critical', re: /\bsk-ant-[A-Za-z0-9_-]{20,}/ },
28
+ { name: 'generic secret assignment', level: 'moderate', re: /\b(?:password|passwd|secret|token|api[_-]?key)\b["']?\s*[:=]\s*["'][^"'\s]{12,}["']/i },
23
29
  ];
24
30
 
31
+ const LEVELS = ['low', 'moderate', 'high', 'critical'];
32
+ const USAGE = 'security-scan: usage: security-scan.mjs <base> <low|moderate|high|critical>';
33
+ const OWNER_OPEN = 'PRE-EXISTING (owner only):';
34
+ const OWNER_CLOSE = 'END PRE-EXISTING';
35
+ // detect-stack's precedence (scripts/detect-stack.mjs:207-210).
36
+ const LOCKFILES = ['pnpm-lock.yaml', 'package-lock.json'];
37
+
38
+ // C1: the router recomputes this from the run file, so the agent never chooses a severity.
39
+ export const severityFor = (level, threshold) => (LEVELS.indexOf(level) >= LEVELS.indexOf(threshold) ? 'blocker' : 'minor');
40
+ const findingLine = (level, threshold, location, source, text) => `- [${severityFor(level, threshold)}] ${location} — ${level} ${source}: ${text}`;
41
+
25
42
  const HOOK_REL = '.claude/hooks/pre-tool-use.mjs';
26
43
  const ALLOWLIST_REL = '.claude/memory/bash-scan-allowlist.txt';
27
44
  const SNIFF_BYTES = 8000;
@@ -92,15 +109,46 @@ function untrackedLines(root) {
92
109
  return out;
93
110
  }
94
111
 
95
- export function scanSecrets(lines) {
112
+ // A line is judged on every match of every pattern: one value missing at the base, or a
113
+ // marker row among them, keeps the whole line introduced (fail closed).
114
+ function lineMatches(text) {
115
+ return SECRET_PATTERNS.flatMap((p) => [...text.matchAll(new RegExp(p.re.source, `${p.re.flags}g`))]
116
+ .map((m) => ({ pattern: p, value: p.marker ? null : m[0] })));
117
+ }
118
+
119
+ const highest = (matches) => matches.reduce((a, b) => (LEVELS.indexOf(b.pattern.level) > LEVELS.indexOf(a.pattern.level) ? b : a)).pattern;
120
+
121
+ export function scanSecrets(lines, threshold) {
96
122
  const out = [];
97
123
  for (const { path, line, text } of lines) {
98
- const hit = SECRET_PATTERNS.find((p) => p.re.test(text));
99
- if (hit) out.push(`- [${hit.severity}] secret ${path}:${line} — ${hit.name}; value withheld`);
124
+ const matches = lineMatches(text);
125
+ if (matches.length === 0) continue;
126
+ const top = highest(matches);
127
+ out.push({
128
+ values: matches.map((m) => m.value),
129
+ line: findingLine(top.level, threshold, `${path}:${line}`, 'secret', `${top.name}; value withheld`),
130
+ });
100
131
  }
101
132
  return out;
102
133
  }
103
134
 
135
+ // C3: matched by value, not by line, so a moved or copied credential is pre-existing.
136
+ // A null value (a marker row) fails closed: the hit stays introduced.
137
+ function atBase(root, base, value) {
138
+ if (value === null) return false;
139
+ const r = spawnSync('git', ['grep', '-F', '-q', '-e', value, base, '--'], { cwd: root });
140
+ if (r.status === 0) return true;
141
+ if (r.status === 1 && !r.error) return false;
142
+ throw new ScanFailure('git grep could not search the base tree');
143
+ }
144
+
145
+ function splitSecrets(root, base, hits) {
146
+ const introduced = [];
147
+ const preExisting = [];
148
+ for (const hit of hits) (hit.values.every((v) => atBase(root, base, v)) ? preExisting : introduced).push(hit.line);
149
+ return { introduced, preExisting };
150
+ }
151
+
104
152
  function parseScripts(text, label) {
105
153
  try { return JSON.parse(text.replace(/^/, '')).scripts ?? {}; }
106
154
  catch { throw new ScanFailure(`${label} does not parse as JSON`); }
@@ -117,13 +165,24 @@ function changedPackagePaths(root, base) {
117
165
  .filter((p) => p && basename(p) === 'package.json' && existsSync(join(root, p)));
118
166
  }
119
167
 
168
+ // 1-based line of a script's key, so a finding can name package.json:<line>.
169
+ export function scriptLine(text, name) {
170
+ const rows = text.split(/\r?\n/);
171
+ const start = rows.findIndex((l) => l.includes('"scripts":'));
172
+ if (start === -1) return 1;
173
+ const key = `${JSON.stringify(name)}:`;
174
+ const at = rows.findIndex((l, i) => i > start && l.trim().startsWith(key));
175
+ return (at === -1 ? start : at) + 1;
176
+ }
177
+
120
178
  export function changedScripts(root, base) {
121
179
  const out = [];
122
180
  for (const path of changedPackagePaths(root, base)) {
123
- const now = parseScripts(readFileSync(join(root, path), 'utf8'), path);
181
+ const text = readFileSync(join(root, path), 'utf8');
182
+ const now = parseScripts(text, path);
124
183
  const before = baseScripts(root, base, path);
125
184
  for (const [name, value] of Object.entries(now ?? {})) {
126
- if (typeof value === 'string' && before?.[name] !== value) out.push({ path, name, value });
185
+ if (typeof value === 'string' && before?.[name] !== value) out.push({ path, name, value, line: scriptLine(text, name) });
127
186
  }
128
187
  }
129
188
  return out;
@@ -166,51 +225,113 @@ function askHook(dir, command) {
166
225
  return hookCode(out.permissionDecisionReason ?? '', out.permissionDecision);
167
226
  }
168
227
 
169
- export function scanScripts(root, base) {
228
+ export function scanScripts(root, base, threshold) {
170
229
  const candidates = changedScripts(root, base);
171
230
  if (candidates.length === 0) return [];
172
231
  const high = withBaseHook(root, base, (dir) => candidates.flatMap((c) => {
173
232
  const code = askHook(dir, c.value);
174
- return code ? [`- [high] script ${c.path} scripts.${c.name} — Guard 3 denies this text as a direct command (${code}); base allowlist applied`] : [];
233
+ if (!code) return [];
234
+ return [findingLine('high', threshold, `${c.path}:${c.line}`, 'script', `scripts.${c.name}; Guard 3 denies this text as a direct command (${code}); base allowlist applied`)];
175
235
  }));
176
236
  const moderate = candidates
177
237
  .filter((c) => c.path === 'package.json' && ROOT_TEST_SCRIPTS.includes(c.name))
178
- .map((c) => `- [moderate] script ${c.path} scripts.${c.name} — npm test runs this changed script`);
238
+ .map((c) => findingLine('moderate', threshold, `package.json:${c.line}`, 'script', `scripts.${c.name}; npm test runs this changed script`));
179
239
  return [...high, ...moderate];
180
240
  }
181
241
 
242
+ const addVersion = (map, name, version) => map.set(name, [...(map.get(name) ?? []), String(version)]);
243
+
244
+ // An empty map would read as "nothing changed" and file every finding owner-only (plan decisions).
245
+ function versionSets(map) {
246
+ if (map.size === 0) throw new Error('no package entry');
247
+ return new Map([...map].map(([k, v]) => [k, [...new Set(v)].sort().join(',')]));
248
+ }
249
+
250
+ function npmVersions(text) {
251
+ const { packages } = JSON.parse(text.replace(/^/, ''));
252
+ if (!packages || typeof packages !== 'object') throw new Error('no packages map');
253
+ const map = new Map();
254
+ for (const [key, entry] of Object.entries(packages)) {
255
+ const at = key.lastIndexOf('node_modules/');
256
+ if (at !== -1) addVersion(map, key.slice(at + 'node_modules/'.length), entry?.version);
257
+ }
258
+ return versionSets(map);
259
+ }
260
+
261
+ const PNPM_KEY = /^ {2}'?\/?((?:@[^@\s/']+\/)?[^@\s/'(]+)@([^\s:'(]+)/;
262
+
263
+ function pnpmVersions(text) {
264
+ const map = new Map();
265
+ for (const line of text.split(/\r?\n/)) {
266
+ const m = PNPM_KEY.exec(line);
267
+ if (m) addVersion(map, m[1], m[2]);
268
+ }
269
+ return versionSets(map);
270
+ }
271
+
272
+ // C4: the agent and the router read this one function, the router through the base commit's copy.
273
+ export function changedPackages(root, base, lockfile) {
274
+ const shown = spawnSync('git', ['show', `${base}:./${lockfile}`], { cwd: root, encoding: 'utf8', maxBuffer: 1 << 30 });
275
+ if (shown.error || shown.status !== 0) return 'all';
276
+ try {
277
+ const read = lockfile === 'pnpm-lock.yaml' ? pnpmVersions : npmVersions;
278
+ const before = read(shown.stdout);
279
+ const now = read(readFileSync(join(root, lockfile), 'utf8'));
280
+ const names = new Set([...before.keys(), ...now.keys()]);
281
+ return [...names].filter((n) => before.get(n) !== now.get(n)).sort();
282
+ } catch { return 'failed'; }
283
+ }
284
+
285
+ const findLockfile = (root) => LOCKFILES.find((f) => existsSync(join(root, f))) ?? null;
286
+
182
287
  function runScan(label, fn) {
183
- try { return { status: 'ran', lines: fn() }; }
288
+ try { return { status: 'ran', found: fn() }; }
184
289
  catch (err) {
185
290
  if (!(err instanceof ScanFailure)) throw err;
186
291
  process.stderr.write(`security-scan: ${label} scan failed: ${err.message}\n`);
187
- return { status: 'failed', lines: [] };
292
+ return { status: 'failed', found: { introduced: [], preExisting: [] } };
188
293
  }
189
294
  }
190
295
 
191
- export function scanChanges(root, base) {
296
+ export function scanChanges(root, base, threshold) {
297
+ const lockfile = findLockfile(root);
192
298
  try { checkBase(root, base); }
193
299
  catch (err) {
194
300
  if (!(err instanceof ScanFailure)) throw err;
195
301
  process.stderr.write(`security-scan: ${err.message}\n`);
196
- return { secrets: 'failed', scripts: 'failed', findings: [] };
302
+ return { secrets: 'failed', scripts: 'failed', introduced: [], preExisting: [], lockfile, changed: 'failed' };
197
303
  }
198
- const secrets = runScan('secrets', () => scanSecrets([
199
- ...diffLines(git(root, ['diff', '--no-color', '--no-ext-diff', '--unified=0', '--relative', '--src-prefix=a/', '--dst-prefix=b/', base]).toString('utf8')),
200
- ...untrackedLines(root),
201
- ]));
202
- const scripts = runScan('scripts', () => scanScripts(root, base));
203
- return { secrets: secrets.status, scripts: scripts.status, findings: [...secrets.lines, ...scripts.lines] };
304
+ const secrets = runScan('secrets', () => {
305
+ const diff = git(root, ['diff', '--no-color', '--no-ext-diff', '--unified=0', '--relative', '--src-prefix=a/', '--dst-prefix=b/', base]).toString('utf8');
306
+ return splitSecrets(root, base, scanSecrets([...diffLines(diff), ...untrackedLines(root)], threshold));
307
+ });
308
+ const scripts = runScan('scripts', () => ({ introduced: scanScripts(root, base, threshold), preExisting: [] }));
309
+ return {
310
+ secrets: secrets.status,
311
+ scripts: scripts.status,
312
+ introduced: [...secrets.found.introduced, ...scripts.found.introduced],
313
+ preExisting: secrets.found.preExisting,
314
+ lockfile,
315
+ changed: lockfile ? changedPackages(root, base, lockfile) : [],
316
+ };
317
+ }
318
+
319
+ function lockfileLine({ lockfile, changed }) {
320
+ if (!lockfile) return 'LOCKFILE none';
321
+ const names = changed === 'all' || changed === 'failed' ? 'all' : changed.length === 0 ? 'none' : changed.join(',');
322
+ return `LOCKFILE ${lockfile} changed=${names}`;
204
323
  }
205
324
 
206
325
  function main(args) {
207
- if (args.length > 1) {
208
- process.stderr.write('security-scan: usage: security-scan.mjs <base>\n');
326
+ if (args.length !== 2 || !LEVELS.includes(args[1])) {
327
+ process.stderr.write(`${USAGE}\n`);
209
328
  return 1;
210
329
  }
211
- const result = scanChanges(process.cwd(), args[0]);
212
- for (const line of result.findings) process.stdout.write(`${line}\n`);
213
- process.stdout.write(`SCAN-RESULT secrets=${result.secrets} scripts=${result.scripts}\n`);
330
+ const result = scanChanges(process.cwd(), args[0], args[1]);
331
+ const out = [];
332
+ if (result.preExisting.length > 0) out.push(OWNER_OPEN, ...result.preExisting, OWNER_CLOSE);
333
+ out.push(...result.introduced, lockfileLine(result), `SCAN-RESULT secrets=${result.secrets} scripts=${result.scripts}`);
334
+ process.stdout.write(`${out.join('\n')}\n`);
214
335
  return 0;
215
336
  }
216
337