@bugb-technologies/bravos 1.24.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/bin.js +12 -0
- package/dist/cli.js +222 -16
- package/dist/context.js +4 -4
- package/dist/cursor.js +24 -5
- package/dist/dashboard-sast.js +113 -0
- package/dist/dashboard.js +22 -11
- package/dist/doctor.js +29 -2
- package/dist/graphbin.js +2 -2
- package/dist/guide.js +4 -2
- package/dist/hook-launcher.js +92 -0
- package/dist/hooks.js +56 -3
- package/dist/plugin-release.js +38 -12
- package/dist/prefs.js +13 -3
- package/dist/principles.js +1 -1
- package/dist/records-conflicts.js +128 -0
- package/dist/records-drafts.js +106 -0
- package/dist/records-ledger.js +103 -0
- package/dist/records-team.js +398 -0
- package/dist/records.js +158 -0
- package/dist/review-server.js +3 -1
- package/dist/review.js +16 -1
- package/dist/rules.js +97 -4
- package/dist/setup.js +6 -6
- package/dist/uninstall.js +1 -1
- package/dist/upkeep.js +3 -0
- package/docs/GUIDE.md +11 -1
- package/docs/UPGRADING.md +56 -0
- package/hooks/cards.mjs +63 -14
- package/hooks/coach.mjs +3 -1
- package/hooks/lib/agent-io.mjs +118 -0
- package/hooks/lib/briefing.mjs +94 -3
- package/hooks/lib/cards.mjs +8 -1
- package/hooks/lib/draft-check.mjs +104 -0
- package/hooks/lib/drafts.mjs +121 -0
- package/hooks/lib/ledger.mjs +270 -0
- package/hooks/lib/pre-pr.mjs +74 -0
- package/hooks/lib/prefs.mjs +7 -3
- package/hooks/lib/record-guard.mjs +272 -0
- package/hooks/lib/records.mjs +581 -0
- package/hooks/lib/replay.mjs +2 -1
- package/hooks/lib/sast.mjs +3 -1
- package/hooks/record-guard.mjs +62 -0
- package/hooks/session-start.mjs +4 -3
- package/package.json +2 -2
- package/skills/bravos/SKILL.md +1 -0
- package/skills/bravos-records/SKILL.md +57 -0
- package/templates/dashboard/dashboard.html +198 -1
- package/templates/omp/bravos.js +85 -1
- package/templates/opencode/bravos.js +84 -1
- package/templates/plugin/workspace-hook.mjs +37 -0
- package/templates/workflows/bravos-pr-gate.yml +23 -0
|
@@ -0,0 +1,581 @@
|
|
|
1
|
+
// @comment -- "Security decision records: one Markdown document per module or feature under .guardlink/records/ (SDR-n-<module>.md), written by people, saying what was decided for that module, the rules that follow, why, and what looks like a bug but is not. A record binds agents only once a named person adopted it; each adoption (.guardlink/records-answers/<name>.json) carries the fingerprint of the text adopted, so a record changed afterwards reads as changed, not adopted. This one file holds the format, the fingerprint, the rule that turns adoptions into states, which record covers a file, and the check. It imports only the principles and context libraries beside it, so the CLI, the briefing and later the hooks and the gate all read records the same way."
|
|
2
|
+
import { spawnSync } from 'node:child_process';
|
|
3
|
+
import { readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { pathToFileURL } from 'node:url';
|
|
6
|
+
import { globMatch, oneLine, sha, treeReader, validGlob } from './principles.mjs';
|
|
7
|
+
import { an, scanPaths, scanSecrets } from './context.mjs';
|
|
8
|
+
import { draftProblems } from './draft-check.mjs';
|
|
9
|
+
|
|
10
|
+
export const RECORDS_DIR = '.guardlink/records';
|
|
11
|
+
export const ANSWERS_DIR = '.guardlink/records-answers';
|
|
12
|
+
export const ANSWERS_SCHEMA = 'bravos.review-answers/v1';
|
|
13
|
+
export const CHECK_SCHEMA = 'bravos.records-check/v1';
|
|
14
|
+
export const ID = /^SDR-[1-9][0-9]{0,3}$/;
|
|
15
|
+
export const RULE_ID = /^R[1-9][0-9]?$/;
|
|
16
|
+
export const RULE_KINDS = ['enforced', 'guidance'];
|
|
17
|
+
export const EXCEPTIONS_FILE = '.guardlink/records-exceptions.json';
|
|
18
|
+
export const EXCEPTIONS_SCHEMA = 'bravos.record-exceptions/v1';
|
|
19
|
+
export const MAX_EXCEPTION_DAYS = 365;
|
|
20
|
+
export const FILE_NAME = /^(SDR-[1-9][0-9]{0,3})(?:-[a-z0-9][a-z0-9-]{0,60})?\.md$/;
|
|
21
|
+
const MAX_RECORDS = 500;
|
|
22
|
+
const MAX_RULES = 40;
|
|
23
|
+
const MAX_PATHS = 40;
|
|
24
|
+
const DAY = /^\d{4}-\d{2}-\d{2}$/;
|
|
25
|
+
|
|
26
|
+
const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
27
|
+
const number = (id) => Number(String(id).slice(4));
|
|
28
|
+
|
|
29
|
+
// ---------------------------------------------------------------------------------------------
|
|
30
|
+
// The document
|
|
31
|
+
// ---------------------------------------------------------------------------------------------
|
|
32
|
+
|
|
33
|
+
// @comment -- "Reads the small header a record starts with: lines between two --- rows, each `key: value`; paths is a [a, b] list on one line or `- a` rows under `paths:`. Only record, module, paths and drafted (who drafted it, for a record a coding agent wrote for review) are read; anything else is named as a problem so a typo is not silently ignored. Not a YAML parser: a record's header is three plain fields."
|
|
34
|
+
function parseHeader(lines) {
|
|
35
|
+
const out = { record: '', module: '', paths: [], drafted: '', problems: [], end: 0 };
|
|
36
|
+
if (lines[0]?.trim() !== '---') {
|
|
37
|
+
out.problems.push('must start with a header between two --- lines (record, module, paths)');
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
const close = lines.findIndex((l, i) => i > 0 && l.trim() === '---');
|
|
41
|
+
if (close < 0) {
|
|
42
|
+
out.problems.push('the header is not closed with a --- line');
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
out.end = close + 1;
|
|
46
|
+
let inPaths = false;
|
|
47
|
+
for (const raw of lines.slice(1, close)) {
|
|
48
|
+
if (!raw.trim()) continue;
|
|
49
|
+
const item = /^\s+-\s+(.+)$/.exec(raw);
|
|
50
|
+
if (inPaths && item) {
|
|
51
|
+
out.paths.push(item[1].trim().replace(/^["']|["']$/g, ''));
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
inPaths = false;
|
|
55
|
+
const m = /^([a-z]+):\s*(.*)$/.exec(raw);
|
|
56
|
+
if (!m) {
|
|
57
|
+
out.problems.push(`header line not understood: "${oneLine(raw, 80)}"`);
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
const [, key, value] = m;
|
|
61
|
+
if (key === 'record') out.record = value.trim();
|
|
62
|
+
else if (key === 'module') out.module = oneLine(value.replace(/^["']|["']$/g, ''), 80);
|
|
63
|
+
else if (key === 'paths') {
|
|
64
|
+
const list = /^\[(.*)\]$/.exec(value.trim());
|
|
65
|
+
if (list) out.paths.push(...list[1].split(',').map((p) => p.trim().replace(/^["']|["']$/g, '')).filter(Boolean));
|
|
66
|
+
else if (!value.trim()) inPaths = true;
|
|
67
|
+
else out.paths.push(value.trim().replace(/^["']|["']$/g, ''));
|
|
68
|
+
} else if (key === 'drafted') out.drafted = oneLine(value, 160);
|
|
69
|
+
else out.problems.push(`header field "${key}" is not one of record, module, paths, drafted`);
|
|
70
|
+
}
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The text under each `## Heading`, by lower-cased heading. A line that is only an HTML comment (a draft's guidance for whoever fills it in) is not part of the text. */
|
|
75
|
+
function sections(lines) {
|
|
76
|
+
const out = new Map();
|
|
77
|
+
let cur = null;
|
|
78
|
+
for (const l of lines) {
|
|
79
|
+
if (/^\s*<!--.*-->\s*$/.test(l)) continue;
|
|
80
|
+
const h = /^##\s+(.+?)\s*$/.exec(l);
|
|
81
|
+
if (h) {
|
|
82
|
+
cur = h[1].toLowerCase();
|
|
83
|
+
if (!out.has(cur)) out.set(cur, []);
|
|
84
|
+
} else if (cur) out.get(cur).push(l);
|
|
85
|
+
}
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The bullets of a section, each joined with its indented continuation lines. */
|
|
90
|
+
function bullets(rows = []) {
|
|
91
|
+
const out = [];
|
|
92
|
+
for (const l of rows) {
|
|
93
|
+
const b = /^\s*[-*]\s+(.*)$/.exec(l);
|
|
94
|
+
if (b) out.push(b[1]);
|
|
95
|
+
else if (out.length && /^\s+\S/.test(l)) out[out.length - 1] += ` ${l.trim()}`;
|
|
96
|
+
}
|
|
97
|
+
return out;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// @comment -- "Parses one record. The header names the record (SDR-n), its module and the repository globs it covers; ## Decision is what was decided; ## Rules holds one bullet per rule as `R1 (enforced): text` or `R1 (guidance): text`; ## Not a bug lists what looks wrong and is intended; ## Why and ## Context are prose for people. Every field that agents are shown is cleaned to one line and cut, so nothing a record says can pose as a heading or an instruction block of its own. Problems are returned, never thrown."
|
|
101
|
+
export function parseRecord(text, file = '') {
|
|
102
|
+
const lines = String(text ?? '').replace(/\r\n?/g, '\n').split('\n');
|
|
103
|
+
const head = parseHeader(lines);
|
|
104
|
+
const problems = [...head.problems];
|
|
105
|
+
const body = lines.slice(head.end);
|
|
106
|
+
const title = oneLine((body.find((l) => /^#\s+\S/.test(l)) ?? '').replace(/^#\s+/, ''), 160);
|
|
107
|
+
const sec = sections(body);
|
|
108
|
+
const id = ID.test(head.record) ? head.record : '';
|
|
109
|
+
if (!id) problems.push(`the header needs "record: SDR-n" (got "${oneLine(head.record, 40)}")`);
|
|
110
|
+
const named = FILE_NAME.exec(file.split('/').pop() ?? '');
|
|
111
|
+
if (file && !named) problems.push('the file name must be SDR-n-<module>.md, lower case, e.g. SDR-3-reports.md');
|
|
112
|
+
else if (named && id && named[1] !== id) problems.push(`the file is named ${named[1]} but its header says ${id}`);
|
|
113
|
+
if (!head.module) problems.push('the header needs "module: <name>"');
|
|
114
|
+
const paths = [...new Set(head.paths)].slice(0, MAX_PATHS);
|
|
115
|
+
for (const p of paths) if (!validGlob(p)) problems.push(`path "${oneLine(p, 80)}" is not a repository glob (letters, digits, . _ - / * ? { } , only; no leading / and no ..)`);
|
|
116
|
+
if (!paths.length) problems.push('the header needs "paths: [<glob>, …]", the code this record covers');
|
|
117
|
+
const decision = oneLine((sec.get('decision') ?? []).join(' '), 1200);
|
|
118
|
+
if (!decision) problems.push('needs a "## Decision" section');
|
|
119
|
+
const rules = [];
|
|
120
|
+
const seen = new Set();
|
|
121
|
+
for (const b of bullets(sec.get('rules')).slice(0, MAX_RULES)) {
|
|
122
|
+
const m = /^(R[1-9][0-9]?)\s*\((enforced|guidance)\)\s*:\s*(.+)$/i.exec(b);
|
|
123
|
+
if (!m) {
|
|
124
|
+
problems.push(`rule not understood: "${oneLine(b, 80)}" (write "R1 (enforced): …" or "R1 (guidance): …")`);
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
const rule = { id: m[1].toUpperCase(), kind: m[2].toLowerCase(), text: oneLine(m[3], 600) };
|
|
128
|
+
if (seen.has(rule.id)) problems.push(`rule ${rule.id} appears twice`);
|
|
129
|
+
seen.add(rule.id);
|
|
130
|
+
rules.push(rule);
|
|
131
|
+
}
|
|
132
|
+
if (!rules.length) problems.push('needs a "## Rules" section with at least one rule');
|
|
133
|
+
return {
|
|
134
|
+
id,
|
|
135
|
+
file,
|
|
136
|
+
module: head.module,
|
|
137
|
+
drafted: head.drafted,
|
|
138
|
+
paths: paths.filter(validGlob).sort(),
|
|
139
|
+
title,
|
|
140
|
+
decision,
|
|
141
|
+
rules,
|
|
142
|
+
notABug: bullets(sec.get('not a bug')).map((b) => oneLine(b, 400)).filter(Boolean).slice(0, 20),
|
|
143
|
+
why: oneLine((sec.get('why') ?? []).join(' '), 1200),
|
|
144
|
+
problems,
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// @comment -- "A record's fingerprint: SHA-256 over its id, module, decision, rules (id, kind, text) and not-a-bug list, cleaned and in a fixed order, cut to 16 hex characters. Paths are left out on purpose and compared separately: a record that grows to cover more code is still the record people adopted, one that covers less is not. Why and Context are prose and may change freely."
|
|
149
|
+
export function fingerprint(r) {
|
|
150
|
+
return sha(JSON.stringify([String(r.id ?? ''), oneLine(r.module, 80), oneLine(r.decision, 1200), (r.rules ?? []).map((x) => [String(x.id), String(x.kind), oneLine(x.text, 600)]), (r.notABug ?? []).map((x) => oneLine(x, 400))])).slice(0, 16);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// @comment -- "Every record file in .guardlink/records/, parsed, in id order. Read through the principles reader: regular files only, inside the repository after links are resolved, at most 1 MB each, so a planted link is skipped and never followed. A second file claiming an id already taken is reported on both."
|
|
154
|
+
export function readRecords(reader) {
|
|
155
|
+
// The module ledger (README.md) lives beside the records and is not one.
|
|
156
|
+
const names = reader.list(RECORDS_DIR).filter((n) => n.endsWith('.md') && n !== 'README.md').slice(0, MAX_RECORDS);
|
|
157
|
+
const records = [];
|
|
158
|
+
for (const name of names) {
|
|
159
|
+
const file = `${RECORDS_DIR}/${name}`;
|
|
160
|
+
const text = reader.read(file);
|
|
161
|
+
if (text === null) continue;
|
|
162
|
+
records.push({ ...parseRecord(text, file), text });
|
|
163
|
+
}
|
|
164
|
+
const count = new Map();
|
|
165
|
+
for (const r of records) if (r.id) count.set(r.id, (count.get(r.id) ?? 0) + 1);
|
|
166
|
+
for (const r of records) if (r.id && count.get(r.id) > 1) r.problems.push(`${r.id} is used by more than one file`);
|
|
167
|
+
return records.sort((a, b) => (a.id && b.id ? number(a.id) - number(b.id) : a.file.localeCompare(b.file)));
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** The next free id: one past the highest in use. */
|
|
171
|
+
export const nextId = (records) => `SDR-${records.reduce((m, r) => (r.id ? Math.max(m, number(r.id)) : m), 0) + 1}`;
|
|
172
|
+
|
|
173
|
+
// ---------------------------------------------------------------------------------------------
|
|
174
|
+
// Adoptions
|
|
175
|
+
// ---------------------------------------------------------------------------------------------
|
|
176
|
+
|
|
177
|
+
/** What an adoption records about the text adopted. */
|
|
178
|
+
export function adoptedFields(r) {
|
|
179
|
+
return { hash: fingerprint(r), module: oneLine(r.module, 80), paths: [...(r.paths ?? [])].sort(), rules: (r.rules ?? []).map((x) => ({ id: x.id, kind: x.kind, text: oneLine(x.text, 600) })) };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// @comment -- "Each person's confirmed answers about records: files under .guardlink/records-answers/ in the review page's answers shape with kind records, one per person, whose answers are keyed by record id. An in-progress save never counts; a file that does not parse or is not a records answers file is named under skipped."
|
|
183
|
+
export function readAdoptionFiles(reader) {
|
|
184
|
+
const files = [];
|
|
185
|
+
const skipped = [];
|
|
186
|
+
for (const name of reader.list(ANSWERS_DIR).filter((n) => n.endsWith('.json'))) {
|
|
187
|
+
let j;
|
|
188
|
+
try {
|
|
189
|
+
j = JSON.parse(reader.read(`${ANSWERS_DIR}/${name}`) ?? '');
|
|
190
|
+
} catch {
|
|
191
|
+
skipped.push(name);
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
if (!isObject(j) || j.schema !== ANSWERS_SCHEMA || j.kind !== 'records' || !isObject(j.answers) || typeof j.by !== 'string' || !oneLine(j.by, 80)) {
|
|
195
|
+
skipped.push(name);
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
if (j.status === 'in-progress') continue;
|
|
199
|
+
files.push({ name, by: oneLine(j.by, 80), date: DAY.test(String(j.date)) ? j.date : String(j.confirmedAt ?? '').slice(0, 10), answers: j.answers });
|
|
200
|
+
}
|
|
201
|
+
return { files, skipped };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// @comment -- "What the adoptions make of one record as it reads now. Adopted: at least one named person adopted exactly this text (same fingerprint) with every path they adopted still covered, and nobody who answered it said no. Changed: people adopted it, but none of them this text, or a path they adopted was taken out; the record binds nobody until someone adopts it again. Disputed: someone adopted this text and someone else said no to it. Draft: nobody has answered. Deterministic and order-free."
|
|
205
|
+
// @mitigates #records against #forged-record using #record-fingerprint -- "A record counts as adopted only while its rules, decision and not-a-bug list hash to what a named person adopted and none of the adopted paths was removed; any other text is reported as changed and binds no agent"
|
|
206
|
+
export function recordState(record, files, ctx = null) {
|
|
207
|
+
const hash = fingerprint(record);
|
|
208
|
+
const adopters = [];
|
|
209
|
+
const stale = [];
|
|
210
|
+
const decliners = [];
|
|
211
|
+
for (const f of files) {
|
|
212
|
+
const a = f.answers[record.id];
|
|
213
|
+
if (!isObject(a)) continue;
|
|
214
|
+
if (a.verdict === 'no') {
|
|
215
|
+
decliners.push({ by: f.by, date: f.date, comment: oneLine(a.comment, 300) });
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
if (!isObject(a.adopted) || typeof a.adopted.hash !== 'string') continue;
|
|
219
|
+
const had = Array.isArray(a.adopted.paths) ? a.adopted.paths.filter((p) => typeof p === 'string') : [];
|
|
220
|
+
const narrowed = had.filter((p) => !record.paths.includes(p));
|
|
221
|
+
if (a.adopted.hash === hash && !narrowed.length) adopters.push({ by: f.by, date: f.date });
|
|
222
|
+
else stale.push({ by: f.by, date: f.date, reason: a.adopted.hash !== hash ? 'its decision, rules or not-a-bug list changed' : `${narrowed.length === 1 ? 'a path' : 'paths'} they adopted (${narrowed.slice(0, 3).join(', ')}) ${narrowed.length === 1 ? 'was' : 'were'} removed` });
|
|
223
|
+
}
|
|
224
|
+
const byName = (a, b) => a.by.localeCompare(b.by);
|
|
225
|
+
adopters.sort(byName);
|
|
226
|
+
stale.sort(byName);
|
|
227
|
+
decliners.sort(byName);
|
|
228
|
+
// @comment -- "With a default branch, the record's exact text there is its approval: the same bytes on this branch means it binds, approved by whatever review that branch requires (see approvalWords). Different text from what the default branch holds is a proposed change, which binds once it is approved there, or once a person adopts it by name (the fallback). A record the default branch does not have yet is a draft unless adopted by name. Without a default branch only typed-name adoption counts, as before."
|
|
229
|
+
if (ctx?.ref) {
|
|
230
|
+
const there = onDefault(ctx, record.file);
|
|
231
|
+
if (there !== null && normal(there) === normal(record.text)) return { state: 'adopted', hash, adopters, stale, decliners, approval: { via: 'main', ref: ctx.ref, asOf: ctx.asOf, review: ctx.review.enforced, reason: ctx.review.reason } };
|
|
232
|
+
if (adopters.length && !decliners.length) return { state: 'adopted', hash, adopters, stale, decliners, approval: { via: 'name', by: adopters.map((a) => a.by) } };
|
|
233
|
+
if (there !== null) return { state: 'proposed', hash, adopters, stale, decliners, approval: null };
|
|
234
|
+
}
|
|
235
|
+
const state = adopters.length && decliners.length ? 'disputed' : adopters.length ? 'adopted' : stale.length ? 'changed' : decliners.length ? 'declined' : 'draft';
|
|
236
|
+
return { state, hash, adopters, stale, decliners, approval: state === 'adopted' ? { via: 'name', by: adopters.map((a) => a.by) } : null };
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// ---------------------------------------------------------------------------------------------
|
|
240
|
+
// Approval on the default branch
|
|
241
|
+
// ---------------------------------------------------------------------------------------------
|
|
242
|
+
|
|
243
|
+
export const REVIEW_SCHEMA = 'bravos.records-review/v1';
|
|
244
|
+
const git = (root, args) => {
|
|
245
|
+
const r = spawnSync('git', args, { cwd: root, encoding: 'utf8', timeout: 5000, maxBuffer: 4 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
246
|
+
return r.status === 0 ? r.stdout : null;
|
|
247
|
+
};
|
|
248
|
+
const normal = (t) => String(t ?? '').replace(/\r\n?/g, '\n');
|
|
249
|
+
|
|
250
|
+
// @comment -- "The remote default branch as this clone last saw it (refs/remotes/origin/HEAD, e.g. origin/main), the time of the last fetch (FETCH_HEAD), and whether code-owner review is enforced there, read from the cache bravos records check fills with gh (never fetched here, so a hook stays fast and offline). Null when the clone has no origin default branch: then only typed-name adoption counts."
|
|
251
|
+
export function approvalContext(root) {
|
|
252
|
+
const ref = git(root, ['symbolic-ref', '--quiet', 'refs/remotes/origin/HEAD'])?.trim().replace(/^refs\/remotes\//, '');
|
|
253
|
+
if (!ref) return null;
|
|
254
|
+
const common = git(root, ['rev-parse', '--git-common-dir'])?.trim();
|
|
255
|
+
const dir = common ? (common.startsWith('/') ? common : join(root, common)) : null;
|
|
256
|
+
let asOf = null;
|
|
257
|
+
let review = { enforced: null, reason: 'not checked: bravos records check asks GitHub with gh when it is signed in', checkedAt: null };
|
|
258
|
+
if (dir) {
|
|
259
|
+
try {
|
|
260
|
+
asOf = statSync(join(dir, 'FETCH_HEAD')).mtime.toISOString();
|
|
261
|
+
} catch {
|
|
262
|
+
/* never fetched: the default branch is as the clone made it */
|
|
263
|
+
}
|
|
264
|
+
try {
|
|
265
|
+
const j = JSON.parse(readFileSync(join(dir, 'bravos', 'records-review.json'), 'utf8'));
|
|
266
|
+
if (j?.schema === REVIEW_SCHEMA && j.branch === ref && (j.enforced === true || j.enforced === false || j.enforced === null)) review = { enforced: j.enforced, reason: oneLine(j.reason, 300), checkedAt: typeof j.checkedAt === 'string' ? j.checkedAt : null };
|
|
267
|
+
} catch {
|
|
268
|
+
/* not checked yet */
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
return { root, ref, asOf, review };
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** A file as the default branch holds it, or null when it is not there. */
|
|
275
|
+
export const onDefault = (ctx, file) => (ctx ? git(ctx.root, ['show', `${ctx.ref}:${file}`]) : null);
|
|
276
|
+
|
|
277
|
+
/** How strong an approval on the default branch is, in words: what it proves and what it does not. */
|
|
278
|
+
export function approvalWords(a) {
|
|
279
|
+
if (!a) return '';
|
|
280
|
+
if (a.via === 'name') return `adopted by name (${a.by.join(', ')}), not verified: a typed name proves only that someone with write access said so`;
|
|
281
|
+
const where = `on ${a.ref}${a.asOf ? ` as of the last fetch (${a.asOf.slice(0, 10)})` : ''}`;
|
|
282
|
+
if (a.review === true) return `approved: ${where}, and ${a.ref} requires a code owner's review for it`;
|
|
283
|
+
if (a.review === false) return `${where}, review not enforced: nothing required a code owner to approve it`;
|
|
284
|
+
return `${where}; whether ${a.ref} requires a code owner's review is not known yet (bravos records check finds out with gh)`;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// ---------------------------------------------------------------------------------------------
|
|
288
|
+
// Which record covers a file
|
|
289
|
+
// ---------------------------------------------------------------------------------------------
|
|
290
|
+
|
|
291
|
+
/** The records whose paths cover a repository file. */
|
|
292
|
+
export const recordsForFile = (records, file) => records.filter((r) => r.paths.some((g) => globMatch(g, file)));
|
|
293
|
+
|
|
294
|
+
// ---------------------------------------------------------------------------------------------
|
|
295
|
+
// Which rule a threat stands for
|
|
296
|
+
// ---------------------------------------------------------------------------------------------
|
|
297
|
+
|
|
298
|
+
// @comment -- "The record rule a threat stands for: the threat carries the reference record:SDR-n of a record given here, and its description starts with that rule ('SDR-3 R1: …'); a threat that names no rule stands for the record's only enforced rule when it has exactly one. The gate reads this from GuardLink's model, the edit hooks from the definitions file; both decide the same way."
|
|
299
|
+
export function ruleOfThreat(threat, records) {
|
|
300
|
+
const refs = (Array.isArray(threat?.refs) ? threat.refs : []).map(String);
|
|
301
|
+
const ref = refs.map((r) => /^record:(SDR-[1-9][0-9]{0,3})$/i.exec(r)?.[1]?.toUpperCase()).find(Boolean);
|
|
302
|
+
const record = ref ? records.find((r) => r.id === ref) : null;
|
|
303
|
+
if (!record) return null;
|
|
304
|
+
const said = /^\s*(SDR-[1-9][0-9]{0,3})\s+(R[1-9][0-9]?)\b/i.exec(String(threat.description ?? ''));
|
|
305
|
+
const enforced = record.rules.filter((x) => x.kind === 'enforced');
|
|
306
|
+
const rule = said && said[1].toUpperCase() === ref ? record.rules.find((x) => x.id === said[2].toUpperCase()) : enforced.length === 1 ? enforced[0] : null;
|
|
307
|
+
return rule ? { record, rule } : null;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// ---------------------------------------------------------------------------------------------
|
|
311
|
+
// Exceptions a person approved
|
|
312
|
+
// ---------------------------------------------------------------------------------------------
|
|
313
|
+
|
|
314
|
+
const today = (now) => now.toISOString().slice(0, 10);
|
|
315
|
+
|
|
316
|
+
// @comment -- "An exception's fingerprint: SHA-256 over the record, the rule, the area, the reason, who approved it, when, and until when, cut to 16 hex characters, so a hand edit to any of them shows."
|
|
317
|
+
export function exceptionFingerprint(e) {
|
|
318
|
+
return sha(JSON.stringify([String(e.record ?? ''), String(e.rule ?? ''), String(e.where ?? ''), oneLine(e.reason, 400), oneLine(e.by, 80), String(e.approved ?? ''), String(e.until ?? '')])).slice(0, 16);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// @comment -- "Reads and validates the record exceptions file: each exception names a record and one of its rules, an area (a repository glob), a reason, the person who approved it, the day they did and the day it ends (at most a year later), and carries its fingerprint. Problems are returned, never thrown."
|
|
322
|
+
export function readRecordExceptions(reader) {
|
|
323
|
+
const text = reader.read(EXCEPTIONS_FILE);
|
|
324
|
+
if (text === null) return { exceptions: [], problems: [] };
|
|
325
|
+
let j;
|
|
326
|
+
try {
|
|
327
|
+
j = JSON.parse(text);
|
|
328
|
+
} catch {
|
|
329
|
+
return { exceptions: [], problems: [`${EXCEPTIONS_FILE} is not valid JSON`] };
|
|
330
|
+
}
|
|
331
|
+
if (!isObject(j) || j.schema !== EXCEPTIONS_SCHEMA || !Array.isArray(j.exceptions)) return { exceptions: [], problems: [`${EXCEPTIONS_FILE} must use schema ${EXCEPTIONS_SCHEMA} with an exceptions list`] };
|
|
332
|
+
const exceptions = [];
|
|
333
|
+
const problems = [];
|
|
334
|
+
for (const [n, e] of j.exceptions.slice(0, 500).entries()) {
|
|
335
|
+
const at = `${EXCEPTIONS_FILE} exception ${n + 1}`;
|
|
336
|
+
if (!isObject(e) || !ID.test(String(e.record)) || !RULE_ID.test(String(e.rule)) || !validGlob(e.where) || !oneLine(e.reason, 400) || !oneLine(e.by, 80) || !DAY.test(String(e.approved)) || !DAY.test(String(e.until))) {
|
|
337
|
+
problems.push(`${at} needs a record id, a rule id, an area, a reason, who approved it, the day approved and the day it ends`);
|
|
338
|
+
continue;
|
|
339
|
+
}
|
|
340
|
+
const x = { record: e.record, rule: e.rule, where: e.where, reason: oneLine(e.reason, 400), by: oneLine(e.by, 80), approved: e.approved, until: e.until, hash: String(e.hash ?? '') };
|
|
341
|
+
if (exceptionFingerprint(x) !== x.hash) problems.push(`${at} (${x.record} ${x.rule} in ${x.where}) was changed by hand: its fingerprint no longer matches`);
|
|
342
|
+
const span = (Date.parse(`${x.until}T00:00:00Z`) - Date.parse(`${x.approved}T00:00:00Z`)) / 86400000;
|
|
343
|
+
if (!(span >= 0 && span <= MAX_EXCEPTION_DAYS)) problems.push(`${at} (${x.record} ${x.rule} in ${x.where}) runs ${Math.round(span)} days; an exception ends within ${MAX_EXCEPTION_DAYS} days of its approval`);
|
|
344
|
+
exceptions.push(x);
|
|
345
|
+
}
|
|
346
|
+
return { exceptions, problems };
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** Whether an exception is still in force on `now`: it ends at the end of its last day. */
|
|
350
|
+
export const liveException = (e, now = new Date()) => e.until >= today(now);
|
|
351
|
+
|
|
352
|
+
// @comment -- "The live exception that covers one place for one record rule, or null. An ended one covers nothing: the gate holds again the day after it ends."
|
|
353
|
+
export function recordExceptionFor(exceptions, record, rule, file, now = new Date()) {
|
|
354
|
+
return exceptions.find((e) => e.record === record && e.rule === rule && liveException(e, now) && globMatch(e.where, file)) ?? null;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
// ---------------------------------------------------------------------------------------------
|
|
358
|
+
// The check
|
|
359
|
+
// ---------------------------------------------------------------------------------------------
|
|
360
|
+
|
|
361
|
+
// @comment -- "The check that every record is well formed and that what binds agents is what was approved: the text on the default branch (opts.root gives the clone to read it from), or, as the weaker fallback, what named people adopted. A record this branch edits is noted as a proposed change, never a failure. It fails on a record that does not parse, an id used twice, a record changed after its adoption (until someone adopts the new text or the old text is restored), a disputed record, an answers file that cannot be read, and a record carrying a secret or a local path (the same scans the design-document store runs, since a record is committed and read by every agent). A draft nobody has adopted is not a failure: it is listed as a draft and binds nobody. With `files` (the repository's tracked files) it also notes a path that matches nothing. Never throws."
|
|
362
|
+
export function checkRecords(reader, opts = {}) {
|
|
363
|
+
// With the repository root, a record's approval is read from the default branch (approvalContext); without it, from typed-name adoptions only.
|
|
364
|
+
const ctx = opts.approval ?? (opts.root ? approvalContext(opts.root) : null);
|
|
365
|
+
const parsed = readRecords(reader);
|
|
366
|
+
const { files, skipped } = readAdoptionFiles(reader);
|
|
367
|
+
const problems = [];
|
|
368
|
+
const notes = [];
|
|
369
|
+
for (const name of skipped) problems.push(`${ANSWERS_DIR}/${name} is not a records answers file bravos wrote; remove it or restore it`);
|
|
370
|
+
const records = [];
|
|
371
|
+
for (const r of parsed) {
|
|
372
|
+
const where = r.file;
|
|
373
|
+
for (const p of r.problems) problems.push(`${where}: ${p}`);
|
|
374
|
+
for (const f of scanSecrets(r.text).slice(0, 5)) problems.push(`${where}:${f.line} looks like it holds ${an(f.rule)}; a record is committed and read by every agent, so take it out`);
|
|
375
|
+
for (const f of scanPaths(r.text, opts.who).slice(0, 5)) problems.push(`${where}:${f.line} names a local path (${f.rule}); write a repository path instead`);
|
|
376
|
+
if (!r.id || r.problems.length) continue;
|
|
377
|
+
const s = recordState({ ...r, text: r.text }, files, ctx);
|
|
378
|
+
// A drafted record is checked for its sources until it is approved; after that the team's words stand.
|
|
379
|
+
if (r.drafted && s.state !== 'adopted') {
|
|
380
|
+
const d = draftProblems(r, reader);
|
|
381
|
+
problems.push(...d.problems);
|
|
382
|
+
notes.push(...d.notes);
|
|
383
|
+
}
|
|
384
|
+
const row = { id: r.id, file: r.file, module: r.module, title: r.title, paths: r.paths, decision: r.decision, rules: r.rules, notABug: r.notABug, why: r.why, ...s };
|
|
385
|
+
records.push(row);
|
|
386
|
+
const names = (xs) => xs.map((x) => x.by).join(', ');
|
|
387
|
+
if (s.state === 'changed') problems.push(`${r.id} (${where}) was changed after ${names(s.stale)} adopted it: ${s.stale[0].reason}. It binds nobody until a person adopts this text (bravos records adopt ${r.id}, at their own terminal) or the adopted text is restored`);
|
|
388
|
+
else if (s.state === 'disputed') problems.push(`${r.id} (${where}) is adopted by ${names(s.adopters)} and declined by ${names(s.decliners)}; they need to settle it`);
|
|
389
|
+
else if (s.state === 'proposed') notes.push(`${r.id} (${where}) differs from ${ctx.ref}: a proposed change that binds once approved there (a code owner's review of its pull request) or adopted by name (bravos review records); until then ${ctx.ref}'s text is the approved one`);
|
|
390
|
+
else if (s.state === 'draft' && ctx?.ref) notes.push(`${r.id} (${where}) is a draft: it is not on ${ctx.ref} yet, so it binds nobody. It is approved when its pull request is reviewed and merges there; the weaker fallback is a person adopting it by name (bravos records adopt ${r.id}, at their own terminal)`);
|
|
391
|
+
else if (s.state === 'draft') notes.push(`${r.id} (${where}) is a draft: nobody has adopted it, so it binds nobody yet (bravos records adopt ${r.id}, at a person's own terminal)`);
|
|
392
|
+
else if (s.state === 'declined') notes.push(`${r.id} (${where}) was declined by ${names(s.decliners)}`);
|
|
393
|
+
if (Array.isArray(opts.files)) for (const g of r.paths) if (!opts.files.some((f) => globMatch(g, f))) notes.push(`${r.id}: path ${g} matches no file in the repository; if the code moved, add its new place`);
|
|
394
|
+
}
|
|
395
|
+
// Exceptions people approved: well formed, for an adopted record's enforced rule; an ended one is only noted.
|
|
396
|
+
const ex = readRecordExceptions(reader);
|
|
397
|
+
problems.push(...ex.problems);
|
|
398
|
+
for (const e of ex.exceptions) {
|
|
399
|
+
const r = records.find((x) => x.id === e.record);
|
|
400
|
+
if (!r || !r.rules.some((x) => x.id === e.rule && x.kind === 'enforced')) problems.push(`${EXCEPTIONS_FILE}: the exception for ${e.record} ${e.rule} in ${e.where} names no enforced rule of a record here`);
|
|
401
|
+
else if (!liveException(e, opts.now ?? new Date())) notes.push(`the exception for ${e.record} ${e.rule} in ${e.where} ended on ${e.until}; bravos records except --clear-expired removes it`);
|
|
402
|
+
}
|
|
403
|
+
// An exception the default branch already holds went through that branch's review; one only on this branch, or without a default branch, rests on a typed name.
|
|
404
|
+
const mainEx = ctx ? onDefault(ctx, EXCEPTIONS_FILE) ?? '' : '';
|
|
405
|
+
for (const e of ex.exceptions) e.approval = ctx && e.hash && mainEx.includes(e.hash) ? { via: 'main', ref: ctx.ref, review: ctx.review.enforced } : { via: 'name', by: [e.by] };
|
|
406
|
+
return { schema: CHECK_SCHEMA, exists: parsed.length > 0, ok: problems.length === 0, records, adopted: records.filter((r) => r.state === 'adopted'), exceptions: ex.exceptions, problems, notes, approval: ctx ? { ref: ctx.ref, asOf: ctx.asOf, review: ctx.review } : null };
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// @comment -- "The check as lines for a terminal or a CI log: each record with its state, then the notes, then each problem."
|
|
410
|
+
export function formatCheck(result) {
|
|
411
|
+
if (!result.exists) return ['records: none here (.guardlink/records/ is empty). Ask your agent to draft one for a module: "write a security decision record for <module>" (bravos-records).'];
|
|
412
|
+
const state = (r) => (r.state === 'adopted' ? approvalWords(r.approval) || `adopted by ${r.adopters.map((a) => a.by).join(', ')}` : r.state === 'proposed' ? 'proposed change, binds once approved' : r.state);
|
|
413
|
+
const lines = result.records.map((r) => `${r.id} ${r.module} ${state(r)} ${r.rules.length} rule${r.rules.length === 1 ? '' : 's'} (${r.paths.join(', ')})`);
|
|
414
|
+
for (const n of result.notes) lines.push(`note: ${n}`);
|
|
415
|
+
if (result.ok) return [...lines, 'records check passed'];
|
|
416
|
+
return [...lines, ...result.problems.map((p) => `✗ ${p}`), `records check failed: ${result.problems.length} problem${result.problems.length === 1 ? '' : 's'}`];
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// @comment -- "The adopted records as the working tree holds them, for the briefing and (later) the hooks and the gate: only records that parse and whose text is what a named person adopted. An empty list when there are none or anything cannot be read. Never throws."
|
|
420
|
+
export function adoptedRecords(root) {
|
|
421
|
+
try {
|
|
422
|
+
return checkRecords(treeReader(root), { root }).adopted;
|
|
423
|
+
} catch {
|
|
424
|
+
return [];
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/** Every record with its state, for the briefing's count of drafts. Never throws. */
|
|
429
|
+
export function allRecords(root) {
|
|
430
|
+
try {
|
|
431
|
+
return checkRecords(treeReader(root), { root }).records;
|
|
432
|
+
} catch {
|
|
433
|
+
return [];
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// ---------------------------------------------------------------------------------------------
|
|
438
|
+
// CODEOWNERS, and the review check CI runs with GITHUB_TOKEN
|
|
439
|
+
// ---------------------------------------------------------------------------------------------
|
|
440
|
+
|
|
441
|
+
export const CODEOWNERS_PLACES = ['.github/CODEOWNERS', 'CODEOWNERS', 'docs/CODEOWNERS'];
|
|
442
|
+
|
|
443
|
+
// @comment -- "Reads the repository's CODEOWNERS (the first of .github/, the root and docs/ that exists, as GitHub does) into its rules: a pattern and its owners per line, comments and blank lines skipped. Patterns become repository globs the way GitHub reads them: a leading / anchors at the root, a trailing / means everything under it, a pattern with no / matches at any depth."
|
|
444
|
+
export function readCodeowners(reader) {
|
|
445
|
+
for (const place of CODEOWNERS_PLACES) {
|
|
446
|
+
const text = reader.read(place);
|
|
447
|
+
if (text === null) continue;
|
|
448
|
+
const rules = [];
|
|
449
|
+
for (const raw of text.split(/\r?\n/).slice(0, 2000)) {
|
|
450
|
+
const line = raw.replace(/(^|\s)#.*$/, '').trim();
|
|
451
|
+
if (!line) continue;
|
|
452
|
+
const [pattern, ...owners] = line.split(/\s+/);
|
|
453
|
+
let g = pattern.replace(/^\//, '');
|
|
454
|
+
if (g.endsWith('/')) g += '**';
|
|
455
|
+
else if (!pattern.includes('/') || (!pattern.startsWith('/') && !pattern.slice(0, -1).includes('/'))) g = `**/${g}`;
|
|
456
|
+
if (!g.includes('*') && !g.endsWith('**')) rules.push({ pattern, globs: [g, `${g}/**`], owners });
|
|
457
|
+
else rules.push({ pattern, globs: [g], owners });
|
|
458
|
+
}
|
|
459
|
+
return { file: place, rules };
|
|
460
|
+
}
|
|
461
|
+
return null;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/** The owners of a file: the last CODEOWNERS rule that matches wins, as on GitHub. */
|
|
465
|
+
export function ownersFor(codeowners, file) {
|
|
466
|
+
let owners = [];
|
|
467
|
+
for (const r of codeowners?.rules ?? []) if (r.globs.some((g) => globMatch(g, file))) owners = r.owners;
|
|
468
|
+
return owners.filter((o) => /^@[\w.-]+(?:\/[\w.-]+)?$/.test(o));
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
// @comment -- "The review check for CI (node .bravos/hooks/lib/records.mjs verify-github, or bravos hook records verify-github), run with the job's own GITHUB_TOKEN against GITHUB_API_URL: for each record this pull request changes, whether a CODEOWNERS owner approved the pull request; for each other record, whether the pull request that last changed it on the base branch was approved by one. A user owner is matched by login; a team owner is asked of the API, and where the token may not read the team that is said, not guessed. It reports and never fails the job: GitHub's own branch protection is what makes a pull request wait. Network access is the GitHub API only, with the token in a header, never in a URL or a log."
|
|
472
|
+
// @flows #records -> GitHub.API via HTTPS -- "verify-github reads pull requests, reviews, commits and team memberships with the job's GITHUB_TOKEN"
|
|
473
|
+
export async function verifyGithub({ root, env = process.env, fetch: f = globalThis.fetch, changed = null } = {}) {
|
|
474
|
+
const repo = String(env.GITHUB_REPOSITORY ?? '');
|
|
475
|
+
const token = String(env.GITHUB_TOKEN ?? '');
|
|
476
|
+
const api = String(env.GITHUB_API_URL || 'https://api.github.com').replace(/\/$/, '');
|
|
477
|
+
if (!/^[\w.-]+\/[\w.-]+$/.test(repo) || !token) return { ok: false, lines: ['records verify-github: needs GITHUB_REPOSITORY and GITHUB_TOKEN (a GitHub Actions job sets both); nothing checked'], records: [] };
|
|
478
|
+
const get = async (path) => {
|
|
479
|
+
const r = await f(`${api}${path}`, { headers: { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json', 'User-Agent': 'bravos-records' } });
|
|
480
|
+
return { status: r.status, json: r.status === 200 ? await r.json() : null };
|
|
481
|
+
};
|
|
482
|
+
const reader = treeReader(root);
|
|
483
|
+
const records = readRecords(reader).filter((r) => r.id && !r.problems.length);
|
|
484
|
+
const codeowners = readCodeowners(reader);
|
|
485
|
+
let pr = null;
|
|
486
|
+
try {
|
|
487
|
+
const ev = JSON.parse(readFileSync(String(env.GITHUB_EVENT_PATH ?? ''), 'utf8'));
|
|
488
|
+
if (Number.isInteger(ev?.pull_request?.number)) pr = ev.pull_request.number;
|
|
489
|
+
} catch {
|
|
490
|
+
pr = null;
|
|
491
|
+
}
|
|
492
|
+
const base = String(env.GITHUB_BASE_REF || 'main');
|
|
493
|
+
const teamCache = new Map();
|
|
494
|
+
const isOwner = async (login, owners) => {
|
|
495
|
+
for (const o of owners) {
|
|
496
|
+
const [org, team] = o.slice(1).split('/');
|
|
497
|
+
if (!team) {
|
|
498
|
+
if (org.toLowerCase() === login.toLowerCase()) return 'yes';
|
|
499
|
+
continue;
|
|
500
|
+
}
|
|
501
|
+
const key = `${o}|${login}`;
|
|
502
|
+
if (!teamCache.has(key)) {
|
|
503
|
+
const m = await get(`/orgs/${encodeURIComponent(org)}/teams/${encodeURIComponent(team)}/memberships/${encodeURIComponent(login)}`);
|
|
504
|
+
teamCache.set(key, m.status === 200 && m.json?.state === 'active' ? 'yes' : m.status === 404 ? 'no' : 'unknown');
|
|
505
|
+
}
|
|
506
|
+
if (teamCache.get(key) === 'yes') return 'yes';
|
|
507
|
+
if (teamCache.get(key) === 'unknown') return 'unknown';
|
|
508
|
+
}
|
|
509
|
+
return 'no';
|
|
510
|
+
};
|
|
511
|
+
const approvers = async (number) => {
|
|
512
|
+
const r = await get(`/repos/${repo}/pulls/${number}/reviews?per_page=100`);
|
|
513
|
+
if (r.status !== 200 || !Array.isArray(r.json)) return null;
|
|
514
|
+
const last = new Map();
|
|
515
|
+
for (const v of r.json) if (v?.user?.login && v.state !== 'COMMENTED') last.set(v.user.login, v.state);
|
|
516
|
+
return [...last.entries()].filter(([, s]) => s === 'APPROVED').map(([l]) => l);
|
|
517
|
+
};
|
|
518
|
+
const judge = async (owners, number) => {
|
|
519
|
+
if (!owners.length) return { verdict: 'no-owner', text: `no CODEOWNERS line names an owner for it` };
|
|
520
|
+
const who = await approvers(number);
|
|
521
|
+
if (who === null) return { verdict: 'unknown', text: `#${number}'s reviews could not be read with this token` };
|
|
522
|
+
let unknown = false;
|
|
523
|
+
for (const login of who) {
|
|
524
|
+
const o = await isOwner(login, owners);
|
|
525
|
+
if (o === 'yes') return { verdict: 'approved', text: `#${number} approved by @${login}, a code owner (${owners.join(' ')})` };
|
|
526
|
+
if (o === 'unknown') unknown = true;
|
|
527
|
+
}
|
|
528
|
+
return unknown ? { verdict: 'unknown', text: `#${number} approved by ${who.map((l) => `@${l}`).join(', ')}; whether they belong to ${owners.join(' ')} could not be read with this token` } : { verdict: 'missing', text: `#${number} has no approval from a code owner (${owners.join(' ')})` };
|
|
529
|
+
};
|
|
530
|
+
const out = [];
|
|
531
|
+
for (const r of records) {
|
|
532
|
+
const owners = ownersFor(codeowners, r.file);
|
|
533
|
+
if (pr !== null && (changed ? changed.includes(r.file) : false)) {
|
|
534
|
+
out.push({ id: r.id, file: r.file, scope: 'this pull request', ...(await judge(owners, pr)) });
|
|
535
|
+
continue;
|
|
536
|
+
}
|
|
537
|
+
const c = await get(`/repos/${repo}/commits?path=${encodeURIComponent(r.file)}&sha=${encodeURIComponent(base)}&per_page=1`);
|
|
538
|
+
const sha = Array.isArray(c.json) ? c.json[0]?.sha : null;
|
|
539
|
+
if (!sha) {
|
|
540
|
+
out.push({ id: r.id, file: r.file, scope: base, verdict: 'unknown', text: `its history on ${base} could not be read` });
|
|
541
|
+
continue;
|
|
542
|
+
}
|
|
543
|
+
const p = await get(`/repos/${repo}/commits/${sha}/pulls`);
|
|
544
|
+
const merged = Array.isArray(p.json) ? p.json.find((x) => x?.merged_at && Number.isInteger(x.number)) : null;
|
|
545
|
+
if (!merged) out.push({ id: r.id, file: r.file, scope: base, verdict: 'missing', text: `its last change on ${base} (${sha.slice(0, 7)}) came without a merged pull request` });
|
|
546
|
+
else out.push({ id: r.id, file: r.file, scope: base, ...(await judge(owners, merged.number)) });
|
|
547
|
+
}
|
|
548
|
+
const lines = out.length ? out.map((x) => `${x.verdict === 'approved' ? '✓' : x.verdict === 'unknown' ? '?' : '✗'} ${x.id} (${x.scope}): ${x.text}`) : ['records verify-github: no records here'];
|
|
549
|
+
return { ok: out.every((x) => x.verdict === 'approved'), lines, records: out };
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
// @comment -- "The command-line entry for CI: verify-github prints one line per record and, in GitHub Actions, the same as a step summary and a warning per record no code owner approved. It always exits 0 unless used wrongly: it reports, and branch protection is what holds a pull request."
|
|
553
|
+
const isMain = (() => {
|
|
554
|
+
try {
|
|
555
|
+
return !!process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href;
|
|
556
|
+
} catch {
|
|
557
|
+
return false;
|
|
558
|
+
}
|
|
559
|
+
})();
|
|
560
|
+
|
|
561
|
+
if (isMain) {
|
|
562
|
+
const [cmd] = process.argv.slice(2);
|
|
563
|
+
if (cmd !== 'verify-github') {
|
|
564
|
+
process.stderr.write('usage: node .bravos/hooks/lib/records.mjs verify-github\n');
|
|
565
|
+
process.exit(2);
|
|
566
|
+
}
|
|
567
|
+
const root = git(process.cwd(), ['rev-parse', '--show-toplevel'])?.trim() || process.cwd();
|
|
568
|
+
const base = process.env.GITHUB_BASE_REF;
|
|
569
|
+
const changed = base ? (git(root, ['diff', '--name-only', `origin/${base}...HEAD`]) ?? '').split('\n').map((l) => l.trim()).filter(Boolean) : [];
|
|
570
|
+
const r = await verifyGithub({ root, changed });
|
|
571
|
+
process.stdout.write(r.lines.join('\n') + '\n');
|
|
572
|
+
for (const x of r.records) if (x.verdict !== 'approved') process.stdout.write(`::warning file=${x.file}::${x.id}: ${x.text}\n`);
|
|
573
|
+
if (process.env.GITHUB_STEP_SUMMARY) {
|
|
574
|
+
try {
|
|
575
|
+
writeFileSync(process.env.GITHUB_STEP_SUMMARY, ['### Security decision records', '', ...r.lines.map((l) => `- ${l}`), ''].join('\n'), { flag: 'a' });
|
|
576
|
+
} catch {
|
|
577
|
+
/* no summary */
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
process.exit(0);
|
|
581
|
+
}
|
package/hooks/lib/replay.mjs
CHANGED
|
@@ -715,6 +715,7 @@ async function main() {
|
|
|
715
715
|
throw new Error('Use preflight <run|run-once> <kit.js>, preflight scheduled, check-port <url>, build <url>, bind <kit.js>, run <kit.js>, run-once <kit.js>, or scheduled.');
|
|
716
716
|
}
|
|
717
717
|
|
|
718
|
-
|
|
718
|
+
// Real paths on both sides, as the other entry scripts compare: run through a linked folder (a symlinked checkout, macOS /var) it still runs.
|
|
719
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {
|
|
719
720
|
try { await main(); } catch (err) { console.error(`Bravos replay: ${err.message}`); process.exitCode = 1; }
|
|
720
721
|
}
|
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
|
|