@bugb-technologies/bravos 1.2.1 → 1.4.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.
Files changed (47) hide show
  1. package/README.md +17 -10
  2. package/dist/ci.js +11 -3
  3. package/dist/cli.js +50 -8
  4. package/dist/doctor.js +4 -16
  5. package/dist/guide.js +5 -3
  6. package/dist/help.js +16 -16
  7. package/dist/hooks.js +21 -0
  8. package/dist/install-proof-tool.js +117 -0
  9. package/dist/proof-tools.js +29 -0
  10. package/dist/report/check.js +4 -1
  11. package/dist/report/data.js +81 -149
  12. package/dist/report/markdown.js +1 -1
  13. package/dist/report/redact.js +16 -0
  14. package/dist/report/runs.js +169 -0
  15. package/dist/resync.js +272 -0
  16. package/dist/setup.js +31 -16
  17. package/dist/start/answers.js +5 -3
  18. package/dist/start/index.js +28 -14
  19. package/dist/versions.js +4 -3
  20. package/docs/GUIDE.md +12 -2
  21. package/hooks/lib/autopilot.mjs +216 -77
  22. package/hooks/lib/briefing.mjs +36 -5
  23. package/hooks/lib/nightly-stage.mjs +66 -0
  24. package/hooks/lib/nightly-tools.sh +45 -0
  25. package/hooks/lib/pre-pr.mjs +88 -17
  26. package/hooks/lib/proof-tool-pins.json +12 -0
  27. package/hooks/lib/replay.mjs +579 -0
  28. package/hooks/lib/resync.mjs +78 -0
  29. package/hooks/lib/setup.mjs +15 -6
  30. package/hooks/lib/snapshot.mjs +189 -0
  31. package/hooks/session-start.mjs +7 -3
  32. package/package.json +1 -1
  33. package/skills/bravos/SKILL.md +2 -1
  34. package/skills/bravos-annotate/SKILL.md +6 -5
  35. package/skills/bravos-annotate/scripts/slice.mjs +15 -8
  36. package/skills/bravos-cicd/SKILL.md +1 -1
  37. package/skills/bravos-env/SKILL.md +3 -3
  38. package/skills/bravos-prove/SKILL.md +11 -15
  39. package/skills/bravos-recheck/SKILL.md +3 -3
  40. package/skills/bravos-report/SKILL.md +1 -1
  41. package/skills/bravos-resync/SKILL.md +52 -0
  42. package/skills/bravos-schedule/SKILL.md +1 -1
  43. package/skills/bravos-ship/SKILL.md +1 -1
  44. package/skills/bravos-templatize/SKILL.md +3 -3
  45. package/templates/workflows/bravos-nightly-claude.yml +131 -74
  46. package/templates/workflows/bravos-nightly-codex.yml +130 -73
  47. package/templates/workflows/bravos-pr-gate.yml +88 -14
@@ -1,14 +1,18 @@
1
1
  import { spawnSync } from 'node:child_process';
2
- import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
3
  import { basename, join, relative } from 'node:path';
4
4
  import { graphBin } from '../codegraph.js';
5
5
  import { version } from '../paths.js';
6
6
  import { graphDetail, lib, parseJson, runner } from '../watch.js';
7
+ import { readRuns } from './runs.js';
8
+ import { red, redact } from './redact.js';
7
9
  import { BravosError } from '../types.js';
8
10
  import { META_SCHEMA, REPORTS_DIR, reportDir, writeMeta } from './meta.js';
11
+ export { readRuns } from './runs.js';
12
+ export { redact, SECRET_PATTERNS } from './redact.js';
9
13
  export { META_SCHEMA, REPORTS_DIR, listReports, readMeta, reportDir, resolveReport, writeMeta } from './meta.js';
10
14
  // @comment -- "bravos report data: gathers the facts a white-box VAPT write-up may cite into one evidence bundle (.bravos/reports/<id>/evidence.json): the threat model, the hypothesis and boundary ledgers, every cxg run under .guardlink/pentest-findings, SAST, the code graph, intent, scope, proving and versions. Every fact gets a stable id, and each exposure's evidence level is computed here from the ledger, runs and SAST, never chosen by the model that writes the prose. Read-only towards the repository except the report folder it creates."
11
- export const EVIDENCE_SCHEMA = 'bravos.report-evidence/v1';
15
+ export const EVIDENCE_SCHEMA = 'bravos.report-evidence/v2';
12
16
  export const REPORT_KINDS = ['assessment', 'finding', 'retest', 'brief'];
13
17
  export const LEVEL_LABEL = {
14
18
  reproduced: 'reproduced at runtime',
@@ -19,114 +23,10 @@ export const LEVEL_LABEL = {
19
23
  const arr = (v) => (Array.isArray(v) ? v : []);
20
24
  const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
21
25
  const strip = (s) => String(s ?? '').replace(/^#/, '');
22
- /** Secret-shaped strings: JWTs, bearer tokens, AWS keys, private keys, key=value credentials. Shared with the report check. */
23
- export const SECRET_PATTERNS = [
24
- { name: 'jwt', re: /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g },
25
- { name: 'bearer token', re: /\bBearer\s+(?!<)[A-Za-z0-9._~+/-]{20,}=*/g },
26
- { name: 'aws access key', re: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g },
27
- { name: 'private key', re: /-----BEGIN [A-Z ]*PRIVATE KEY-----/g },
28
- { name: 'credential assignment', re: /\b(?:api[_-]?key|secret[_-]?key|password|passwd|access[_-]?token|auth[_-]?token)\s*[:=]\s*["']?(?!<)[A-Za-z0-9/+_.-]{12,}/gi },
29
- ];
30
- // @comment -- "Replaces secret-shaped substrings with <redacted:kind> so evidence.json and the report never carry a live token, even locally."
31
- export function redact(text) {
32
- let out = text;
33
- for (const p of SECRET_PATTERNS)
34
- out = out.replace(p.re, `<redacted:${p.name}>`);
35
- return out;
36
- }
37
- const red = (v, max = 1200) => redact(String(v ?? '')).slice(0, max);
38
26
  const key8 = (k) => k.replace(/[^a-f0-9]/gi, '').slice(0, 8);
39
- // @comment -- "Reads every cxg result under .guardlink/pentest-findings (depth 3, JSON only): a pentest run report (confirmed_findings, mitigation_verifications, not_run, auth_skipped, probe_refusals) or a cxg scan output (findings, executions). Each becomes RUN-n with its findings, executions and not-run causes as items; unreadable files are skipped and named as a gap."
40
- export function readRuns(root, items, gaps) {
41
- const base = join(root, '.guardlink', 'pentest-findings');
42
- if (!existsSync(base))
43
- return [];
44
- const files = [];
45
- const walk = (dir, depth) => {
46
- for (const e of readdirSync(dir, { withFileTypes: true })) {
47
- const p = join(dir, e.name);
48
- if (e.isDirectory() && depth < 3)
49
- walk(p, depth + 1);
50
- else if (e.isFile() && e.name.endsWith('.json'))
51
- files.push(p);
52
- }
53
- };
54
- walk(base, 0);
55
- const runs = [];
56
- let n = 0;
57
- for (const file of files.sort()) {
58
- let j;
59
- try {
60
- j = JSON.parse(readFileSync(file, 'utf8'));
61
- }
62
- catch {
63
- gaps.push(`unreadable run file ${relative(root, file)}`);
64
- continue;
65
- }
66
- const pentest = j && (Array.isArray(j.confirmed_findings) || Array.isArray(j.mitigation_verifications));
67
- const scan = j && typeof j.scan_id === 'string' && Array.isArray(j.findings) && Array.isArray(j.executions);
68
- if (!pentest && !scan)
69
- continue;
70
- n += 1;
71
- const id = `RUN-${n}`;
72
- const rel = relative(root, file);
73
- const findings = pentest ? arr(j.confirmed_findings) : arr(j.findings);
74
- findings.forEach((f, k) => {
75
- items.push({
76
- id: `${id}/F-${k + 1}`,
77
- kind: 'run-finding',
78
- supports: ['reproduced'],
79
- summary: red(f.title ?? f.description ?? f.vuln_class ?? 'finding', 300),
80
- data: {
81
- template: f.template_id ?? null,
82
- severity: f.severity ?? null,
83
- endpoint: f.endpoint ?? f.target ?? null,
84
- cwe: arr(f.cwe_ids),
85
- claimKey: f.claim_key ?? null,
86
- threat: f.threat ?? f.threat_id ?? null,
87
- request: red(f.evidence?.request ?? f.evidence?.observed?.request ?? f.payload ?? ''),
88
- response: red(f.evidence?.response ?? f.evidence?.observed ?? ''),
89
- proofStatus: f.proof_status ?? null,
90
- triage: f.triage ?? null,
91
- },
92
- });
93
- });
94
- const executions = pentest ? arr(j.probe_executions) : arr(j.executions);
95
- executions.forEach((x, k) => {
96
- const status = String(x.status ?? '?');
97
- items.push({
98
- id: `${id}/X-${k + 1}`,
99
- kind: 'run-execution',
100
- supports: status === 'confirmed' ? ['reproduced'] : status === 'refuted' ? ['held'] : [],
101
- summary: `${x.template_id ?? x.template ?? '?'}: ${status}`,
102
- data: { template: x.template_id ?? x.template ?? null, status, detail: x.detail ?? x.reason ?? null },
103
- });
104
- });
105
- const held = pentest ? arr(j.mitigation_verifications) : [];
106
- held.forEach((h, k) => items.push({ id: `${id}/H-${k + 1}`, kind: 'run-execution', supports: ['held'], summary: red(h.title ?? h.template_id ?? 'mitigation held', 300), data: { template: h.template_id ?? null } }));
107
- const notRun = pentest ? [...arr(j.not_run), ...arr(j.auth_skipped), ...arr(j.probe_refusals)] : [];
108
- notRun.forEach((x, k) => items.push({ id: `${id}/N-${k + 1}`, kind: 'run-not-run', supports: [], summary: `${x.template ?? '?'} not run: ${x.cause ?? x.reason_kind ?? x.status ?? 'unknown'} — ${red(x.reason ?? '', 200)}` }));
109
- const summary = {
110
- id,
111
- path: rel,
112
- kind: pentest ? 'pentest' : 'scan',
113
- scanId: j.scan_id ?? null,
114
- at: j.completed_at ?? j.started_at ?? null,
115
- target: j.target ?? findings[0]?.target ?? null,
116
- authProfiles: arr(j.auth_profiles),
117
- confirmed: findings.length + executions.filter((x) => x.status === 'confirmed' && !findings.length).length,
118
- held: held.length + executions.filter((x) => x.status === 'refuted').length,
119
- notRun: notRun.length,
120
- caveats: arr(j.caveats).map((c) => red(typeof c === 'string' ? c : JSON.stringify(c), 300)),
121
- };
122
- items.push({ id, kind: 'run', supports: [], summary: `${summary.kind} ${summary.scanId ?? ''} at ${summary.at ?? '?'} against ${summary.target ?? '?'}: ${summary.confirmed} confirmed, ${summary.held} held, ${summary.notRun} not run`, file: rel });
123
- runs.push(summary);
124
- }
125
- return runs;
126
- }
127
- // @comment -- "The level an exposure's evidence supports: a ledger confirmation is reproduced, a refutation is a held control, a reachable SAST finding joined to its file is code review, anything else open is suspected."
27
+ // @comment -- "The level an exposure's evidence supports: a ledger confirmation is reproduced, a refutation is a held control, a current reachable SAST finding joined to its exact claim is code review, anything else open is suspected."
128
28
  export function levelFor(state, sastCorroborated) {
129
- if (state === 'confirmed' || state === 'retest')
29
+ if (state === 'confirmed')
130
30
  return 'reproduced';
131
31
  if (state === 'refuted')
132
32
  return 'held';
@@ -156,60 +56,86 @@ export async function gatherEvidence(root, env, opts) {
156
56
  const model = parseJson(parseR);
157
57
  if (!model)
158
58
  gaps.push(parseR.missing ? 'guardlink is not installed: no threat model' : 'guardlink parse failed: no threat model');
159
- const ledgerJ = parseJson(ledgerR);
160
- const boundJ = parseJson(boundR);
59
+ const parsedLedger = parseJson(ledgerR);
60
+ const ledgerJ = parsedLedger?.ledger === 'corrupt' ? null : parsedLedger;
61
+ const parsedBoundaries = parseJson(boundR);
62
+ const boundJ = parsedBoundaries?.ledger === 'corrupt' ? null : parsedBoundaries;
63
+ if (!boundJ)
64
+ gaps.push('boundary hypothesis ledger unavailable: tested boundaries unknown');
161
65
  if (!ledgerJ)
162
66
  gaps.push('guardlink hypothesis list failed: tested states unknown');
163
67
  const items = [];
164
68
  const runs = readRuns(root, items, gaps);
165
69
  if (!runs.length)
166
- gaps.push('no cxg run results under .guardlink/pentest-findings: nothing was exercised at runtime');
167
- // SAST: the candidates' reachable findings corroborate an exposure in the same file.
70
+ gaps.push('no readable cxg run results under .guardlink/pentest-findings');
71
+ const sha = git(['rev-parse', 'HEAD']);
72
+ const trackedChanges = git(['diff', '--name-only', '-z', 'HEAD']);
73
+ const untracked = git(['ls-files', '--others', '--exclude-standard', '-z']);
74
+ const dirty = new Set([...(trackedChanges ?? '').split('\0'), ...(untracked ?? '').split('\0')]);
168
75
  const sastLib = await lib('sast.mjs');
169
76
  const sastSummary = sastLib.readSast(root, env);
170
77
  const cands = sastLib.sastCandidates(root, { all: false });
171
78
  if (!sastSummary)
172
79
  gaps.push('no SAST run in .bravos/sast');
173
- const sastFiles = new Set();
80
+ const currentSast = sha != null && cands?.sha === sha && trackedChanges != null && untracked != null;
81
+ const claimAddress = (asset, threat, at) => JSON.stringify([strip(asset), strip(threat), at]);
82
+ const sastForClaim = new Map();
174
83
  let s = 0;
175
84
  for (const [group, list] of [['joined', cands?.joined], ['unjoined', cands?.unjoined], ['dependency', cands?.dependencies], ['secret', cands?.secrets]]) {
176
85
  for (const f of arr(list)) {
177
- s += 1;
178
- const reached = group !== 'dependency' || f.vulnerableFunctionReached === true;
179
- if (group !== 'dependency' && f.file)
180
- sastFiles.add(String(f.file));
181
- items.push({
182
- id: `SAST-${s}`,
183
- kind: 'sast',
184
- supports: reached ? ['code-review'] : [],
86
+ const id = `SAST-${++s}`;
87
+ const checked = currentSast && typeof f.file === 'string' && !dirty.has(f.file);
88
+ const join = f.claimState;
89
+ if (checked && group === 'joined' && join?.asset && join.threat && typeof join.declared_at === 'string') {
90
+ const address = claimAddress(join.asset, join.threat, join.declared_at);
91
+ const citations = sastForClaim.get(address) ?? [];
92
+ citations.push(id);
93
+ sastForClaim.set(address, citations);
94
+ }
95
+ items.push({ id, kind: 'sast',
96
+ supports: checked && (group !== 'dependency' || f.vulnerableFunctionReached === true || f.vulnerableFunctionReached === 'reached') ? ['code-review'] : [],
185
97
  summary: `${group}: ${f.rule ?? '?'} ${f.severity ?? ''} ${f.file ?? '?'}:${f.line ?? '?'}${f.route ? ` (${f.route})` : ''}${group === 'dependency' ? ` vulnerable function reached: ${sastLib.reachLabel(f.vulnerableFunctionReached)}` : ''}`,
186
- file: f.file,
187
- line: num(f.line),
188
- });
98
+ file: f.file, line: num(f.line), });
189
99
  }
190
100
  }
191
- // Ledger records by file:line:threat, to join each exposure to its tested state.
101
+ // hypothesis list addresses the physical annotation, parse returns its logical code location as well.
192
102
  const ledgerBy = new Map();
103
+ const ledgerItems = new Map();
104
+ const shortIds = new Map();
193
105
  for (const r of arr(ledgerJ?.records)) {
194
- ledgerBy.set(`${r.file}:${r.line}:${strip(r.threat)}`, r);
195
- if (r.outcome) {
196
- const outcome = String(r.outcome.outcome ?? r.state);
197
- items.push({
198
- id: `LED-${key8(String(r.key))}`,
199
- kind: 'ledger',
200
- supports: outcome === 'confirmed' ? ['reproduced'] : outcome === 'refuted' ? ['held'] : [],
201
- summary: `${r.claim ?? `${r.asset} to ${r.threat}`}: ${outcome} by ${r.outcome.by ?? '?'} at ${r.outcome.at ?? '?'}${r.state === 'retest' ? ' (code changed since: retest due)' : ''}`,
202
- file: r.file,
203
- line: num(r.line),
204
- data: { evidence: red(r.outcome.evidence ?? '', 2000), source: r.outcome.source ?? null, state: r.state, previous: r.previous ?? null },
205
- });
206
- }
106
+ const address = claimAddress(r.asset, r.threat, `${r.file}:${r.line}`);
107
+ const there = ledgerBy.get(address) ?? [];
108
+ there.push(r);
109
+ ledgerBy.set(address, there);
110
+ if (!r.outcome)
111
+ continue;
112
+ const outcome = String(r.outcome.outcome ?? r.state);
113
+ const source = r.outcome.source;
114
+ const engineEvidence = items.filter(i => i.data?.claimKey === r.key && i.data?.scanId === source?.scan_id
115
+ && i.data?.template === source?.template_id && i.supports.includes(outcome === 'confirmed' ? 'reproduced' : 'held'));
116
+ const recorded = Boolean(r.outcome.evidence) && (!source || source.kind === 'manual'
117
+ || (source.kind === 'scan' && source.joined_by === 'claim-key' && engineEvidence.length > 0));
118
+ const current = !r.expired && r.state === outcome;
119
+ const short = key8(String(r.key));
120
+ const index = (shortIds.get(short) ?? 0) + 1;
121
+ shortIds.set(short, index);
122
+ const id = `LED-${short}${index > 1 ? `-${index}` : ''}`;
123
+ const item = {
124
+ id, kind: 'ledger', supports: current && recorded && ['confirmed', 'refuted'].includes(outcome) ? [levelFor(outcome, false)] : [],
125
+ summary: `${r.claim ?? `${r.asset} to ${r.threat}`}: ${outcome} by ${r.outcome.by ?? '?'} at ${r.outcome.at ?? '?'}${current ? '' : ' (historical outcome; retest due)'}`,
126
+ file: r.file, line: num(r.line),
127
+ data: { claimKey: r.key, evidence: red(r.outcome.evidence ?? '', 2000), source: source ?? null, state: r.state, previous: r.previous ?? null, runEvidence: engineEvidence.map(i => i.id) },
128
+ };
129
+ ledgerItems.set(r.key, item);
130
+ items.push(item);
131
+ if (current && !recorded)
132
+ gaps.push(`${id} has no attributable proof for its recorded ${outcome} outcome`);
207
133
  }
208
134
  const mitigations = arr(model?.mitigations);
209
135
  mitigations.forEach((m, k) => items.push({ id: `CTL-${k + 1}`, kind: 'control', supports: [], summary: `${m.control} mitigates ${m.threat} on ${m.asset}: ${red(m.description, 300)}`, file: m.location?.file, line: num(m.location?.line) }));
210
136
  arr(boundJ?.records).forEach((b, k) => {
211
137
  const st = String(b.state ?? 'unverified');
212
- items.push({ id: `BND-${k + 1}`, kind: 'boundary', supports: st === 'supported' ? ['held'] : st === 'contradicted' ? ['reproduced'] : [], summary: `${b.claim ?? b.id}: ${st}`, file: b.file, line: num(b.line) });
138
+ items.push({ id: `BND-${k + 1}`, kind: 'boundary', supports: b.expired || !b.outcome?.evidence ? [] : st === 'supported' ? ['held'] : st === 'contradicted' ? ['reproduced'] : [], summary: `${b.claim ?? b.id}: ${st}`, file: b.file, line: num(b.line) });
213
139
  });
214
140
  arr(model?.acceptances).forEach((a, k) => items.push({ id: `ACC-${k + 1}`, kind: 'acceptance', supports: [], summary: `${a.threat} on ${a.asset} accepted by ${a.accepted_by ?? '?'}${a.expires ? ` until ${a.expires}` : ''}: ${red(a.description, 300)}`, file: a.location?.file, line: num(a.location?.line) }));
215
141
  const candidates = [];
@@ -218,19 +144,24 @@ export async function gatherEvidence(root, env, opts) {
218
144
  const line = num(e.location?.line);
219
145
  const threat = strip(e.threat);
220
146
  const asset = strip(e.asset);
221
- const rec = ledgerBy.get(`${file}:${line}:${threat}`);
222
- const state = String(rec?.state ?? e.hypothesis?.state ?? 'untested');
223
- const level = levelFor(state, sastFiles.has(file));
147
+ const logical = `${file}:${line}`;
148
+ const origin = e.location?.origin_file ? `${e.location.origin_file}:${e.location.origin_line}` : logical;
149
+ const matches = ledgerBy.get(claimAddress(asset, threat, origin)) ?? [];
150
+ const rec = matches.length === 1 ? matches[0] : null;
151
+ if (matches.length !== 1)
152
+ gaps.push(`${logical}: ${matches.length ? 'ambiguous' : 'missing'} hypothesis ledger association`);
153
+ const state = String(rec?.state ?? e.hypothesis?.state ?? 'unknown');
154
+ const ledgerItem = ledgerItems.get(rec?.key);
155
+ const sastIds = dirty.has(file) || dirty.has(e.location?.origin_file) ? [] : [...new Set([logical, origin].flatMap(at => sastForClaim.get(claimAddress(asset, threat, at)) ?? []))];
156
+ const level = ledgerItem?.supports[0] ?? (sastIds.length ? 'code-review' : 'suspected');
224
157
  const id = `EXP-${k + 1}`;
225
158
  const ctl = mitigations
226
159
  .map((m, j) => (strip(m.threat) === threat && strip(m.asset) === asset ? `CTL-${j + 1}` : null))
227
160
  .filter((x) => !!x);
228
161
  const evidence = [id];
229
- if (rec?.outcome)
230
- evidence.push(`LED-${key8(String(rec.key))}`);
231
- for (const it of items)
232
- if (it.kind === 'sast' && it.file === file && it.supports.length)
233
- evidence.push(it.id);
162
+ if (ledgerItem)
163
+ evidence.push(ledgerItem.id, ...arr(ledgerItem.data?.runEvidence));
164
+ evidence.push(...sastIds);
234
165
  // The exposure's level comes from its tested state in the ledger (or SAST), so citing the exposure supports that level.
235
166
  items.push({ id, kind: 'exposure', supports: level === 'suspected' ? ['suspected'] : [level, 'suspected'], summary: `${asset} exposed to ${threat} [${e.severity ?? 'unset'}]: ${red(e.description, 400)}`, file, line });
236
167
  candidates.push({
@@ -246,7 +177,7 @@ export async function gatherEvidence(root, env, opts) {
246
177
  claimKey: rec?.key ?? null,
247
178
  state,
248
179
  level,
249
- retestDue: state === 'retest',
180
+ retestDue: state === 'retest' || rec?.expired === true,
250
181
  mitigatedBy: ctl,
251
182
  evidence,
252
183
  previous: rec?.previous ? { outcome: String(rec.previous.outcome), by: String(rec.previous.by ?? '?'), at: String(rec.previous.at ?? '?') } : null,
@@ -270,7 +201,6 @@ export async function gatherEvidence(root, env, opts) {
270
201
  const scopeFile = ['.guardlink/scope.yaml', '.guardlink/scope.yml'].find((p) => existsSync(join(root, p)));
271
202
  const autopilot = await lib('autopilot.mjs');
272
203
  const proving = autopilot.readProving(root);
273
- const sha = git(['rev-parse', 'HEAD']);
274
204
  const porcelain = git(['status', '--porcelain']);
275
205
  const kindSlug = opts.kind === 'finding' && opts.finding ? `-${slugOf(narrowed[0]?.threat ?? opts.finding)}` : '';
276
206
  const stamp = now.toISOString().replace(/[-:]/g, '').replace('T', '-').slice(0, 13);
@@ -339,6 +269,8 @@ export function readEvidence(root, id) {
339
269
  if (!existsSync(file))
340
270
  throw new BravosError(`no evidence for report ${id}: run bravos report data first`);
341
271
  const b = JSON.parse(readFileSync(file, 'utf8'));
272
+ if (b?.schema === 'bravos.report-evidence/v1')
273
+ throw new BravosError(`report ${id} predates engine-proof attribution; gather evidence again with bravos report data at the revision being assessed, then check the report against the new evidence ids`);
342
274
  if (b?.schema !== EVIDENCE_SCHEMA)
343
275
  throw new BravosError(`${relative(root, file)} is not a ${EVIDENCE_SCHEMA} bundle`);
344
276
  return b;
@@ -27,7 +27,7 @@ function inline(text) {
27
27
  s = s.replace(new RegExp(`(^|[\\s(>])(${label})`, 'gi'), (_, pre, l) => `${pre}<span class="chip ${LEVEL_CLASS[k]}">${l}</span>`);
28
28
  }
29
29
  // Evidence ids become links into the appendix index when the page has one.
30
- s = s.replace(/(?<![\w:-])((?:[a-z0-9][a-z0-9._-]{0,40}:)?(?:RUN-\d+(?:\/[FXHN]-\d+)?|(?:EXP|SAST|CTL|BND|ACC|EDGE|UNR)-\d+|LED-[a-f0-9]{8}))\b/g, '<span class="eid">$1</span>');
30
+ s = s.replace(/(?<![\w:-])((?:[a-z0-9][a-z0-9._-]{0,40}:)?(?:RUN-\d+(?:\/[FXHN]-\d+)?|(?:EXP|SAST|CTL|BND|ACC|EDGE|UNR)-\d+|LED-[a-f0-9]{8}(?:-\d+)?))\b/g, '<span class="eid">$1</span>');
31
31
  return s.replace(/(\d+)/g, (_, i) => `<code>${escHtml(codes[Number(i)])}</code>`);
32
32
  }
33
33
  const isTableSep = (l) => /^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/.test(l);
@@ -0,0 +1,16 @@
1
+ /** Secret-shaped strings: JWTs, bearer tokens, AWS keys, private keys, key=value credentials. Shared with the report check. */
2
+ export const SECRET_PATTERNS = [
3
+ { name: 'jwt', re: /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g },
4
+ { name: 'bearer token', re: /\bBearer\s+(?!<)[A-Za-z0-9._~+/-]{20,}=*/g },
5
+ { name: 'aws access key', re: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g },
6
+ { name: 'private key', re: /-----BEGIN [A-Z ]*PRIVATE KEY-----/g },
7
+ { name: 'credential assignment', re: /\b(?:api[_-]?key|secret[_-]?key|password|passwd|access[_-]?token|auth[_-]?token)\s*[:=]\s*["']?(?!<)[A-Za-z0-9/+_.-]{12,}/gi },
8
+ ];
9
+ // @comment -- "Replaces secret-shaped substrings with <redacted:kind> so evidence.json and the report never carry a live token, even locally."
10
+ export function redact(text) {
11
+ let out = text;
12
+ for (const p of SECRET_PATTERNS)
13
+ out = out.replace(p.re, `<redacted:${p.name}>`);
14
+ return out;
15
+ }
16
+ export const red = (v, max = 1200) => redact(String(v ?? '')).slice(0, max);
@@ -0,0 +1,169 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { dirname, join, relative, resolve } from 'node:path';
3
+ import { red } from './redact.js';
4
+ const rows = (v) => Array.isArray(v) ? v.filter(x => x && typeof x === 'object' && !Array.isArray(x)) : [];
5
+ const native = (v) => Array.isArray(v?.confirmed_findings) || Array.isArray(v?.mitigation_verifications);
6
+ const scan = (v) => typeof v.scan_id === 'string' && Array.isArray(v.findings) && Array.isArray(v.executions);
7
+ const template = (v) => v.template_id ?? v.template ?? v.hypothesis_id ?? v.id ?? '?';
8
+ // @comment -- "Only a finding in an engine verdict bucket with positive proof can support runtime reproduction or a control that held. A scan template, including a scanner's declared execution status, can describe an observation but cannot adjudicate its own proof."
9
+ function engineLevel(v, expected) {
10
+ if (v.proof_status !== 'proven' || (v.triage != null && v.triage !== expected))
11
+ return [];
12
+ if (v.confirmed != null && v.confirmed !== (expected === 'confirmed'))
13
+ return [];
14
+ return [expected === 'confirmed' ? 'reproduced' : 'held'];
15
+ }
16
+ // @comment -- "Reads run JSON only from ordinary files already discovered under pentest-findings. A combined report's report_path can select only one of those files, never an arbitrary path named by a report. Embedded sessions supersede their on-disk copies and outer projections, retaining scanner-only findings, refusals and partial results."
17
+ export function readRuns(root, items, gaps) {
18
+ const base = resolve(root, '.guardlink/pentest-findings');
19
+ if (!existsSync(base))
20
+ return [];
21
+ const docs = new Map();
22
+ function walk(dir, depth) {
23
+ for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
24
+ const file = join(dir, entry.name);
25
+ if (entry.isDirectory() && depth < 6)
26
+ walk(file, depth + 1);
27
+ if (!entry.isFile() || !file.endsWith('.json'))
28
+ continue;
29
+ try {
30
+ const value = JSON.parse(readFileSync(file, 'utf8'));
31
+ if (value && (native(value) || scan(value) || value.probe_results))
32
+ docs.set(file, value);
33
+ }
34
+ catch {
35
+ gaps.push(`unreadable run file ${relative(root, file)}`);
36
+ }
37
+ }
38
+ }
39
+ walk(base, 0);
40
+ const consumed = new Set();
41
+ const sessions = new Map();
42
+ for (const [file, doc] of docs) {
43
+ if (!doc.probe_results)
44
+ continue;
45
+ const linked = [];
46
+ for (const s of rows(doc.probe_results.sessions)) {
47
+ const path = typeof s.report_path === 'string' ? s.report_path : '';
48
+ const paths = path ? [resolve(root, path), resolve(dirname(file), path)] : [];
49
+ let saved = paths.find(p => native(docs.get(p)));
50
+ // On a different checkout the recorded absolute path can be stale. Match the embedded copy's full content.
51
+ if (!saved && native(s.report)) {
52
+ const content = JSON.stringify(s.report);
53
+ saved = [...docs].find(([p, v]) => !consumed.has(p) && native(v) && JSON.stringify(v) === content)?.[0];
54
+ }
55
+ const report = native(s.report) ? s.report : saved ? docs.get(saved) : null;
56
+ if (saved && native(s.report) && JSON.stringify(docs.get(saved)) !== JSON.stringify(s.report)) {
57
+ consumed.add(saved);
58
+ gaps.push(`${relative(root, file)}: embedded native session conflicts with ${relative(root, saved)}; proof withheld`);
59
+ continue;
60
+ }
61
+ if (saved)
62
+ consumed.add(saved);
63
+ if (report)
64
+ linked.push(report);
65
+ else
66
+ gaps.push(`${relative(root, file)}: native probe report unavailable for ${red(s.target ?? 'unknown target', 160)}`);
67
+ }
68
+ sessions.set(file, linked);
69
+ }
70
+ const runs = [];
71
+ for (const [file, doc] of docs) {
72
+ if (consumed.has(file))
73
+ continue;
74
+ const id = `RUN-${runs.length + 1}`;
75
+ const rel = relative(root, file);
76
+ const result = {
77
+ id, path: rel, kind: native(doc) ? 'pentest' : 'scan', scanId: doc.scan_id ?? null,
78
+ at: doc.completed_at ?? doc.started_at ?? null, target: doc.target ?? null, authProfiles: [],
79
+ confirmed: 0, held: 0, notRun: 0, caveats: [],
80
+ };
81
+ const seenSkips = new Set();
82
+ let findings = 0, held = 0, executions = 0;
83
+ function finding(f, proof, report, mitigation = false) {
84
+ const label = mitigation ? `H-${++held}` : `F-${++findings}`;
85
+ const prefix = proof.length ? '' : 'Observed without engine proof: ';
86
+ items.push({
87
+ id: `${id}/${label}`, kind: mitigation ? 'run-execution' : 'run-finding', supports: proof,
88
+ summary: prefix + red(f.title ?? f.description ?? f.vuln_class ?? template(f), 300),
89
+ data: { template: template(f), claimKey: f.claim_key ?? f.annotation?.claim_key ?? null,
90
+ scanId: report.scan_id ?? null, threat: f.threat ?? f.threat_id ?? null, severity: f.severity ?? null,
91
+ request: red(f.evidence?.request ?? f.evidence?.observed?.request ?? ''),
92
+ response: red(f.evidence?.response ?? f.evidence?.observed?.response ?? ''),
93
+ proofStatus: f.proof_status ?? null, triage: f.triage ?? null },
94
+ });
95
+ if (proof.includes('reproduced'))
96
+ result.confirmed++;
97
+ if (proof.includes('held'))
98
+ result.held++;
99
+ }
100
+ function skip(v, kind, target) {
101
+ const who = template(v);
102
+ const reason = red(v.reason ?? v.triage_reason ?? v.description ?? '', 220);
103
+ const key = JSON.stringify([target, who, reason || kind]);
104
+ if (seenSkips.has(key))
105
+ return;
106
+ seenSkips.add(key);
107
+ items.push({ id: `${id}/N-${++result.notRun}`, kind: 'run-not-run', supports: [],
108
+ summary: `${red(who)} not run: ${red(v.cause ?? v.reason_kind ?? kind)} — ${reason}` });
109
+ }
110
+ function execution(x) {
111
+ items.push({ id: `${id}/X-${++executions}`, kind: 'run-execution', supports: [],
112
+ summary: `${red(template(x))}: ${red(x.status ?? '?')}`, data: { status: x.status, detail: red(x.reason ?? x.detail ?? '') } });
113
+ }
114
+ const nativeReports = native(doc) ? [doc] : sessions.get(file) ?? [];
115
+ if (!native(doc)) {
116
+ for (const f of rows(doc.findings)) {
117
+ if (f.verdict_source === 'engine-adjudicated') {
118
+ if (doc.probe_results)
119
+ continue; // A combined scan projects native findings to this list, even if their session is missing.
120
+ const original = f.evidence?.data?.engine_finding;
121
+ if (original) {
122
+ finding(original, engineLevel(original, 'confirmed'), doc);
123
+ continue;
124
+ }
125
+ }
126
+ result.target ??= f.target ?? null;
127
+ finding(f, [], doc);
128
+ }
129
+ for (const x of rows(doc.executions)) {
130
+ if (doc.probe_results && x.declared_by_template === false && String(x.detail).startsWith('engine-adjudicated:'))
131
+ continue;
132
+ execution(x);
133
+ }
134
+ }
135
+ for (const r of nativeReports) {
136
+ result.target ??= r.target ?? null;
137
+ for (const name of Array.isArray(r.auth_profiles) ? r.auth_profiles : []) {
138
+ if (typeof name === 'string' && !result.authProfiles.includes(name))
139
+ result.authProfiles.push(name);
140
+ }
141
+ for (const f of rows(r.confirmed_findings))
142
+ finding(f, engineLevel(f, 'confirmed'), r);
143
+ for (const f of rows(r.mitigation_verifications))
144
+ finding(f, engineLevel(f, 'refuted'), r, true);
145
+ for (const f of rows(r.ambiguous))
146
+ finding(f, [], r);
147
+ for (const f of rows(r.inconclusive_refusal))
148
+ finding(f, [], r);
149
+ for (const x of rows(r.probe_executions))
150
+ execution(x);
151
+ for (const kind of ['not_run', 'auth_skipped', 'probe_refusals', 'chain_skipped', 'rejected_templates', 'review_only_threats', 'not_selected_threats', 'identity_withdrawn', 'template_errors']) {
152
+ for (const v of rows(r[kind]))
153
+ skip(v, kind, r.target ?? null);
154
+ }
155
+ if (r.status && r.status !== 'ok')
156
+ result.caveats.push(`Engine status: ${red(r.status)}`);
157
+ for (const c of Array.isArray(r.caveats) ? r.caveats : [])
158
+ result.caveats.push(red(typeof c === 'string' ? c : JSON.stringify(c), 300));
159
+ }
160
+ for (const v of rows(doc.probe_results?.refused_probes))
161
+ skip(v, 'refused', v.target ?? null);
162
+ if (Array.isArray(doc.errors))
163
+ for (const error of doc.errors)
164
+ result.caveats.push(red(error, 300));
165
+ items.push({ id, kind: 'run', supports: [], summary: `${result.kind}: ${result.confirmed} confirmed, ${result.held} held, ${result.notRun} skipped or unavailable`, file: rel });
166
+ runs.push(result);
167
+ }
168
+ return runs;
169
+ }