@su-sws/synthetic-web-team 0.2.0 → 0.2.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@su-sws/synthetic-web-team",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Stanford Web Services standards and agent team: policy, patterns, recipes, fragments, prior art, 31 skills, the two-part install wizard, and the advisory compliance CLI.",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "repository": {
@@ -9,7 +9,7 @@
9
9
  },
10
10
  "scripts": {
11
11
  "sync-skills": "node scripts/sync-skills.mjs",
12
- "validate": "node scripts/validate-skills.mjs && node scripts/validate-emit.mjs && node scripts/validate-install.mjs && node scripts/validate-criteria.mjs && node scripts/validate-state-classifier.mjs && node scripts/validate-hooks.mjs",
12
+ "validate": "node scripts/validate-skills.mjs && node scripts/validate-emit.mjs && node scripts/validate-install.mjs && node scripts/validate-criteria.mjs && node scripts/validate-state-classifier.mjs && node scripts/validate-hooks.mjs && node scripts/validate-acknowledged.mjs",
13
13
  "check": "npm run validate && npm run sync-skills -- --check",
14
14
  "pack:all": "mkdir -p .pack && npm pack --pack-destination ./.pack && npm pack -w @su-sws/synthetic-web-team-mcp --pack-destination ./.pack"
15
15
  },
@@ -12,7 +12,7 @@ import { join, resolve, dirname, relative } from 'node:path';
12
12
  import { fileURLToPath } from 'node:url';
13
13
  import { parseArgs } from 'node:util';
14
14
  import YAML from 'yaml';
15
- import { ALL, findHtml } from '../src/checks.mjs';
15
+ import { ALL, findHtml, scanSecrets } from '../src/checks.mjs';
16
16
  import { runAxe, RESULTS_PATH as AXE_RESULTS_PATH } from '../src/axe.mjs';
17
17
  import { runPerf, RESULTS_PATH as PERF_RESULTS_PATH } from '../src/perf.mjs';
18
18
  import { runStates, RESULTS_PATH as STATE_RESULTS_PATH } from '../src/states.mjs';
@@ -24,6 +24,7 @@ import * as history from '../src/history.mjs';
24
24
  import * as gh from '../src/github.mjs';
25
25
  import { preflight, summarise } from '../src/preflight.mjs';
26
26
  import { findStandards as locateStandards } from '../src/standards.mjs';
27
+ import { loadAcknowledged, applyAcknowledgements, sha256 } from '../src/acknowledged.mjs';
27
28
  // Sibling directory inside the same published package (@su-sws/synthetic-web-team), so this
28
29
  // relative path resolves in the repository and in a tarball alike. One reader
29
30
  // of the install record means the CLI and the wizard cannot disagree about what
@@ -85,6 +86,10 @@ const USAGE = `
85
86
  project, plus: npx playwright install chromium
86
87
  perf Measure the performance budget in a real browser. Writes
87
88
  .sws/perf-results.json. Needs @playwright/test. Exits 0.
89
+ digest <path>[:<line>]
90
+ Print the sha256 of each value the secrets check matches in
91
+ a file, to narrow an acknowledgement to one false positive.
92
+ Local only: no report ever carries these hashes.
88
93
  prior-art scan Index Stanford projects on this machine. Never transmitted.
89
94
  version
90
95
 
@@ -168,15 +173,6 @@ function loadManifest() {
168
173
  try { return YAML.parse(readFileSync(p, 'utf8')) || {}; } catch { return {}; }
169
174
  }
170
175
 
171
- function loadAcknowledged() {
172
- const p = join(root, '.sws', 'acknowledged.yml');
173
- if (!existsSync(p)) return [];
174
- try {
175
- const y = YAML.parse(readFileSync(p, 'utf8'));
176
- return Array.isArray(y) ? y : (y?.accepted ?? []);
177
- } catch { return []; }
178
- }
179
-
180
176
  // Recipes may `extends: <recipeId>`. Only differences live in the child, so the
181
177
  // shared criteria cannot drift between recipes, which is the failure this whole
182
178
  // project is organised against.
@@ -258,25 +254,30 @@ async function run() {
258
254
  // Attach weights and severities from the criteria. A finding with no matching
259
255
  // criterion still reports, at weight 0, so a check is never silently dropped.
260
256
  const byId = new Map((acceptance.criteria || []).map((c) => [c.id, c]));
261
- const ack = loadAcknowledged();
257
+ const ack = loadAcknowledged(root);
262
258
  const now = new Date();
263
259
 
260
+ // An acknowledgement covers what it names, not the whole check: see
261
+ // src/acknowledged.mjs. Entries a blocking check cannot honour are reported.
264
262
  const findings = raw.map((f) => {
265
263
  const c = byId.get(f.id) || {};
266
- const a = ack.find((x) => x.check === f.id);
267
- let state = f.state;
268
- let note;
269
- if (a && state === 'fail') {
270
- state = 'acknowledged';
271
- note = `accepted by ${a.accepted_by ?? 'unknown'}${a.reason ? `: ${a.reason}` : ''}`;
272
- if (a.review_by && new Date(a.review_by) < now) note += ` [review overdue since ${a.review_by}]`;
264
+ const blocking = Boolean(f.blocking || c.severity === 'block');
265
+ const entries = ack.filter((x) => x.check === f.id);
266
+ const a = entries.length ? applyAcknowledgements(f, entries, { blocking, now }) : null;
267
+ if (a?.ignored.length) {
268
+ console.error(` warning: ${a.ignored.length} acknowledgement(s) for ${f.id} ignored; the report says why.`);
273
269
  }
270
+ // The value hashes were for matching entries, just above. Nothing below
271
+ // this line, no report, comment or artifact, gets to see them.
272
+ const locations = (a?.locations ?? f.locations)?.map(({ sha256: _hash, ...l }) => l);
274
273
  return {
275
- ...f, state,
276
- detail: note ? `${f.detail} (${note})` : f.detail,
274
+ ...f,
275
+ state: a?.state ?? f.state,
276
+ detail: a?.detail ?? f.detail,
277
+ ...(locations ? { locations } : {}),
277
278
  weight: c.weight ?? 0,
278
279
  severity: c.severity ?? 'warn',
279
- blocking: f.blocking || c.severity === 'block',
280
+ blocking,
280
281
  policy: c.policy ?? null,
281
282
  };
282
283
  });
@@ -693,6 +694,39 @@ function runPreflight() {
693
694
  return ready || !flags.strict ? 0 : 1;
694
695
  }
695
696
 
697
+ // --- digest -----------------------------------------------------------------
698
+ // The sha256 that narrows an acknowledgement to one matched value. Computed
699
+ // here, on this machine, from the file itself, because no report carries it:
700
+ // a hash of a human-chosen password in a public PR comment is a guess-checker.
701
+ // Reading the value from the file also keeps it out of shell history.
702
+
703
+ function runDigest() {
704
+ const target = positionals[1];
705
+ const m = target?.match(/^(.+?)(?::(\d+))?$/);
706
+ if (!m) {
707
+ console.error('Usage: sws digest <path>[:<line>]');
708
+ return 2;
709
+ }
710
+ const [, rel, lineArg] = m;
711
+ const p = resolve(root, rel);
712
+ if (!existsSync(p)) {
713
+ console.error(`No such file: ${rel}`);
714
+ return 2;
715
+ }
716
+ const hits = scanSecrets(readFileSync(p, 'utf8'))
717
+ .filter((s) => !s.placeholder && (!lineArg || s.line === Number(lineArg)));
718
+ if (!hits.length) {
719
+ console.log(` Nothing the secrets check would report in ${rel}${lineArg ? ` at line ${lineArg}` : ''}.`);
720
+ return 0;
721
+ }
722
+ for (const s of hits) console.log(` ${rel}:${s.line} ${s.label} sha256: ${sha256(s.value)}`);
723
+ console.log('');
724
+ console.log(' Only if a match is NOT a credential, accept just that one, in .sws/acknowledged.yml:');
725
+ console.log(` - check: minweb.no-secrets\n path: ${rel.replace(/^\.\//, '')}\n sha256: <from above>`);
726
+ console.log(' A real credential is rotated, never accepted.');
727
+ return 0;
728
+ }
729
+
696
730
  // --- dispatch ---------------------------------------------------------------
697
731
 
698
732
  switch (cmd) {
@@ -709,6 +743,9 @@ switch (cmd) {
709
743
  case 'perf':
710
744
  process.exit(await perf());
711
745
  break;
746
+ case 'digest':
747
+ process.exit(runDigest());
748
+ break;
712
749
  case 'prior-art':
713
750
  console.log('prior-art scan is not implemented yet. It will index Stanford');
714
751
  console.log('projects on this machine (metadata only) to .sws/prior-art.local.yml,');
@@ -0,0 +1,159 @@
1
+ // Accepted risks, from .sws/acknowledged.yml, and what each one covers.
2
+ //
3
+ // AN ACKNOWLEDGEMENT COVERS WHAT IT NAMES, NOT THE WHOLE CHECK. This used to
4
+ // match on the check id alone and ignore `path`, though the template showed
5
+ // one. For minweb.no-secrets, the one blocking check, that meant accepting a
6
+ // single false positive in a vendored README also hid every real credential
7
+ // committed afterwards, anywhere in the repository. Found on a pilot, where the
8
+ // team noticed the risk and rewrote their fixtures instead.
9
+ //
10
+ // So a finding that reports `locations` (today, minweb.no-secrets) is accepted
11
+ // only location by location:
12
+ //
13
+ // path required for a blocking check. An exact file, a directory ending in
14
+ // `/`, or a glob (`*` within a segment, `**` across segments). A path
15
+ // that matches everything, such as `**`, `**/*` or `**/*.*`, counts
16
+ // as no path: it would bring back the check-wide acceptance this
17
+ // exists to stop.
18
+ // line optional. Narrows the entry to that line, so an edit that moves the
19
+ // match brings it back for a fresh look.
20
+ // sha256 optional. Narrows the entry to one matched value, by the full
21
+ // SHA-256 of that value. `sws digest <path>:<line>` prints it,
22
+ // locally. It is never printed in a report: a hash of a human-chosen
23
+ // password lets anyone holding the report check guesses offline.
24
+ //
25
+ // NOT `value`. An entry that names the matched text is ignored, loudly. The
26
+ // text would be copied into this tracked file, where a value found by the
27
+ // generic pattern no longer matches anything, so once it left its own file the
28
+ // only copy left would sit here unreported.
29
+ //
30
+ // Narrowing is only ever for a false positive. A real credential is rotated,
31
+ // not accepted.
32
+ //
33
+ // Any location no entry covers keeps the finding failing. A finding with no
34
+ // locations is accepted by check id as before, except that a blocking one
35
+ // never is: there is nothing to scope the acceptance to.
36
+
37
+ import { existsSync, readFileSync } from 'node:fs';
38
+ import { createHash } from 'node:crypto';
39
+ import { join } from 'node:path';
40
+ import YAML from 'yaml';
41
+
42
+ export const ACKNOWLEDGED_PATH = join('.sws', 'acknowledged.yml');
43
+
44
+ export function loadAcknowledged(root) {
45
+ const p = join(root, ACKNOWLEDGED_PATH);
46
+ if (!existsSync(p)) return [];
47
+ try {
48
+ const y = YAML.parse(readFileSync(p, 'utf8'));
49
+ return Array.isArray(y) ? y : (y?.accepted ?? []);
50
+ } catch { return []; }
51
+ }
52
+
53
+ // The full hash of a matched value, for comparing against an entry in this
54
+ // process. Never serialised: the CLI strips it from every location before a
55
+ // report is rendered.
56
+ export const sha256 = (s) => createHash('sha256').update(String(s)).digest('hex');
57
+
58
+ // A path that names nothing: empty once its wildcards are taken away, or one
59
+ // that matches file names nobody would ever choose, which is how `**/*.*` and
60
+ // `*.*` give themselves away. A scoped pattern (`**/*.js`, `vendor/**`,
61
+ // `**/README.md`, `src/`) matches neither probe.
62
+ const PROBES = ['sws-probe.q7x', 'sws-probe-a/sws-probe-b/sws-probe.q7x'];
63
+ const namesNothing = (p) => !String(p ?? '').replace(/^\.\//, '').replace(/[*?/]/g, '')
64
+ || PROBES.some((probe) => pathMatches(p, probe));
65
+
66
+ // `path:line looks like a <label>`, for up to `max` locations.
67
+ export function describeLocations(locations, max = 5) {
68
+ const shown = locations.slice(0, max).map((l) =>
69
+ `${l.path}${l.line ? `:${l.line}` : ''}${l.label ? ` looks like a ${l.label}` : ''}`);
70
+ const more = locations.length - shown.length;
71
+ return shown.join('; ') + (more > 0 ? `; and ${more} more` : '');
72
+ }
73
+
74
+ // `**/` is any number of directories, including none; any other `**` is
75
+ // anything at all, so `test/**.json` covers `test/a.json` and `test/b/c.json`,
76
+ // and `vendor/**` everything under vendor/. `*` and `?` stay within one segment.
77
+ export function pathMatches(pattern, path) {
78
+ let p = String(pattern).replace(/^\.\//, '');
79
+ if (p.endsWith('/')) {
80
+ if (!/[*?]/.test(p)) return path.startsWith(p);
81
+ p += '**';
82
+ }
83
+ if (!/[*?]/.test(p)) return path === p;
84
+ const re = p.replace(/[.+^${}()|[\]\\]/g, '\\$&')
85
+ .replace(/\*\*\//g, '\u0000')
86
+ .replace(/\*\*/g, '\u0001')
87
+ .replace(/\*/g, '[^/]*')
88
+ .replace(/\?/g, '[^/]')
89
+ .replace(/\u0000/g, '(?:.*/)?')
90
+ .replace(/\u0001/g, '.*');
91
+ return new RegExp(`^${re}$`).test(path);
92
+ }
93
+
94
+ function covers(entry, loc) {
95
+ if (!pathMatches(entry.path, loc.path)) return false;
96
+ if (entry.line != null && Number(entry.line) !== loc.line) return false;
97
+ if (entry.sha256 != null && String(entry.sha256).toLowerCase() !== loc.sha256) return false;
98
+ return true;
99
+ }
100
+
101
+ function acceptedBy(entries, now) {
102
+ const by = [...new Set(entries.map((a) => a.accepted_by ?? 'unknown'))].join(', ');
103
+ const reasons = [...new Set(entries.map((a) => a.reason).filter(Boolean))];
104
+ let note = `accepted by ${by}${reasons.length === 1 ? `: ${reasons[0]}` : ''}`;
105
+ const overdue = entries.map((a) => a.review_by).filter((d) => d && new Date(d) < now).sort();
106
+ if (overdue.length) note += ` [review overdue since ${overdue[0]}]`;
107
+ return note;
108
+ }
109
+
110
+ /**
111
+ * Apply the entries for one check to its finding.
112
+ *
113
+ * Returns the finding's new `state` and `detail`, plus `ignored`: entries that
114
+ * were not applied because a blocking check was accepted with no path. Those
115
+ * are said out loud in the detail, never dropped quietly, because someone
116
+ * wrote them believing they worked.
117
+ */
118
+ export function applyAcknowledgements(finding, entries, { blocking = false, now = new Date() } = {}) {
119
+ const everywhere = blocking ? entries.filter((a) => namesNothing(a.path)) : [];
120
+ const byValue = entries.filter((a) => a.value != null && !everywhere.includes(a));
121
+ const ignored = [...everywhere, ...byValue];
122
+ const usable = entries.filter((a) => !ignored.includes(a));
123
+ const n = (k) => `${k} acknowledgement${k > 1 ? 's' : ''} ignored`;
124
+ const warn = [
125
+ everywhere.length && ` (${n(everywhere.length)}: an entry for ${finding.id} must name a file or directory, not every path, because accepting a blocking check everywhere would hide the next real one)`,
126
+ byValue.length && ` (${n(byValue.length)}: \`value:\` would copy the matched text into ${ACKNOWLEDGED_PATH}; narrow by \`sha256:\` from \`sws digest <path>:<line>\` instead)`,
127
+ ].filter(Boolean).join('');
128
+
129
+ if (finding.state !== 'fail' || !usable.length) {
130
+ return { state: finding.state, detail: finding.detail + warn, ignored };
131
+ }
132
+
133
+ const locations = finding.locations ?? [];
134
+ if (!locations.length) {
135
+ // Nothing to scope to. A non-blocking finding is accepted by id, as it always
136
+ // was; a blocking one stays a failure.
137
+ if (blocking) return { state: 'fail', detail: finding.detail + warn, ignored };
138
+ return { state: 'acknowledged', detail: `${finding.detail} (${acceptedBy(usable, now)})${warn}`, ignored };
139
+ }
140
+
141
+ const used = new Set();
142
+ const open = locations.filter((loc) => {
143
+ // A non-blocking entry without a path still covers the whole check.
144
+ const hit = usable.find((a) => (!a.path && !blocking) || (a.path && covers(a, loc)));
145
+ if (hit) used.add(hit);
146
+ return !hit;
147
+ });
148
+
149
+ if (!open.length) {
150
+ return { state: 'acknowledged', detail: `${finding.detail} (${acceptedBy([...used], now)})${warn}`, ignored };
151
+ }
152
+ const accepted = locations.length - open.length;
153
+ return {
154
+ state: 'fail',
155
+ detail: describeLocations(open) + (accepted ? ` (${accepted} other match${accepted > 1 ? 'es' : ''} accepted in ${ACKNOWLEDGED_PATH})` : '') + warn,
156
+ locations: open,
157
+ ignored,
158
+ };
159
+ }
@@ -19,6 +19,7 @@ import { RESULTS_PATH as AXE_RESULTS_PATH, SCHEMA as AXE_SCHEMA } from './axe.mj
19
19
  import { RESULTS_PATH as PERF_RESULTS_PATH, SCHEMA as PERF_SCHEMA } from './perf.mjs';
20
20
  import { RESULTS_PATH as STATE_RESULTS_PATH, SCHEMA as STATE_SCHEMA } from './states.mjs';
21
21
  import { newestMtime } from './browser.mjs';
22
+ import { describeLocations, sha256 } from './acknowledged.mjs';
22
23
 
23
24
  const read = (p) => readFileSync(p, 'utf8');
24
25
  const readYaml = (p) => YAML.parse(read(p));
@@ -749,51 +750,169 @@ export function perf({ root, dist, html }) {
749
750
  // --------------------------------------------------------------------------
750
751
 
751
752
  const SECRET_PATTERNS = [
752
- [/AKIA[0-9A-Z]{16}/, 'AWS access key id'],
753
- [/gh[pousr]_[A-Za-z0-9]{36,}/, 'GitHub token'],
754
- [/sk_live_[A-Za-z0-9]{20,}/, 'Stripe live secret key'],
755
- [/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/, 'private key'],
756
- [/eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\./, 'JWT'],
757
- [/(?:api[_-]?key|secret|password|token)\s*[:=]\s*['"][A-Za-z0-9!@#$%^&*_\-]{16,}['"]/i, 'hardcoded credential'],
753
+ [/AKIA[0-9A-Z]{16}/g, 'AWS access key id'],
754
+ [/gh[pousr]_[A-Za-z0-9]{36,}/g, 'GitHub token'],
755
+ [/sk_live_[A-Za-z0-9]{20,}/g, 'Stripe live secret key'],
756
+ [/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/g, 'private key'],
757
+ // Header, payload AND signature: two tokens that differ only in their
758
+ // signature are two credentials, and must not share a hash.
759
+ [/eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]*/g, 'JWT'],
760
+ // The quoted value is captured, so a placeholder can be told from a key. The
761
+ // optional quote after the name catches a JSON key, `"secret": "..."`, which
762
+ // the pattern used to miss entirely.
763
+ [/(?:api[_-]?key|secret|password|token)['"]?\s*[:=]\s*['"]([A-Za-z0-9!@#$%^&*_\-]{16,})['"]/gi, 'hardcoded credential'],
758
764
  ];
759
765
 
766
+ // Values that are plainly not credentials, so a usage example or a test fixture
767
+ // does not block a deploy. Both came from a pilot: `'storyblok-user-access-token'`
768
+ // in a vendored README, and a fixture that wrapped the word `key` in a PEM
769
+ // header. Deliberately narrow. Anything with digits, mixed case or no telling
770
+ // word still counts, because a false pass here is the one irreversible mistake.
771
+ // (A value in angle brackets, `'<management-token>'`, never matched at all.)
772
+ //
773
+ // The telling word must be a whole word of the phrase. Matching inside words
774
+ // let `monkey-horse-battery-staple` and `secretary-desk-lamp-blue`, real
775
+ // passphrases, through as placeholders.
776
+ const PLACEHOLDER_WORDS = new Set(['token', 'key', 'secret', 'password', 'passwd', 'example', 'placeholder',
777
+ 'dummy', 'sample', 'fake', 'your', 'changeme', 'redacted']);
778
+
779
+ // (A private key's placeholder rule is in scanSecrets, which knows its block.)
780
+ function isPlaceholder(label, value) {
781
+ if (label !== 'hardcoded credential') return false;
782
+ if (/^(.)\1+$/.test(value)) return true; // xxxxxxxxxxxxxxxx
783
+ return /^[a-z]+(?:[-_][a-z]+)+$/.test(value) // storyblok-user-access-token
784
+ && value.split(/[-_]/).some((w) => PLACEHOLDER_WORDS.has(w));
785
+ }
786
+
787
+ // Every match in one file's text, with the WHOLE credential each one stands for.
788
+ //
789
+ // The span matters twice. It is what gets hashed, so a private key is its whole
790
+ // block, not the header every key of that type shares, and a quoted value is
791
+ // all of it, not a prefix another pattern happened to match. And matches are
792
+ // folded only when their spans are IDENTICAL (`api_key: 'ghp_...'` is one
793
+ // credential). Folding any overlap let one match hide another three ways: a
794
+ // placeholder hid the real value after it on a line, a BEGIN...END span hid a
795
+ // token written between the two, and an AWS-shaped prefix hid the rest of a
796
+ // longer secret, so accepting the prefix accepted whatever followed it.
797
+ export function scanSecrets(body) {
798
+ const found = [];
799
+ for (const [re, label] of SECRET_PATTERNS) {
800
+ for (const m of body.matchAll(re)) {
801
+ let start = m.index;
802
+ let end = m.index + m[0].length;
803
+ let placeholder;
804
+ if (m[1] !== undefined) {
805
+ // The quoted value sits at the end of the match, before its quote.
806
+ end -= 1;
807
+ start = end - m[1].length;
808
+ } else if (label === 'private key') {
809
+ // Only up to the next header, so one block never takes another's footer.
810
+ const rest = body.slice(end);
811
+ const next = rest.search(/-----BEGIN [A-Z ]*PRIVATE KEY-----/);
812
+ const k = keyBlock(next === -1 ? rest : rest.slice(0, next));
813
+ end += k.end;
814
+ // A placeholder only when the footer directly follows too little
815
+ // material to be a key: the pilot's header around the word `key`.
816
+ // Anything else counts, failing closed: a key missing its footer is
817
+ // still the key, and a header with code after it is reported, as main
818
+ // always reported every header.
819
+ placeholder = k.terminated && k.material < 64;
820
+ }
821
+ const value = body.slice(start, end);
822
+ placeholder ??= isPlaceholder(label, value);
823
+ if (found.some((x) => (x.start === start && x.end === end)
824
+ || (placeholder && start < x.end && x.start < end))) continue;
825
+ found.push({
826
+ start, end, label, value, placeholder,
827
+ line: body.slice(0, start).split('\n').length,
828
+ });
829
+ }
830
+ }
831
+ return found.sort((a, b) => a.start - b.start);
832
+ }
833
+
834
+ // What follows a private-key header, up to the next header: its key material,
835
+ // and its footer if that comes straight after.
836
+ //
837
+ // Key material is base64 and nothing else, unit by unit: a unit is a line, or a
838
+ // piece of a string literal between `\n` escapes, with the glue code puts round
839
+ // key material taken off (quotes, `+`, commas, a trailing `\`, indentation).
840
+ // The first unit that is anything else ends it, so a block can never take in
841
+ // code: a constant `'-----BEGIN ...'`, then a token, then `'-----END ...'`, is
842
+ // a header and a separate token, not one key that hides the token.
843
+ const KEY_GLUE = /^[\s'"`+,\\]+|[\s'"`+,\\]+$/g;
844
+
845
+ function keyBlock(rest) {
846
+ const units = /\\r\\n|\\n|\r?\n/g;
847
+ let pos = 0;
848
+ let end = 0;
849
+ let material = 0;
850
+ for (;;) {
851
+ units.lastIndex = pos;
852
+ const sep = units.exec(rest);
853
+ const raw = rest.slice(pos, sep ? sep.index : rest.length);
854
+ const core = raw.replace(KEY_GLUE, '');
855
+ const footer = core.match(/^-----END [A-Z ]*PRIVATE KEY-----/);
856
+ if (footer) return { end: pos + raw.indexOf(footer[0]) + footer[0].length, material, terminated: true };
857
+ if (core && !/^[A-Za-z0-9+/=]+$/.test(core)) break;
858
+ if (core) {
859
+ material += core.length;
860
+ end = pos + raw.lastIndexOf(core) + core.length;
861
+ }
862
+ if (!sep) break;
863
+ pos = sep.index + sep[0].length;
864
+ }
865
+ return { end, material, terminated: false };
866
+ }
867
+
760
868
  export function secrets({ root }) {
761
869
  let files;
762
870
  try {
763
- files = execFileSync('git', ['ls-files'], { cwd: root, encoding: 'utf8' })
764
- .split('\n').filter(Boolean);
871
+ // -z, because without it git quotes any path with a non-ASCII byte, and a
872
+ // quoted path never exists on disk, so `docs/café.js` was never read.
873
+ files = execFileSync('git', ['ls-files', '-z'], { cwd: root, encoding: 'utf8' })
874
+ .split('\0').filter(Boolean);
765
875
  } catch {
766
876
  return [dunno('minweb.no-secrets', 'not a git repository, or git unavailable; cannot enumerate tracked files')];
767
877
  }
768
878
 
879
+ // EVERY match, not the first per file. Stopping at the first meant fixing one
880
+ // only revealed the next, one doctor run at a time. Each becomes a location,
881
+ // which is what an acknowledgement is scoped to. The value's hash is for
882
+ // matching an entry in this process only, and is stripped before any report
883
+ // is written: a hash of a human-chosen password is a guess-checker.
769
884
  const SKIP = /\.(png|jpe?g|gif|webp|avif|ico|woff2?|ttf|otf|eot|pdf|zip|mp4|webm)$/i;
770
- const hits = [];
885
+ const locations = [];
886
+ const placeholders = [];
771
887
  for (const f of files) {
772
888
  if (SKIP.test(f) || f.includes('node_modules')) continue;
773
889
  const p = join(root, f);
774
890
  if (!existsSync(p) || statSync(p).size > 512 * 1024) continue;
775
- const body = read(p);
776
- for (const [re, label] of SECRET_PATTERNS) {
777
- const m = body.match(re);
778
- if (m) {
779
- const line = body.slice(0, m.index).split('\n').length;
780
- hits.push(`${f}:${line} looks like a ${label}`);
781
- break;
782
- }
891
+ for (const s of scanSecrets(read(p))) {
892
+ if (s.placeholder) placeholders.push(`${f}:${s.line}`);
893
+ else locations.push({ path: f, line: s.line, label: s.label, sha256: sha256(s.value) });
783
894
  }
784
895
  }
785
896
 
786
- if (!hits.length) return [ok('minweb.no-secrets', `${files.length} tracked files scanned, nothing found`)];
897
+ const skipped = placeholders.length
898
+ ? ` (${placeholders.length} placeholder${placeholders.length > 1 ? 's' : ''} skipped: ${placeholders.slice(0, 3).join(', ')}${placeholders.length > 3 ? ', ...' : ''})`
899
+ : '';
900
+ if (!locations.length) {
901
+ return [ok('minweb.no-secrets', `${files.length} tracked files scanned, nothing found${skipped}`)];
902
+ }
787
903
 
788
904
  return [{
789
905
  id: 'minweb.no-secrets',
790
906
  state: 'fail',
791
907
  blocking: true,
792
- detail: hits.slice(0, 5).join('; '),
908
+ locations,
909
+ detail: describeLocations(locations) + skipped,
793
910
  fix: [
794
911
  'ROTATE THE CREDENTIAL NOW. It is already in git history and blocking a deploy does not un-leak it.',
795
912
  'Then remove it from history (git filter-repo or BFG), then force-push.',
796
913
  'Then move the value into Vault or your host\'s environment settings.',
914
+ 'Only if a match is NOT a credential: accept that one location in .sws/acknowledged.yml by its path,',
915
+ 'narrowed with `sws digest <path>:<line>`, never the whole check.',
797
916
  ].join(' '),
798
917
  }];
799
918
  }
@@ -368,6 +368,15 @@ const ACKNOWLEDGED_TEMPLATE = `# Accepted risks.
368
368
  # It then moves out of the nag and into an "accepted risks" section of the
369
369
  # report, and it still counts toward the score with the total annotated.
370
370
  #
371
+ # An entry covers what it names, not the whole check. Where a check reports
372
+ # where it found something (minweb.no-secrets does), \`path\` scopes the entry
373
+ # to that file, a directory ending in \`/\`, or a glob such as \`test/fixtures/**\`,
374
+ # and \`line\` or \`sha256\` narrow it further (\`sws digest <path>:<line>\`
375
+ # prints the sha256, locally). Anything not covered still fails. An entry for
376
+ # minweb.no-secrets whose \`path\` is missing or matches everything (\`**\`) is
377
+ # ignored: accept a false positive in one file, never the check. A real
378
+ # credential is rotated, not accepted here.
379
+ #
371
380
  # This is the same shape a MinSec temporary exception takes, so the record is
372
381
  # useful beyond this tool. Expired review dates resurface once.
373
382
  #
@@ -377,6 +386,13 @@ const ACKNOWLEDGED_TEMPLATE = `# Accepted risks.
377
386
  # accepted_by: you@stanford.edu
378
387
  # date: 2026-08-11
379
388
  # review_by: 2026-11-10
389
+ #
390
+ # - check: minweb.no-secrets
391
+ # path: vendor/sdk/README.md
392
+ # reason: Usage example in a vendored README, not a credential
393
+ # accepted_by: you@stanford.edu
394
+ # date: 2026-10-23
395
+ # review_by: 2027-01-23
380
396
 
381
397
  []
382
398
  `;
@@ -126,6 +126,22 @@ It then moves out of the nag and into an "accepted risks" section. This is the
126
126
  same shape a MinSec temporary exception takes, so the record is useful beyond
127
127
  this tool. Resurface expired `review_by` dates once, kindly, without lecturing.
128
128
 
129
+ **An entry covers what it names, not the whole check.** Where a check reports
130
+ locations (`minweb.no-secrets` does), `path` scopes the entry to a file, a
131
+ directory ending in `/`, or a glob, and `line` or `sha256` narrow it further.
132
+ Anything it does not cover still fails. For `minweb.no-secrets` a `path` is
133
+ required, and an entry without one, or with one that matches everything
134
+ (`**`), is ignored and reported: accepting the check everywhere would hide the
135
+ next real credential. **Only ever accept a false positive there.** A real
136
+ credential is rotated, never acknowledged. For a fixture, prefer a value the
137
+ patterns do not match (`'<token>'`) to an entry.
138
+
139
+ To narrow an entry to one value, run `sws digest <path>:<line>` and copy the
140
+ `sha256` it prints. Never write the value itself into the file: an entry with
141
+ `value:` is ignored and reported, because the text would sit in a tracked file
142
+ that nothing scans it in. No report shows the hash either, because a hash of a
143
+ weak password lets anyone holding the report check guesses.
144
+
129
145
  **Never edit `acceptance.yml` or a fragment to make a project pass.** Fragments
130
146
  change when upstream changes, with a date. If a criterion genuinely seems wrong,
131
147
  say so and let a person decide.
@@ -461,6 +461,22 @@ criteria:
461
461
  un-leak it, (2) then clean the history, (3) then push again. A failure
462
462
  that only says "secret detected" teaches nothing and gets worked around.
463
463
 
464
+ Every match in every tracked file is reported as a location: path and
465
+ line, never the value, and never a hash of it, because a hash of a weak
466
+ password is a guess-checker. Only matches with identical spans fold, so
467
+ no match hides another: not a placeholder, not a BEGIN...END pair, not a
468
+ prefix. A private key is its base64 block and nothing else, a JWT
469
+ includes its signature, and a key whose footer is missing still counts:
470
+ anyone holding it can add the footer back. An acknowledgement must
471
+ name a `path` and covers only the locations it matches, so accepting a
472
+ false positive in one file never hides a credential in another; an
473
+ entry whose path is missing or matches everything (`**`) is ignored and
474
+ reported. `line`, or a `sha256` from `sws digest`, narrows it further.
475
+ Values that plainly are not credentials are skipped and listed: a
476
+ hyphenated phrase with a whole word naming what it stands for
477
+ (`storyblok-user-access-token`), a single repeated character, or a PEM
478
+ header with no key body.
479
+
464
480
  - id: minweb.https-only
465
481
  requires: >
466
482
  No hardcoded http:// URLs to Stanford or first-party resources. Deploy