@bugb-technologies/bravos 1.25.0 → 1.26.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/dist/cli.js +35 -3
- package/dist/dashboard-sast.js +113 -0
- package/dist/dashboard.js +17 -12
- package/dist/guide.js +2 -2
- package/dist/plugin-release.js +38 -12
- package/dist/records-conflicts.js +128 -0
- package/dist/rules.js +52 -3
- package/dist/setup.js +6 -6
- package/docs/GUIDE.md +2 -2
- package/docs/UPGRADING.md +16 -0
- package/hooks/cards.mjs +3 -3
- package/hooks/lib/agent-io.mjs +13 -0
- package/hooks/lib/sast.mjs +3 -1
- package/hooks/record-guard.mjs +4 -2
- package/package.json +1 -1
- package/skills/bravos-records/SKILL.md +1 -1
- package/templates/dashboard/dashboard.html +145 -1
- package/templates/plugin/workspace-hook.mjs +37 -0
package/dist/cli.js
CHANGED
|
@@ -1034,7 +1034,7 @@ export function buildProgram(io, result) {
|
|
|
1034
1034
|
// @comment -- "bravos records: the security decision records in this repository, one Markdown document per module under .guardlink/records/. list, show, for and check only read and are free; new writes the skeleton of a draft; adopt records a person's adoption of a record as it reads now, at an interactive terminal where they type their name and the record id. A draft binds nobody: only an adopted record is followed."
|
|
1035
1035
|
program
|
|
1036
1036
|
.command('records [action] [args...]')
|
|
1037
|
-
.description('Security decision records: one document per module or feature (.guardlink/records/SDR-n-<module>.md) saying what was decided there, the rules that follow, why, and what looks like a bug but is not. `records list` (the default); `records show SDR-n`; `records for <file>` says which record covers a file; `records check` verifies every record parses, that an adopted one still reads as it did when adopted and that the exceptions are sound (free; exit 1 on a problem); `records new "<module>" --paths "<glob>,<glob>"` writes the skeleton of a draft; `records adopt SDR-n` makes a record binding, approved by the person typing their name at a terminal (never by an agent), or adopt on the page with bravos review records; `records except SDR-n R1 --where "<glob>" --reason "<why>" --until YYYY-MM-DD` lets a break of one rule in one area through the pre-PR gate until that day, approved the same way; `records except --clear-expired`; `records gaps` lists modules with security claims no record covers; `records ledger` lists the module ledger (.guardlink/records/README.md: which modules make security decisions, their code, owner and record), `records ledger propose [--write]` proposes modules from the stored documents, the threat model and the folders, `records ledger add|remove|refresh` keep it (free; reviewed by a person in a pull request, never enforced); `records drafts` lists the modules of the reviewed ledger to draft a record for now (at most 2 a run, 3 waiting, one per module) and `records draft "<module>"` starts one on its own branch and worktree (Team plan; the agent drafts, pushes nothing, and opens the pull request only on the person\'s yes); `records codeowners --owner @<who>` shows the CODEOWNERS lines that make a record need that owner\'s review on GitHub (--yes writes them, after the person said so). A record is approved when its text is on the default branch (a code owner\'s review where GitHub requires one); adopting by typed name is the fallback, labelled not verified. Runs no model.')
|
|
1037
|
+
.description('Security decision records: one document per module or feature (.guardlink/records/SDR-n-<module>.md) saying what was decided there, the rules that follow, why, and what looks like a bug but is not. `records list` (the default); `records show SDR-n`; `records for <file>` says which record covers a file; `records check` verifies every record parses, that an adopted one still reads as it did when adopted and that the exceptions are sound (free; exit 1 on a problem); `records new "<module>" --paths "<glob>,<glob>"` writes the skeleton of a draft; `records adopt SDR-n` makes a record binding, approved by the person typing their name at a terminal (never by an agent), or adopt on the page with bravos review records; `records except SDR-n R1 --where "<glob>" --reason "<why>" --until YYYY-MM-DD` lets a break of one rule in one area through the pre-PR gate until that day, approved the same way; `records except --clear-expired`; `records gaps` lists modules with security claims no record covers; `records ledger` lists the module ledger (.guardlink/records/README.md: which modules make security decisions, their code, owner and record), `records ledger propose [--write]` proposes modules from the stored documents, the threat model and the folders, `records ledger add|remove|refresh` keep it (free; reviewed by a person in a pull request, never enforced); `records drafts` lists the modules of the reviewed ledger to draft a record for now (at most 2 a run, 3 waiting, one per module) and `records draft "<module>"` starts one on its own branch and worktree (Team plan; the agent drafts, pushes nothing, and opens the pull request only on the person\'s yes); `records conflicts` lists the open exposures and SAST findings in a record\'s paths that may go against one of its rules, with why (suggestions, never a status; `records conflicts dismiss <key> --reason "<why>"` at your own terminal; Team plan); `records codeowners --owner @<who>` shows the CODEOWNERS lines that make a record need that owner\'s review on GitHub (--yes writes them, after the person said so). A record is approved when its text is on the default branch (a code owner\'s review where GitHub requires one); adopting by typed name is the fallback, labelled not verified. Runs no model.')
|
|
1038
1038
|
.option('-C, --dir <dir>', 'the repository (default: the current directory)')
|
|
1039
1039
|
.option('--json', 'list/show/for/check: print JSON')
|
|
1040
1040
|
.option('--paths <globs>', 'new: the code the record covers, as repository globs separated by commas (src/reports/**,app/api/reports/**)')
|
|
@@ -1117,6 +1117,38 @@ export function buildProgram(io, result) {
|
|
|
1117
1117
|
throw new BravosError('usage: bravos records codeowners --owner @<user or org/team> [--yes]');
|
|
1118
1118
|
lines.push(...(await (await import('./records-team.js')).codeownersLines(root, opts.owner, !!opts.yes)));
|
|
1119
1119
|
}
|
|
1120
|
+
else if (act === 'conflicts') {
|
|
1121
|
+
// @comment -- "bravos records conflicts: the possible conflicts between each record and the code it covers, the same list the dashboard's Decision records view shows (Team plan, like that view). dismiss <key> is a person's decision, at their own terminal where they type their name, as adopting is: recorded in .guardlink/records-dismissals.json, never as @accepts, and the exposure or finding is left as it is."
|
|
1122
|
+
await requireFeature(io.env, 'principles', 'Possible conflicts between records and the code');
|
|
1123
|
+
const C = await import('./records-conflicts.js');
|
|
1124
|
+
const doc = await (await import('./rules.js')).gatherRules(root, io.env, { names: true, details: false });
|
|
1125
|
+
const conflicts = doc.conflicts ?? [];
|
|
1126
|
+
if (args[0] === 'dismiss') {
|
|
1127
|
+
const key = args[1];
|
|
1128
|
+
if (!key || !opts.reason)
|
|
1129
|
+
throw new BravosError('usage: bravos records conflicts dismiss <key> --reason "<why it is not a conflict>"');
|
|
1130
|
+
// @mitigates #records against #forged-record using #person-only-adoption -- "A dismissal needs an interactive terminal where the person types their own name; a coding agent's shell has none, so it cannot dismiss one"
|
|
1131
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY)
|
|
1132
|
+
throw new BravosError('dismissing a possible conflict is a person\'s decision: run this yourself in a terminal, where you type your name. A coding agent cannot dismiss one.');
|
|
1133
|
+
const c = conflicts.find((x) => x.key === key);
|
|
1134
|
+
if (!c)
|
|
1135
|
+
throw new BravosError(`no possible conflict with key ${key} here (bravos records conflicts lists them)`);
|
|
1136
|
+
const rl = (await import('node:readline/promises')).createInterface({ input: process.stdin, output: process.stdout });
|
|
1137
|
+
try {
|
|
1138
|
+
io.stdout(`${c.record} ${c.rule} "${c.ruleText}"\n ${c.what} at ${c.file}${c.line ? `:${c.line}` : ''}\n why it was suggested: ${c.reason}\n your reason: ${opts.reason}`);
|
|
1139
|
+
const by = (await rl.question('Your name, dismissing this as not a conflict: ')).trim();
|
|
1140
|
+
if (!by)
|
|
1141
|
+
throw new BravosError('not dismissed: no name was typed');
|
|
1142
|
+
const d = C.addDismissal(root, c, by, opts.reason);
|
|
1143
|
+
lines.push(`Dismissed ${d.key} for ${d.record} ${d.rule}, by ${d.by} on ${d.at}, in ${C.DISMISSALS_FILE}. The exposure or finding is unchanged; commit the file so the team sees the decision.`);
|
|
1144
|
+
}
|
|
1145
|
+
finally {
|
|
1146
|
+
rl.close();
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
else
|
|
1150
|
+
lines.push(...(opts.json ? [JSON.stringify({ schema: 'bravos.records-conflicts/v1', conflicts }, null, 2)] : C.conflictLines(conflicts)));
|
|
1151
|
+
}
|
|
1120
1152
|
else if (act === 'drafts' || act === 'draft') {
|
|
1121
1153
|
// @comment -- "Background drafting is on the Team plan, like writing a record: drafts lists what to draft now within the limits, draft starts one module's draft on its own branch and worktree. Neither pushes nor opens a pull request."
|
|
1122
1154
|
await requireFeature(io.env, 'principles', 'Drafting security decision records');
|
|
@@ -1185,7 +1217,7 @@ export function buildProgram(io, result) {
|
|
|
1185
1217
|
}
|
|
1186
1218
|
}
|
|
1187
1219
|
else
|
|
1188
|
-
throw new BravosError(`unknown records action '${act}'; use list, show, for, check, new, adopt, except, gaps, codeowners, ledger, drafts or
|
|
1220
|
+
throw new BravosError(`unknown records action '${act}'; use list, show, for, check, new, adopt, except, gaps, codeowners, ledger, drafts, draft or conflicts`);
|
|
1189
1221
|
}));
|
|
1190
1222
|
program
|
|
1191
1223
|
.command('review <kind> [dir]')
|
|
@@ -1374,7 +1406,7 @@ export function buildProgram(io, result) {
|
|
|
1374
1406
|
lines.push(JSON.stringify({ schema: 'bravos.dashboard-run/v1', path: r.path, opened, threatModel: r.threatModel, rules: r.rules, codeGraph: r.codeGraph }, null, 2));
|
|
1375
1407
|
return;
|
|
1376
1408
|
}
|
|
1377
|
-
lines.push(`Dashboard: ${r.path}${opened ? ' (opened in your browser)' : ''}`, ` threat model: ${r.threatModel.note}`, ` design rules: ${r.rules.note}`, ` code graph: ${r.codeGraph.note}`);
|
|
1409
|
+
lines.push(`Dashboard: ${r.path}${opened ? ' (opened in your browser)' : ''}`, ` threat model: ${r.threatModel.note}`, ` design rules: ${r.rules.note}`, ` code graph: ${r.codeGraph.note}`, ` sast: ${r.sast.note}`);
|
|
1378
1410
|
if (!opened && opts.open !== false)
|
|
1379
1411
|
lines.push(' No browser could be opened here; open the file above.');
|
|
1380
1412
|
}));
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { pathToFileURL } from 'node:url';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { featureState } from './licence.js';
|
|
4
|
+
import { hooksDir } from './paths.js';
|
|
5
|
+
const lib = (name) => import(pathToFileURL(join(hooksDir(), 'lib', name)).href);
|
|
6
|
+
const MAX_ROWS = 300;
|
|
7
|
+
const str = (v, max = 300) => String(v ?? '').replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, max);
|
|
8
|
+
const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
|
|
9
|
+
const TIERS = { t1: 'T1', t2: 'T2', t3: 'T3' };
|
|
10
|
+
// @mitigates #dashboard-sast against #secret-on-shared-page using #withhold-credentials -- "safeText scans every copied string and withholds one that looks like a credential; secret findings carry type and place only"
|
|
11
|
+
// @comment -- "Every string bound for the page goes through this: cleaned to one line and cut, then the secret scan; a string that looks like it holds a credential is replaced by what kind it looks like, so no value reaches a file people share even if an analyzer message ever quoted one."
|
|
12
|
+
function safeText(ctx) {
|
|
13
|
+
return (v, max = 300) => {
|
|
14
|
+
const s = str(v, max);
|
|
15
|
+
const hit = s ? ctx.scanSecrets(s)[0] : undefined;
|
|
16
|
+
return hit ? `[withheld: ${ctx.an(hit.rule)}]` : s;
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
/** The SAST part of the dashboard for this repository, never throwing: a run that cannot be read is said, not hidden. */
|
|
20
|
+
export async function buildSastPart(root, env) {
|
|
21
|
+
const f = await featureState(env, 'sast', 'The SAST view');
|
|
22
|
+
if (!f.entitled)
|
|
23
|
+
return { state: 'off', note: `SAST is on the Team plan; with it this view lists the analyzer's findings, what they reach and the threats they join. ${f.refusal}.`, view: null, issues: null, reportId: null };
|
|
24
|
+
try {
|
|
25
|
+
const S = await lib('sast.mjs');
|
|
26
|
+
const C = await lib('context.mjs');
|
|
27
|
+
const run = S.latestRun(root);
|
|
28
|
+
if (!run)
|
|
29
|
+
return { state: 'missing', note: 'No SAST run here yet. bravos sast run analyzes the repository (with the code graph built first, it also says which findings are reached); then run bravos dashboard again.', view: null, issues: null, reportId: null };
|
|
30
|
+
const summary = S.readSast(root, env);
|
|
31
|
+
const t = safeText(C);
|
|
32
|
+
const findings = (Array.isArray(run.report.findings) ? run.report.findings : []).filter((x) => x && typeof x === 'object' && !x.suppressed);
|
|
33
|
+
const view = {
|
|
34
|
+
run: t(run.name, 80),
|
|
35
|
+
at: typeof run.meta?.at === 'string' ? t(run.meta.at, 40) : null,
|
|
36
|
+
sha: typeof run.meta?.sha === 'string' && /^[0-9a-f]{7,40}$/.test(run.meta.sha) ? run.meta.sha.slice(0, 12) : null,
|
|
37
|
+
staleCommits: summary?.staleCommits ?? null,
|
|
38
|
+
analyzer: run.report.analyzer_version ? t(run.report.analyzer_version, 40) : null,
|
|
39
|
+
graph: run.report.graph_currency && typeof run.report.graph_currency === 'object' ? t(run.report.graph_currency.state, 40) || null : null,
|
|
40
|
+
total: findings.length,
|
|
41
|
+
suppressed: (Array.isArray(run.report.findings) ? run.report.findings.length : 0) - findings.length,
|
|
42
|
+
byClass: {},
|
|
43
|
+
bySeverity: {},
|
|
44
|
+
joined: [],
|
|
45
|
+
unjoined: [],
|
|
46
|
+
dependencies: [],
|
|
47
|
+
secrets: [],
|
|
48
|
+
agentConfig: { count: 0, rules: [] },
|
|
49
|
+
};
|
|
50
|
+
const issues = [];
|
|
51
|
+
findings.forEach((x, i) => {
|
|
52
|
+
const cls = t(x.finding_class || 'static_analysis', 40);
|
|
53
|
+
const severity = t(x.severity || 'unrated', 20).toLowerCase();
|
|
54
|
+
view.byClass[cls] = (view.byClass[cls] ?? 0) + 1;
|
|
55
|
+
view.bySeverity[severity] = (view.bySeverity[severity] ?? 0) + 1;
|
|
56
|
+
const key = t(x.finding_id || x.id || `${run.name}/${i}`, 120);
|
|
57
|
+
const file = x.file ? t(x.file, 400) : null;
|
|
58
|
+
const line = num(x.line);
|
|
59
|
+
const tier = TIERS[String(x.evidence_tier ?? '').slice(0, 2).toLowerCase()] ?? null;
|
|
60
|
+
if (tier && file && issues.length < 2000)
|
|
61
|
+
issues.push({ key, tier, rule: t(x.rule_id, 160), title: t(x.title || x.rule_id, 200), location: { file, line, symbol: x.enclosing_function ? t(x.enclosing_function, 160) : null } });
|
|
62
|
+
if (cls === 'agent_config') {
|
|
63
|
+
view.agentConfig.count += 1;
|
|
64
|
+
const rule = t(x.rule_id, 160);
|
|
65
|
+
if (rule && !view.agentConfig.rules.includes(rule) && view.agentConfig.rules.length < 20)
|
|
66
|
+
view.agentConfig.rules.push(rule);
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
if (cls === 'secret') {
|
|
70
|
+
// A secret by its type and place only: never the analyzer's message, never a snippet.
|
|
71
|
+
if (view.secrets.length < MAX_ROWS)
|
|
72
|
+
view.secrets.push({ key, type: t(x.title || x.rule_id, 120), rule: t(x.rule_id, 160), file, line, inHistory: !!x.secret_in_history, remediation: t(String(x.secret_remediation ?? 'rotate the credential and remove it from the source').replace(/_/g, ' '), 160) });
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
const reachable = x.reachable === true ? true : x.reachable === false ? false : null;
|
|
76
|
+
const row = {
|
|
77
|
+
key,
|
|
78
|
+
severity,
|
|
79
|
+
rule: t(x.rule_id, 160),
|
|
80
|
+
title: t(x.title || x.vuln_type || x.rule_id, 200),
|
|
81
|
+
file,
|
|
82
|
+
line,
|
|
83
|
+
reachable,
|
|
84
|
+
reach: t(x.reach_label || (reachable === true ? 'reached from an entry point' : reachable === false ? 'not reached from any entry point' : 'not known'), 200),
|
|
85
|
+
claim: x.guardlink_join && x.guardlink_join !== 'unjoined' && x.guardlink_join !== 'none' ? t(S.claimLabel(x.guardlink_join), 200) : null,
|
|
86
|
+
tier: tier ?? (x.evidence_tier ? t(x.evidence_tier, 30) : null),
|
|
87
|
+
route: x.http_method || x.http_path ? t(`${x.http_method ?? ''} ${x.http_path ?? ''}`, 200) : null,
|
|
88
|
+
function: x.enclosing_function ? t(x.enclosing_function, 160) : null,
|
|
89
|
+
};
|
|
90
|
+
if (cls === 'dependency') {
|
|
91
|
+
if (view.dependencies.length < MAX_ROWS)
|
|
92
|
+
view.dependencies.push({ ...row, manifests: (Array.isArray(x.dep_manifests) ? x.dep_manifests : []).slice(0, 10).map((m) => t(m, 200)), devOnly: !!x.dep_dev_only, vulnerableFunction: t(S.reachLabel(x.vulnerable_function_reachability), 200) });
|
|
93
|
+
}
|
|
94
|
+
else if (row.claim) {
|
|
95
|
+
if (view.joined.length < MAX_ROWS)
|
|
96
|
+
view.joined.push(row);
|
|
97
|
+
}
|
|
98
|
+
else if (view.unjoined.length < MAX_ROWS)
|
|
99
|
+
view.unjoined.push(row);
|
|
100
|
+
});
|
|
101
|
+
// Reached first, then not known, then not reached; worst severity first within each.
|
|
102
|
+
const rank = (r) => (r.reachable === true ? 0 : r.reachable === null ? 1 : 2) * 10 + (r.severity === 'error' || r.severity === 'critical' || r.severity === 'high' ? 0 : r.severity === 'warning' || r.severity === 'medium' ? 1 : 2);
|
|
103
|
+
for (const list of [view.joined, view.unjoined, view.dependencies])
|
|
104
|
+
list.sort((a, b) => rank(a) - rank(b) || String(a.file).localeCompare(String(b.file)) || (a.line ?? 0) - (b.line ?? 0));
|
|
105
|
+
const age = view.staleCommits === null ? '' : view.staleCommits === 0 ? ', at the commit checked out now' : `, ${view.staleCommits} commit${view.staleCommits === 1 ? '' : 's'} behind HEAD (bravos sast run again for the current code)`;
|
|
106
|
+
const reached = findings.filter((x) => x.reachable === true).length;
|
|
107
|
+
const note = `SAST run ${view.run}${view.at ? ` (${view.at.slice(0, 16).replace('T', ' ')} UTC)` : ''}${age}: ${view.total} finding${view.total === 1 ? '' : 's'}, ${reached} reached from an entry point, ${view.joined.length} joined to the threat model, ${view.unjoined.length} not in it yet, ${view.secrets.length} secret${view.secrets.length === 1 ? '' : 's'}.`;
|
|
108
|
+
return { state: 'present', note, view, issues, reportId: view.run };
|
|
109
|
+
}
|
|
110
|
+
catch (e) {
|
|
111
|
+
return { state: 'missing', note: `The newest SAST run could not be read (${str(e.message, 200)}); bravos sast status says more.`, view: null, issues: null, reportId: null };
|
|
112
|
+
}
|
|
113
|
+
}
|
package/dist/dashboard.js
CHANGED
|
@@ -8,6 +8,7 @@ import { templatesDir, version } from './paths.js';
|
|
|
8
8
|
import { BravosError } from './types.js';
|
|
9
9
|
import { gatherRules } from './rules.js';
|
|
10
10
|
import { intakeSummary } from './review.js';
|
|
11
|
+
import { buildSastPart } from './dashboard-sast.js';
|
|
11
12
|
export const DASHBOARD_DIR = '.bravos/dashboard';
|
|
12
13
|
export const DASHBOARD_PATH = `${DASHBOARD_DIR}/index.html`;
|
|
13
14
|
/** What the saved page was built from, for the session briefing to tell a current page from an old one. */
|
|
@@ -111,8 +112,8 @@ export function scrubAnswers(value, opts) {
|
|
|
111
112
|
};
|
|
112
113
|
return walk(value, '', '');
|
|
113
114
|
}
|
|
114
|
-
// @comment -- "Pure: turns the graph's answers into the message each Code graph page is drawn from, with the rules the VS Code extension's host applies (siete: pagesPanel.ts `load`). A page whose main question was not answered gets a 'refused' message carrying the graph's own words, never an empty drawing; a secondary answer that is missing is passed through as not-ok so the page says so itself. Every message lists the command lines it came from.
|
|
115
|
-
export function codeGraphStore(answers) {
|
|
115
|
+
// @comment -- "Pure: turns the graph's answers into the message each Code graph page is drawn from, with the rules the VS Code extension's host applies (siete: pagesPanel.ts `load`). A page whose main question was not answered gets a 'refused' message carrying the graph's own words, never an empty drawing; a secondary answer that is missing is passed through as not-ok so the page says so itself. Every message lists the command lines it came from. The newest SAST run's findings (src/dashboard-sast.ts) are the issues the Map's Findings lens and the Attack surface's pinned column draw; with no run (or on Free) none are supplied and both pages say so."
|
|
116
|
+
export function codeGraphStore(answers, sast = null) {
|
|
116
117
|
const got = (q) => {
|
|
117
118
|
const a = answers[QUESTIONS[q].tool];
|
|
118
119
|
if (!a)
|
|
@@ -126,7 +127,7 @@ export function codeGraphStore(answers) {
|
|
|
126
127
|
const asked = (...qs) => qs.map(commandLine);
|
|
127
128
|
const [threat, hot, mix, co, surface, entries, access] = [got('threat'), got('hotspots'), got('mix'), got('coChange'), got('surface'), got('entries'), got('access')];
|
|
128
129
|
return {
|
|
129
|
-
map: codemap.ok ? { type: 'map', codemap: codemap.value, asked: asked('codemap'), findings: null } : refused('map', 'The map could not be built', codemap),
|
|
130
|
+
map: codemap.ok ? { type: 'map', codemap: codemap.value, asked: asked('codemap'), findings: sast?.issues ? { issues: sast.issues, reportId: sast.reportId } : null } : refused('map', 'The map could not be built', codemap),
|
|
130
131
|
trust: codemap.ok ? { type: 'trust', codemap: codemap.value, threatModel: threat, asked: asked('codemap', 'threat') } : refused('trust', 'The graph could not describe itself', codemap),
|
|
131
132
|
owners: !hot.ok
|
|
132
133
|
? refused('owners', 'Churn and ownership are not available', hot)
|
|
@@ -134,7 +135,7 @@ export function codeGraphStore(answers) {
|
|
|
134
135
|
? refused('owners', 'Churn and ownership are not available', codemap)
|
|
135
136
|
: { type: 'owners', hotspots: hot.value, codemap: codemap.value, commitMix: mix, asked: asked('hotspots', 'codemap', 'mix') },
|
|
136
137
|
coupling: co.ok ? { type: 'coupling', coChange: co.value, codemap, asked: asked('coChange', 'codemap') } : refused('coupling', 'Co-change coupling is not available', co),
|
|
137
|
-
surface: surface.ok ? { type: 'surface', attackSurface: surface.value, issues: null, asked: asked('surface') } : refused('surface', 'The attack surface is not available', surface),
|
|
138
|
+
surface: surface.ok ? { type: 'surface', attackSurface: surface.value, issues: sast?.issues ?? null, asked: asked('surface') } : refused('surface', 'The attack surface is not available', surface),
|
|
138
139
|
entries: entries.ok ? { type: 'entries', entryPoints: entries.value, access, asked: asked('entries', 'access') } : refused('entries', 'Entry points are not available', entries),
|
|
139
140
|
links: { type: 'links', entryPoints: entries, asked: asked('entries') },
|
|
140
141
|
};
|
|
@@ -214,7 +215,7 @@ export async function buildCodeGraph(root, env, opts = {}) {
|
|
|
214
215
|
if (errors.every(Boolean))
|
|
215
216
|
return note('failed', `The code graph answered none of the questions (${errors[0].slice(0, 200)}).`);
|
|
216
217
|
// Scrubbed first, so the pages that share the code map still share one object and it is stored once.
|
|
217
|
-
const store = codeGraphStore(scrubAnswers(answered.answers, { root: resolve(root), repo: repoName(root, env), names: opts.names !== false }));
|
|
218
|
+
const store = codeGraphStore(scrubAnswers(answered.answers, { root: resolve(root), repo: repoName(root, env), names: opts.names !== false }), opts.sast ?? null);
|
|
218
219
|
const states = Object.values(answered.answers).map((a) => ('result' in a ? text(obj(obj(a.result).graph_currency).state) : '')).filter(Boolean);
|
|
219
220
|
const stale = states.find((x) => x !== 'current');
|
|
220
221
|
return { state: 'present', store, note: `The code graph's answers when this page was built: the map, owners and history, coupling, trust, attack surface, entry points and links.${rebuilt}${stale ? ` The graph is ${stale}: the code has moved since it was built, so rebuild it with bravos graph build .` : ''}` };
|
|
@@ -232,7 +233,7 @@ export function shareCodeMap(store) {
|
|
|
232
233
|
return { codemap: shared, pages };
|
|
233
234
|
}
|
|
234
235
|
// @comment -- "Renders the one-file dashboard: the page template with its facts and GuardLink's page each embedded as JSON in a non-executing script tag, every '<' escaped so none can close its tag. When there are code graph answers, they and the vendored Code graph pages (script and stylesheet) are embedded the same way; the page assembles them into a second sandboxed frame. Both go in through one pass with a function replacer, so nothing in either is read as a placeholder or a replacement pattern."
|
|
235
|
-
export function renderDashboard(data, threatModelHtml, store = null, rules = null) {
|
|
236
|
+
export function renderDashboard(data, threatModelHtml, store = null, rules = null, sast = null) {
|
|
236
237
|
const template = readFileSync(join(templatesDir(), 'dashboard', 'dashboard.html'), 'utf8');
|
|
237
238
|
// One pass over the template, so text inside either value that looks like a placeholder is never filled in turn.
|
|
238
239
|
// The pages' script and stylesheet travel only with a page that has graph answers to draw.
|
|
@@ -244,8 +245,9 @@ export function renderDashboard(data, threatModelHtml, store = null, rules = nul
|
|
|
244
245
|
PAGES_JS: () => asset('codegraph-pages.js'),
|
|
245
246
|
PAGES_CSS: () => asset('codegraph-pages.css'),
|
|
246
247
|
RULES: () => rules,
|
|
248
|
+
SAST: () => sast,
|
|
247
249
|
};
|
|
248
|
-
return template.replace(/__BRAVOS_(DATA|THREAT_MODEL|CODEGRAPH|PAGES_JS|PAGES_CSS|RULES)__/g, (_m, which) => inert(fill[which]()));
|
|
250
|
+
return template.replace(/__BRAVOS_(DATA|THREAT_MODEL|CODEGRAPH|PAGES_JS|PAGES_CSS|RULES|SAST)__/g, (_m, which) => inert(fill[which]()));
|
|
249
251
|
}
|
|
250
252
|
// @comment -- "bravos dashboard: gathers the repository's facts (read-only git, this machine's plan label), builds GuardLink's page and, on the Team plan, the Code graph pages from the graph's answers, and writes one self-contained HTML file. By default that is .bravos/dashboard/index.html beside a .gitignore of '*', since the page can carry git identities and findings; with `out` nothing is written inside the repository. A page is written even when GuardLink has nothing to show, so the person always gets a file that says what to do next."
|
|
251
253
|
export async function buildDashboard(root, env, opts = {}) {
|
|
@@ -255,7 +257,9 @@ export async function buildDashboard(root, env, opts = {}) {
|
|
|
255
257
|
}
|
|
256
258
|
const base = opts.since ?? baseRef(root, env);
|
|
257
259
|
const tm = buildThreatModel(root, env, { base, blame: opts.blame !== false });
|
|
258
|
-
|
|
260
|
+
// The newest SAST run, for its own view and for the Code graph pages' findings (Team plan; a line on Free).
|
|
261
|
+
const sast = await buildSastPart(root, env);
|
|
262
|
+
const cg = await buildCodeGraph(root, env, { names: opts.blame !== false, refresh: opts.graphBuild !== false, onProgress: opts.onProgress, sast });
|
|
259
263
|
// The design rules: free on every plan, read from the intent, GuardLink's model and its test ledger. A failure
|
|
260
264
|
// here is a note on that view, never a failed page.
|
|
261
265
|
let rules = null;
|
|
@@ -269,7 +273,7 @@ export async function buildDashboard(root, env, opts = {}) {
|
|
|
269
273
|
if (rules.records?.length) {
|
|
270
274
|
const f = await featureState(env, 'principles', 'The Decision records view');
|
|
271
275
|
if (!f.entitled)
|
|
272
|
-
rules = { ...rules, records: [], recordsNote: `${rules.records.length} record rule${rules.records.length === 1 ? ' is' : 's are'} written down here, and coding agents follow the adopted ones on every plan. ${f.refusal}.` };
|
|
276
|
+
rules = { ...rules, records: [], conflicts: [], conflictsNote: '', recordsNote: `${rules.records.length} record rule${rules.records.length === 1 ? ' is' : 's are'} written down here, and coding agents follow the adopted ones on every plan. ${f.refusal}.` };
|
|
273
277
|
}
|
|
274
278
|
if (rules.principles.length) {
|
|
275
279
|
const f = await featureState(env, 'principles', 'The Security design view');
|
|
@@ -299,9 +303,10 @@ export async function buildDashboard(root, env, opts = {}) {
|
|
|
299
303
|
threatModel: { state: tm.state, note: tm.note, blame: tm.blame, since: tm.since },
|
|
300
304
|
codeGraph: { state: cg.state, note: cg.note },
|
|
301
305
|
rules: rulesPart,
|
|
306
|
+
sast: { state: sast.state === 'off' ? 'locked' : sast.state, note: sast.note },
|
|
302
307
|
intake: intakeSummary(root),
|
|
303
308
|
};
|
|
304
|
-
const page = renderDashboard(data, tm.html, cg.store, rules);
|
|
309
|
+
const page = renderDashboard(data, tm.html, cg.store, rules, sast.view);
|
|
305
310
|
let path;
|
|
306
311
|
if (opts.out) {
|
|
307
312
|
path = resolve(opts.out);
|
|
@@ -315,9 +320,9 @@ export async function buildDashboard(root, env, opts = {}) {
|
|
|
315
320
|
writeFileSync(ignore, '*\n');
|
|
316
321
|
path = join(root, DASHBOARD_PATH);
|
|
317
322
|
// Beside the page: what it was built from, so the session briefing can say when it has fallen behind.
|
|
318
|
-
const meta = { schema: 'bravos.dashboard-meta/v1', generatedAt: data.generatedAt, commit: git(root, env, ['rev-parse', 'HEAD']), branch: data.branch, threatModel: tm.state, codeGraph: cg.state, rules: rulesPart.state };
|
|
323
|
+
const meta = { schema: 'bravos.dashboard-meta/v1', generatedAt: data.generatedAt, commit: git(root, env, ['rev-parse', 'HEAD']), branch: data.branch, threatModel: tm.state, codeGraph: cg.state, rules: rulesPart.state, sast: sast.state };
|
|
319
324
|
writeFileSync(join(root, DASHBOARD_META), `${JSON.stringify(meta, null, 2)}\n`);
|
|
320
325
|
}
|
|
321
326
|
writeFileSync(path, page);
|
|
322
|
-
return { path, threatModel: { state: tm.state, note: tm.note }, codeGraph: { state: cg.state, note: cg.note }, rules: rulesPart };
|
|
327
|
+
return { path, threatModel: { state: tm.state, note: tm.note }, codeGraph: { state: cg.state, note: cg.note }, rules: rulesPart, sast: { state: sast.state === 'off' ? 'locked' : sast.state, note: sast.note } };
|
|
323
328
|
}
|
package/dist/guide.js
CHANGED
|
@@ -117,7 +117,7 @@ export const GUIDE_TOPICS = [
|
|
|
117
117
|
{ name: 'Teach bravos what the app is for', skills: ['bravos-context'], body: ['Writes .guardlink/intent.md: invariants (INV-n) that become threats, and intended-by-design items (INT-n) that get an "intended?" audit instead of a high rating.'] },
|
|
118
118
|
{ name: 'Start from your design documents', skills: ['bravos-context'], body: ['Give bravos-context your PRDs, design documents or an earlier threat model, as files or links. Each is kept in the repository as Markdown under .bravos/context/ (bravos context add; committed, so the team can keep it current) after a check for secrets and local paths; a link is kept beside its snapshot. Every rule then names the document it came from (INV-4, source: SRC-2), including who may do what: "sales may see every report except the revenue report" becomes a rule that can be tested, where a scan would see nothing wrong. bravos context list shows the documents, bravos context check re-checks them, and a pre-push check stops a push that would send a secret in one. Free; the CLI runs no model and fetches nothing: your agent converts and fetches with your own access.'] },
|
|
119
119
|
{ name: 'Write down your company\'s security design principles', skills: ['bravos-principles'], body: ['Ask for "our security design principles". bravos-principles proposes candidates only from your stored documents (cited by section, checked against the text), INV rules a person already confirmed in this or another repository, or an optional starter list mapped to OWASP ASVS 4.0.3, which is never pre-selected; bravos review principles refuses anything else. On the page each principle is its own decision (Agree, Change the wording, or No); there is no adopt-all. Confirm records your adoption with the exact wording and a fingerprint, and bravos writes .guardlink/principles.md from the adoptions: committed, so every developer who pulls gets it, and the Bravos block in AGENTS.md and CLAUDE.md tells every coding agent to read and follow it and never edit it. A principle is enforced (it becomes a threat with principle:SDP-n, is tested, and the pre-PR gate stops a change that breaks it, whatever the PR body says) or guidance (followed, not tested). bravos principles check (free; the pre-push hook and the gate run it) fails a hand-edited line, an adoption nobody made, or an exception past its date. An exception is approved by a person at their own terminal: bravos principles except SDP-n --where "<glob>" --reason "<why>" --until <date>, at most a year, never extended; a coding agent cannot run it. bravos principles copy --from <repository> takes the same set into another repository, and check says when the source changes. The dashboard\'s Security design view shows each principle, where it is enforced, its exceptions, and what it caught or stopped in the last 30 and 90 days. Team plan for authoring, the gate and the view; adopted principles are followed on every plan.'] },
|
|
120
|
-
{ name: 'Write down what was decided for one module', skills: ['bravos-records'], body: ['Ask for "a security decision record for <module>". bravos-records drafts one document for that module (.guardlink/records/SDR-n-<module>.md) from what you tell it, your documents and confirmed rules: the decision, the rules that follow, why, and what looks like a bug but is not. It is a draft until its text reaches the default branch: approved when a code owner reviews the pull request that merges it (bravos records check asks GitHub with gh whether the branch requires that review, and offers CODEOWNERS lines for .guardlink/records/ that it writes only after you say yes: bravos records codeowners --owner @you). Without that review, a record on the default branch reads \'on main, review not enforced\'; the weaker fallback is a person running bravos records adopt SDR-n at their own terminal and typing their name, which shows who said so, not that anyone reviewed it. An agent cannot approve or adopt one. From then on every coding agent asks bravos records for <file> before changing covered code and follows the record; in Claude Code, Codex, Cursor, Antigravity, opencode and omp the first edit of a covered file in a session is refused once with the record in full (each in its own hook shape, through the installed CLI; any hook error lets the edit through), so it is read before anything changes. A change that goes against a rule is raised with you first and shows as a decision-record card after the edit, as does a removed check, and a record edited on a branch is a proposal: the default branch\'s text binds until the edit is approved, and only the branch that edits it waits (bravos records check). In CI, the PR gate checks with the workflow\'s GITHUB_TOKEN that a code owner approved the last change to each record and reports what it could not prove. A module ledger, .guardlink/records/README.md, lists which modules of the application make security decisions: the agent proposes it (bravos records ledger propose: features found from the stored documents, the threat model and the folders, with the code graph\'s routes on the Team plan; without the graph a feature split over folders with different names can show as two modules, so the boundaries are for a person to review), a person reviews it in its pull request, and Bravos keeps its Record and Owner columns (bravos records ledger refresh, owners from CODEOWNERS). It is never enforced. From the first session the briefing counts it ("9 modules, 2 with records"), and the first edit in a session to a module it says needs a record, and has none, gets one line offering to draft one, never a block; the company principles apply either way (bravos prefs set nudge off silences it). On the Team plan, once a person has reviewed the ledger, the agent drafts records for the modules that need one in the background: a subagent runs bravos records drafts (at most 2 a run, 3 waiting for review at once, never two for one module) and bravos records draft "<module>", which starts each draft on its own branch and worktree so your checkout is never touched. A draft states only what your documents (SRC-n § Section), confirmed intent rules or people said, cited on the line; what the code does today is marked observed and kept as guidance; Not a bug is never filled from code. bravos records check holds every citation to the repository. The agent pushes nothing and asks you before opening each draft\'s pull request; it binds nobody until a code owner approves it, and only that branch waits. bravos prefs set drafts off stops it. bravos rules lists each rule with its status. On the Team plan the pre-PR gate holds a change that breaks an adopted enforced rule whatever the PR body says, until the code is fixed, a person approves a dated exception (bravos records except SDR-n R1, at their own terminal), or the record is changed and the new text approved; people can adopt on a page with bravos review records (Agree, Change or No per rule); bravos records gaps lists modules no record covers; and the dashboard has a Decision records view. Reading and following records is free; writing, adopting, exceptions, the gate, gaps and the view are on the Team plan.'] },
|
|
120
|
+
{ name: 'Write down what was decided for one module', skills: ['bravos-records'], body: ['Ask for "a security decision record for <module>". bravos-records drafts one document for that module (.guardlink/records/SDR-n-<module>.md) from what you tell it, your documents and confirmed rules: the decision, the rules that follow, why, and what looks like a bug but is not. It is a draft until its text reaches the default branch: approved when a code owner reviews the pull request that merges it (bravos records check asks GitHub with gh whether the branch requires that review, and offers CODEOWNERS lines for .guardlink/records/ that it writes only after you say yes: bravos records codeowners --owner @you). Without that review, a record on the default branch reads \'on main, review not enforced\'; the weaker fallback is a person running bravos records adopt SDR-n at their own terminal and typing their name, which shows who said so, not that anyone reviewed it. An agent cannot approve or adopt one. From then on every coding agent asks bravos records for <file> before changing covered code and follows the record; in Claude Code, Codex, Cursor, Antigravity, opencode and omp the first edit of a covered file in a session is refused once with the record in full (each in its own hook shape, through the installed CLI; any hook error lets the edit through), so it is read before anything changes. A change that goes against a rule is raised with you first and shows as a decision-record card after the edit, as does a removed check, and a record edited on a branch is a proposal: the default branch\'s text binds until the edit is approved, and only the branch that edits it waits (bravos records check). In CI, the PR gate checks with the workflow\'s GITHUB_TOKEN that a code owner approved the last change to each record and reports what it could not prove. A module ledger, .guardlink/records/README.md, lists which modules of the application make security decisions: the agent proposes it (bravos records ledger propose: features found from the stored documents, the threat model and the folders, with the code graph\'s routes on the Team plan; without the graph a feature split over folders with different names can show as two modules, so the boundaries are for a person to review), a person reviews it in its pull request, and Bravos keeps its Record and Owner columns (bravos records ledger refresh, owners from CODEOWNERS). It is never enforced. From the first session the briefing counts it ("9 modules, 2 with records"), and the first edit in a session to a module it says needs a record, and has none, gets one line offering to draft one, never a block; the company principles apply either way (bravos prefs set nudge off silences it). On the Team plan, once a person has reviewed the ledger, the agent drafts records for the modules that need one in the background: a subagent runs bravos records drafts (at most 2 a run, 3 waiting for review at once, never two for one module) and bravos records draft "<module>", which starts each draft on its own branch and worktree so your checkout is never touched. A draft states only what your documents (SRC-n § Section), confirmed intent rules or people said, cited on the line; what the code does today is marked observed and kept as guidance; Not a bug is never filled from code. bravos records check holds every citation to the repository. The agent pushes nothing and asks you before opening each draft\'s pull request; it binds nobody until a code owner approves it, and only that branch waits. bravos prefs set drafts off stops it. bravos rules lists each rule with its status. On the Team plan the pre-PR gate holds a change that breaks an adopted enforced rule whatever the PR body says, until the code is fixed, a person approves a dated exception (bravos records except SDR-n R1, at their own terminal), or the record is changed and the new text approved; people can adopt on a page with bravos review records (Agree, Change or No per rule); bravos records gaps lists modules no record covers; and the dashboard has a Decision records view, with possible conflicts: open exposures and SAST findings in a record\'s paths whose kind of weakness bears on one of its rules, each with the reason (bravos records conflicts lists the same; they never change a rule\'s status, and a person dismisses one at their own terminal). Reading and following records is free; writing, adopting, exceptions, the gate, gaps and the view are on the Team plan.'] },
|
|
121
121
|
{ name: 'See which design rules hold', skills: ['bravos', 'bravos-recheck'], body: ['bravos rules lists every rule your design states (INV-n in the intent) with its status: broken (a test got through), retest due (the code under it changed since it was tested), unguarded (it can break somewhere and nothing stops it), guarded but untested, not placed (no code is tied to it yet), or holds (a test tried and was refused everywhere it is enforced). Each line names the document the rule came from and the places it is enforced. bravos dashboard shows the same under Threat model, as Design rules in GuardLink\'s sidebar beside Exposures, worst first. Free, read-only, no model; --json prints bravos.rules/v1. On the Team plan the pre-PR check and the PR workflow hold a pull request that changes a file a holding rule is enforced in (the check, or the role table that grants the permission) after that rule was last tested, until its test is replayed or the PR body names the rule; the after-edit note says the same while you work.'] },
|
|
122
122
|
{ name: 'The intake asks, it never blocks', skills: ['bravos-context', 'bravos-annotate'], body: ['Annotation starts in the first session. With no confirmed intent, the agent drafts what the product is for from the README, docs and code (.guardlink/intent.md, every item marked draft), annotates against that draft, and opens the intake page without waiting. Each session asks once for a person to confirm it (bravos review intent, a few minutes) until someone confirms or declines; the agent never confirms for you. Rules drafted from the design are tested and can block a pull request right away; bravos rules and the block message label them draft until a person confirms them. When the answers arrive, the agent re-judges what they changed: an item you mark intended by design is annotated as intended, not as a finding. The intake page brings back the answers each person gave when they reopen it, and saves them as they go; only Confirm makes them count, and it records who and when. Design documents (a PRD, a design document, an earlier threat model) can be added on the page itself: Markdown and text are stored with the usual checks, and a PDF, Word file, slides or link waits for the agent to convert. Every rule cites the section of the document it came from, the page shows that passage under the question, and bravos context check refuses a section the document does not have. The intake and the documents are committed so the team gets them on their next pull; bravos doctor warns when a .gitignore rule keeps them on one machine, and bravos context share --yes narrows a blanket .bravos/ rule. A team that chooses to go without records that under a name, bravos context decline --by "<name>", which is committed like the intent and ends the asking; a coding agent is told never to decline for you. bravos context gate says which state a repository is in.'] },
|
|
123
123
|
{ name: 'Updates', skills: ['bravos'], body: ['Bravos tells you when it is updated. At most once a day a session start asks the npm registry, in a background process the session never waits on, for the latest published version: the same request npm install makes, with only the package name. A newer version shows in the banner and the briefing, and the coach tells a session that is already running, once. Installing it is yours to do (npm install -g @bugb-technologies/bravos); once it is installed the coach has the agent run bravos setup in the repository, which brings its Bravos files up to date. bravos doctor shows the last check. BRAVOS_UPDATE_CHECK=off stops the check, and it never runs in CI.'] },
|
|
@@ -140,7 +140,7 @@ export const GUIDE_TOPICS = [
|
|
|
140
140
|
{ name: 'An app made of several repositories (microservices)', skills: ['bravos-annotate', 'bravos-codegraph', 'bravos-prove'], body: ['Clone the services side by side in one folder, then run bravos workspace create NAME --member ./gateway=gateway@http://127.0.0.1:8080 --member ./orders=orders@http://127.0.0.1:8081 (bravos workspace plus guardlink link-project plus bravos in each repo and in the shared folder). Work on a service from its own repo; ask questions that cross services from the shared folder, where the briefing and bravos watch show every service. Declare each call to another service as @flows #<this>-<x> -> #<other>-<y> via http (plain ids, not #repo.tag). Build the code graph over the shared folder so it links one service\'s client calls to another\'s handlers. bravos report data --workspace writes one report across the services.'] },
|
|
141
141
|
{ name: 'After updating bravos', skills: ['bravos'], body: ['Nothing to run by hand in a repository you work in with an agent: at the start of a session bravos upkeep (read-only, no network) tells the agent what is behind the installed version, and the agent runs bravos setup, which brings the repository\'s skills and hooks and Bravos\'s own bundles up to date, without asking. If a teammate synced the repository with a newer bravos than yours, the agent syncs nothing and tells you to update. Installing guardlink and cxg (bravos setup --tools) still waits for your go-ahead.'] },
|
|
142
142
|
{ name: 'Stop being asked about commits', skills: ['bravos'], body: ['Say once whether your agent commits the files Bravos writes (annotations, intent, definitions, tests): bravos prefs set commits commit|leave|ask --by "<your name>". bravos setup asks it too. The answer is kept in this clone\'s git directory, never committed, and your own code is never part of such a commit. bravos prefs get shows it.'] },
|
|
143
|
-
{ name: 'See the findings on one page', skills: ['bravos'], body: ['Run bravos dashboard (free, no model): it writes one self-contained page under .bravos/dashboard/ (git-ignored) and opens it in your browser. It is GuardLink\'s threat model with who introduced and fixed each exposure and what changed since the default branch; on the Team plan, with the code graph built, a second tab shows the code graph: a map of where the risk sits, owners and history, coupling, trust, the attack surface, entry points and links. Run it again whenever you want the picture: it rebuilds from the code as it stands, rebuilding a code graph that is missing or behind first, and a saved page says when it is more than half a day old. --no-blame leaves git names out of a page you will share; --no-open only prints the path. Or ask your agent "show me the findings".'] },
|
|
143
|
+
{ name: 'See the findings on one page', skills: ['bravos'], body: ['Run bravos dashboard (free, no model): it writes one self-contained page under .bravos/dashboard/ (git-ignored) and opens it in your browser. It is GuardLink\'s threat model with who introduced and fixed each exposure and what changed since the default branch; on the Team plan, with the code graph built, a second tab shows the code graph: a map of where the risk sits, owners and history, coupling, trust, the attack surface, entry points and links. Run it again whenever you want the picture: it rebuilds from the code as it stands, rebuilding a code graph that is missing or behind first, and a saved page says when it is more than half a day old. --no-blame leaves git names out of a page you will share; --no-open only prints the path. Or ask your agent "show me the findings". With a SAST run (Team plan), a SAST view lists its findings, those joined to a claim, those not in the threat model yet, dependencies and secrets (by type and place, never the value), with how many commits the run is behind; the code graph Map\'s Findings lens draws the same findings.'] },
|
|
144
144
|
{ name: 'Write up the assessment, a finding or a retest', skills: ['bravos-report'], body: ['Ask "write the assessment report" (or a finding, a retest, an executive brief). bravos report data gathers the evidence; the agent writes report.md in the eight-section reading order, with every proof claim citing its evidence; bravos report check refuses a finding labelled reproduced without a run or ledger record; bravos report export writes md, txt, html and pdf. bravos watch shows the newest report (p to read it, o to open the pdf or html).'] },
|
|
145
145
|
],
|
|
146
146
|
},
|
package/dist/plugin-release.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
2
2
|
import { dirname, join, relative } from 'node:path';
|
|
3
|
+
import { AGY_EDIT_MATCHER } from './hooks.js';
|
|
3
4
|
import { SERVERS } from './mcp.js';
|
|
4
5
|
import { hooksDir, packageRoot, version } from './paths.js';
|
|
5
6
|
import { listBundledSkills, renderPluginSkillFile, renderPortableSkillFile, viaCliHooks } from './skills.js';
|
|
@@ -16,8 +17,8 @@ const KEYWORDS = ['security', 'threat-modeling', 'guardlink', 'pentest', 'cxg',
|
|
|
16
17
|
const SESSION_MATCHER = 'startup|resume|clear|compact';
|
|
17
18
|
const json = (v) => Buffer.from(JSON.stringify(v, null, 2) + '\n');
|
|
18
19
|
const text = (s) => Buffer.from(s.endsWith('\n') ? s : s + '\n');
|
|
19
|
-
// @comment -- "The hook files a plugin ships: the session-start
|
|
20
|
-
export function hookClosure(hooks,
|
|
20
|
+
// @comment -- "The hook files a plugin ships: the session-start and cards scripts and every file they import, followed through relative imports. The record guard, the pre-PR gate and autopilot run through the installed CLI (bravos hook), so their scripts are not shipped where a reviewer would have to read them."
|
|
21
|
+
export function hookClosure(hooks, entries = ['session-start.mjs', 'cards.mjs']) {
|
|
21
22
|
const seen = new Set();
|
|
22
23
|
const visit = (abs) => {
|
|
23
24
|
if (seen.has(abs))
|
|
@@ -27,11 +28,18 @@ export function hookClosure(hooks, entry = 'session-start.mjs') {
|
|
|
27
28
|
for (const m of src.matchAll(/(?:from\s+|import\s*\(\s*)['"](\.{1,2}\/[^'"]+)['"]/g))
|
|
28
29
|
visit(join(dirname(abs), m[1]));
|
|
29
30
|
};
|
|
30
|
-
|
|
31
|
+
for (const entry of Array.isArray(entries) ? entries : [entries])
|
|
32
|
+
visit(join(hooks, entry));
|
|
31
33
|
return [...seen].sort();
|
|
32
34
|
}
|
|
35
|
+
// @comment -- "The edit hooks a plugin registers, the same protection bravos setup writes into a repository: the record guard before an edit, through the installed CLI only and with --plugin, so it stays quiet where the repository registers its own; and the cards (threat cards, record cards, the no-record nudge) after one, from the plugin's own copy, which defers to a repository's. The guard runs only where the repository keeps records and bravos is on PATH; any failure lets the edit through."
|
|
36
|
+
const CLAUDE_EDIT_MATCHER = 'Edit|Write|MultiEdit|NotebookEdit';
|
|
37
|
+
const CODEX_EDIT_MATCHER = 'apply_patch|Edit|Write';
|
|
38
|
+
export const pluginGuardCommand = (harness) => harness === 'claude'
|
|
39
|
+
? 'if [ -d "${CLAUDE_PROJECT_DIR}/.guardlink/records" ] && command -v bravos >/dev/null 2>&1; then bravos hook record-guard --harness claude --plugin; fi'
|
|
40
|
+
: 'r="$(git rev-parse --show-toplevel 2>/dev/null)"; if [ -n "$r" ] && [ -d "$r/.guardlink/records" ] && command -v bravos >/dev/null 2>&1; then bravos hook record-guard --harness codex --plugin; fi';
|
|
33
41
|
const guardlinkServer = () => ({ type: 'stdio', command: SERVERS.guardlink.command, args: [...SERVERS.guardlink.args] });
|
|
34
|
-
// @comment -- "Every file of the public plugin repository, computed and not written. Skills: Claude Code's copy uses ${CLAUDE_SKILL_DIR} and ${CLAUDE_PLUGIN_ROOT}, which it substitutes; every other copy uses the portable SKILL_DIR wording. In every copy a skill's `node .bravos/hooks/<hook>.mjs` is `bravos hook <hook>`, because a plugin install has no .bravos/hooks/. Session hooks are registered where the harness's plugin format and SessionStart output are known: Claude Code, Codex, Gemini CLI and Antigravity. Copilot, VS Code and Cursor get the skills and MCP, and the bravos skill loads the briefing itself."
|
|
42
|
+
// @comment -- "Every file of the public plugin repository, computed and not written. Skills: Claude Code's copy uses ${CLAUDE_SKILL_DIR} and ${CLAUDE_PLUGIN_ROOT}, which it substitutes; every other copy uses the portable SKILL_DIR wording. In every copy a skill's `node .bravos/hooks/<hook>.mjs` is `bravos hook <hook>`, because a plugin install has no .bravos/hooks/. Session hooks are registered where the harness's plugin format and SessionStart output are known: Claude Code, Codex, Gemini CLI and Antigravity; the edit hooks (record guard, cards) for Claude Code, Codex and Antigravity, whose edit-hook contracts were checked. Gemini CLI, Copilot, VS Code and Cursor plugins get no edit hooks yet; Copilot, VS Code and Cursor get the skills and MCP, and the bravos skill loads the briefing itself."
|
|
35
43
|
export function releaseFiles(opts = {}) {
|
|
36
44
|
const v = version();
|
|
37
45
|
const files = [];
|
|
@@ -60,7 +68,11 @@ export function releaseFiles(opts = {}) {
|
|
|
60
68
|
// Claude Code: claude/, listed by .claude-plugin/marketplace.json.
|
|
61
69
|
addSkills('claude/', (c, rel) => viaCliHooks(renderPluginSkillFile(c, rel)));
|
|
62
70
|
addHookScripts('claude/');
|
|
63
|
-
add('claude/hooks/hooks.json', json({ hooks: {
|
|
71
|
+
add('claude/hooks/hooks.json', json({ hooks: {
|
|
72
|
+
SessionStart: [sessionArgs('${CLAUDE_PLUGIN_ROOT}/hooks/session-start.mjs', 'claude')],
|
|
73
|
+
PreToolUse: [{ matcher: CLAUDE_EDIT_MATCHER, hooks: [{ type: 'command', command: pluginGuardCommand('claude'), timeout: 10 }] }],
|
|
74
|
+
PostToolUse: [{ matcher: CLAUDE_EDIT_MATCHER, hooks: [{ type: 'command', command: 'node', args: ['${CLAUDE_PLUGIN_ROOT}/hooks/cards.mjs', '--harness', 'claude'], timeout: 10 }] }],
|
|
75
|
+
} }));
|
|
64
76
|
add('claude/.claude-plugin/icon.png', icon);
|
|
65
77
|
add('claude/.mcp.json', json({ mcpServers: { guardlink: SERVERS.guardlink } }));
|
|
66
78
|
// Claude's directory shows these links on the listing; the pages are the company site's own.
|
|
@@ -73,7 +85,7 @@ export function releaseFiles(opts = {}) {
|
|
|
73
85
|
termsOfServiceUrl: 'https://www.bugb.io/terms',
|
|
74
86
|
}));
|
|
75
87
|
add('claude/LICENSE', licence);
|
|
76
|
-
add('claude/README.md', text(readme(v)));
|
|
88
|
+
add('claude/README.md', text(readme(v, skills.length)));
|
|
77
89
|
add('.claude-plugin/marketplace.json', json({
|
|
78
90
|
name: NAME,
|
|
79
91
|
owner: AUTHOR,
|
|
@@ -83,7 +95,12 @@ export function releaseFiles(opts = {}) {
|
|
|
83
95
|
// Codex: codex/, listed by .agents/plugins/marketplace.json. Hooks at the plugin root, as Codex's own plugins keep them.
|
|
84
96
|
addSkills('codex/', renderPortableSkillFile);
|
|
85
97
|
addHookScripts('codex/');
|
|
86
|
-
|
|
98
|
+
// Codex names its edit tool differently across versions, so cards run after every tool and read the files from the payload or the working tree.
|
|
99
|
+
add('codex/hooks.json', json({ hooks: {
|
|
100
|
+
SessionStart: [sessionGroup('node "${PLUGIN_ROOT}/hooks/session-start.mjs" --harness codex')],
|
|
101
|
+
PreToolUse: [{ matcher: CODEX_EDIT_MATCHER, hooks: [{ type: 'command', command: pluginGuardCommand('codex'), timeout: 10 }] }],
|
|
102
|
+
PostToolUse: [{ hooks: [{ type: 'command', command: 'node "${PLUGIN_ROOT}/hooks/cards.mjs" --harness codex', timeout: 10 }] }],
|
|
103
|
+
} }));
|
|
87
104
|
add('codex/.mcp.json', json({ mcpServers: { guardlink: guardlinkServer() } }));
|
|
88
105
|
add('codex/.codex-plugin/plugin.json', json({
|
|
89
106
|
...base,
|
|
@@ -150,13 +167,20 @@ export function releaseFiles(opts = {}) {
|
|
|
150
167
|
logo: 'assets/icon.png',
|
|
151
168
|
suggestedPrompts: ['Where do I start on security here?', 'Threat-model this repository', 'Is this PR safe to open?'],
|
|
152
169
|
}));
|
|
153
|
-
|
|
170
|
+
// The guard goes through a small workspace shim: a plugin's hooks run in the plugin's folder, and bravos hook finds the repository from where it runs. PostToolUse cannot reach the model, so the cards' note waits for PreInvocation.
|
|
171
|
+
add('hooks/workspace-hook.mjs', readFileSync(join(packageRoot(), 'templates', 'plugin', 'workspace-hook.mjs')));
|
|
172
|
+
add('hooks.json', json({ bravos: {
|
|
173
|
+
SessionStart: [{ type: 'command', command: 'node hooks/session-start.mjs --harness agy', timeout: 30 }],
|
|
174
|
+
PreToolUse: [{ matcher: AGY_EDIT_MATCHER, hooks: [{ type: 'command', command: 'node hooks/workspace-hook.mjs record-guard --harness agy --plugin', timeout: 10 }] }],
|
|
175
|
+
PostToolUse: [{ matcher: AGY_EDIT_MATCHER, hooks: [{ type: 'command', command: 'node hooks/cards.mjs --harness agy', timeout: 10 }] }],
|
|
176
|
+
PreInvocation: [{ type: 'command', command: 'node hooks/cards.mjs --harness agy --deliver', timeout: 5 }],
|
|
177
|
+
} }));
|
|
154
178
|
// Antigravity loads a plugin's context only from rules/; GEMINI.md is Gemini CLI's.
|
|
155
179
|
add('rules/bravos.md', text(GEMINI_CONTEXT));
|
|
156
180
|
add('mcp_config.json', json({ mcpServers: { guardlink: { command: SERVERS.guardlink.command, args: [...SERVERS.guardlink.args] } } }));
|
|
157
181
|
add('assets/icon.png', icon);
|
|
158
182
|
add('LICENSE', licence);
|
|
159
|
-
add('README.md', text(readme(v)));
|
|
183
|
+
add('README.md', text(readme(v, skills.length)));
|
|
160
184
|
return files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
161
185
|
}
|
|
162
186
|
const GEMINI_CONTEXT = `# Bravos
|
|
@@ -170,12 +194,14 @@ The skills drive the \`bravos\` CLI (\`npm install -g @bugb-technologies/bravos\
|
|
|
170
194
|
\`guardlink\` and \`cxg\`. Never send a request to a host other than loopback
|
|
171
195
|
without a committed, reviewed \`.guardlink/scope.yaml\` and the user's own typed
|
|
172
196
|
authorization naming the target.`;
|
|
173
|
-
function readme(v) {
|
|
197
|
+
function readme(v, n) {
|
|
174
198
|
return `# Bravos plugins
|
|
175
199
|
|
|
176
|
-
Bravos ${v} for the coding agent you already use. Each plugin carries the same
|
|
200
|
+
Bravos ${v} for the coding agent you already use. Each plugin carries the same ${n}
|
|
177
201
|
skills and the guardlink MCP server; the session-start briefing loads by itself
|
|
178
|
-
where the agent supports it.
|
|
202
|
+
where the agent supports it. In Claude Code, Codex and Antigravity the plugin also
|
|
203
|
+
reads a security decision record before the first edit to the code it covers, and
|
|
204
|
+
shows threat and record cards after an edit.
|
|
179
205
|
|
|
180
206
|
**First, install the CLI** (Node 20 or newer). The skills drive it:
|
|
181
207
|
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { BravosError } from './types.js';
|
|
5
|
+
// @comment -- "Possible conflicts between a security decision record and the code it covers: open exposures (no control, not accepted) and SAST findings inside a record's paths whose weakness bears on one of its rules, each with the reason it was matched. Deterministic, no model: a fixed table maps a rule's words to weakness families, and a candidate matches a family by its CWE, or, with none, by its threat or rule name. These are suggestions for a person: they never mark a rule broken or unguarded, never reach the pre-PR gate and never write an annotation. A person dismisses one at their own terminal, recorded with their name in .guardlink/records-dismissals.json, never as @accepts."
|
|
6
|
+
export const DISMISSALS_FILE = '.guardlink/records-dismissals.json';
|
|
7
|
+
export const DISMISSALS_SCHEMA = 'bravos.records-dismissals/v1';
|
|
8
|
+
// The weakness families a rule can be about. Words are matched in a rule's text; CWEs and names in a candidate's.
|
|
9
|
+
export const FAMILIES = [
|
|
10
|
+
{ id: 'access', label: 'an access-control weakness', about: 'who may see or do what', strong: /\b(admins?|owners?|roles?|permissions?|authori[sz]\w*|tenants?|private)\b/i, words: /\b(admins?|owners?|roles?|permissions?|authori[sz]\w*|allowed|only|may|can (?:open|view|see|read|edit|delete|change)|access|tenants?|private|visible|sees?|opens?)\b/i, cwes: [284, 285, 269, 266, 425, 639, 732, 862, 863, 915, 1220], names: /idor|access|authz|authori[sz]|privilege|bac\b|permission|tenant|ownership|admin/i },
|
|
11
|
+
{ id: 'injection', label: 'an injection weakness', about: 'how input reaches a query, a command or a page', words: /\b(sql|query|queries|parameters?|parameteri[sz]ed|escaped?|saniti[sz]ed?|input|shell|commands?|exec\w*|templates?|html|scripts?|inject\w*)\b/i, cwes: [74, 77, 78, 79, 80, 89, 90, 91, 94, 95, 611, 643, 917, 943, 1336], names: /sqli|sql|inject|cmdi|command|xss|script|template|rce|ssti|xxe/i },
|
|
12
|
+
{ id: 'credentials', label: 'a credentials weakness', about: 'how secrets and credentials are kept', words: /\b(secrets?|passwords?|tokens?|keys?|credentials?|api[- ]keys?)\b/i, cwes: [256, 259, 312, 321, 522, 532, 798], names: /secret|password|token|credential|hard-?coded|key/i },
|
|
13
|
+
{ id: 'crypto', label: 'a cryptography weakness', about: 'encryption, hashing or signing', words: /\b(encrypt\w*|hash\w*|tls|https|cipher|signatures?|signed|sign)\b/i, cwes: [319, 326, 327, 328, 330, 338, 347, 916], names: /crypt|hash|tls|cipher|signature|random/i },
|
|
14
|
+
{ id: 'session', label: 'a session weakness', about: 'sessions, cookies and sign-out', words: /\b(sessions?|cookies?|expire\w*|log ?out|sign ?out)\b/i, cwes: [384, 613, 614, 1004], names: /session|cookie|fixation/i },
|
|
15
|
+
{ id: 'files', label: 'a file-handling weakness', about: 'files, uploads and paths', words: /\b(files?|uploads?|paths?|downloads?)\b/i, cwes: [22, 23, 73, 434], names: /path|travers|upload|file/i },
|
|
16
|
+
{ id: 'logging', label: 'a logging weakness', about: 'what is logged or audited', words: /\b(logs?|logged|logging|audit\w*)\b/i, cwes: [117, 223, 532, 778], names: /log|audit/i },
|
|
17
|
+
{ id: 'rate', label: 'a rate-limiting weakness', about: 'limits on how often something is tried', words: /\b(rate|limits?|throttl\w*|brute\w*|attempts?)\b/i, cwes: [307, 770, 799], names: /brute|rate|throttl|dos\b|flood/i },
|
|
18
|
+
{ id: 'data', label: 'a data-exposure weakness', about: 'which data leaves the application', words: /\b(personal|pii|customer data|emails?|phone|exports?|leak\w*|disclos\w*|shared?|revenue)\b/i, cwes: [200, 201, 359, 538], names: /disclos|leak|exposure|pii|privacy/i },
|
|
19
|
+
{ id: 'redirect', label: 'an open-redirect weakness', about: 'where users are sent', words: /\bredirect\w*\b/i, cwes: [601], names: /redirect/i },
|
|
20
|
+
{ id: 'csrf', label: 'a cross-site request forgery weakness', about: 'requests made on a user\'s behalf', words: /\b(csrf|cross-site request|forged requests?)\b/i, cwes: [352], names: /csrf/i },
|
|
21
|
+
];
|
|
22
|
+
export const cweNumbers = (refs) => [...new Set((Array.isArray(refs) ? refs : [refs]).flatMap((r) => [...String(r ?? '').matchAll(/CWE-(\d{1,5})/gi)].map((m) => Number(m[1]))))].sort((a, b) => a - b);
|
|
23
|
+
/** The families a rule's words are about, with the word that showed each. */
|
|
24
|
+
export function ruleFamilies(text) {
|
|
25
|
+
return FAMILIES.flatMap((f) => {
|
|
26
|
+
// The telling word when there is one ("admins"), else the first the family knows ("only").
|
|
27
|
+
const m = f.strong?.exec(text) ?? f.words.exec(text);
|
|
28
|
+
return m ? [{ family: f, word: m[0] }] : [];
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
// @comment -- "Why a candidate bears on a family: its CWE is one the family lists (the strongest reason), or, when it carries no CWE at all, its threat or rule name says so. A candidate whose CWEs all lie outside the family is not matched by name: the CWE is what the person or the analyzer chose."
|
|
32
|
+
function candidateReason(c, f) {
|
|
33
|
+
const hit = c.cwes.find((n) => f.cwes.includes(n));
|
|
34
|
+
if (hit)
|
|
35
|
+
return `CWE-${hit} is ${f.label}`;
|
|
36
|
+
if (!c.cwes.length) {
|
|
37
|
+
const m = f.names.exec(c.names);
|
|
38
|
+
if (m) {
|
|
39
|
+
// The whole word the match sits in ("authorization", not "authoriz").
|
|
40
|
+
const start = c.names.slice(0, m.index).search(/[\w]*$/);
|
|
41
|
+
const word = (c.names.slice(start).match(/^[\w]+/) ?? [m[0]])[0];
|
|
42
|
+
return `its name ("${word}") is ${f.label}`;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
/** A stable key for one suggestion: the record and rule, where it came from, what it is and the file it is in. */
|
|
48
|
+
export const conflictKey = (record, rule, c) => createHash('sha256').update(JSON.stringify([record, rule, c.source, c.id, c.file])).digest('hex').slice(0, 12);
|
|
49
|
+
// @comment -- "The possible conflicts for each record: every candidate inside the record's paths (as the record's own globs say) whose weakness bears on a family one of the record's rules is about, once per rule, with the reason. A candidate on a rule's own threat is not a conflict, that is the rule's own place; guidance rules are matched too, since a person may still want to know. Dismissed ones are kept, marked, for the person to review."
|
|
50
|
+
export function findConflicts(records, candidates, opts) {
|
|
51
|
+
const dismissed = new Map((opts.dismissals ?? []).map((d) => [d.key, d]));
|
|
52
|
+
const out = [];
|
|
53
|
+
for (const rec of records) {
|
|
54
|
+
const mine = candidates.filter((c) => rec.paths.some((g) => opts.inPaths(g, c.file)));
|
|
55
|
+
if (!mine.length)
|
|
56
|
+
continue;
|
|
57
|
+
for (const rule of rec.rules) {
|
|
58
|
+
const own = opts.ruleThreat(rec.id, rule.id);
|
|
59
|
+
for (const { family, word } of ruleFamilies(rule.text)) {
|
|
60
|
+
for (const c of mine) {
|
|
61
|
+
if (own && c.threat === own)
|
|
62
|
+
continue;
|
|
63
|
+
const why = candidateReason(c, family);
|
|
64
|
+
if (!why)
|
|
65
|
+
continue;
|
|
66
|
+
const key = conflictKey(rec.id, rule.id, c);
|
|
67
|
+
if (out.some((x) => x.key === key))
|
|
68
|
+
continue;
|
|
69
|
+
const d = dismissed.get(key);
|
|
70
|
+
out.push({
|
|
71
|
+
key,
|
|
72
|
+
record: rec.id,
|
|
73
|
+
rule: rule.id,
|
|
74
|
+
ruleText: rule.text,
|
|
75
|
+
source: c.source,
|
|
76
|
+
what: c.title,
|
|
77
|
+
file: c.file,
|
|
78
|
+
line: c.line,
|
|
79
|
+
severity: c.severity,
|
|
80
|
+
family: family.id,
|
|
81
|
+
reason: `${why}, and ${rec.id} ${rule.id} is about ${family.about} ("${word}"); ${c.file} is in ${rec.id}'s paths.`,
|
|
82
|
+
dismissed: d ? { by: d.by, at: d.at, reason: d.reason } : null,
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const sev = (s) => ['critical', 'error', 'high', 'medium', 'warning', 'low'].indexOf(String(s ?? '').toLowerCase());
|
|
89
|
+
return out.sort((a, b) => a.record.localeCompare(b.record, undefined, { numeric: true }) || a.rule.localeCompare(b.rule, undefined, { numeric: true }) || (a.dismissed ? 1 : 0) - (b.dismissed ? 1 : 0) || sev(a.severity) - sev(b.severity) || a.file.localeCompare(b.file));
|
|
90
|
+
}
|
|
91
|
+
/** The dismissals people recorded; a missing file is none, a damaged one is said. */
|
|
92
|
+
export function readDismissals(root) {
|
|
93
|
+
const abs = join(root, DISMISSALS_FILE);
|
|
94
|
+
if (!existsSync(abs))
|
|
95
|
+
return [];
|
|
96
|
+
const j = JSON.parse(readFileSync(abs, 'utf8'));
|
|
97
|
+
if (j?.schema !== DISMISSALS_SCHEMA || !Array.isArray(j.dismissals))
|
|
98
|
+
throw new BravosError(`${DISMISSALS_FILE} is not a records dismissals file bravos wrote; fix or remove it`);
|
|
99
|
+
return j.dismissals.filter((d) => !!d && typeof d === 'object' && typeof d.key === 'string' && typeof d.by === 'string');
|
|
100
|
+
}
|
|
101
|
+
// @comment -- "Records one person's dismissal of one possible conflict: the key, the record and rule, what it was and where, the person's name, the day and their reason. Called only from an interactive terminal after the person typed their name (a person's decision, as adopting is); it writes nothing else, and never an @accepts: the exposure or finding stays exactly as it is."
|
|
102
|
+
// @mitigates #records against #forged-record using #person-only-adoption -- "A dismissal is recorded only for a name a person typed at an interactive terminal; the CLI refuses an agent's shell"
|
|
103
|
+
export function addDismissal(root, c, by, reason, now = new Date()) {
|
|
104
|
+
const list = readDismissals(root).filter((d) => d.key !== c.key);
|
|
105
|
+
const d = { key: c.key, record: c.record, rule: c.rule, what: c.what.slice(0, 200), where: `${c.file}${c.line ? `:${c.line}` : ''}`, by: by.slice(0, 80), at: now.toISOString().slice(0, 10), reason: reason.replace(/\s+/g, ' ').trim().slice(0, 400) };
|
|
106
|
+
writeFileSync(join(root, DISMISSALS_FILE), `${JSON.stringify({ schema: DISMISSALS_SCHEMA, dismissals: [...list, d] }, null, 2)}\n`);
|
|
107
|
+
return d;
|
|
108
|
+
}
|
|
109
|
+
/** The conflicts as terminal lines, grouped by record and rule. */
|
|
110
|
+
export function conflictLines(conflicts) {
|
|
111
|
+
if (!conflicts.length)
|
|
112
|
+
return ['records conflicts: none found: no open exposure or SAST finding in a record\'s paths bears on one of its rules.'];
|
|
113
|
+
const open = conflicts.filter((c) => !c.dismissed);
|
|
114
|
+
const lines = [`records conflicts: ${open.length} possible conflict${open.length === 1 ? '' : 's'}${conflicts.length > open.length ? ` (${conflicts.length - open.length} dismissed)` : ''}. Suggestions for a person: they change no rule's status and never hold a pull request.`];
|
|
115
|
+
let last = '';
|
|
116
|
+
for (const c of conflicts) {
|
|
117
|
+
const head = `${c.record} ${c.rule}`;
|
|
118
|
+
if (head !== last)
|
|
119
|
+
lines.push(`${head} "${c.ruleText}"`);
|
|
120
|
+
last = head;
|
|
121
|
+
lines.push(` ${c.dismissed ? 'dismissed ' : ''}[${c.key}] ${c.source === 'sast' ? 'SAST' : 'exposure'} ${c.what} at ${c.file}${c.line ? `:${c.line}` : ''}${c.severity ? ` (${c.severity})` : ''}`);
|
|
122
|
+
lines.push(` why: ${c.reason}`);
|
|
123
|
+
if (c.dismissed)
|
|
124
|
+
lines.push(` dismissed by ${c.dismissed.by} on ${c.dismissed.at}: ${c.dismissed.reason}`);
|
|
125
|
+
}
|
|
126
|
+
lines.push('Link one to its rule: ask your agent to "link records conflict <key>" (bravos-annotate records it as an exposure of the rule\'s threat). Not a conflict: bravos records conflicts dismiss <key> --reason "<why>", at your own terminal.');
|
|
127
|
+
return lines;
|
|
128
|
+
}
|
package/dist/rules.js
CHANGED
|
@@ -4,6 +4,9 @@ import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
|
4
4
|
import { isAbsolute, join, resolve, sep } from 'node:path';
|
|
5
5
|
import { contextLib } from './context.js';
|
|
6
6
|
import { parseJson, runner } from './watch.js';
|
|
7
|
+
import { cweNumbers, findConflicts, readDismissals } from './records-conflicts.js';
|
|
8
|
+
import { pathToFileURL } from 'node:url';
|
|
9
|
+
import { hooksDir } from './paths.js';
|
|
7
10
|
export const STATUS_ORDER = ['broken', 'retest-due', 'unguarded', 'guarded-untested', 'not-placed', 'holds'];
|
|
8
11
|
export const STATUS_LABEL = {
|
|
9
12
|
broken: 'broken',
|
|
@@ -352,6 +355,52 @@ export async function gatherRules(root, env, opts = {}) {
|
|
|
352
355
|
recordRules.push({ id: `${rec.id} ${rule.id}`, record: rec.id, rule: rule.id, module: rec.module, kind: rule.kind, text: rule.text, recordState: rec.state, adoptedBy: names ? rec.adopters : null, threat: t ? `#${t.id}` : null, severity: t?.severity ?? null, status: verdict.status, why: `${verdict.why}${unbound}`, sites });
|
|
353
356
|
}
|
|
354
357
|
}
|
|
358
|
+
// @comment -- "Possible conflicts for each record: the open exposures (no control on the same asset and threat, not accepted) and the newest SAST run's findings that no claim already carries, inside a record's paths, matched to a rule by weakness family (src/records-conflicts.ts). Read here, beside the records, so the dashboard and bravos records conflicts say the same. They are listed, never counted into a rule's status."
|
|
359
|
+
let conflicts = [];
|
|
360
|
+
let conflictsNote = '';
|
|
361
|
+
if (recordCheck.records.length && model) {
|
|
362
|
+
const accepted = arr(model?.acceptances);
|
|
363
|
+
const candidates = [];
|
|
364
|
+
for (const e of exposures) {
|
|
365
|
+
const asset = bare(e.asset);
|
|
366
|
+
const threat = bare(e.threat);
|
|
367
|
+
if (mitigations.some((m) => bare(m.asset) === asset && bare(m.threat) === threat) || accepted.some((a) => bare(a.asset) === asset && bare(a.threat) === threat))
|
|
368
|
+
continue;
|
|
369
|
+
const t = threats.find((x) => x.id === threat);
|
|
370
|
+
const file = String(e.location?.file ?? '');
|
|
371
|
+
if (!file)
|
|
372
|
+
continue;
|
|
373
|
+
candidates.push({ source: 'exposure', id: `#${asset} #${threat}`, title: `#${threat} on #${asset}${e.description ? `: ${String(e.description).slice(0, 160)}` : ''}`, file, line: num(e.location?.line), severity: typeof e.severity === 'string' ? e.severity : t?.severity ?? null, cwes: cweNumbers([...arr(e.external_refs), ...(t?.refs ?? [])]), names: `${threat} ${t?.name ?? ''}`, threat });
|
|
374
|
+
}
|
|
375
|
+
try {
|
|
376
|
+
const S = (await import(pathToFileURL(join(hooksDir(), 'lib', 'sast.mjs')).href));
|
|
377
|
+
const run = S.latestRun(root);
|
|
378
|
+
for (const x of arr(run?.report?.findings)) {
|
|
379
|
+
// A finding the analyzer already joined to a claim is that claim's evidence: the claim is the candidate.
|
|
380
|
+
if (x.suppressed || x.finding_class === 'agent_config' || (x.guardlink_join && x.guardlink_join !== 'unjoined' && x.guardlink_join !== 'none') || typeof x.file !== 'string')
|
|
381
|
+
continue;
|
|
382
|
+
candidates.push({ source: 'sast', id: String(x.finding_id ?? x.id ?? `${x.rule_id}@${x.file}:${x.line}`), title: String(x.title ?? x.rule_id ?? 'SAST finding').slice(0, 200), file: x.file, line: num(x.line), severity: typeof x.severity === 'string' ? x.severity.toLowerCase() : null, cwes: cweNumbers([x.cwe, ...(Array.isArray(x.cwes) ? x.cwes : [])]), names: `${x.rule_id ?? ''} ${x.vuln_type ?? ''} ${x.title ?? ''} ${x.finding_class ?? ''}`, threat: null });
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
catch {
|
|
386
|
+
/* no SAST run: exposures only */
|
|
387
|
+
}
|
|
388
|
+
let dismissals = [];
|
|
389
|
+
try {
|
|
390
|
+
dismissals = readDismissals(root);
|
|
391
|
+
}
|
|
392
|
+
catch (e) {
|
|
393
|
+
conflictsNote = `${e.message}. `;
|
|
394
|
+
}
|
|
395
|
+
conflicts = findConflicts(recordCheck.records.map((r) => ({ id: r.id, module: r.module, state: r.state, paths: r.paths, rules: r.rules })), candidates, {
|
|
396
|
+
inPaths: (g, f) => P.globMatch(g, f),
|
|
397
|
+
ruleThreat: (record, rule) => bare(recordRules.find((x) => x.record === record && x.rule === rule)?.threat ?? '') || null,
|
|
398
|
+
dismissals,
|
|
399
|
+
});
|
|
400
|
+
const open = conflicts.filter((c) => !c.dismissed).length;
|
|
401
|
+
if (conflicts.length)
|
|
402
|
+
conflictsNote += `${open} possible conflict${open === 1 ? '' : 's'} between the records and the code they cover${conflicts.length > open ? ` (${conflicts.length - open} dismissed)` : ''}: suggestions for a person, which change no rule's status (bravos records conflicts).`;
|
|
403
|
+
}
|
|
355
404
|
const recordOrder = (r) => (r.recordState === 'adopted' ? 0 : 1) * 100 + (r.status === 'guidance' ? STATUS_ORDER.length : STATUS_ORDER.indexOf(r.status));
|
|
356
405
|
recordRules.sort((a, b) => recordOrder(a) - recordOrder(b) || a.id.localeCompare(b.id, undefined, { numeric: true }));
|
|
357
406
|
const adoptedCount = recordCheck.adopted.length;
|
|
@@ -363,12 +412,12 @@ export async function gatherRules(root, env, opts = {}) {
|
|
|
363
412
|
for (const r of rules)
|
|
364
413
|
summary[r.status] += 1;
|
|
365
414
|
if (!rules.length) {
|
|
366
|
-
return { schema: 'bravos.rules/v1', state: 'none', note: 'No design rules are recorded yet. Run /bravos-context: it asks for your design documents and writes the rules they state (who may do what, what must never happen) into .guardlink/intent.md.', summary, rules, principles, principlesNote, records: recordRules, recordsNote };
|
|
415
|
+
return { schema: 'bravos.rules/v1', state: 'none', note: 'No design rules are recorded yet. Run /bravos-context: it asks for your design documents and writes the rules they state (who may do what, what must never happen) into .guardlink/intent.md.', summary, rules, principles, principlesNote, records: recordRules, recordsNote, conflicts, conflictsNote };
|
|
367
416
|
}
|
|
368
417
|
if (!model)
|
|
369
|
-
return { schema: 'bravos.rules/v1', state: 'no-guardlink', note: 'GuardLink is not installed on this machine, so the rules are listed without where the code enforces them: run bravos setup --tools -y, then bravos dashboard again.', summary, rules, principles, principlesNote, records: recordRules, recordsNote };
|
|
418
|
+
return { schema: 'bravos.rules/v1', state: 'no-guardlink', note: 'GuardLink is not installed on this machine, so the rules are listed without where the code enforces them: run bravos setup --tools -y, then bravos dashboard again.', summary, rules, principles, principlesNote, records: recordRules, recordsNote, conflicts, conflictsNote };
|
|
370
419
|
const said = STATUS_ORDER.filter((s) => summary[s]).map((s) => `${summary[s]} ${STATUS_LABEL[s]}`);
|
|
371
|
-
return { schema: 'bravos.rules/v1', state: 'present', note: `${rules.length} design rule${rules.length === 1 ? '' : 's'} from the intent: ${said.join(', ')}${summary.draft ? `; ${summary.draft} still a draft nobody has confirmed` : ''}.`, summary, rules, principles, principlesNote, records: recordRules, recordsNote };
|
|
420
|
+
return { schema: 'bravos.rules/v1', state: 'present', note: `${rules.length} design rule${rules.length === 1 ? '' : 's'} from the intent: ${said.join(', ')}${summary.draft ? `; ${summary.draft} still a draft nobody has confirmed` : ''}.`, summary, rules, principles, principlesNote, records: recordRules, recordsNote, conflicts, conflictsNote };
|
|
372
421
|
}
|
|
373
422
|
// @comment -- "The pre-PR gate's record of the times it stopped a change for breaking a principle, kept on this machine under the git directory (<git-common-dir>/bravos/principles-gate.jsonl, never committed): what the dashboard counts as the changes a principle stopped. Read-only, bounded; a missing or damaged file counts nothing."
|
|
374
423
|
export function gateStops(root, env) {
|
package/dist/setup.js
CHANGED
|
@@ -231,7 +231,7 @@ export function sastCache(root, env) {
|
|
|
231
231
|
}
|
|
232
232
|
return { dir, workspace, env: out, ownGraph, sharedStore };
|
|
233
233
|
}
|
|
234
|
-
// @comment -- "Runs the analyzer the way the Python adapter did: bravos-cli analyze ROOT --ci --fail-on never --allow-incomplete-analysis --codegraph <reuse when a graph store exists, auto when it keeps its own> --scip off --workspace .bravos/sast/cache/workspace -f json,sarif -o .bravos/sast/<run>/report, under the bundle's environment with its caches in the repository (sastCache), then writes meta.json (sha, exit, at, cache, graphStore) so the briefing's SAST line and bravos sast candidates read it. The exit code is a health signal; findings are read from the report."
|
|
234
|
+
// @comment -- "Runs the analyzer the way the Python adapter did: bravos-cli analyze ROOT --ci --fail-on never --allow-incomplete-analysis --codegraph <reuse when a graph store exists, auto when it keeps its own or has no graph to reuse> --scip off --workspace .bravos/sast/cache/workspace -f json,sarif -o .bravos/sast/<run>/report, under the bundle's environment with its caches in the repository (sastCache), then writes meta.json (sha, exit, at, cache, graphStore) so the briefing's SAST line and bravos sast candidates read it. The exit code is a health signal; findings are read from the report."
|
|
235
235
|
export async function runSast(root, env, opts = {}) {
|
|
236
236
|
const licence = await requireFeature(env, 'sast', 'bravos sast run');
|
|
237
237
|
const dir = staged(env, 'analyzer');
|
|
@@ -252,8 +252,8 @@ export async function runSast(root, env, opts = {}) {
|
|
|
252
252
|
mkdirSync(runDir, { recursive: true });
|
|
253
253
|
const sha = spawnSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8', timeout: 5000 }).stdout?.trim() || null;
|
|
254
254
|
const cache = sastCache(root, env);
|
|
255
|
-
// @comment -- "A graph store of the analyzer's own starts empty, so reuse would refuse every first run: let the analyzer build the graph there (auto) unless the caller chose a mode."
|
|
256
|
-
let codegraph = opts.codegraph ?? (cache.ownGraph ? 'auto' : graphBin('codegraph-mcp', env) ? 'reuse' : '
|
|
255
|
+
// @comment -- "A graph store of the analyzer's own starts empty, so reuse would refuse every first run: let the analyzer build the graph there (auto) unless the caller chose a mode. bravos-cli takes auto, build or reuse and nothing else (0.6.2 and 0.6.4 both refuse 'off', on purpose), so with no graph tool installed it is auto too: the analyzer builds what it needs."
|
|
256
|
+
let codegraph = opts.codegraph ?? (cache.ownGraph ? 'auto' : graphBin('codegraph-mcp', env) ? 'reuse' : 'auto');
|
|
257
257
|
const argvFor = (graph) => {
|
|
258
258
|
const a = ['analyze', root, '--ci', '--fail-on', 'never', '--allow-incomplete-analysis', '--codegraph', graph, '--scip', opts.scip ?? 'off', '--workspace', cache.workspace, '-f', 'json,sarif', '-o', join(runDir, 'report')];
|
|
259
259
|
if (opts.scope?.length)
|
|
@@ -277,10 +277,10 @@ export async function runSast(root, env, opts = {}) {
|
|
|
277
277
|
if (cache.ownGraph)
|
|
278
278
|
notes.push(` ${cache.sharedStore ? `the shared code-graph store ${cache.sharedStore} is not writable here (a sandbox that allows writes only in the workspace?)` : 'there is no shared code-graph store'}, so the analyzer kept its graph in ${cache.env.BRAVOS_CODEGRAPH_DIR}`);
|
|
279
279
|
let r = spawn(codegraph);
|
|
280
|
-
// No graph built for this commit yet: reuse refuses outright.
|
|
280
|
+
// No graph built for this commit yet: reuse refuses outright. Let the analyzer build one for this run (auto) rather than fail; 'off' is not a mode bravos-cli has.
|
|
281
281
|
if (codegraph === 'reuse' && r.status === 3 && /CodeGraph unavailable|No CodeGraph/i.test(`${r.stdout}\n${r.stderr}`)) {
|
|
282
|
-
notes.push(' no code graph for this commit yet, so the
|
|
283
|
-
codegraph = '
|
|
282
|
+
notes.push(' no code graph for this commit yet, so the analyzer built one for this run (--codegraph auto, which takes longer); bravos graph build . --scip no-exec keeps one current for the dashboard and later runs');
|
|
283
|
+
codegraph = 'auto';
|
|
284
284
|
r = spawn(codegraph);
|
|
285
285
|
}
|
|
286
286
|
writeFileSync(join(runDir, 'meta.json'), JSON.stringify({ sha, base: null, scope: opts.scope?.length ? opts.scope.join(',') : 'all', exit: r.status, at: new Date().toISOString(), analyzer: bin, codegraph, cache: cache.dir, graphStore: runEnv.BRAVOS_CODEGRAPH_DIR ?? null }, null, 2) + '\n');
|
package/docs/GUIDE.md
CHANGED
|
@@ -120,7 +120,7 @@ Ask for "our security design principles". bravos-principles proposes candidates
|
|
|
120
120
|
|
|
121
121
|
Skills: `/bravos-records`
|
|
122
122
|
|
|
123
|
-
Ask for "a security decision record for <module>". bravos-records drafts one document for that module (.guardlink/records/SDR-n-<module>.md) from what you tell it, your documents and confirmed rules: the decision, the rules that follow, why, and what looks like a bug but is not. It is a draft until its text reaches the default branch: approved when a code owner reviews the pull request that merges it (bravos records check asks GitHub with gh whether the branch requires that review, and offers CODEOWNERS lines for .guardlink/records/ that it writes only after you say yes: bravos records codeowners --owner @you). Without that review, a record on the default branch reads 'on main, review not enforced'; the weaker fallback is a person running bravos records adopt SDR-n at their own terminal and typing their name, which shows who said so, not that anyone reviewed it. An agent cannot approve or adopt one. From then on every coding agent asks bravos records for <file> before changing covered code and follows the record; in Claude Code, Codex, Cursor, Antigravity, opencode and omp the first edit of a covered file in a session is refused once with the record in full (each in its own hook shape, through the installed CLI; any hook error lets the edit through), so it is read before anything changes. A change that goes against a rule is raised with you first and shows as a decision-record card after the edit, as does a removed check, and a record edited on a branch is a proposal: the default branch's text binds until the edit is approved, and only the branch that edits it waits (bravos records check). In CI, the PR gate checks with the workflow's GITHUB_TOKEN that a code owner approved the last change to each record and reports what it could not prove. A module ledger, .guardlink/records/README.md, lists which modules of the application make security decisions: the agent proposes it (bravos records ledger propose: features found from the stored documents, the threat model and the folders, with the code graph's routes on the Team plan; without the graph a feature split over folders with different names can show as two modules, so the boundaries are for a person to review), a person reviews it in its pull request, and Bravos keeps its Record and Owner columns (bravos records ledger refresh, owners from CODEOWNERS). It is never enforced. From the first session the briefing counts it ("9 modules, 2 with records"), and the first edit in a session to a module it says needs a record, and has none, gets one line offering to draft one, never a block; the company principles apply either way (bravos prefs set nudge off silences it). On the Team plan, once a person has reviewed the ledger, the agent drafts records for the modules that need one in the background: a subagent runs bravos records drafts (at most 2 a run, 3 waiting for review at once, never two for one module) and bravos records draft "<module>", which starts each draft on its own branch and worktree so your checkout is never touched. A draft states only what your documents (SRC-n § Section), confirmed intent rules or people said, cited on the line; what the code does today is marked observed and kept as guidance; Not a bug is never filled from code. bravos records check holds every citation to the repository. The agent pushes nothing and asks you before opening each draft's pull request; it binds nobody until a code owner approves it, and only that branch waits. bravos prefs set drafts off stops it. bravos rules lists each rule with its status. On the Team plan the pre-PR gate holds a change that breaks an adopted enforced rule whatever the PR body says, until the code is fixed, a person approves a dated exception (bravos records except SDR-n R1, at their own terminal), or the record is changed and the new text approved; people can adopt on a page with bravos review records (Agree, Change or No per rule); bravos records gaps lists modules no record covers; and the dashboard has a Decision records view. Reading and following records is free; writing, adopting, exceptions, the gate, gaps and the view are on the Team plan.
|
|
123
|
+
Ask for "a security decision record for <module>". bravos-records drafts one document for that module (.guardlink/records/SDR-n-<module>.md) from what you tell it, your documents and confirmed rules: the decision, the rules that follow, why, and what looks like a bug but is not. It is a draft until its text reaches the default branch: approved when a code owner reviews the pull request that merges it (bravos records check asks GitHub with gh whether the branch requires that review, and offers CODEOWNERS lines for .guardlink/records/ that it writes only after you say yes: bravos records codeowners --owner @you). Without that review, a record on the default branch reads 'on main, review not enforced'; the weaker fallback is a person running bravos records adopt SDR-n at their own terminal and typing their name, which shows who said so, not that anyone reviewed it. An agent cannot approve or adopt one. From then on every coding agent asks bravos records for <file> before changing covered code and follows the record; in Claude Code, Codex, Cursor, Antigravity, opencode and omp the first edit of a covered file in a session is refused once with the record in full (each in its own hook shape, through the installed CLI; any hook error lets the edit through), so it is read before anything changes. A change that goes against a rule is raised with you first and shows as a decision-record card after the edit, as does a removed check, and a record edited on a branch is a proposal: the default branch's text binds until the edit is approved, and only the branch that edits it waits (bravos records check). In CI, the PR gate checks with the workflow's GITHUB_TOKEN that a code owner approved the last change to each record and reports what it could not prove. A module ledger, .guardlink/records/README.md, lists which modules of the application make security decisions: the agent proposes it (bravos records ledger propose: features found from the stored documents, the threat model and the folders, with the code graph's routes on the Team plan; without the graph a feature split over folders with different names can show as two modules, so the boundaries are for a person to review), a person reviews it in its pull request, and Bravos keeps its Record and Owner columns (bravos records ledger refresh, owners from CODEOWNERS). It is never enforced. From the first session the briefing counts it ("9 modules, 2 with records"), and the first edit in a session to a module it says needs a record, and has none, gets one line offering to draft one, never a block; the company principles apply either way (bravos prefs set nudge off silences it). On the Team plan, once a person has reviewed the ledger, the agent drafts records for the modules that need one in the background: a subagent runs bravos records drafts (at most 2 a run, 3 waiting for review at once, never two for one module) and bravos records draft "<module>", which starts each draft on its own branch and worktree so your checkout is never touched. A draft states only what your documents (SRC-n § Section), confirmed intent rules or people said, cited on the line; what the code does today is marked observed and kept as guidance; Not a bug is never filled from code. bravos records check holds every citation to the repository. The agent pushes nothing and asks you before opening each draft's pull request; it binds nobody until a code owner approves it, and only that branch waits. bravos prefs set drafts off stops it. bravos rules lists each rule with its status. On the Team plan the pre-PR gate holds a change that breaks an adopted enforced rule whatever the PR body says, until the code is fixed, a person approves a dated exception (bravos records except SDR-n R1, at their own terminal), or the record is changed and the new text approved; people can adopt on a page with bravos review records (Agree, Change or No per rule); bravos records gaps lists modules no record covers; and the dashboard has a Decision records view, with possible conflicts: open exposures and SAST findings in a record's paths whose kind of weakness bears on one of its rules, each with the reason (bravos records conflicts lists the same; they never change a rule's status, and a person dismisses one at their own terminal). Reading and following records is free; writing, adopting, exceptions, the gate, gaps and the view are on the Team plan.
|
|
124
124
|
|
|
125
125
|
### See which design rules hold
|
|
126
126
|
|
|
@@ -258,7 +258,7 @@ Say once whether your agent commits the files Bravos writes (annotations, intent
|
|
|
258
258
|
|
|
259
259
|
Skills: `/bravos`
|
|
260
260
|
|
|
261
|
-
Run bravos dashboard (free, no model): it writes one self-contained page under .bravos/dashboard/ (git-ignored) and opens it in your browser. It is GuardLink's threat model with who introduced and fixed each exposure and what changed since the default branch; on the Team plan, with the code graph built, a second tab shows the code graph: a map of where the risk sits, owners and history, coupling, trust, the attack surface, entry points and links. Run it again whenever you want the picture: it rebuilds from the code as it stands, rebuilding a code graph that is missing or behind first, and a saved page says when it is more than half a day old. --no-blame leaves git names out of a page you will share; --no-open only prints the path. Or ask your agent "show me the findings".
|
|
261
|
+
Run bravos dashboard (free, no model): it writes one self-contained page under .bravos/dashboard/ (git-ignored) and opens it in your browser. It is GuardLink's threat model with who introduced and fixed each exposure and what changed since the default branch; on the Team plan, with the code graph built, a second tab shows the code graph: a map of where the risk sits, owners and history, coupling, trust, the attack surface, entry points and links. Run it again whenever you want the picture: it rebuilds from the code as it stands, rebuilding a code graph that is missing or behind first, and a saved page says when it is more than half a day old. --no-blame leaves git names out of a page you will share; --no-open only prints the path. Or ask your agent "show me the findings". With a SAST run (Team plan), a SAST view lists its findings, those joined to a claim, those not in the threat model yet, dependencies and secrets (by type and place, never the value), with how many commits the run is behind; the code graph Map's Findings lens draws the same findings.
|
|
262
262
|
|
|
263
263
|
### Write up the assessment, a finding or a retest
|
|
264
264
|
|
package/docs/UPGRADING.md
CHANGED
|
@@ -2,6 +2,22 @@
|
|
|
2
2
|
|
|
3
3
|
After `npm install -g @bugb-technologies/bravos`, run **`bravos setup`** in a repository you work in: it brings this machine and that repository up to date. In repositories you work in with an agent you can skip even that: the agent runs it at the start of a session. From 1.12 on you do not have to watch for releases: Bravos tells you when a newer version is out, and after you install it the agent brings each repository up to date. The notes below say what else changes, newest first. (Before 1.9 the same was `bravos setup --tools -y` per machine and `bravos sync` per repository; both still work.)
|
|
4
4
|
|
|
5
|
+
## 1.26.0
|
|
6
|
+
|
|
7
|
+
- **`bravos sast run` works on a repository with no code graph yet.** On the first scan of a new repository, 1.25.0 asked the analyzer for `--codegraph off`, a mode it doesn't have, so the run failed with "invalid value 'off'". Now the analyzer builds the graph it needs for the run (it takes longer, and the findings say which are reached). `bravos graph build . --scip no-exec` keeps a graph current so later runs are quicker.
|
|
8
|
+
- **SAST on the dashboard (Team plan).** `bravos dashboard` has a SAST tab for the newest run:
|
|
9
|
+
- how old the run is (commits behind HEAD);
|
|
10
|
+
- the findings joined to the threat model, those not in it yet, dependencies, and secrets, reached ones first, each with whether it is reached and why.
|
|
11
|
+
|
|
12
|
+
A secret shows only its type and place, never its value; every text on the page is checked so no credential reaches the file. The code graph Map's Findings lens now draws the same findings instead of saying there are none. On Free the tab says SAST is on the Team plan; with no run yet it says to run `bravos sast run`.
|
|
13
|
+
- **Possible conflicts in the Decision records view (Team plan).** For each record, the open exposures and SAST findings in its paths whose kind of weakness bears on one of its rules, each with the reason it was matched. Before, a rule like "only admins open the revenue report" read "not placed" even with an access-control exposure right there.
|
|
14
|
+
- **Suggestions only.** They never change a rule's status and never hold a pull request.
|
|
15
|
+
- **Acting on one:** ask your agent to link it to the rule, or, if it isn't a conflict, run `bravos records conflicts dismiss <key> --reason "<why>"` at your own terminal. Dismissals are kept with your name in `.guardlink/records-dismissals.json`, never as an acceptance.
|
|
16
|
+
- **In the terminal:** `bravos records conflicts` lists the same suggestions.
|
|
17
|
+
- **Fixed:** `bravos sast candidates` and the dashboard printed claims as `##asset → ##threat`.
|
|
18
|
+
- **Plugins:** the Claude Code, Codex and Antigravity plugins read the record before an edit and show cards after one, as `bravos setup` already does in a repository. With 1.26.0, in a repository that also runs `bravos setup`, the plugin's record guard stays quiet so the record is shown once.
|
|
19
|
+
- Run `bravos setup` in each repository to refresh its installed hook copy.
|
|
20
|
+
|
|
5
21
|
## 1.25.0
|
|
6
22
|
|
|
7
23
|
- **Security decision records.** A record is one short document per module or feature, at `.guardlink/records/SDR-n-<module>.md`. It says what was decided for that code: the decision, the rules that follow, why, and what looks like a bug but is intended ("Not a bug"). Your coding agent reads it before changing that code and follows it. Ask your agent for "a security decision record for <module>", or see `bravos guide`.
|
package/hooks/cards.mjs
CHANGED
|
@@ -40,7 +40,7 @@ async function readPayload() {
|
|
|
40
40
|
}
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
-
// @comment -- "The plugin's copy stays quiet where the repository registers its own cards: its .bravos/hooks/cards.mjs, or the hook launcher (bravos hook cards). The copy the launcher runs is the repository's own, so it never defers."
|
|
43
|
+
// @comment -- "The plugin's copy stays quiet where the repository registers its own cards (Claude Code, Codex, Antigravity or Cursor settings): its .bravos/hooks/cards.mjs, or the hook launcher (bravos hook cards). The copy the launcher runs is the repository's own, so it never defers."
|
|
44
44
|
function deferToRepo(root) {
|
|
45
45
|
if (globalThis[Symbol.for('bravos.hook-launcher')] === true) return false;
|
|
46
46
|
try {
|
|
@@ -48,7 +48,7 @@ function deferToRepo(root) {
|
|
|
48
48
|
} catch {
|
|
49
49
|
/* no repository copy */
|
|
50
50
|
}
|
|
51
|
-
for (const f of ['.claude/settings.json', '.codex/hooks.json']) {
|
|
51
|
+
for (const f of ['.claude/settings.json', '.codex/hooks.json', '.agents/hooks.json', '.cursor/hooks.json']) {
|
|
52
52
|
try {
|
|
53
53
|
if (/\.bravos\/hooks\/cards\.mjs|\bbravos hook cards\b/.test(readFileSync(join(root, f), 'utf8'))) return true;
|
|
54
54
|
} catch {
|
|
@@ -72,12 +72,12 @@ async function main() {
|
|
|
72
72
|
if (top.status !== 0) throw new Error('not a repository');
|
|
73
73
|
const root = top.stdout.trim();
|
|
74
74
|
commonDir = gitCommonDir(root);
|
|
75
|
+
if (deferToRepo(root)) throw new Error('repo copy');
|
|
75
76
|
// Antigravity's PreInvocation: hand over what its after-edit hooks queued for this session, and nothing else.
|
|
76
77
|
if (process.argv.includes('--deliver')) {
|
|
77
78
|
process.stdout.write(JSON.stringify(n.harness === 'agy' ? deliverNotes(commonDir, n.sessionId) : {}) + '\n');
|
|
78
79
|
process.exit(0);
|
|
79
80
|
}
|
|
80
|
-
if (deferToRepo(root)) throw new Error('repo copy');
|
|
81
81
|
// Cursor also runs the Claude Code registration; where it has its own, that one answers.
|
|
82
82
|
if (n.viaCursor && cursorRunsOwn(root, 'cards')) throw new Error('cursor runs its own');
|
|
83
83
|
const payload = { tool_name: n.toolName, tool_input: n.toolInput, session_id: n.sessionId };
|
package/hooks/lib/agent-io.mjs
CHANGED
|
@@ -103,3 +103,16 @@ export function cursorRunsOwn(root, name) {
|
|
|
103
103
|
return false;
|
|
104
104
|
}
|
|
105
105
|
}
|
|
106
|
+
|
|
107
|
+
const OWN_SETTINGS = { claude: '.claude/settings.json', codex: '.codex/hooks.json', agy: '.agents/hooks.json', cursor: '.cursor/hooks.json' };
|
|
108
|
+
// @comment -- "Whether the repository's own settings for this agent register the record guard (bravos hook record-guard --harness <agent>, not a plugin's --plugin form). Then a plugin's copy of the registration stays quiet, so the person and the model see the record once."
|
|
109
|
+
export function repoRunsOwn(root, harness) {
|
|
110
|
+
const rel = OWN_SETTINGS[harness];
|
|
111
|
+
if (!rel) return false;
|
|
112
|
+
try {
|
|
113
|
+
const text = readFileSync(join(root, rel), 'utf8');
|
|
114
|
+
return [...text.matchAll(new RegExp(`bravos hook record-guard --harness ${harness}([^"\\n]*)`, 'g'))].some((m) => !/--plugin/.test(m[1]));
|
|
115
|
+
} catch {
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
}
|
package/hooks/lib/sast.mjs
CHANGED
|
@@ -115,7 +115,9 @@ export function sastCandidates(root, { all = false } = {}) {
|
|
|
115
115
|
export function claimLabel(cs) {
|
|
116
116
|
if (cs == null) return 'claim';
|
|
117
117
|
if (typeof cs !== 'object') return String(cs);
|
|
118
|
-
|
|
118
|
+
// The analyzer's ids may already carry their '#' (current reports do): never print it twice.
|
|
119
|
+
const id = (v) => `#${String(v).replace(/^#+/, '')}`;
|
|
120
|
+
const what = cs.asset && cs.threat ? `${id(cs.asset)} → ${id(cs.threat)}` : cs.threat ? id(cs.threat) : 'claim';
|
|
119
121
|
return cs.declared_at ? `${what} at ${cs.declared_at}` : what;
|
|
120
122
|
}
|
|
121
123
|
|
package/hooks/record-guard.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
// @comment -- "bravos record guard, the before-edit hook (Claude Code PreToolUse on Edit, Write, MultiEdit and NotebookEdit; Codex PreToolUse on apply_patch; Cursor preToolUse on Write and Delete; Antigravity PreToolUse on its file tools; opencode and omp through their plugins, which call it before an edit tool): the first edit in a session to a file an adopted security decision record covers is refused once, with the record in full, so the agent reads the team's decision before changing that code; the next attempt goes through. It is run only through the installed CLI (bravos hook record-guard), never from a repository copy. Each agent gets its own answer shape (hooks/lib/agent-io.mjs). Any error, no session id, no adopted record, or a machine without Bravos: the edit goes ahead, with nothing printed or the agent's empty answer."
|
|
1
|
+
// @comment -- "bravos record guard, the before-edit hook (Claude Code PreToolUse on Edit, Write, MultiEdit and NotebookEdit; Codex PreToolUse on apply_patch; Cursor preToolUse on Write and Delete; Antigravity PreToolUse on its file tools; opencode and omp through their plugins, which call it before an edit tool): the first edit in a session to a file an adopted security decision record covers is refused once, with the record in full, so the agent reads the team's decision before changing that code; the next attempt goes through. It is run only through the installed CLI (bravos hook record-guard), never from a repository copy. Each agent gets its own answer shape (hooks/lib/agent-io.mjs). Started with --plugin (a plugin's registration), it stays quiet where the repository registers its own guard. Any error, no session id, no adopted record, or a machine without Bravos: the edit goes ahead, with nothing printed or the agent's empty answer."
|
|
2
2
|
import { spawnSync } from 'node:child_process';
|
|
3
|
-
import { cursorRunsOwn, guardAnswer, harnessArg, normalize } from './lib/agent-io.mjs';
|
|
3
|
+
import { cursorRunsOwn, guardAnswer, harnessArg, normalize, repoRunsOwn } from './lib/agent-io.mjs';
|
|
4
4
|
import { audience } from './lib/audience.mjs';
|
|
5
5
|
import { gitCommonDir } from './lib/prefs.mjs';
|
|
6
6
|
import { guardDecision, readSession, writeSession } from './lib/record-guard.mjs';
|
|
@@ -40,6 +40,8 @@ async function main() {
|
|
|
40
40
|
if (!n.sessionId) throw new Error('no session');
|
|
41
41
|
// Cursor also runs the Claude Code registration; where it has its own, that one answers.
|
|
42
42
|
if (n.viaCursor && cursorRunsOwn(root, 'record-guard')) throw new Error('cursor runs its own');
|
|
43
|
+
// A plugin's registration stays quiet where the repository registers its own guard for this agent, so the record is shown once.
|
|
44
|
+
if (process.argv.includes('--plugin') && repoRunsOwn(root, harness)) throw new Error('the repository runs its own');
|
|
43
45
|
const commonDir = gitCommonDir(root);
|
|
44
46
|
const { refuse, state } = guardDecision({ root, toolInput: n.toolInput, state: readSession(commonDir, n.sessionId) });
|
|
45
47
|
if (refuse) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bugb-technologies/bravos",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.26.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",
|
|
@@ -17,7 +17,7 @@ A record is the standard for the code it covers. Follow an approved record exact
|
|
|
17
17
|
|
|
18
18
|
1. Before changing a file, ask which record covers it: `bravos records for <file>`. In Claude Code, Codex, Cursor, Antigravity, opencode and omp the first edit in a session to a covered file is refused once with the record in full: that is Bravos, not an error. Read the record, then make the edit again, and it goes through. Read each record it names in full (the file under `.guardlink/records/`) and follow it: every rule, and everything under "Not a bug" is intended behaviour, not a defect to fix. Only an approved record binds; for a draft, tell the person it binds nobody yet and ask how they want to proceed. A record this branch edits is a proposal: the default branch's text still binds until the pull request is approved and merged.
|
|
19
19
|
2. When what you are asked to do would break a rule, stop before editing. Tell the person which rule (its id and its words), how it was approved (`bravos records show SDR-n`), and that the change goes against it; ask whether they want to change the decision. Do not make the change on your own reading of the request.
|
|
20
|
-
3. If they still want the change and the record stays as it is, make it and record the break where it happens: an `@exposes` of the rule's threat on that code, its description starting with the rule ("SDR-3 R1 broken: sales can open the margin report, asked for by <their name>"), with `@audit` beside it. Tell them `bravos rules` now shows the rule as unguarded and that it stays open until the code is fixed or the record is changed and adopted again.
|
|
20
|
+
3. If they still want the change and the record stays as it is, make it and record the break where it happens: an `@exposes` of the rule's threat on that code, its description starting with the rule ("SDR-3 R1 broken: sales can open the margin report, asked for by <their name>"), with `@audit` beside it. Tell them `bravos rules` now shows the rule as unguarded and that it stays open until the code is fixed or the record is changed and adopted again. When asked to link a possible conflict (`bravos records conflicts`, or the dashboard's Decision records view, gives its key), read it with `bravos records conflicts --json`, check in the code that it really goes against that rule, and if it does record it the same way: an `@exposes` of the rule's threat at that place, with `@audit`, keeping the original claim as it is; if it does not, tell the person, who may dismiss it at their own terminal. Never dismiss one yourself.
|
|
21
21
|
4. Map the modules once per repository. When the briefing says there is no module ledger, offer once to map them; on a yes run `bravos records ledger propose`, check each proposed module against the code and what the person tells you (on the Team plan also ask the code graph: `codegraph_routes`, `codegraph_auth_boundary`, `codegraph_attack_surface`, and merge or split modules by feature; without the graph, say that boundaries come from folders, documents and annotations only), then `--write`, fix rows with `bravos records ledger add` or `remove`, and rewrite each Why in their words. Tell them it is a proposal a person reviews in its pull request, never enforced. When the after-edit hook says a module needs a record and has none, or no record covers security-relevant code you are changing, look for a decision already written down (`bravos context list`, `docs/`, the README, `.guardlink/intent.md`), tell the person in one line, say the company principles and the application's rules still apply, and offer to draft one. Never copy principles into a record. Carry on with their request; a missing record never blocks it.
|
|
22
22
|
5. To draft a record, gather what was decided from exactly three places and nothing else: what the person tells you in this conversation, a document that says it (`SRC-n` and the section), and rules people confirmed in `.guardlink/intent.md`. Cite each on its line: `(said by <name>)`, `(SRC-n § Section)`, `(intent: INV-n)`. When the decision is unclear, ask one question; never fill a gap with your own view of good practice. In the background (the briefing's Background drafting line, Team plan), the code is a fourth source, as observation only: run `bravos records drafts`, draft only the modules it lists, each with `bravos records draft "<module>"`, which starts its own branch and worktree (never switch the person's branch). A rule read from the code is `(observed: <file>:<line>)`, what the code does today and not a decision, so it is guidance; Not a bug stays empty unless a document, a confirmed rule or the person says it, never from code; the decision stays the team's placeholder when nobody stated one. Then `bravos records check -C <worktree>` until it passes and `bravos records ledger refresh -C <worktree>`, commit there, push nothing, and in one line ask the person whether to open each draft's pull request.
|
|
23
23
|
6. In the foreground, run `bravos records new "<module>" --paths "<glob>,<glob>"` (the code the record covers); it writes the skeleton with the next free id. Fill it in, in the person's words: the decision in two or three sentences; each rule as one sentence someone can check, marked `enforced` when a test could show it broken at a place in the code and `guidance` otherwise; why; and under "Not a bug" each behaviour that looks wrong and is the decision.
|
|
@@ -94,6 +94,19 @@ code { font: 12.5px var(--mono); background: var(--raised); border: 1px solid va
|
|
|
94
94
|
.sites .state.broken { color: var(--sev-critical); }
|
|
95
95
|
.sites .state.retest { color: var(--review); }
|
|
96
96
|
.sites .state.held { color: var(--resolved); }
|
|
97
|
+
.findings { width: 100%; border-collapse: collapse; margin: 6px 0 18px; font-size: 12.5px; background: var(--panel); border: 1px solid var(--border); border-radius: var(--radius); }
|
|
98
|
+
.findings th { text-align: left; font: 600 11px/1.2 var(--mono); text-transform: uppercase; letter-spacing: .05em; color: var(--fg-muted); padding: 8px 10px; border-bottom: 1px solid var(--border); }
|
|
99
|
+
.findings td { padding: 7px 10px; border-bottom: 1px solid var(--border); vertical-align: top; }
|
|
100
|
+
.findings tr:last-child td { border-bottom: 0; }
|
|
101
|
+
.findings .where { font-family: var(--mono); overflow-wrap: anywhere; }
|
|
102
|
+
.findings .muted, .sast-h .muted { color: var(--fg-muted); }
|
|
103
|
+
.sev { font: 600 11px/1 var(--mono); text-transform: uppercase; }
|
|
104
|
+
.sev.error, .sev.critical, .sev.high { color: var(--sev-critical); }
|
|
105
|
+
.sev.warning, .sev.medium { color: var(--sev-medium); }
|
|
106
|
+
.reach.yes { color: var(--sev-critical); font-weight: 600; }
|
|
107
|
+
.sast-h { margin: 18px 0 4px; font-size: 14px; }
|
|
108
|
+
.sites li.conflict { margin-top: 10px; padding-top: 8px; border-top: 1px dashed var(--border); }
|
|
109
|
+
.sites li.conflict:first-child { margin-top: 0; padding-top: 0; border-top: 0; }
|
|
97
110
|
</style>
|
|
98
111
|
</head>
|
|
99
112
|
<body>
|
|
@@ -110,6 +123,7 @@ code { font: 12.5px var(--mono); background: var(--raised); border: 1px solid va
|
|
|
110
123
|
<script type="application/json" id="bravos-pages-css">__BRAVOS_PAGES_CSS__</script>
|
|
111
124
|
<script type="application/json" id="bravos-pages-js">__BRAVOS_PAGES_JS__</script>
|
|
112
125
|
<script type="application/json" id="bravos-rules">__BRAVOS_RULES__</script>
|
|
126
|
+
<script type="application/json" id="bravos-sast">__BRAVOS_SAST__</script>
|
|
113
127
|
<script>
|
|
114
128
|
(() => {
|
|
115
129
|
const DATA = JSON.parse(document.getElementById('bravos-data').textContent);
|
|
@@ -120,7 +134,7 @@ code { font: 12.5px var(--mono); background: var(--raised); border: 1px solid va
|
|
|
120
134
|
return n;
|
|
121
135
|
};
|
|
122
136
|
// Commands inside a note are shown as code; everything is set as text, never as markup.
|
|
123
|
-
const COMMAND = /(bravos setup --tools -y|bravos setup --codegraph|bravos graph build \.|bravos account activate|bravos dashboard|guardlink validate \.|\/bravos-[a-z]+)/g;
|
|
137
|
+
const COMMAND = /(bravos setup --tools -y|bravos setup --codegraph|bravos graph build \.|bravos account activate|bravos sast run|bravos sast status|bravos sast candidates|bravos records conflicts(?: dismiss)?|bravos dashboard|guardlink validate \.|\/bravos-[a-z]+)/g;
|
|
124
138
|
const prose = (text) => {
|
|
125
139
|
const p = el('p');
|
|
126
140
|
String(text).split(COMMAND).forEach((part, k) => p.append(k % 2 ? el('code', {}, part) : part));
|
|
@@ -654,6 +668,136 @@ code { font: 12.5px var(--mono); background: var(--raised); border: 1px solid va
|
|
|
654
668
|
}
|
|
655
669
|
inner.append(card);
|
|
656
670
|
}
|
|
671
|
+
// @comment -- "Possible conflicts, per record: open exposures and SAST findings in the record's paths whose weakness bears on one of its rules, each with the reason it was matched and the two ways to act on it. They are suggestions for a person: drawn apart from the rule cards, they never change a rule's status. Dismissed ones are folded below, with who dismissed them and why. All text is set as text."
|
|
672
|
+
const conflicts = Array.isArray(RULES.conflicts) ? RULES.conflicts : [];
|
|
673
|
+
if (conflicts.length) {
|
|
674
|
+
inner.append(el('h3', { class: 'sast-h' }, 'Possible conflicts'));
|
|
675
|
+
inner.append(prose((RULES.conflictsNote || '') + ' Each is a suggestion for a person, matched by the kind of weakness and the record\'s paths; it never marks a rule broken or unguarded and never holds a pull request. A rule is broken only when a test got through.'));
|
|
676
|
+
const byRecord = new Map();
|
|
677
|
+
for (const c of conflicts) {
|
|
678
|
+
if (!byRecord.has(c.record)) byRecord.set(c.record, []);
|
|
679
|
+
byRecord.get(c.record).push(c);
|
|
680
|
+
}
|
|
681
|
+
for (const [record, list] of byRecord) {
|
|
682
|
+
const open = list.filter((c) => !c.dismissed);
|
|
683
|
+
const card = el('article', { class: 'rule unguarded' });
|
|
684
|
+
const head = el('div', { class: 'rule-head' });
|
|
685
|
+
head.append(el('span', { class: 'pill unguarded' }, open.length + ' possible'), el('span', { class: 'rule-id' }, record));
|
|
686
|
+
card.append(head);
|
|
687
|
+
const items = el('ul', { class: 'sites' });
|
|
688
|
+
for (const c of open) {
|
|
689
|
+
const li = el('li', { class: 'conflict' });
|
|
690
|
+
li.append(el('span', { class: 'pill' }, c.source === 'sast' ? 'SAST' : 'exposure'), el('span', { class: 'rule-id' }, c.record + ' ' + c.rule), el('span', {}, c.what), el('span', { class: 'where' }, c.file + (c.line ? ':' + c.line : '')));
|
|
691
|
+
items.append(li);
|
|
692
|
+
const why = el('li');
|
|
693
|
+
why.append(el('span', {}, 'why: ' + c.reason));
|
|
694
|
+
items.append(why);
|
|
695
|
+
const act = el('li');
|
|
696
|
+
act.append(el('span', {}, 'link it: ask your agent to "link records conflict ' + c.key + '" · not a conflict:'), el('code', {}, 'bravos records conflicts dismiss ' + c.key + ' --reason "<why>"'));
|
|
697
|
+
items.append(act);
|
|
698
|
+
}
|
|
699
|
+
card.append(items);
|
|
700
|
+
const gone = list.filter((c) => c.dismissed);
|
|
701
|
+
if (gone.length) {
|
|
702
|
+
const d = el('details');
|
|
703
|
+
d.append(el('summary', {}, gone.length + ' dismissed'));
|
|
704
|
+
const ul = el('ul', { class: 'sites' });
|
|
705
|
+
for (const c of gone) {
|
|
706
|
+
const li = el('li');
|
|
707
|
+
li.append(el('span', { class: 'rule-id' }, c.record + ' ' + c.rule), el('span', {}, c.what), el('span', { class: 'where' }, c.file + (c.line ? ':' + c.line : '')), el('span', {}, 'dismissed by ' + c.dismissed.by + ' on ' + c.dismissed.at + ': ' + c.dismissed.reason));
|
|
708
|
+
ul.append(li);
|
|
709
|
+
}
|
|
710
|
+
d.append(ul);
|
|
711
|
+
card.append(d);
|
|
712
|
+
}
|
|
713
|
+
inner.append(card);
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
wrap.append(inner);
|
|
717
|
+
section.append(wrap);
|
|
718
|
+
},
|
|
719
|
+
});
|
|
720
|
+
|
|
721
|
+
// SAST: the newest bravos-sast run, finding by finding, so a person who ran it can read it here. Bravos copies only
|
|
722
|
+
// named fields onto the page (src/dashboard-sast.ts) and withholds anything that looks like a credential; a secret is
|
|
723
|
+
// shown by its type and place, never its value. On the Free plan, or with no run yet, the view is one note.
|
|
724
|
+
// @comment -- "The SAST view: the run's age and commit, counts by class and severity, then the findings joined to a GuardLink claim, those not in the threat model yet, dependencies and secrets, reached ones first, each with severity, rule, title, file:line, whether it is reached (with the analyzer's reason) and the claim it joins; agent-configuration findings in one line. Every value is set as text, never as markup."
|
|
725
|
+
const SAST = JSON.parse(document.getElementById('bravos-sast').textContent);
|
|
726
|
+
if (SAST || (DATA.sast && DATA.sast.note)) views.push({
|
|
727
|
+
id: 'sast',
|
|
728
|
+
label: 'SAST',
|
|
729
|
+
build(section) {
|
|
730
|
+
const st = DATA.sast || {};
|
|
731
|
+
if (!SAST) {
|
|
732
|
+
section.append(note(st.state === 'locked' ? 'SAST is on the Team plan' : 'No SAST run yet', st.note || 'bravos sast run analyzes the repository; then run bravos dashboard again.'));
|
|
733
|
+
return;
|
|
734
|
+
}
|
|
735
|
+
const wrap = el('div', { class: 'rules' });
|
|
736
|
+
const inner = el('div', { class: 'rules-inner' });
|
|
737
|
+
const lead = prose(st.note || '');
|
|
738
|
+
lead.className = 'rules-lead';
|
|
739
|
+
inner.append(lead);
|
|
740
|
+
const facts = el('ul', { class: 'rule-meta' });
|
|
741
|
+
const fact = (label, value) => {
|
|
742
|
+
if (value === null || value === undefined || value === '') return;
|
|
743
|
+
const li = el('li');
|
|
744
|
+
li.append(el('b', {}, label + ' '), String(value));
|
|
745
|
+
facts.append(li);
|
|
746
|
+
};
|
|
747
|
+
fact('run', SAST.run);
|
|
748
|
+
fact('commit', SAST.sha);
|
|
749
|
+
fact('behind HEAD', SAST.staleCommits === null ? 'not known' : SAST.staleCommits + ' commit' + (SAST.staleCommits === 1 ? '' : 's'));
|
|
750
|
+
fact('analyzer', SAST.analyzer);
|
|
751
|
+
fact('code graph', SAST.graph);
|
|
752
|
+
fact('by class', Object.entries(SAST.byClass || {}).map(([k, v]) => k.replace(/_/g, ' ') + ' ' + v).join(', '));
|
|
753
|
+
fact('by severity', Object.entries(SAST.bySeverity || {}).map(([k, v]) => k + ' ' + v).join(', '));
|
|
754
|
+
if (SAST.suppressed) fact('suppressed', SAST.suppressed);
|
|
755
|
+
inner.append(facts);
|
|
756
|
+
const reachWord = (r) => (r.reachable === true ? 'reached' : r.reachable === false ? 'not reached' : 'not known');
|
|
757
|
+
const table = (title, rows, extra) => {
|
|
758
|
+
inner.append(el('h3', { class: 'sast-h' }, title + ' (' + rows.length + ')'));
|
|
759
|
+
if (!rows.length) {
|
|
760
|
+
inner.append(el('p', { class: 'muted' }, 'None in this run.'));
|
|
761
|
+
return;
|
|
762
|
+
}
|
|
763
|
+
const t = el('table', { class: 'findings' });
|
|
764
|
+
const head = el('tr');
|
|
765
|
+
for (const h of ['severity', 'finding', 'where', 'reached', extra.label]) head.append(el('th', {}, h));
|
|
766
|
+
t.append(head);
|
|
767
|
+
for (const r of rows) {
|
|
768
|
+
const tr = el('tr');
|
|
769
|
+
tr.append(el('td', { class: 'sev ' + String(r.severity || '') }, r.severity || ''));
|
|
770
|
+
const what = el('td');
|
|
771
|
+
what.append(el('div', {}, r.title || r.rule || ''), el('div', { class: 'muted' }, r.rule || ''));
|
|
772
|
+
tr.append(what);
|
|
773
|
+
const where = el('td', { class: 'where' }, (r.file || '') + (r.line ? ':' + r.line : ''));
|
|
774
|
+
if (r.function) where.append(el('div', { class: 'muted' }, r.function));
|
|
775
|
+
tr.append(where);
|
|
776
|
+
const reach = el('td');
|
|
777
|
+
reach.append(el('div', { class: 'reach ' + (r.reachable === true ? 'yes' : '') }, reachWord(r)), el('div', { class: 'muted' }, r.reach || ''));
|
|
778
|
+
tr.append(reach, el('td', {}, extra.value(r)));
|
|
779
|
+
t.append(tr);
|
|
780
|
+
}
|
|
781
|
+
inner.append(t);
|
|
782
|
+
};
|
|
783
|
+
table('Joined to the threat model', SAST.joined || [], { label: 'claim', value: (r) => r.claim || '' });
|
|
784
|
+
table('Not in the threat model yet', SAST.unjoined || [], { label: 'next', value: () => 'annotate it (/bravos-annotate)' });
|
|
785
|
+
table('Dependencies', SAST.dependencies || [], { label: 'vulnerable function', value: (r) => r.vulnerableFunction + (r.devOnly ? ' (dev only)' : '') });
|
|
786
|
+
inner.append(el('h3', { class: 'sast-h' }, 'Secrets (' + (SAST.secrets || []).length + ')'));
|
|
787
|
+
if ((SAST.secrets || []).length) {
|
|
788
|
+
inner.append(el('p', { class: 'muted' }, 'Shown by type and place only; the value never reaches this page.'));
|
|
789
|
+
const t = el('table', { class: 'findings' });
|
|
790
|
+
const head = el('tr');
|
|
791
|
+
for (const h of ['type', 'where', 'in git history', 'what to do']) head.append(el('th', {}, h));
|
|
792
|
+
t.append(head);
|
|
793
|
+
for (const s of SAST.secrets) {
|
|
794
|
+
const tr = el('tr');
|
|
795
|
+
tr.append(el('td', {}, s.type || s.rule || ''), el('td', { class: 'where' }, (s.file || '') + (s.line ? ':' + s.line : '')), el('td', {}, s.inHistory ? 'yes' : 'no'), el('td', {}, s.remediation || ''));
|
|
796
|
+
t.append(tr);
|
|
797
|
+
}
|
|
798
|
+
inner.append(t);
|
|
799
|
+
} else inner.append(el('p', { class: 'muted' }, 'None in this run.'));
|
|
800
|
+
if (SAST.agentConfig && SAST.agentConfig.count) inner.append(el('p', { class: 'muted' }, SAST.agentConfig.count + ' agent-configuration finding' + (SAST.agentConfig.count === 1 ? '' : 's') + ' (' + SAST.agentConfig.rules.join(', ') + '): bravos sast candidates --all lists them.'));
|
|
657
801
|
wrap.append(inner);
|
|
658
802
|
section.append(wrap);
|
|
659
803
|
},
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// @comment -- "For a plugin whose hooks run in the plugin's own folder (Antigravity): reads the hook payload, finds the workspace it names (workspacePaths), and runs the installed CLI there (bravos hook <name> <args>) with the same payload on stdin, printing its answer. The CLI is found on PATH, never shipped. Fail-open: no workspace, no bravos, an error, more than 8 seconds or output that is not JSON all print {}, so the edit goes ahead."
|
|
2
|
+
import { execFile } from 'node:child_process';
|
|
3
|
+
|
|
4
|
+
// @flows #records -> #hook-launcher via stdin -- "A plugin's hook payload goes to bravos hook in the workspace it names: a fixed argv (no shell), the payload on stdin only"
|
|
5
|
+
const read = async () => {
|
|
6
|
+
const chunks = [];
|
|
7
|
+
for await (const c of process.stdin) chunks.push(c);
|
|
8
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
const allow = () => {
|
|
12
|
+
process.stdout.write('{}\n');
|
|
13
|
+
process.exit(0);
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
try {
|
|
17
|
+
const raw = await Promise.race([read(), new Promise((r) => setTimeout(() => r(''), 3000).unref())]);
|
|
18
|
+
const payload = JSON.parse(raw || '{}');
|
|
19
|
+
const cwd = Array.isArray(payload?.workspacePaths) ? payload.workspacePaths.find((p) => typeof p === 'string' && p) : null;
|
|
20
|
+
if (!cwd) allow();
|
|
21
|
+
const child = execFile('bravos', ['hook', ...process.argv.slice(2)], { cwd, timeout: 8000, maxBuffer: 1024 * 1024 }, (err, stdout) => {
|
|
22
|
+
try {
|
|
23
|
+
const last = String(stdout).trim().split('\n').pop() || '{}';
|
|
24
|
+
if (err) allow();
|
|
25
|
+
JSON.parse(last);
|
|
26
|
+
process.stdout.write(`${last}\n`);
|
|
27
|
+
process.exit(0);
|
|
28
|
+
} catch {
|
|
29
|
+
allow();
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
child.on('error', allow);
|
|
33
|
+
child.stdin?.on('error', () => {});
|
|
34
|
+
child.stdin?.end(raw);
|
|
35
|
+
} catch {
|
|
36
|
+
allow();
|
|
37
|
+
}
|