@bugb-technologies/bravos 1.18.0 → 1.22.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/account.js +19 -2
- package/dist/cli.js +133 -15
- package/dist/context.js +126 -3
- package/dist/cursor.js +4 -2
- package/dist/dashboard.js +9 -0
- package/dist/device.js +3 -1
- package/dist/doctor.js +4 -0
- package/dist/guide.js +7 -3
- package/dist/help.js +15 -8
- package/dist/instruction-blocks.js +257 -0
- package/dist/principles.js +279 -0
- package/dist/review-server.js +19 -4
- package/dist/review-wait.js +11 -0
- package/dist/review.js +342 -41
- package/dist/rules.js +82 -6
- package/dist/uninstall.js +9 -2
- package/docs/GUIDE.md +18 -2
- package/docs/UPGRADING.md +63 -0
- package/hooks/autopilot.mjs +2 -1
- package/hooks/cards.mjs +23 -5
- package/hooks/coach.mjs +3 -0
- package/hooks/invite.mjs +10 -0
- package/hooks/lib/audience.mjs +83 -0
- package/hooks/lib/briefing.mjs +83 -2
- package/hooks/lib/context.mjs +57 -1
- package/hooks/lib/display.mjs +11 -0
- package/hooks/lib/licence.mjs +2 -1
- package/hooks/lib/machine.mjs +77 -0
- package/hooks/lib/pre-pr.mjs +82 -1
- package/hooks/lib/principles.mjs +513 -0
- package/hooks/lib/refresh.mjs +11 -1
- package/hooks/lib/replay.mjs +218 -100
- package/hooks/pre-pr.mjs +3 -0
- package/hooks/session-start.mjs +35 -7
- package/package.json +1 -1
- package/skills/bravos/SKILL.md +1 -0
- package/skills/bravos-context/SKILL.md +4 -4
- package/skills/bravos-principles/SKILL.md +52 -0
- package/templates/dashboard/dashboard.html +75 -1
- package/templates/omp/bravos.js +10 -1
- package/templates/opencode/bravos.js +11 -2
- package/templates/review/review.html +140 -11
- package/templates/workflows/bravos-nightly-claude.yml +1 -1
- package/templates/workflows/bravos-nightly-codex.yml +1 -1
- package/templates/workflows/bravos-pr-gate.yml +1 -1
|
@@ -0,0 +1,513 @@
|
|
|
1
|
+
// @comment -- "A company's security design principles, kept in the repository: .guardlink/principles.md (written by bravos, never by hand), the adoptions behind it (.guardlink/principles-answers/<name>.json, each person's confirmed answers from the review page), and the exceptions people approved (.guardlink/principles-exceptions.json). This one file holds the format, the fingerprints, the rule that turns answers into adopted principles, and the check that the file still says only what named people adopted. It imports nothing of bravos's own, so the CLI, the pre-push hook, the pre-PR gate and a CI step all run the same check."
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { execFileSync } from 'node:child_process';
|
|
4
|
+
import { lstatSync, readdirSync, readFileSync, realpathSync } from 'node:fs';
|
|
5
|
+
import { join, resolve, sep } from 'node:path';
|
|
6
|
+
import { pathToFileURL } from 'node:url';
|
|
7
|
+
|
|
8
|
+
export const PRINCIPLES_FILE = '.guardlink/principles.md';
|
|
9
|
+
export const EXCEPTIONS_FILE = '.guardlink/principles-exceptions.json';
|
|
10
|
+
export const SOURCE_FILE = '.guardlink/principles-source.json';
|
|
11
|
+
export const ANSWERS_DIR = '.guardlink/principles-answers';
|
|
12
|
+
export const DRAFT_FILE = '.guardlink/principles-draft.json';
|
|
13
|
+
export const EXCEPTIONS_SCHEMA = 'bravos.principle-exceptions/v1';
|
|
14
|
+
export const SOURCE_SCHEMA = 'bravos.principles-source/v1';
|
|
15
|
+
export const CHECK_SCHEMA = 'bravos.principles-check/v1';
|
|
16
|
+
export const MARKER = '<!-- bravos:principles v1';
|
|
17
|
+
export const ID = /^SDP-[1-9][0-9]{0,3}$/;
|
|
18
|
+
export const KINDS = ['enforced', 'guidance'];
|
|
19
|
+
export const ORIGINS = ['document', 'intent', 'starter'];
|
|
20
|
+
/** The longest an exception may run before a person approves it again. */
|
|
21
|
+
export const MAX_EXCEPTION_DAYS = 365;
|
|
22
|
+
const MAX_FILE_BYTES = 1024 * 1024;
|
|
23
|
+
|
|
24
|
+
// @comment -- "The starter list bravos ships: a few principles most teams hold, each mapped to the OWASP ASVS 4.0.3 requirement it restates. They are offered as optional candidates on the review page and never pre-selected; nothing here is adopted until a named person adopts it."
|
|
25
|
+
export const STARTER = Object.freeze([
|
|
26
|
+
{ id: 'authorize-on-server', kind: 'enforced', asvs: 'V4.1.1', statement: 'Every request is authorised on the server, never only in the client.', why: 'A check that runs only in the browser or the app can be skipped by anyone who sends the request themselves.', scope: 'every endpoint and handler' },
|
|
27
|
+
{ id: 'fail-closed', kind: 'enforced', asvs: 'V4.1.5', statement: 'Access checks fail closed: an error or a missing rule denies the request.', why: 'An exception that falls through to the allowed path grants access nobody decided to give.', scope: 'every access check' },
|
|
28
|
+
{ id: 'scope-to-owner', kind: 'enforced', asvs: 'V4.2.1', statement: 'Every read and write of a record is scoped to the account or tenant that owns it.', why: 'An identifier in a request is attacker-controlled; without the scope one customer reads or changes another customer\'s data.', scope: 'every query and handler that takes a record id' },
|
|
29
|
+
{ id: 'no-secrets-in-logs', kind: 'enforced', asvs: 'V7.1.1', statement: 'Secrets, tokens, passwords and payment details are never written to logs.', why: 'Logs are copied to many places and read by many people; a secret written there is no longer secret.', scope: 'all code' },
|
|
30
|
+
{ id: 'parameterised-queries', kind: 'enforced', asvs: 'V5.3.4', statement: 'Database queries are parameterised; input is never concatenated into a query.', why: 'Concatenated input lets a caller change what the query does.', scope: 'all database access' },
|
|
31
|
+
{ id: 'no-secrets-in-source', kind: 'enforced', asvs: 'V2.10.4', statement: 'Secrets and keys are kept out of source code and read from the environment or a secret store.', why: 'Source code is copied to every clone, build and backup.', scope: 'all code and configuration' },
|
|
32
|
+
{ id: 'validate-input-on-server', kind: 'guidance', asvs: 'V5.1.3', statement: 'Input from outside is validated on the server against what is allowed, not against what is forbidden.', why: 'A list of forbidden values is always missing one.', scope: 'every entry point' },
|
|
33
|
+
{ id: 'outbound-allow-list', kind: 'enforced', asvs: 'V12.6.1', statement: 'The server only makes outbound requests to destinations on an allow list.', why: 'A server that fetches any address it is given can be pointed at internal systems.', scope: 'every outbound HTTP call built from input' },
|
|
34
|
+
]);
|
|
35
|
+
|
|
36
|
+
// ---------------------------------------------------------------------------------------------
|
|
37
|
+
// Text and fingerprints
|
|
38
|
+
// ---------------------------------------------------------------------------------------------
|
|
39
|
+
|
|
40
|
+
const INVISIBLE = /[----]/g;
|
|
41
|
+
const CONTROL = /[\u0000-\u001F\u007F-\u009F]/g;
|
|
42
|
+
|
|
43
|
+
// @comment -- "One clean line of text a person or the draft supplied: control and invisible characters removed, whitespace collapsed, cut to max. Every field of a principle is one line, so nothing in it can start a new heading or field in principles.md."
|
|
44
|
+
export function oneLine(value, max = 600) {
|
|
45
|
+
return String(value ?? '').replace(INVISIBLE, '').replace(CONTROL, ' ').replace(/\s+/g, ' ').trim().slice(0, max);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export const sha = (s) => createHash('sha256').update(s).digest('hex');
|
|
49
|
+
|
|
50
|
+
// @comment -- "A glob a principle or an exception applies to: repository-relative, letters, digits and . _ - / * ? { } , only, no '..' segment and no leading slash."
|
|
51
|
+
export function validGlob(g) {
|
|
52
|
+
return typeof g === 'string' && g.length > 0 && g.length <= 200 && /^[A-Za-z0-9_.\-/*?{},]+$/.test(g) && !g.startsWith('/') && !g.split('/').includes('..');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// @comment -- "Whether a repository path matches a glob: ** crosses folders, * and ? stay inside one, {a,b} is either. Built as an anchored regular expression from escaped literal pieces, so the glob's text cannot add pattern syntax of its own."
|
|
56
|
+
export function globMatch(glob, file) {
|
|
57
|
+
if (!validGlob(glob)) return false;
|
|
58
|
+
let re = '';
|
|
59
|
+
for (let i = 0; i < glob.length; i++) {
|
|
60
|
+
const c = glob[i];
|
|
61
|
+
if (c === '*' && glob[i + 1] === '*') {
|
|
62
|
+
i++;
|
|
63
|
+
if (glob[i + 1] === '/') {
|
|
64
|
+
i++;
|
|
65
|
+
re += '(?:[^/]+/)*';
|
|
66
|
+
} else re += '.*';
|
|
67
|
+
} else if (c === '*') re += '[^/]*';
|
|
68
|
+
else if (c === '?') re += '[^/]';
|
|
69
|
+
else if (c === '{') {
|
|
70
|
+
const end = glob.indexOf('}', i);
|
|
71
|
+
if (end < 0) return false;
|
|
72
|
+
re += `(?:${glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|')})`;
|
|
73
|
+
i = end;
|
|
74
|
+
} else re += c.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
75
|
+
}
|
|
76
|
+
return new RegExp(`^${re}$`).test(String(file ?? '').replace(/^\.\//, ''));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The fields a principle is made of, cleaned. */
|
|
80
|
+
export function principleFields(p) {
|
|
81
|
+
return {
|
|
82
|
+
id: String(p.id ?? ''),
|
|
83
|
+
kind: KINDS.includes(p.kind) ? p.kind : 'guidance',
|
|
84
|
+
statement: oneLine(p.statement, 600),
|
|
85
|
+
scope: oneLine(p.scope, 200) || 'all code',
|
|
86
|
+
why: oneLine(p.why, 600),
|
|
87
|
+
paths: Array.isArray(p.paths) ? [...new Set(p.paths.filter(validGlob))].sort() : [],
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// @comment -- "A principle's fingerprint: SHA-256 over its id, kind, statement, scope, why and paths, cleaned and in a fixed order, cut to 16 hex characters. It is recorded with each person's adoption and printed beside the principle, so a hand edit to any of those fields shows."
|
|
92
|
+
export function fingerprint(p) {
|
|
93
|
+
const f = principleFields(p);
|
|
94
|
+
return sha(JSON.stringify([f.id, f.kind, f.statement, f.scope, f.why, f.paths])).slice(0, 16);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// @comment -- "An exception's fingerprint, over the principle, the area, the reason, who approved it, when, and until when."
|
|
98
|
+
export function exceptionFingerprint(e) {
|
|
99
|
+
return sha(JSON.stringify([String(e.principle ?? ''), String(e.where ?? ''), oneLine(e.reason, 400), oneLine(e.by, 80), String(e.approved ?? ''), String(e.until ?? '')])).slice(0, 16);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const DAY = /^\d{4}-\d{2}-\d{2}$/;
|
|
103
|
+
const today = (now) => now.toISOString().slice(0, 10);
|
|
104
|
+
|
|
105
|
+
// ---------------------------------------------------------------------------------------------
|
|
106
|
+
// Readers: the working tree, or one commit
|
|
107
|
+
// ---------------------------------------------------------------------------------------------
|
|
108
|
+
|
|
109
|
+
const git = (root, args, opts = {}) => execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 15000, maxBuffer: 16 * 1024 * 1024, ...opts });
|
|
110
|
+
|
|
111
|
+
// @comment -- "Reads the principles files from the working tree: only regular files that sit, after links are resolved, where their name says inside the repository, and at most 1 MB each. A planted link is skipped, never followed."
|
|
112
|
+
export function treeReader(root) {
|
|
113
|
+
let base;
|
|
114
|
+
try {
|
|
115
|
+
base = realpathSync(root);
|
|
116
|
+
} catch {
|
|
117
|
+
base = resolve(root);
|
|
118
|
+
}
|
|
119
|
+
const regular = (rel) => {
|
|
120
|
+
const abs = resolve(base, rel);
|
|
121
|
+
try {
|
|
122
|
+
return abs.startsWith(base + sep) && lstatSync(abs).isFile() && realpathSync(abs) === abs && lstatSync(abs).size <= MAX_FILE_BYTES ? abs : null;
|
|
123
|
+
} catch {
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
return {
|
|
128
|
+
read: (rel) => {
|
|
129
|
+
const abs = regular(rel);
|
|
130
|
+
if (!abs) return null;
|
|
131
|
+
try {
|
|
132
|
+
return readFileSync(abs, 'utf8');
|
|
133
|
+
} catch {
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
},
|
|
137
|
+
list: (rel) => {
|
|
138
|
+
try {
|
|
139
|
+
return readdirSync(join(base, rel)).filter((n) => !!regular(`${rel}/${n}`)).sort();
|
|
140
|
+
} catch {
|
|
141
|
+
return [];
|
|
142
|
+
}
|
|
143
|
+
},
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// @comment -- "Reads the principles files as one commit holds them (git ls-tree and git cat-file, argv only), so a push is judged by what it sends."
|
|
148
|
+
export function commitReader(root, commit) {
|
|
149
|
+
let cache;
|
|
150
|
+
const all = () => {
|
|
151
|
+
if (cache) return cache;
|
|
152
|
+
try {
|
|
153
|
+
cache = git(root, ['ls-tree', '-r', '-z', commit, '--', '.guardlink/']).split('\0').filter(Boolean).map((l) => {
|
|
154
|
+
const [meta, path] = l.split('\t');
|
|
155
|
+
const [mode, type] = meta.split(' ');
|
|
156
|
+
return { path, regular: type === 'blob' && mode !== '120000' };
|
|
157
|
+
});
|
|
158
|
+
} catch {
|
|
159
|
+
cache = [];
|
|
160
|
+
}
|
|
161
|
+
return cache;
|
|
162
|
+
};
|
|
163
|
+
return {
|
|
164
|
+
read: (rel) => {
|
|
165
|
+
if (!all().some((e) => e.path === rel && e.regular)) return null;
|
|
166
|
+
try {
|
|
167
|
+
const text = git(root, ['cat-file', 'blob', `${commit}:${rel}`]);
|
|
168
|
+
return text.length > MAX_FILE_BYTES ? null : text;
|
|
169
|
+
} catch {
|
|
170
|
+
return null;
|
|
171
|
+
}
|
|
172
|
+
},
|
|
173
|
+
list: (rel) => all().filter((e) => e.regular && e.path.startsWith(`${rel}/`) && !e.path.slice(rel.length + 1).includes('/')).map((e) => e.path.slice(rel.length + 1)).sort(),
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// ---------------------------------------------------------------------------------------------
|
|
178
|
+
// From answers to adopted principles
|
|
179
|
+
// ---------------------------------------------------------------------------------------------
|
|
180
|
+
|
|
181
|
+
const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
182
|
+
|
|
183
|
+
// @comment -- "Each person's confirmed principles answers: the review page's answers files for kind principles that a person confirmed (an in-progress save never counts). A file that does not parse, or is not a principles answers file, is named under skipped."
|
|
184
|
+
export function readAdoptionFiles(reader) {
|
|
185
|
+
const files = [];
|
|
186
|
+
const skipped = [];
|
|
187
|
+
for (const name of reader.list(ANSWERS_DIR).filter((n) => n.endsWith('.json'))) {
|
|
188
|
+
let j;
|
|
189
|
+
try {
|
|
190
|
+
j = JSON.parse(reader.read(`${ANSWERS_DIR}/${name}`) ?? '');
|
|
191
|
+
} catch {
|
|
192
|
+
skipped.push(name);
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
if (!isObject(j) || j.schema !== 'bravos.review-answers/v1' || j.kind !== 'principles' || !isObject(j.answers) || typeof j.by !== 'string' || !oneLine(j.by, 80)) {
|
|
196
|
+
skipped.push(name);
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
if (j.status === 'in-progress') continue;
|
|
200
|
+
files.push({ name, by: oneLine(j.by, 80), date: DAY.test(String(j.date)) ? j.date : String(j.confirmedAt ?? '').slice(0, 10), confirmedAt: typeof j.confirmedAt === 'string' ? j.confirmedAt : null, answers: j.answers });
|
|
201
|
+
}
|
|
202
|
+
return { files, skipped };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** An answer that adopts a principle: a deliberate yes with the adopted wording recorded by the review server. */
|
|
206
|
+
const adoption = (a) => (isObject(a) && a.verdict !== 'no' && isObject(a.adopted) && typeof a.adopted.hash === 'string' ? a.adopted : null);
|
|
207
|
+
|
|
208
|
+
// @comment -- "What the confirmed answers make of each principle. A principle is adopted when at least one named person adopted it and nobody who answered it said no; if people adopted different wordings it is not adopted until they settle on one (disagreed). A principle someone said no to, after someone else adopted it, is disputed; one only declined is declined. Deterministic and order-free: the same answers files always give the same result."
|
|
209
|
+
export function principleStates(files) {
|
|
210
|
+
const by = new Map();
|
|
211
|
+
for (const f of files) {
|
|
212
|
+
for (const [id, a] of Object.entries(f.answers)) {
|
|
213
|
+
if (!ID.test(id) || !isObject(a)) continue;
|
|
214
|
+
const row = by.get(id) ?? { adopters: [], decliners: [] };
|
|
215
|
+
const ad = adoption(a);
|
|
216
|
+
if (ad) row.adopters.push({ by: f.by, date: f.date, principle: { ...principleFields({ ...ad, id }), hash: ad.hash } });
|
|
217
|
+
else if (a.verdict === 'no') row.decliners.push({ by: f.by, date: f.date, comment: oneLine(a.comment, 300) });
|
|
218
|
+
by.set(id, row);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
const out = new Map();
|
|
222
|
+
for (const [id, row] of by) {
|
|
223
|
+
const hashes = [...new Set(row.adopters.map((x) => x.principle.hash))];
|
|
224
|
+
if (row.adopters.length && row.decliners.length) out.set(id, { id, state: 'disputed', adopters: row.adopters, decliners: row.decliners });
|
|
225
|
+
else if (hashes.length > 1) out.set(id, { id, state: 'disagreed', adopters: row.adopters, decliners: [] });
|
|
226
|
+
else if (row.adopters.length) {
|
|
227
|
+
const p = row.adopters[0].principle;
|
|
228
|
+
// A recorded fingerprint that does not match the recorded wording is not an adoption anybody made.
|
|
229
|
+
if (fingerprint(p) !== p.hash) out.set(id, { id, state: 'tampered', adopters: row.adopters, decliners: [] });
|
|
230
|
+
else out.set(id, { id, state: 'adopted', principle: p, adopters: row.adopters.map(({ by: who, date }) => ({ by: who, date })).sort((a, b) => a.by.localeCompare(b.by)), decliners: [] });
|
|
231
|
+
} else out.set(id, { id, state: 'declined', adopters: [], decliners: row.decliners });
|
|
232
|
+
}
|
|
233
|
+
return [...out.values()].sort((a, b) => Number(a.id.slice(4)) - Number(b.id.slice(4)));
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// ---------------------------------------------------------------------------------------------
|
|
237
|
+
// Exceptions
|
|
238
|
+
// ---------------------------------------------------------------------------------------------
|
|
239
|
+
|
|
240
|
+
// @comment -- "Reads and validates the exceptions file: each exception names an adopted principle, an area (a 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."
|
|
241
|
+
export function readExceptions(reader) {
|
|
242
|
+
const text = reader.read(EXCEPTIONS_FILE);
|
|
243
|
+
if (text === null) return { exceptions: [], problems: [] };
|
|
244
|
+
let j;
|
|
245
|
+
try {
|
|
246
|
+
j = JSON.parse(text);
|
|
247
|
+
} catch {
|
|
248
|
+
return { exceptions: [], problems: [`${EXCEPTIONS_FILE} is not valid JSON`] };
|
|
249
|
+
}
|
|
250
|
+
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`] };
|
|
251
|
+
const exceptions = [];
|
|
252
|
+
const problems = [];
|
|
253
|
+
for (const [n, e] of j.exceptions.entries()) {
|
|
254
|
+
const at = `${EXCEPTIONS_FILE} exception ${n + 1}`;
|
|
255
|
+
if (!isObject(e) || !ID.test(String(e.principle)) || !validGlob(e.where) || !oneLine(e.reason, 400) || !oneLine(e.by, 80) || !DAY.test(String(e.approved)) || !DAY.test(String(e.until))) {
|
|
256
|
+
problems.push(`${at} needs a principle id, an area, a reason, who approved it, the day approved and the day it ends`);
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
const x = { principle: e.principle, where: e.where, reason: oneLine(e.reason, 400), by: oneLine(e.by, 80), approved: e.approved, until: e.until, hash: String(e.hash ?? '') };
|
|
260
|
+
if (exceptionFingerprint(x) !== x.hash) problems.push(`${at} (${x.principle} in ${x.where}) was changed by hand: its fingerprint no longer matches`);
|
|
261
|
+
const span = (Date.parse(`${x.until}T00:00:00Z`) - Date.parse(`${x.approved}T00:00:00Z`)) / 86400000;
|
|
262
|
+
if (!(span >= 0 && span <= MAX_EXCEPTION_DAYS)) problems.push(`${at} (${x.principle} in ${x.where}) runs ${Math.round(span)} days; an exception ends within ${MAX_EXCEPTION_DAYS} days of its approval`);
|
|
263
|
+
exceptions.push(x);
|
|
264
|
+
}
|
|
265
|
+
return { exceptions, problems };
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** Whether an exception is still in force on `now`: it ends at the end of its last day. */
|
|
269
|
+
export const live = (e, now = new Date()) => e.until >= today(now);
|
|
270
|
+
|
|
271
|
+
// @comment -- "The live exception that covers a file for a principle, or null. Expired ones cover nothing: the gate blocks again the day after an exception ends."
|
|
272
|
+
export function exceptionFor(exceptions, principle, file, now = new Date()) {
|
|
273
|
+
return exceptions.find((e) => e.principle === principle && live(e, now) && globMatch(e.where, file)) ?? null;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// ---------------------------------------------------------------------------------------------
|
|
277
|
+
// principles.md: written by bravos, read back by the check
|
|
278
|
+
// ---------------------------------------------------------------------------------------------
|
|
279
|
+
|
|
280
|
+
// @comment -- "The text of .guardlink/principles.md, built only from adopted principles and the approved exceptions. Every field is one cleaned line, so the file's structure cannot be changed by what a principle says. Retired principles (adopted before, not any more) are listed so the history reads plainly; the agent follows only the Adopted section."
|
|
281
|
+
export function renderPrinciples({ adopted, exceptions = [], retired = [], source = null }) {
|
|
282
|
+
const out = [
|
|
283
|
+
'# Security design principles',
|
|
284
|
+
'',
|
|
285
|
+
`${MARKER} — written by bravos from the adoptions in ${ANSWERS_DIR}/ and the exceptions in ${EXCEPTIONS_FILE}. Do not edit this file: bravos principles check fails a changed line. To change a principle, run bravos review principles. -->`,
|
|
286
|
+
'',
|
|
287
|
+
];
|
|
288
|
+
if (source) out.push(`Copied from ${oneLine(source.repo, 200)} at commit ${oneLine(source.commit, 40)} (principles.md sha256:${oneLine(source.hash, 64)}). Copy again with bravos principles copy --from <that repository>.`, '');
|
|
289
|
+
out.push('Every coding agent and developer changing code here follows each adopted principle. A change that would break one is raised with a person first; an enforced principle is also tested, and the pre-PR gate stops a change that breaks it unless an approved exception covers that code.', '');
|
|
290
|
+
out.push('## Adopted', '');
|
|
291
|
+
if (!adopted.length) out.push('None yet.', '');
|
|
292
|
+
for (const s of adopted) {
|
|
293
|
+
const p = s.principle;
|
|
294
|
+
out.push(`### ${p.id} · ${p.kind}`, p.statement, `- Applies to: ${p.scope}`);
|
|
295
|
+
if (p.paths.length) out.push(`- Paths: ${p.paths.join(', ')}`);
|
|
296
|
+
if (p.why) out.push(`- Why: ${p.why}`);
|
|
297
|
+
out.push(`- Adopted by: ${s.adopters.map((a) => `${a.by} (${a.date})`).join(', ')}`, `- Fingerprint: ${p.hash}`, '');
|
|
298
|
+
}
|
|
299
|
+
if (exceptions.length) {
|
|
300
|
+
out.push('## Exceptions', '');
|
|
301
|
+
for (const e of exceptions) out.push(`- ${e.principle} in ${e.where} until ${e.until}: ${e.reason} — approved by ${e.by} on ${e.approved} · ${e.hash}`);
|
|
302
|
+
out.push('');
|
|
303
|
+
}
|
|
304
|
+
if (retired.length) {
|
|
305
|
+
out.push('## Retired', '', 'No longer adopted; not followed.', '');
|
|
306
|
+
for (const r of retired) out.push(`- ${r.id}: ${oneLine(r.statement, 600)} — ${oneLine(r.why, 300)}`);
|
|
307
|
+
out.push('');
|
|
308
|
+
}
|
|
309
|
+
return out.join('\n');
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// @comment -- "Reads principles.md back: each adopted principle with every field and its printed fingerprint, the exception lines, the retired ids, and whether bravos's marker is there. Lines it does not recognise are reported, so a principle added by hand in another shape is not silently ignored."
|
|
313
|
+
export function parsePrinciples(text) {
|
|
314
|
+
const doc = { marker: false, adopted: [], exceptions: [], retired: [], unknown: [] };
|
|
315
|
+
let section = '';
|
|
316
|
+
let cur = null;
|
|
317
|
+
const flush = () => {
|
|
318
|
+
if (cur) doc.adopted.push(cur);
|
|
319
|
+
cur = null;
|
|
320
|
+
};
|
|
321
|
+
for (const raw of String(text ?? '').split('\n')) {
|
|
322
|
+
const line = raw.replace(/\r$/, '');
|
|
323
|
+
if (line.startsWith(MARKER)) doc.marker = true;
|
|
324
|
+
const h2 = /^##\s+(.+?)\s*$/.exec(line);
|
|
325
|
+
if (h2 && !line.startsWith('###')) {
|
|
326
|
+
flush();
|
|
327
|
+
section = h2[1].toLowerCase();
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
if (section === 'adopted') {
|
|
331
|
+
const h3 = /^###\s+(SDP-[1-9][0-9]{0,3})\s+·\s+(\S+)\s*$/.exec(line);
|
|
332
|
+
if (h3) {
|
|
333
|
+
flush();
|
|
334
|
+
cur = { id: h3[1], kind: h3[2], statement: '', scope: '', why: '', paths: [], adopters: [], hash: '' };
|
|
335
|
+
continue;
|
|
336
|
+
}
|
|
337
|
+
if (/^###\s/.test(line) || /^\s*[-*]\s+SDP-/.test(line)) {
|
|
338
|
+
doc.unknown.push(line);
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
if (!cur) continue;
|
|
342
|
+
const field = /^-\s+(Applies to|Paths|Why|Adopted by|Fingerprint):\s*(.*)$/.exec(line);
|
|
343
|
+
if (field) {
|
|
344
|
+
const [, name, value] = field;
|
|
345
|
+
if (name === 'Applies to') cur.scope = value;
|
|
346
|
+
else if (name === 'Paths') cur.paths = value.split(',').map((s) => s.trim()).filter(Boolean);
|
|
347
|
+
else if (name === 'Why') cur.why = value;
|
|
348
|
+
else if (name === 'Fingerprint') cur.hash = value.trim();
|
|
349
|
+
else cur.adopters = [...value.matchAll(/([^,(]+?)\s*\((\d{4}-\d{2}-\d{2})\)/g)].map((m) => ({ by: m[1].trim(), date: m[2] }));
|
|
350
|
+
} else if (line.trim() && !cur.statement) cur.statement = line.trim();
|
|
351
|
+
else if (line.trim()) cur.statement += ` ${line.trim()}`;
|
|
352
|
+
} else if (section === 'exceptions') {
|
|
353
|
+
const m = /^-\s+(SDP-[1-9][0-9]{0,3})\s+in\s+(\S+)\s+until\s+(\d{4}-\d{2}-\d{2}):.*·\s*([0-9a-f]{16})\s*$/.exec(line);
|
|
354
|
+
if (m) doc.exceptions.push({ principle: m[1], where: m[2], until: m[3], hash: m[4] });
|
|
355
|
+
else if (line.trim()) doc.unknown.push(line);
|
|
356
|
+
} else if (section === 'retired') {
|
|
357
|
+
const m = /^-\s+(SDP-[1-9][0-9]{0,3}):\s*(.*?)(?:\s+—\s+(.*))?$/.exec(line);
|
|
358
|
+
if (m) doc.retired.push({ id: m[1], statement: m[2] ?? '', why: m[3] ?? '' });
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
flush();
|
|
362
|
+
return doc;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// ---------------------------------------------------------------------------------------------
|
|
366
|
+
// The check
|
|
367
|
+
// ---------------------------------------------------------------------------------------------
|
|
368
|
+
|
|
369
|
+
// @comment -- "The check that principles.md says only what named people adopted. It fails when the file was edited by hand (a fingerprint no longer matches its text), when a principle has no named person's confirmed adoption behind it or names someone who did not adopt it, when an adopted principle is missing from the file, when the exceptions in the file differ from the approved ones, and when an exception has expired. Read-only; takes a reader so a push can be judged as its commit holds the files."
|
|
370
|
+
export function checkPrinciples(reader, now = new Date()) {
|
|
371
|
+
const text = reader.read(PRINCIPLES_FILE);
|
|
372
|
+
const { files, skipped } = readAdoptionFiles(reader);
|
|
373
|
+
const states = principleStates(files);
|
|
374
|
+
const { exceptions, problems: exceptionProblems } = readExceptions(reader);
|
|
375
|
+
const result = { schema: CHECK_SCHEMA, exists: text !== null || files.length > 0, ok: true, problems: [], notes: [], adopted: [], exceptions: [], skipped };
|
|
376
|
+
if (!result.exists) return result;
|
|
377
|
+
const problems = [...exceptionProblems];
|
|
378
|
+
const notes = [];
|
|
379
|
+
for (const name of skipped) notes.push(`${ANSWERS_DIR}/${name} is not a principles answers file bravos can read; it was skipped`);
|
|
380
|
+
const adopted = states.filter((s) => s.state === 'adopted');
|
|
381
|
+
const expected = new Map(adopted.map((s) => [s.id, s]));
|
|
382
|
+
for (const s of states) {
|
|
383
|
+
if (s.state === 'tampered') problems.push(`${s.id}: the adoption recorded in ${ANSWERS_DIR}/ does not match its own fingerprint, so it was edited after it was confirmed`);
|
|
384
|
+
if (s.state === 'disagreed') notes.push(`${s.id}: ${s.adopters.map((a) => a.by).join(', ')} adopted different wordings; it is not adopted until they settle on one (bravos review principles)`);
|
|
385
|
+
if (s.state === 'disputed') notes.push(`${s.id}: adopted by ${s.adopters.map((a) => a.by).join(', ')} and declined by ${s.decliners.map((d) => d.by).join(', ')}; it is not adopted until they agree`);
|
|
386
|
+
}
|
|
387
|
+
if (text === null) {
|
|
388
|
+
if (adopted.length) problems.push(`${PRINCIPLES_FILE} is missing but ${adopted.length} principle${adopted.length === 1 ? ' is' : 's are'} adopted: run bravos principles write`);
|
|
389
|
+
} else {
|
|
390
|
+
const doc = parsePrinciples(text);
|
|
391
|
+
if (!doc.marker) problems.push(`${PRINCIPLES_FILE} was not written by bravos (its header is missing): run bravos principles write`);
|
|
392
|
+
for (const line of doc.unknown) problems.push(`${PRINCIPLES_FILE} has a line bravos did not write: ${oneLine(line, 120)}`);
|
|
393
|
+
const seen = new Set();
|
|
394
|
+
for (const p of doc.adopted) {
|
|
395
|
+
if (seen.has(p.id)) {
|
|
396
|
+
problems.push(`${p.id} is listed twice in ${PRINCIPLES_FILE}`);
|
|
397
|
+
continue;
|
|
398
|
+
}
|
|
399
|
+
seen.add(p.id);
|
|
400
|
+
const want = expected.get(p.id);
|
|
401
|
+
if (fingerprint(p) !== p.hash) problems.push(`${p.id} was changed by hand in ${PRINCIPLES_FILE}: its text no longer matches its fingerprint`);
|
|
402
|
+
else if (!want) problems.push(`${p.id} is listed as adopted, but no named person's confirmed adoption stands behind it`);
|
|
403
|
+
else if (want.principle.hash !== p.hash) problems.push(`${p.id}'s wording in ${PRINCIPLES_FILE} is not the wording ${want.adopters.map((a) => a.by).join(', ')} adopted`);
|
|
404
|
+
else {
|
|
405
|
+
const names = new Set(want.adopters.map((a) => a.by));
|
|
406
|
+
const extra = p.adopters.filter((a) => !names.has(a.by));
|
|
407
|
+
if (extra.length) problems.push(`${p.id} names ${extra.map((a) => a.by).join(', ')} as adopting it, but their answers do not`);
|
|
408
|
+
if (!p.adopters.length) problems.push(`${p.id} names nobody as adopting it`);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
for (const s of adopted) if (!seen.has(s.id)) problems.push(`${s.id} was adopted by ${s.adopters.map((a) => a.by).join(', ')} but is missing from ${PRINCIPLES_FILE}: run bravos principles write`);
|
|
412
|
+
for (const r of doc.retired) if (expected.has(r.id)) problems.push(`${r.id} is listed as retired, but its adoption still stands`);
|
|
413
|
+
const fileSet = new Set(doc.exceptions.map((e) => e.hash));
|
|
414
|
+
const approvedSet = new Set(exceptions.map((e) => e.hash));
|
|
415
|
+
if (fileSet.size !== approvedSet.size || [...fileSet].some((h) => !approvedSet.has(h))) problems.push(`the exceptions in ${PRINCIPLES_FILE} differ from ${EXCEPTIONS_FILE}: run bravos principles write`);
|
|
416
|
+
}
|
|
417
|
+
for (const e of exceptions) {
|
|
418
|
+
if (!live(e, now)) problems.push(`the exception for ${e.principle} in ${e.where} ended on ${e.until}: remove it (bravos principles except --clear-expired), or a person approves a new one`);
|
|
419
|
+
else if (!expected.has(e.principle)) notes.push(`the exception for ${e.principle} in ${e.where} names a principle that is not adopted`);
|
|
420
|
+
}
|
|
421
|
+
result.problems = problems;
|
|
422
|
+
result.notes = notes;
|
|
423
|
+
result.ok = problems.length === 0;
|
|
424
|
+
result.adopted = adopted.map((s) => ({ ...s.principle, adopters: s.adopters }));
|
|
425
|
+
result.exceptions = exceptions;
|
|
426
|
+
return result;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// @comment -- "The check as lines for a terminal or a CI log: what is adopted and excepted, then each problem."
|
|
430
|
+
export function formatCheck(result) {
|
|
431
|
+
if (!result.exists) return ['principles: none adopted here (bravos review principles proposes them).'];
|
|
432
|
+
const enforced = result.adopted.filter((p) => p.kind === 'enforced').length;
|
|
433
|
+
const head = `principles: ${result.adopted.length} adopted (${enforced} enforced, ${result.adopted.length - enforced} guidance)${result.exceptions.length ? `, ${result.exceptions.length} exception${result.exceptions.length === 1 ? '' : 's'}` : ''} — ${result.ok ? 'matches what people adopted' : `${result.problems.length} problem${result.problems.length === 1 ? '' : 's'}`}`;
|
|
434
|
+
return [head, ...result.problems.map((p) => ` ✗ ${p}`), ...result.notes.map((n) => ` · ${n}`)];
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// @comment -- "The adopted principles as the working tree holds them, for the briefing, the after-edit note and the gate: an empty list when there are none or the file cannot be read. Never throws."
|
|
438
|
+
export function adoptedPrinciples(root) {
|
|
439
|
+
try {
|
|
440
|
+
const doc = parsePrinciples(treeReader(root).read(PRINCIPLES_FILE) ?? '');
|
|
441
|
+
return doc.adopted.filter((p) => ID.test(p.id) && KINDS.includes(p.kind) && fingerprint(p) === p.hash).map((p) => ({ ...principleFields(p), hash: p.hash }));
|
|
442
|
+
} catch {
|
|
443
|
+
return [];
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** The adopted principles that name a path matching this file; principles with no paths apply everywhere and are not listed per file. */
|
|
448
|
+
export const principlesForFile = (principles, file) => principles.filter((p) => p.paths.length && p.paths.some((g) => globMatch(g, file)));
|
|
449
|
+
|
|
450
|
+
// ---------------------------------------------------------------------------------------------
|
|
451
|
+
// The pre-push check
|
|
452
|
+
// ---------------------------------------------------------------------------------------------
|
|
453
|
+
|
|
454
|
+
const ZERO = /^0+$/;
|
|
455
|
+
|
|
456
|
+
// @comment -- "git's pre-push protocol: for each ref being pushed whose commits change the principles files (or when that cannot be worked out), the check runs on the files as the pushed commit holds them. A push that leaves them alone is never slowed or blocked."
|
|
457
|
+
// @mitigates #principles against #forged-principle using #adoption-fingerprint -- "A push whose commits change principles.md, the adoptions or the exceptions is checked as the pushed commit holds them and stopped when a line no longer matches what a named person adopted, so a hand edit or an agent-written principle does not reach the team's other clones unseen"
|
|
458
|
+
export function prePush(root, stdin, now = new Date()) {
|
|
459
|
+
const lines = [];
|
|
460
|
+
let blocked = false;
|
|
461
|
+
const seen = new Set();
|
|
462
|
+
for (const row of String(stdin ?? '').split('\n')) {
|
|
463
|
+
const [, local, , remote] = row.trim().split(/\s+/);
|
|
464
|
+
if (!local || ZERO.test(local) || seen.has(local)) continue;
|
|
465
|
+
seen.add(local);
|
|
466
|
+
let touched = true;
|
|
467
|
+
try {
|
|
468
|
+
const base = remote && !ZERO.test(remote) ? remote : git(root, ['merge-base', local, 'refs/remotes/origin/HEAD']).trim();
|
|
469
|
+
touched = git(root, ['diff', '--name-only', `${base}..${local}`, '--', PRINCIPLES_FILE, EXCEPTIONS_FILE, ANSWERS_DIR]).trim() !== '';
|
|
470
|
+
} catch {
|
|
471
|
+
touched = true;
|
|
472
|
+
}
|
|
473
|
+
if (!touched) continue;
|
|
474
|
+
const result = checkPrinciples(commitReader(root, local), now);
|
|
475
|
+
if (!result.exists || result.ok) continue;
|
|
476
|
+
blocked = true;
|
|
477
|
+
lines.push(`bravos: the security design principles in this push (${local.slice(0, 9)}) do not match what people adopted:`, ...formatCheck(result).slice(1).map((l) => ` ${l}`));
|
|
478
|
+
}
|
|
479
|
+
if (blocked) lines.push('Fix them (bravos principles check shows the same list; bravos principles write rewrites the file from the adoptions). To push anyway: git push --no-verify.');
|
|
480
|
+
return { blocked, lines };
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
const isMain = (() => {
|
|
484
|
+
try {
|
|
485
|
+
return !!process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href;
|
|
486
|
+
} catch {
|
|
487
|
+
return false;
|
|
488
|
+
}
|
|
489
|
+
})();
|
|
490
|
+
|
|
491
|
+
if (isMain) {
|
|
492
|
+
const [mode, ...rest] = process.argv.slice(2);
|
|
493
|
+
if (mode === 'pre-push') {
|
|
494
|
+
let input = '';
|
|
495
|
+
try {
|
|
496
|
+
input = readFileSync(0, 'utf8');
|
|
497
|
+
} catch {
|
|
498
|
+
/* nothing is being pushed */
|
|
499
|
+
}
|
|
500
|
+
const { blocked, lines } = prePush(process.cwd(), input);
|
|
501
|
+
for (const l of lines) process.stderr.write(`${l}\n`);
|
|
502
|
+
process.exit(blocked ? 1 : 0);
|
|
503
|
+
} else if (mode === 'check') {
|
|
504
|
+
const dir = rest.find((a) => !a.startsWith('--')) ?? process.cwd();
|
|
505
|
+
const result = checkPrinciples(treeReader(resolve(dir)));
|
|
506
|
+
process.stdout.write(rest.includes('--json') ? `${JSON.stringify(result, null, 2)}\n` : `${formatCheck(result).join('\n')}\n`);
|
|
507
|
+
process.exit(result.ok ? 0 : 1);
|
|
508
|
+
} else {
|
|
509
|
+
process.stderr.write('usage: node principles.mjs check [dir] [--json] | pre-push\n');
|
|
510
|
+
process.exit(2);
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
|
package/hooks/lib/refresh.mjs
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
import { ACCOUNT_LICENCES, ACCOUNT_UPGRADE, LICENCE_ENV, LICENCE_ENV_ALT, LICENCE_FILES, bravosHome, verify } from './licence.mjs';
|
|
5
|
+
import { machineFingerprint } from './machine.mjs';
|
|
5
6
|
|
|
6
7
|
export const DEVICE_FILE = 'device.json';
|
|
7
8
|
export const REFRESH_PATH = '/api/v1/cli/licence/refresh';
|
|
@@ -201,11 +202,20 @@ export async function refreshIfDue(env = process.env, opts = {}) {
|
|
|
201
202
|
}
|
|
202
203
|
return { outcome: 'kept', reason };
|
|
203
204
|
};
|
|
205
|
+
const fingerprint = (opts.machine ?? machineFingerprint)(env);
|
|
204
206
|
let r;
|
|
205
207
|
try {
|
|
206
208
|
r = await f(`${device.origin}${REFRESH_PATH}`, {
|
|
207
209
|
method: 'POST',
|
|
208
|
-
|
|
210
|
+
// The machine's one-way fingerprint (./machine.mjs), so the portal can
|
|
211
|
+
// tell a copied device.json on another machine from this one. Absent in a
|
|
212
|
+
// container or CI, where the portal keeps today's behaviour.
|
|
213
|
+
headers: {
|
|
214
|
+
'User-Agent': opts.userAgent ?? 'bravos-cli',
|
|
215
|
+
Accept: 'application/json',
|
|
216
|
+
Authorization: `Bearer ${device.device_secret}`,
|
|
217
|
+
...(fingerprint.key ? { 'X-Bravos-Machine': fingerprint.key } : {}),
|
|
218
|
+
},
|
|
209
219
|
signal: AbortSignal.timeout(opts.timeoutMs ?? REFRESH_TIMEOUT_MS),
|
|
210
220
|
});
|
|
211
221
|
} catch {
|