@bugb-technologies/bravos 1.12.0 → 1.14.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.
@@ -0,0 +1,343 @@
1
+ #!/usr/bin/env node
2
+ // @comment -- "The nightly's opt-in team view (repository variable BRAVOS_THREAT_ISSUES=on): one GitHub issue per critical or high @exposes claim still untested BRAVOS_THREAT_ISSUES_DAYS days (default 2) after its annotation was committed, and the issue closed again once the claim is refuted, fixed (a covering @mitigates), accepted by a named person, lowered below high, or removed. A confirmed claim keeps its issue open, relabelled confirmed; a claim whose code changed after its last result (retest, or untested again) reopens the issue the nightly closed. Reads three files the workflow step wrote from guardlink parse, guardlink hypothesis list --json and guardlink blame --json; talks to GitHub only through gh with argument arrays and --body-file, so no annotation text is ever part of a shell line. One issue per claim key, found again by a hidden marker on the body's first line of an issue the workflow's own bot opened, listed both by the bravos label and by that author so a removed label never makes a second one. Dependency-free."
3
+ import { spawnSync } from 'node:child_process';
4
+ import { appendFileSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
5
+ import { tmpdir } from 'node:os';
6
+ import { join } from 'node:path';
7
+ import { pathToFileURL } from 'node:url';
8
+
9
+ export const MARKER = 'bravos:threat-issue';
10
+ export const CLOSED_MARKER = `<!-- ${MARKER}-closed -->`;
11
+ const KEY = /^[0-9a-f]{64}:\d+$/;
12
+ const SEVERE = new Set(['critical', 'high']);
13
+ const DAY_MS = 86400000;
14
+ /** New issues per run, so turning the view on over a large backlog opens them over a few nights instead of all at once. */
15
+ export const MAX_NEW = 10;
16
+ /** gh's page for one issue list; the summary says when a list reaches it. */
17
+ export const LIST_LIMIT = 1000;
18
+ const BOT = /^(app\/)?github-actions(\[bot\])?$/;
19
+ const LABELS = {
20
+ bravos: ['1E9A6C', 'Opened by the bravos nightly'],
21
+ untested: ['FBCA04', 'A threat no test has confirmed or refuted yet'],
22
+ confirmed: ['5C0011', 'A test showed this threat is exploitable'],
23
+ critical: ['B60205', 'Critical severity'],
24
+ high: ['D93F0B', 'High severity'],
25
+ };
26
+
27
+ // Only printable text from an annotation reaches an issue.
28
+ // @exposes #threat-issues to #issue-markup-injection [low] cwe:CWE-116 -- "renderTitle() and renderBody() write the description, file path and ids that guardlink parse read from @exposes lines, text anyone who can edit the repository controls, into a GitHub issue that the whole team is notified of"
29
+ // @mitigates #threat-issues against #issue-markup-injection using #code-fenced-text -- "clean() strips control, bidirectional and invisible characters and caps the length; the description sits inside a code fence longer than any backtick run in it and ids and paths in inline code, so no @mention, link or markup in it renders; the title is cleaned and reaches gh as one argument"
30
+ export const clean = (s, max) => String(s ?? '').replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u2069\uFEFF]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, max);
31
+ const code = (s, max = 200) => '`' + clean(s, max).replace(/`/g, "'") + '`';
32
+ function fenced(text) {
33
+ const run = Math.max(0, ...[...text.matchAll(/`+/g)].map((m) => m[0].length));
34
+ const fence = '`'.repeat(Math.max(3, run + 1));
35
+ return `${fence}text\n${text}\n${fence}`;
36
+ }
37
+ const titleCase = (s) => s.charAt(0).toUpperCase() + s.slice(1);
38
+
39
+ // @comment -- "The issue's title: [bravos] <Severity>: <description> (<file>:<line>), or [bravos] <Severity>, confirmed: … once a test confirmed it, cleaned and short enough for GitHub's limit."
40
+ export function renderTitle(c, { confirmed = false } = {}) {
41
+ const desc = clean(c.description, 110) || `${clean(c.threat, 40)} on ${clean(c.asset, 40)}`;
42
+ const more = clean(c.description, 111).length > 110 ? '…' : '';
43
+ return `[bravos] ${titleCase(c.severity)}${confirmed ? ', confirmed' : ''}: ${desc}${more} (${clean(c.file, 100)}:${c.line})`;
44
+ }
45
+
46
+ // @comment -- "The issue's body: the hidden key marker on the first line, the claim, where it is (a link to the line at the commit the nightly read), how long it has waited, and the three ways to close it: test it with bravos-prove, fix it with a @mitigates, or have a named person accept it. Annotation text appears only fenced or in inline code."
47
+ export function renderBody(c, { days, link }) {
48
+ const where = link ? `[${code(`${c.file}:${c.line}`)}](${link})` : code(`${c.file}:${c.line}`);
49
+ return [
50
+ `<!-- ${MARKER} ${c.key} -->`,
51
+ `**${titleCase(c.severity)}** · untested · ${code(c.threat, 80)} on ${code(c.asset, 80)}${c.cwe ? ` · ${c.cwe}` : ''}`,
52
+ '',
53
+ fenced(clean(c.description, 2000) || '(no description)'),
54
+ '',
55
+ `- **Where:** ${where}`,
56
+ `- **Recorded:** ${c.since.slice(0, 10)}${c.commit ? ` in ${code(c.commit.slice(0, 12))}` : ''}, and no test has confirmed or refuted it in the ${days} day${days === 1 ? '' : 's'} since.`,
57
+ '',
58
+ '### How to close it',
59
+ '',
60
+ 'Test it first. The nightly closes this issue by itself once a refutation, a fix or an acceptance is on the default branch:',
61
+ '',
62
+ `- **Test it.** Run \`bravos-prove\` on this claim against your own app (\`bravos-env\` sets up the target first). A refuted result in \`.guardlink/hypotheses.json\` closes it. A confirmed one keeps it open, relabelled \`confirmed\`, and blocks pull requests that change this code until it is fixed or ticketed.`,
63
+ `- **Fix it.** Fix the code and add \`@mitigates ${clean(c.asset, 80).replace(/`/g, "'")} against ${clean(c.threat, 80).replace(/`/g, "'")} using #<control>\` beside the fix.`,
64
+ `- **Accept it.** A named person decides to live with it and writes the \`@accepts\` line themselves, with their name and reasons. Agents never write it.`,
65
+ '',
66
+ 'Removing a claim that turns out to be wrong closes it too.',
67
+ '',
68
+ `<sub>Opened by the bravos nightly team view (repository variable \`BRAVOS_THREAT_ISSUES\`). Claim key \`${c.key}\`.</sub>`,
69
+ ].join('\n');
70
+ }
71
+
72
+ const readJson = (p, what) => {
73
+ try {
74
+ return JSON.parse(readFileSync(p, 'utf8'));
75
+ } catch {
76
+ throw new Error(`unknown: ${what} is not JSON`);
77
+ }
78
+ };
79
+
80
+ // @comment -- "Joins the three GuardLink answers into one row per critical or high @exposes claim: the hypothesis record (key, state, severity) to its model exposure by declaration site, as the PR gate does, for the description, cwe and the logical file and line; to its blame entry by claim key, for when its annotation was committed (found_by) and whether a @mitigates covers it (fixed_by); and to an unexpired @accepts on the same asset and threat. Rows that cannot be joined are counted, never guessed."
81
+ export function claims(model, ledger, blame, today = new Date().toISOString().slice(0, 10)) {
82
+ const exposures = Array.isArray(model?.exposures) ? model.exposures : [];
83
+ const acceptances = Array.isArray(model?.acceptances) ? model.acceptances : [];
84
+ const byKey = new Map((Array.isArray(blame?.entries) ? blame.entries : []).filter((e) => e && e.verb === 'exposes').map((e) => [e.key, e]));
85
+ const rows = new Map();
86
+ let unjoined = 0;
87
+ for (const r of ledger.records) {
88
+ if (!r || typeof r.key !== 'string' || !KEY.test(r.key)) continue;
89
+ const severity = String(r.severity ?? '').toLowerCase();
90
+ const site = exposures.filter((e) => e.asset === r.asset && e.threat === r.threat && (e.location?.origin_file ?? e.location?.file) === r.file && (e.location?.origin_line ?? e.location?.line) === r.line);
91
+ if (site.length !== 1) {
92
+ if (SEVERE.has(severity)) unjoined++;
93
+ rows.set(r.key, { key: r.key, state: r.state, severity, joined: false });
94
+ continue;
95
+ }
96
+ const e = site[0];
97
+ const b = byKey.get(r.key)?.blame;
98
+ const accepted = acceptances.find((a) => a.asset === r.asset && a.threat === r.threat && (!a.expires || String(a.expires) >= today));
99
+ const cwe = (e.external_refs ?? []).map((x) => /^cwe:(CWE-\d{1,5})$/i.exec(String(x))?.[1]).find(Boolean)?.toUpperCase() ?? null;
100
+ rows.set(r.key, {
101
+ key: r.key,
102
+ joined: true,
103
+ state: r.state,
104
+ severity,
105
+ asset: r.asset,
106
+ threat: r.threat,
107
+ description: e.description ?? '',
108
+ cwe,
109
+ file: e.location?.file ?? r.file,
110
+ line: e.location?.line ?? r.line,
111
+ since: typeof b?.found_by?.date === 'string' ? b.found_by.date : null,
112
+ commit: typeof b?.found_by?.sha === 'string' ? b.found_by.sha : null,
113
+ fixed: !!b?.fixed_by,
114
+ // A recorded result, holding or lapsed: GuardLink keeps the entry (outcome) and, once code changed, the lapsed result (previous).
115
+ tested: !!(r.outcome || r.previous),
116
+ last: r.outcome?.outcome ?? r.previous?.outcome ?? null,
117
+ accepted: accepted ? (accepted.accepted_by ?? 'a named person') : null,
118
+ });
119
+ }
120
+ return { rows, unjoined };
121
+ }
122
+
123
+ // @comment -- "Why a claim no longer needs its issue, or null while it still does. Confirmed and retest are never reasons: a proven threat stays in the team's view until it is fixed or accepted, and a retest is untested again."
124
+ export function closeReason(row) {
125
+ if (!row) return 'The claim is no longer in the threat model (its @exposes was removed or rewritten).';
126
+ if (row.state === 'refuted') return 'A test refuted it: the attack did not work against this code.';
127
+ if (row.accepted) return `Accepted by ${code(row.accepted, 80)} with an @accepts line.`;
128
+ if (row.fixed) return 'Fixed: a @mitigates now covers it.';
129
+ if (!SEVERE.has(row.severity)) return `Its severity is now ${code(row.severity || 'unrated', 20)}, below high.`;
130
+ return null;
131
+ }
132
+
133
+ // @comment -- "The comment on an issue the nightly reopens, by the reason the claim needs it again."
134
+ export function reopenComment(row) {
135
+ if (row.state === 'retest') return 'Retest due: a test confirmed this threat, and the code under it changed after that, so the result no longer applies. Replay the test (bravos-recheck) or run bravos-prove again.';
136
+ if (row.last === 'refuted') return 'Untested again: a test refuted this threat, and the code under it changed after that, so the result no longer applies.';
137
+ return 'Open again: this claim is critical or high and untested once more; what closed the issue (a fix, an acceptance, a lower severity or its removal) no longer holds.';
138
+ }
139
+
140
+ // @comment -- "An issue counts as a claim's issue only when the workflow's own bot opened it and its body's first line is the marker with a key of GuardLink's shape: a marker in someone else's issue, or quoted inside a description further down, is never read."
141
+ // @exposes #threat-issues to #forged-issue-key [low] cwe:CWE-345 -- "existing() trusts the hidden marker on an issue's first line to say which claim the issue tracks; a forged marker would hide a claim's issue or close the wrong one"
142
+ // @mitigates #threat-issues against #forged-issue-key using #bot-authored-marker -- "only issues whose author is exactly the github-actions bot (app/github-actions or github-actions[bot], is_bot) are read, never another app whose name merely contains it; only the first line is parsed, and the key must match GuardLink's claim-key shape"
143
+ export function existing(issues) {
144
+ const out = new Map();
145
+ for (const i of Array.isArray(issues) ? issues : []) {
146
+ if (!i?.author?.is_bot || !BOT.test(String(i.author.login ?? ''))) continue;
147
+ const body = String(i.body ?? '');
148
+ const m = new RegExp(`^<!-- ${MARKER} ([0-9a-f]{64}:\\d+) -->`).exec(body.split('\n')[0] ?? '');
149
+ if (!m || out.has(m[1])) continue;
150
+ const lines = body.trimEnd().split('\n');
151
+ const labels = (Array.isArray(i.labels) ? i.labels : []).map((l) => String(l?.name ?? l).toLowerCase());
152
+ out.set(m[1], { number: i.number, open: String(i.state).toUpperCase() === 'OPEN', closedByBravos: lines[lines.length - 1]?.trim() === CLOSED_MARKER, labels, body });
153
+ }
154
+ return out;
155
+ }
156
+
157
+ // @comment -- "What one run does, decided before gh is called: close the open issues whose claim no longer needs one; relabel and retitle an open issue whose claim a test confirmed; open an issue for each due claim that has none and never had a test result (most severe and oldest first, at most MAX_NEW); and reopen an issue the nightly itself closed when its claim is untested or due a retest again. An issue a person closed stays closed, and one a person reopened after the nightly closed it stays open."
158
+ export function plan(rows, issues, { days, now = Date.now() }) {
159
+ const close = [];
160
+ const confirm = [];
161
+ const open = [];
162
+ const reopen = [];
163
+ const waiting = [];
164
+ let manual = 0;
165
+ let manualOpen = 0;
166
+ let tested = 0;
167
+ for (const [key, issue] of issues) {
168
+ if (!issue.open) continue;
169
+ // Still ends with the nightly's closing note, yet open: a person reopened it, and that is their call.
170
+ if (issue.closedByBravos) {
171
+ manualOpen++;
172
+ continue;
173
+ }
174
+ const row = rows.get(key);
175
+ const reason = closeReason(row);
176
+ if (reason) close.push({ key, number: issue.number, reason, body: issue.body, labels: issue.labels });
177
+ else if (row?.joined && row.state === 'confirmed' && !issue.labels.includes('confirmed')) confirm.push({ ...row, number: issue.number, labels: issue.labels });
178
+ }
179
+ const due = [];
180
+ for (const row of rows.values()) {
181
+ if (!row.joined || (row.state !== 'untested' && row.state !== 'retest') || closeReason(row)) continue;
182
+ const issue = issues.get(row.key);
183
+ if (issue?.open) continue;
184
+ if (issue && !issue.closedByBravos) {
185
+ manual++;
186
+ continue;
187
+ }
188
+ // A claim with a test result, holding or lapsed (every retest has one), was tested in time: it gets no new issue,
189
+ // only its old one back. Its changed code is the PR gate's to flag.
190
+ if (!issue && row.tested) {
191
+ tested++;
192
+ continue;
193
+ }
194
+ if (!row.since || Number.isNaN(Date.parse(row.since))) {
195
+ waiting.push({ ...row, why: 'no commit date from guardlink blame' });
196
+ continue;
197
+ }
198
+ const age = Math.floor((now - Date.parse(row.since)) / DAY_MS);
199
+ if (age < days) {
200
+ waiting.push({ ...row, why: `untested for ${age} of ${days} days` });
201
+ continue;
202
+ }
203
+ (issue ? reopen : due).push({ ...row, age, number: issue?.number });
204
+ }
205
+ due.sort((a, b) => (a.severity === b.severity ? 0 : a.severity === 'critical' ? -1 : 1) || Date.parse(a.since) - Date.parse(b.since) || a.key.localeCompare(b.key));
206
+ open.push(...due.slice(0, MAX_NEW));
207
+ return { close, confirm, open, reopen, waiting, manual, manualOpen, tested, deferred: Math.max(0, due.length - MAX_NEW) };
208
+ }
209
+
210
+ function gh(args) {
211
+ const r = spawnSync('gh', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
212
+ return { ok: r.status === 0, out: r.stdout ?? '', err: (r.stderr || r.error?.message || '').trim() };
213
+ }
214
+
215
+ // @comment -- "Runs the plan with gh against the job's repository and GITHUB_TOKEN: creates any of its labels that are missing, writes every body to a private temp file passed by --body-file, and passes titles, labels and comments as single arguments. A failed gh call is reported and fails the run at the end; the rest still runs, and the next run picks up where it stopped."
216
+ // @flows #threat-issues -> #github-issues via gh -- "issue list, label list/create, issue create/edit/close/reopen with the job's GITHUB_TOKEN (issues: write)"
217
+ export function main(argv = process.argv.slice(2), env = process.env) {
218
+ const [modelPath, ledgerPath, blamePath] = argv;
219
+ const out = (l) => process.stdout.write(l + '\n');
220
+ const fail = (l) => {
221
+ out(`::error::${l}`);
222
+ return 1;
223
+ };
224
+ const repo = String(env.REPO ?? '');
225
+ if (!/^[\w.-]+\/[\w.-]+$/.test(repo)) return fail('unknown: REPO is not owner/name');
226
+ const rawDays = String(env.DAYS ?? '').trim();
227
+ if (rawDays && !/^\d{1,3}$/.test(rawDays)) return fail(`BRAVOS_THREAT_ISSUES_DAYS must be a whole number of days, not ${JSON.stringify(clean(rawDays, 20))}`);
228
+ const days = rawDays ? Number(rawDays) : 2;
229
+ let model, ledger, blame;
230
+ try {
231
+ model = readJson(modelPath, 'guardlink parse');
232
+ ledger = readJson(ledgerPath, 'guardlink hypothesis list');
233
+ blame = readJson(blamePath, 'guardlink blame');
234
+ } catch (e) {
235
+ return fail(e.message);
236
+ }
237
+ if (!Array.isArray(model?.exposures)) return fail('unknown: guardlink parse has no exposures[]');
238
+ if (!['present', 'absent'].includes(ledger?.ledger) || !Array.isArray(ledger?.records)) return fail('unknown: GuardLink hypothesis ledger unreadable');
239
+ if (!Array.isArray(blame?.entries)) return fail('unknown: guardlink blame has no entries[]');
240
+
241
+ // Listed twice and joined by number: by the bravos label, and by the github-actions author (GitHub's author:app/ search),
242
+ // so an issue whose label someone removed is still found and never gets a second one.
243
+ const fields = 'number,state,title,body,author,labels';
244
+ const issues = new Map();
245
+ let full = false;
246
+ for (const by of [['--label', 'bravos'], ['--search', 'author:app/github-actions']]) {
247
+ const listed = gh(['issue', 'list', '-R', repo, ...by, '--state', 'all', '--limit', String(LIST_LIMIT), '--json', fields]);
248
+ try {
249
+ if (!listed.ok) throw new Error(listed.err);
250
+ const page = JSON.parse(listed.out);
251
+ if (!Array.isArray(page)) throw new Error('not a list');
252
+ if (page.length >= LIST_LIMIT) full = true;
253
+ for (const i of page) if (i && !issues.has(i.number)) issues.set(i.number, i);
254
+ } catch (e) {
255
+ return fail(`unknown: gh issue list ${by.join(' ')} failed: ${clean(e.message, 200)}`);
256
+ }
257
+ }
258
+ if (full) out(`::warning::An issue list reached gh's ${LIST_LIMIT}-issue limit: an older claim's issue may be missed, and opened again.`);
259
+ const { rows, unjoined } = claims(model, ledger, blame);
260
+ const p = plan(rows, existing([...issues.values()]), { days });
261
+ const sha = /^[0-9a-f]{40}$/.test(String(env.SHA ?? '')) ? env.SHA : null;
262
+ const server = /^https:\/\/[\w.-]+(:\d+)?$/.test(String(env.SERVER ?? '')) ? env.SERVER : null;
263
+ const link = (c) => (sha && server ? `${server}/${repo}/blob/${sha}/${String(c.file).split('/').map(encodeURIComponent).join('/')}#L${Number(c.line) || 1}` : null);
264
+ const dir = mkdtempSync(join(env.RUNNER_TEMP || tmpdir(), 'bravos-issues-'));
265
+ let n = 0;
266
+ const bodyFile = (text) => {
267
+ const f = join(dir, `body-${++n}.md`);
268
+ writeFileSync(f, text + '\n', { mode: 0o600 });
269
+ return f;
270
+ };
271
+ let failed = 0;
272
+ const run = (args, what) => {
273
+ const r = gh(args);
274
+ if (!r.ok) {
275
+ failed++;
276
+ out(`::warning::${what} failed: ${clean(r.err, 300)}`);
277
+ }
278
+ return r;
279
+ };
280
+
281
+ // Labels the new and reopened issues carry, created when missing.
282
+ const wanted = new Set();
283
+ for (const c of [...p.open, ...p.reopen]) for (const l of ['bravos', 'untested', c.severity, ...(c.cwe ? [c.cwe] : [])]) wanted.add(l);
284
+ if (p.confirm.length) wanted.add('confirmed');
285
+ if (wanted.size) {
286
+ const have = gh(['label', 'list', '-R', repo, '--limit', '1000', '--json', 'name']);
287
+ let names = new Set();
288
+ try {
289
+ names = new Set(JSON.parse(have.out).map((l) => String(l.name).toLowerCase()));
290
+ } catch {
291
+ /* unknown: try to create each; an existing one only fails that call */
292
+ }
293
+ for (const l of wanted) {
294
+ if (names.has(l.toLowerCase())) continue;
295
+ const [color, description] = LABELS[l] ?? ['5319E7', `Weakness ${l}`];
296
+ gh(['label', 'create', l, '-R', repo, '--color', color, '--description', description]);
297
+ }
298
+ }
299
+
300
+ const today = new Date().toISOString().slice(0, 10);
301
+ for (const c of p.close) {
302
+ const closedBody = `${c.body.trimEnd()}\n\n---\n\nClosed by the bravos nightly on ${today}: ${c.reason}\n\n${CLOSED_MARKER}`;
303
+ const drop = c.labels.includes('untested') ? ['--remove-label', 'untested'] : [];
304
+ if (run(['issue', 'edit', String(c.number), '-R', repo, '--body-file', bodyFile(closedBody), ...drop], `editing #${c.number}`).ok &&
305
+ run(['issue', 'close', String(c.number), '-R', repo, '--reason', 'completed', '--comment', c.reason], `closing #${c.number}`).ok) out(`closed #${c.number}: ${c.reason}`);
306
+ }
307
+ for (const c of p.confirm) {
308
+ const drop = c.labels.includes('untested') ? ['--remove-label', 'untested'] : [];
309
+ if (run(['issue', 'edit', String(c.number), '-R', repo, '--title', renderTitle(c, { confirmed: true }), '--add-label', 'confirmed', ...drop], `relabelling #${c.number}`).ok &&
310
+ run(['issue', 'comment', String(c.number), '-R', repo, '--body-file', bodyFile('A test confirmed this threat is exploitable. The issue stays open until it is fixed (a @mitigates beside the fix) or a named person accepts it, and the PR gate blocks changes to this code until then unless a @ticket tracks it.')], `commenting on #${c.number}`).ok) out(`confirmed #${c.number}`);
311
+ }
312
+ for (const c of p.reopen) {
313
+ const labels = ['untested', c.severity, ...(c.cwe ? [c.cwe] : [])].join(',');
314
+ if (run(['issue', 'edit', String(c.number), '-R', repo, '--title', renderTitle(c), '--body-file', bodyFile(renderBody(c, { days: c.age, link: link(c) })), '--add-label', labels], `editing #${c.number}`).ok &&
315
+ run(['issue', 'reopen', String(c.number), '-R', repo, '--comment', reopenComment(c)], `reopening #${c.number}`).ok) out(`reopened #${c.number}`);
316
+ }
317
+ for (const c of p.open) {
318
+ const labels = ['bravos', c.severity, 'untested', ...(c.cwe ? [c.cwe] : [])].join(',');
319
+ const r = run(['issue', 'create', '-R', repo, '--title', renderTitle(c), '--body-file', bodyFile(renderBody(c, { days: c.age, link: link(c) })), '--label', labels], `opening an issue for ${c.file}:${c.line}`);
320
+ if (r.ok) out(`opened ${clean(r.out, 200)}`);
321
+ }
322
+
323
+ const summary = [
324
+ '### Untested threats (team view)',
325
+ '',
326
+ `Critical and high claims still untested ${days} day${days === 1 ? '' : 's'} after they were committed get an issue; a confirmed one keeps it open.`,
327
+ '',
328
+ `- opened ${p.open.length}, reopened ${p.reopen.length}, marked confirmed ${p.confirm.length}, closed ${p.close.length}`,
329
+ `- ${issues.size} issue(s) read (labelled bravos or opened by github-actions; at most ${LIST_LIMIT} each list)${full ? `: a list reached the limit, so an older issue may be missed and opened again` : ''}`,
330
+ ...(p.deferred ? [`- ${p.deferred} more due: opened on later runs, ${MAX_NEW} a run`] : []),
331
+ ...(p.waiting.length ? [`- ${p.waiting.length} not due yet (${p.waiting.slice(0, 5).map((w) => `${code(`${w.file}:${w.line}`, 120)} ${w.why}`).join('; ')}${p.waiting.length > 5 ? '; …' : ''})`] : []),
332
+ ...(p.manual ? [`- ${p.manual} still untested with an issue a person closed: left closed`] : []),
333
+ ...(p.manualOpen ? [`- ${p.manualOpen} reopened by a person after the nightly closed it: left open`] : []),
334
+ ...(p.tested ? [`- ${p.tested} untested again or due a retest after an earlier result, with no issue: none opened (the PR gate flags changes under them)`] : []),
335
+ ...(unjoined ? [`- ${unjoined} critical or high claim(s) could not be matched to one exposure in the model: skipped`] : []),
336
+ '',
337
+ ].join('\n');
338
+ out(summary);
339
+ if (env.GITHUB_STEP_SUMMARY) appendFileSync(env.GITHUB_STEP_SUMMARY, summary + '\n');
340
+ return failed ? fail(`${failed} gh call(s) failed; the next run retries them`) : 0;
341
+ }
342
+
343
+ if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) process.exitCode = main();
@@ -0,0 +1,56 @@
1
+ // @comment -- "The hooks' copy of src/tool-path.ts (the hook scripts are installed apart from the CLI and cannot import it): finds a tool on PATH or, for cxg, in cargo's folder (CARGO_INSTALL_ROOT, else CARGO_HOME, else ~/.cargo, then /bin) so a session whose PATH is shorter than the person's terminal still runs cxg and is told how to fix PATH. File checks only; nothing is run. Dependency-free."
2
+ import { accessSync, constants, statSync } from 'node:fs';
3
+ import { delimiter, isAbsolute, join, resolve } from 'node:path';
4
+
5
+ export function cargoBinDir(env) {
6
+ const root = env.CARGO_INSTALL_ROOT || env.CARGO_HOME || (env.HOME ? join(env.HOME, '.cargo') : null);
7
+ return root ? join(isAbsolute(root) ? root : resolve(root), 'bin') : null;
8
+ }
9
+
10
+ const executable = (file) => {
11
+ try {
12
+ if (!statSync(file).isFile()) return false;
13
+ accessSync(file, constants.X_OK);
14
+ return true;
15
+ } catch {
16
+ return false;
17
+ }
18
+ };
19
+
20
+ // cargo's folder, for cxg: other tools are found on PATH only.
21
+ export function fallbackDirs(name, env) {
22
+ const dir = name === 'cxg' ? cargoBinDir(env) : null;
23
+ return dir ? [dir] : [];
24
+ }
25
+
26
+ // @comment -- "The first executable named name on PATH, else (unless fallback is false) in its fallback folders; { path, onPath, dir } or null."
27
+ export function findTool(name, env = process.env, { fallback = true } = {}) {
28
+ for (const dir of String(env.PATH ?? '').split(delimiter)) {
29
+ if (dir && executable(join(dir, name))) return { path: join(dir, name), onPath: true, dir };
30
+ }
31
+ if (!fallback) return null;
32
+ for (const dir of fallbackDirs(name, env)) {
33
+ if (executable(join(dir, name))) return { path: join(dir, name), onPath: false, dir };
34
+ }
35
+ return null;
36
+ }
37
+
38
+ /** env with the tool's folder added to the end of PATH, so the tool and what it starts are found. */
39
+ export function withToolDir(env, found) {
40
+ if (!found || found.onPath) return env;
41
+ return { ...env, PATH: [env.PATH, found.dir].filter(Boolean).join(delimiter) };
42
+ }
43
+
44
+ /** How to put the folder on PATH for good, in the person's own shell: ~/.zshenv for zsh, which every zsh reads. */
45
+ export function pathFix(dir, env) {
46
+ const shown = env.HOME && dir.startsWith(env.HOME + '/') ? `$HOME${dir.slice(env.HOME.length)}` : dir;
47
+ const shell = String(env.SHELL ?? '').split('/').pop();
48
+ if (shell === 'fish') return `fish_add_path ${shown}`;
49
+ return `echo 'export PATH="${shown}:$PATH"' >> ${shell === 'bash' ? '~/.bash_profile' : shell === 'zsh' ? '~/.zshenv' : '~/.profile'}`;
50
+ }
51
+
52
+ // @comment -- "The briefing's cxg line when cxg is installed but its folder is not on this session's PATH: run it by its full path (or put the folder in front of PATH for the command), never say it is not installed, and tell the person once the line that fixes their shell. Null when cxg is on PATH or not installed at all."
53
+ export function cxgPathLine(found, env) {
54
+ if (!found || found.onPath) return null;
55
+ return `cxg: installed at ${found.path}, but its folder is not on PATH in this session. It is not missing: run it as ${found.path} (or start the command with PATH="${found.dir}:$PATH"), and tell the person once that ${pathFix(found.dir, env)} makes every new session find it.`;
56
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bugb-technologies/bravos",
3
- "version": "1.12.0",
3
+ "version": "1.14.0",
4
4
  "description": "Skills pack and installer that make Claude Code and Codex power users of guardlink (threat-model-as-code) and cert-x-gen (pentest-as-code).",
5
5
  "keywords": [
6
6
  "security",
@@ -9,6 +9,7 @@ description: "Bring up a test target the user owns and prepare it for an authori
9
9
  - bravos-prove or bravos-recheck needs a running target and none is up.
10
10
  - The user asks to start the app for testing, seed test users, roles or orgs, or capture a login session.
11
11
  - A run was refused at pre-flight (cxg exit 4) or stopped on a dead session (exit 5).
12
+ - cxg looks missing: Before you say cxg is missing, check where it is: the briefing's `cxg:` line or `bravos doctor` names it when it is installed but its folder is not on this session's PATH (cxg lives in cargo's folder, `~/.cargo/bin`). Then it is not missing: run it by that full path, or start each command with `PATH="$HOME/.cargo/bin:$PATH"`, and tell the person once the line that fixes their shell. Only `bravos doctor` saying `✘ cxg` means it is not installed (`bravos setup --tools` installs it, with their go-ahead).
12
13
 
13
14
  ## Do
14
15
 
@@ -12,7 +12,7 @@ description: "Prove a new or changed GuardLink claim, or replay it after a fix,
12
12
 
13
13
  ## Do
14
14
 
15
- 1. Check the preconditions from bravos-env before any traffic: authorization for this run, a target that answers, `.guardlink/scope.yaml` committed, each profile passing `cxg pentest auth verify --profile <name>`, and for any non-loopback target both a reviewed scope and the human's authorization typed in this session. If one is missing, stop and hand back to bravos-env. Read the effort: the user's words ("at high"), else a `bravos effort: <level>` line in `AGENTS.md` / `CLAUDE.md`, else medium. It sets a starting budget, not a limit; go beyond it when the work needs it and say why in one line. Starting budget — low: replay a matching kit; medium: also author the first missing test in this session; high: include affected callers and controls; max: cover the testable in-scope queue. A higher effort does not authorize spending on an external model.
15
+ 1. Before you say cxg is missing, check where it is: the briefing's `cxg:` line or `bravos doctor` names it when it is installed but its folder is not on this session's PATH (cxg lives in cargo's folder, `~/.cargo/bin`). Then it is not missing: run it by that full path, or start each command with `PATH="$HOME/.cargo/bin:$PATH"`, and tell the person once the line that fixes their shell. Only `bravos doctor` saying `✘ cxg` means it is not installed (`bravos setup --tools` installs it, with their go-ahead). Check the preconditions from bravos-env before any traffic: authorization for this run, a target that answers, `.guardlink/scope.yaml` committed, each profile passing `cxg pentest auth verify --profile <name>`, and for any non-loopback target both a reviewed scope and the human's authorization typed in this session. If one is missing, stop and hand back to bravos-env. Read the effort: the user's words ("at high"), else a `bravos effort: <level>` line in `AGENTS.md` / `CLAUDE.md`, else medium. It sets a starting budget, not a limit; go beyond it when the work needs it and say why in one line. Starting budget — low: replay a matching kit; medium: also author the first missing test in this session; high: include affected callers and controls; max: cover the testable in-scope queue. A higher effort does not authorize spending on an external model.
16
16
  2. Order what to test, then read how the person wants proving handled. With the code graph (its MCP tools, or `bravos graph <question> --json` — same answers; see bravos-codegraph) (briefing `Code graph:` says `current`): `codegraph_untested_exposures` and `codegraph_untested_reach` rank untested exposures by reach; test the ones intent.md's Assumptions put in scope first, least privileged entry point first, and report exposures only an out-of-scope attacker reaches instead of running them. Without the graph, say "code graph unavailable; using guardlink hypothesis next order" and use that queue. Within that order, an exposure with a reachable SAST finding joined to it (`bravos sast candidates`) goes before one without, and its route goes into the run notes; with no SAST report or SAST unavailable, skip this. Then, for how the person wants proving handled: the briefing's `Proving:` line, from `.guardlink/proving.md`. If it is not set, ask them once, with a suggestion drawn from the repo (for example, "you have a docker-compose; I'd prove automatically on 127.0.0.1:8080"): prove automatically on their loopback target whenever new or changed exposures appear, ask each time, on a schedule (bravos-schedule's nightly), or not now. Record their answer in `.guardlink/proving.md`: lines `choice: auto|ask|schedule|none`, `target: <loopback url>`, `start: <start command>`, `generation: no` (Bravos never uses cxg's model generation), their words quoted verbatim, and `— confirmed by <their name>, <date>`. Before offering or following `auto`, check that `git symbolic-ref --quiet refs/remotes/origin/HEAD` names an existing commit. If missing, warn: fetch the default branch, then `git remote set-head origin --auto` (or `git remote set-head origin <branch>`); use `ask` meanwhile. Then follow it: `auto` proceeds on that target with their quoted words as the attestation; `ask` asks now; `schedule` hands to bravos-schedule; `none` stops here and says so. When they change their mind, rewrite the file with their new words.
17
17
  3. Read the affected claim from `guardlink hypothesis list --json`. Include a declared mitigation awaiting its first test and a previously confirmed claim now marked retest. Match its key to the logical source location in `guardlink sarif . --profile pentest -o whitebox/findings.sarif`; external annotations also have a physical declaration in a .gal file. Keep both locations. Record the tested source revision or worktree, application build, identity roles and intended oracle.
18
18
  4. For a web claim, use its bound JavaScript kit in .guardlink/cxg-replay/. For a missing or mismatched kit, follow bravos-templatize in this session. A matching kit exercises the intended operation and includes a positive control for a claimed defense. Validate the kit and review its scope. Honor the recorded kit policy and the person’s stated limits. An automatic reviewed-only policy requires identical bound test bytes on the default branch. On a clone whose upstream has no testing policy, use `ask` with locally committed policy and scope and typed authorization for loopback `run-once`. The earlier wizard’s “only replay tests I approved” choice retains that restriction.
@@ -11,6 +11,11 @@
11
11
  # delete that secret to run on your plan instead. Also enable Settings > Actions > General >
12
12
  # "Allow GitHub Actions to create and approve pull requests". Pin the actions to commit SHAs if
13
13
  # your organisation requires it.
14
+ # Team view, off by default: set the repository variable BRAVOS_THREAT_ISSUES to on (Settings > Secrets and
15
+ # variables > Actions > Variables) and the threat-issues job opens one issue per critical or high threat still
16
+ # untested BRAVOS_THREAT_ISSUES_DAYS days (default 2) after it was committed. A confirmed threat keeps its issue,
17
+ # relabelled confirmed; it closes once the threat is refuted, fixed, accepted or removed. It needs no secret: the
18
+ # job's own token opens the issues.
14
19
  name: bravos nightly (Claude Code)
15
20
 
16
21
  on:
@@ -267,3 +272,58 @@ jobs:
267
272
  guardlink diff "$START" --markdown || true
268
273
  } > "$RUNNER_TEMP/body.md"
269
274
  gh pr create --base "$base" --head "$branch" --title "annotate: nightly coverage slice" --body-file "$RUNNER_TEMP/body.md"
275
+
276
+ # The team view, off by default: with the repository variable BRAVOS_THREAT_ISSUES set to on, one issue per critical
277
+ # or high @exposes claim still untested BRAVOS_THREAT_ISSUES_DAYS days (default 2) after its annotation was committed,
278
+ # relabelled confirmed when a test confirms it, and closed by a later run once the claim is refuted, fixed, accepted
279
+ # or removed; a claim untested again or due a retest reopens the issue the nightly closed. It reads the default
280
+ # branch as merged with guardlink and writes issues with gh and this job's own token; no agent runs here, and annotation
281
+ # text reaches gh only as arguments and --body-file from hooks/lib/threat-issues.mjs, never as a shell line.
282
+ threat-issues:
283
+ if: vars.BRAVOS_THREAT_ISSUES == 'on' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch)
284
+ runs-on: ubuntu-latest
285
+ timeout-minutes: 15
286
+ permissions:
287
+ contents: read
288
+ issues: write
289
+ defaults:
290
+ run:
291
+ shell: bash
292
+ steps:
293
+ - uses: actions/checkout@v4
294
+ with:
295
+ # guardlink blame reads when each claim was committed from the full history.
296
+ fetch-depth: 0
297
+ persist-credentials: false
298
+
299
+ - uses: actions/setup-node@v4
300
+ with:
301
+ node-version: 22
302
+
303
+ - name: Install guardlink
304
+ run: bash .bravos/hooks/lib/nightly-tools.sh annotate
305
+
306
+ - name: Issues for untested threats
307
+ env:
308
+ GH_TOKEN: ${{ github.token }}
309
+ REPO: ${{ github.repository }}
310
+ SERVER: ${{ github.server_url }}
311
+ SHA: ${{ github.sha }}
312
+ DAYS: ${{ vars.BRAVOS_THREAT_ISSUES_DAYS }}
313
+ run: |
314
+ model="$RUNNER_TEMP/bravos-issues-model.json"
315
+ ledger="$RUNNER_TEMP/bravos-issues-ledger.json"
316
+ blame="$RUNNER_TEMP/bravos-issues-blame.json"
317
+ if ! guardlink parse . > "$model" || ! jq -e '.exposures | arrays' "$model" > /dev/null; then
318
+ echo "::error::unknown: guardlink parse failed"
319
+ exit 1
320
+ fi
321
+ if ! guardlink hypothesis list --json > "$ledger" || ! jq -e '(.ledger == "present" or .ledger == "absent") and (.records | arrays)' "$ledger" > /dev/null; then
322
+ echo "::error::unknown: GuardLink hypothesis ledger unreadable"
323
+ exit 1
324
+ fi
325
+ if ! guardlink blame . --json > "$blame" || ! jq -e '.entries | arrays' "$blame" > /dev/null; then
326
+ echo "::error::unknown: guardlink blame failed"
327
+ exit 1
328
+ fi
329
+ node .bravos/hooks/lib/threat-issues.mjs "$model" "$ledger" "$blame"
@@ -8,6 +8,11 @@
8
8
  # Needs the repo secret OPENAI_API_KEY, and Settings > Actions > General > "Allow GitHub
9
9
  # Actions to create and approve pull requests". Pin the actions to commit SHAs if your
10
10
  # organisation requires it.
11
+ # Team view, off by default: set the repository variable BRAVOS_THREAT_ISSUES to on (Settings > Secrets and
12
+ # variables > Actions > Variables) and the threat-issues job opens one issue per critical or high threat still
13
+ # untested BRAVOS_THREAT_ISSUES_DAYS days (default 2) after it was committed. A confirmed threat keeps its issue,
14
+ # relabelled confirmed; it closes once the threat is refuted, fixed, accepted or removed. It needs no secret: the
15
+ # job's own token opens the issues.
11
16
  name: bravos nightly (Codex)
12
17
 
13
18
  on:
@@ -262,3 +267,58 @@ jobs:
262
267
  guardlink diff "$START" --markdown || true
263
268
  } > "$RUNNER_TEMP/body.md"
264
269
  gh pr create --base "$base" --head "$branch" --title "annotate: nightly coverage slice" --body-file "$RUNNER_TEMP/body.md"
270
+
271
+ # The team view, off by default: with the repository variable BRAVOS_THREAT_ISSUES set to on, one issue per critical
272
+ # or high @exposes claim still untested BRAVOS_THREAT_ISSUES_DAYS days (default 2) after its annotation was committed,
273
+ # relabelled confirmed when a test confirms it, and closed by a later run once the claim is refuted, fixed, accepted
274
+ # or removed; a claim untested again or due a retest reopens the issue the nightly closed. It reads the default
275
+ # branch as merged with guardlink and writes issues with gh and this job's own token; no agent runs here, and annotation
276
+ # text reaches gh only as arguments and --body-file from hooks/lib/threat-issues.mjs, never as a shell line.
277
+ threat-issues:
278
+ if: vars.BRAVOS_THREAT_ISSUES == 'on' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch)
279
+ runs-on: ubuntu-latest
280
+ timeout-minutes: 15
281
+ permissions:
282
+ contents: read
283
+ issues: write
284
+ defaults:
285
+ run:
286
+ shell: bash
287
+ steps:
288
+ - uses: actions/checkout@v4
289
+ with:
290
+ # guardlink blame reads when each claim was committed from the full history.
291
+ fetch-depth: 0
292
+ persist-credentials: false
293
+
294
+ - uses: actions/setup-node@v4
295
+ with:
296
+ node-version: 22
297
+
298
+ - name: Install guardlink
299
+ run: bash .bravos/hooks/lib/nightly-tools.sh annotate
300
+
301
+ - name: Issues for untested threats
302
+ env:
303
+ GH_TOKEN: ${{ github.token }}
304
+ REPO: ${{ github.repository }}
305
+ SERVER: ${{ github.server_url }}
306
+ SHA: ${{ github.sha }}
307
+ DAYS: ${{ vars.BRAVOS_THREAT_ISSUES_DAYS }}
308
+ run: |
309
+ model="$RUNNER_TEMP/bravos-issues-model.json"
310
+ ledger="$RUNNER_TEMP/bravos-issues-ledger.json"
311
+ blame="$RUNNER_TEMP/bravos-issues-blame.json"
312
+ if ! guardlink parse . > "$model" || ! jq -e '.exposures | arrays' "$model" > /dev/null; then
313
+ echo "::error::unknown: guardlink parse failed"
314
+ exit 1
315
+ fi
316
+ if ! guardlink hypothesis list --json > "$ledger" || ! jq -e '(.ledger == "present" or .ledger == "absent") and (.records | arrays)' "$ledger" > /dev/null; then
317
+ echo "::error::unknown: GuardLink hypothesis ledger unreadable"
318
+ exit 1
319
+ fi
320
+ if ! guardlink blame . --json > "$blame" || ! jq -e '.entries | arrays' "$blame" > /dev/null; then
321
+ echo "::error::unknown: guardlink blame failed"
322
+ exit 1
323
+ fi
324
+ node .bravos/hooks/lib/threat-issues.mjs "$model" "$ledger" "$blame"