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

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.2",
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 && node scripts/validate-layouts.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));
@@ -60,6 +61,44 @@ function installed(root, name) {
60
61
  return existsSync(p) ? JSON.parse(read(p)) : null;
61
62
  }
62
63
 
64
+ // The project's own source files, relative to root and sorted shallowest first,
65
+ // wherever the project keeps them. Recipes disagree on the layout: Astro puts
66
+ // everything under src/, Next keeps styles/ and app/ at the root or under src/.
67
+ // A check that guesses one folder reports a fail on every project laid out the
68
+ // other way, so source checks search the whole project instead.
69
+ //
70
+ // Through git when it can, tracked files plus untracked ones git would not
71
+ // ignore, so .gitignore decides what is build output and no list of folder
72
+ // names goes stale. node_modules is never source, ignored or not. Outside a
73
+ // repository, walk the tree and skip node_modules, dot-folders and the usual
74
+ // build output.
75
+ const NOT_SOURCE = new Set(['node_modules', 'dist', '_site', 'build', 'out']);
76
+
77
+ export function projectFiles(root) {
78
+ let files;
79
+ try {
80
+ files = execFileSync('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard'],
81
+ { cwd: root, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] })
82
+ .split('\0').filter(Boolean)
83
+ .filter((f) => !f.split('/').includes('node_modules'))
84
+ // A file deleted but not yet staged is still listed.
85
+ .filter((f) => existsSync(join(root, f)));
86
+ } catch {
87
+ files = [];
88
+ (function walk(d) {
89
+ if (!existsSync(d)) return;
90
+ for (const n of readdirSync(d)) {
91
+ const p = join(d, n);
92
+ if (statSync(p).isDirectory()) {
93
+ if (!n.startsWith('.') && !NOT_SOURCE.has(n)) walk(p);
94
+ } else files.push(relative(root, p));
95
+ }
96
+ })(root);
97
+ }
98
+ const depth = (f) => f.split('/').length;
99
+ return files.sort((a, b) => depth(a) - depth(b) || a.localeCompare(b));
100
+ }
101
+
63
102
  // --------------------------------------------------------------------------
64
103
  // footer: reads the contract, never hardcodes the link set
65
104
  // --------------------------------------------------------------------------
@@ -357,17 +396,10 @@ export function decanter({ root }) {
357
396
  'Dead package: supports neither current Astro nor Tailwind 4. Use @tailwindcss/vite.')
358
397
  : ok('decanter.no-dead-integration', '@astrojs/tailwind absent'));
359
398
 
360
- // Entry CSS: redundant tailwind import, and the @source myth.
361
- const cssFiles = [];
362
- (function walk(d) {
363
- if (!existsSync(d)) return;
364
- for (const n of readdirSync(d)) {
365
- const p = join(d, n);
366
- if (statSync(p).isDirectory()) { if (n !== 'node_modules') walk(p); }
367
- else if (n.endsWith('.css')) cssFiles.push(p);
368
- }
369
- })(join(root, 'src'));
370
-
399
+ // Entry CSS: redundant tailwind import, and the @source myth. Searched across
400
+ // the project, because Astro keeps it in src/styles/ and Next in styles/ or
401
+ // app/, at the root or under src/.
402
+ const cssFiles = projectFiles(root).filter((f) => f.endsWith('.css')).map((f) => join(root, f));
371
403
  const entry = cssFiles.find((f) => /@import\s+['"]decanter['"]/.test(read(f)));
372
404
  if (!entry) {
373
405
  out.push(d ? bad('decanter.entry-css', 'no CSS file imports decanter',
@@ -749,51 +781,169 @@ export function perf({ root, dist, html }) {
749
781
  // --------------------------------------------------------------------------
750
782
 
751
783
  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'],
784
+ [/AKIA[0-9A-Z]{16}/g, 'AWS access key id'],
785
+ [/gh[pousr]_[A-Za-z0-9]{36,}/g, 'GitHub token'],
786
+ [/sk_live_[A-Za-z0-9]{20,}/g, 'Stripe live secret key'],
787
+ [/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/g, 'private key'],
788
+ // Header, payload AND signature: two tokens that differ only in their
789
+ // signature are two credentials, and must not share a hash.
790
+ [/eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]*/g, 'JWT'],
791
+ // The quoted value is captured, so a placeholder can be told from a key. The
792
+ // optional quote after the name catches a JSON key, `"secret": "..."`, which
793
+ // the pattern used to miss entirely.
794
+ [/(?:api[_-]?key|secret|password|token)['"]?\s*[:=]\s*['"]([A-Za-z0-9!@#$%^&*_\-]{16,})['"]/gi, 'hardcoded credential'],
758
795
  ];
759
796
 
797
+ // Values that are plainly not credentials, so a usage example or a test fixture
798
+ // does not block a deploy. Both came from a pilot: `'storyblok-user-access-token'`
799
+ // in a vendored README, and a fixture that wrapped the word `key` in a PEM
800
+ // header. Deliberately narrow. Anything with digits, mixed case or no telling
801
+ // word still counts, because a false pass here is the one irreversible mistake.
802
+ // (A value in angle brackets, `'<management-token>'`, never matched at all.)
803
+ //
804
+ // The telling word must be a whole word of the phrase. Matching inside words
805
+ // let `monkey-horse-battery-staple` and `secretary-desk-lamp-blue`, real
806
+ // passphrases, through as placeholders.
807
+ const PLACEHOLDER_WORDS = new Set(['token', 'key', 'secret', 'password', 'passwd', 'example', 'placeholder',
808
+ 'dummy', 'sample', 'fake', 'your', 'changeme', 'redacted']);
809
+
810
+ // (A private key's placeholder rule is in scanSecrets, which knows its block.)
811
+ function isPlaceholder(label, value) {
812
+ if (label !== 'hardcoded credential') return false;
813
+ if (/^(.)\1+$/.test(value)) return true; // xxxxxxxxxxxxxxxx
814
+ return /^[a-z]+(?:[-_][a-z]+)+$/.test(value) // storyblok-user-access-token
815
+ && value.split(/[-_]/).some((w) => PLACEHOLDER_WORDS.has(w));
816
+ }
817
+
818
+ // Every match in one file's text, with the WHOLE credential each one stands for.
819
+ //
820
+ // The span matters twice. It is what gets hashed, so a private key is its whole
821
+ // block, not the header every key of that type shares, and a quoted value is
822
+ // all of it, not a prefix another pattern happened to match. And matches are
823
+ // folded only when their spans are IDENTICAL (`api_key: 'ghp_...'` is one
824
+ // credential). Folding any overlap let one match hide another three ways: a
825
+ // placeholder hid the real value after it on a line, a BEGIN...END span hid a
826
+ // token written between the two, and an AWS-shaped prefix hid the rest of a
827
+ // longer secret, so accepting the prefix accepted whatever followed it.
828
+ export function scanSecrets(body) {
829
+ const found = [];
830
+ for (const [re, label] of SECRET_PATTERNS) {
831
+ for (const m of body.matchAll(re)) {
832
+ let start = m.index;
833
+ let end = m.index + m[0].length;
834
+ let placeholder;
835
+ if (m[1] !== undefined) {
836
+ // The quoted value sits at the end of the match, before its quote.
837
+ end -= 1;
838
+ start = end - m[1].length;
839
+ } else if (label === 'private key') {
840
+ // Only up to the next header, so one block never takes another's footer.
841
+ const rest = body.slice(end);
842
+ const next = rest.search(/-----BEGIN [A-Z ]*PRIVATE KEY-----/);
843
+ const k = keyBlock(next === -1 ? rest : rest.slice(0, next));
844
+ end += k.end;
845
+ // A placeholder only when the footer directly follows too little
846
+ // material to be a key: the pilot's header around the word `key`.
847
+ // Anything else counts, failing closed: a key missing its footer is
848
+ // still the key, and a header with code after it is reported, as main
849
+ // always reported every header.
850
+ placeholder = k.terminated && k.material < 64;
851
+ }
852
+ const value = body.slice(start, end);
853
+ placeholder ??= isPlaceholder(label, value);
854
+ if (found.some((x) => (x.start === start && x.end === end)
855
+ || (placeholder && start < x.end && x.start < end))) continue;
856
+ found.push({
857
+ start, end, label, value, placeholder,
858
+ line: body.slice(0, start).split('\n').length,
859
+ });
860
+ }
861
+ }
862
+ return found.sort((a, b) => a.start - b.start);
863
+ }
864
+
865
+ // What follows a private-key header, up to the next header: its key material,
866
+ // and its footer if that comes straight after.
867
+ //
868
+ // Key material is base64 and nothing else, unit by unit: a unit is a line, or a
869
+ // piece of a string literal between `\n` escapes, with the glue code puts round
870
+ // key material taken off (quotes, `+`, commas, a trailing `\`, indentation).
871
+ // The first unit that is anything else ends it, so a block can never take in
872
+ // code: a constant `'-----BEGIN ...'`, then a token, then `'-----END ...'`, is
873
+ // a header and a separate token, not one key that hides the token.
874
+ const KEY_GLUE = /^[\s'"`+,\\]+|[\s'"`+,\\]+$/g;
875
+
876
+ function keyBlock(rest) {
877
+ const units = /\\r\\n|\\n|\r?\n/g;
878
+ let pos = 0;
879
+ let end = 0;
880
+ let material = 0;
881
+ for (;;) {
882
+ units.lastIndex = pos;
883
+ const sep = units.exec(rest);
884
+ const raw = rest.slice(pos, sep ? sep.index : rest.length);
885
+ const core = raw.replace(KEY_GLUE, '');
886
+ const footer = core.match(/^-----END [A-Z ]*PRIVATE KEY-----/);
887
+ if (footer) return { end: pos + raw.indexOf(footer[0]) + footer[0].length, material, terminated: true };
888
+ if (core && !/^[A-Za-z0-9+/=]+$/.test(core)) break;
889
+ if (core) {
890
+ material += core.length;
891
+ end = pos + raw.lastIndexOf(core) + core.length;
892
+ }
893
+ if (!sep) break;
894
+ pos = sep.index + sep[0].length;
895
+ }
896
+ return { end, material, terminated: false };
897
+ }
898
+
760
899
  export function secrets({ root }) {
761
900
  let files;
762
901
  try {
763
- files = execFileSync('git', ['ls-files'], { cwd: root, encoding: 'utf8' })
764
- .split('\n').filter(Boolean);
902
+ // -z, because without it git quotes any path with a non-ASCII byte, and a
903
+ // quoted path never exists on disk, so `docs/café.js` was never read.
904
+ files = execFileSync('git', ['ls-files', '-z'], { cwd: root, encoding: 'utf8' })
905
+ .split('\0').filter(Boolean);
765
906
  } catch {
766
907
  return [dunno('minweb.no-secrets', 'not a git repository, or git unavailable; cannot enumerate tracked files')];
767
908
  }
768
909
 
910
+ // EVERY match, not the first per file. Stopping at the first meant fixing one
911
+ // only revealed the next, one doctor run at a time. Each becomes a location,
912
+ // which is what an acknowledgement is scoped to. The value's hash is for
913
+ // matching an entry in this process only, and is stripped before any report
914
+ // is written: a hash of a human-chosen password is a guess-checker.
769
915
  const SKIP = /\.(png|jpe?g|gif|webp|avif|ico|woff2?|ttf|otf|eot|pdf|zip|mp4|webm)$/i;
770
- const hits = [];
916
+ const locations = [];
917
+ const placeholders = [];
771
918
  for (const f of files) {
772
919
  if (SKIP.test(f) || f.includes('node_modules')) continue;
773
920
  const p = join(root, f);
774
921
  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
- }
922
+ for (const s of scanSecrets(read(p))) {
923
+ if (s.placeholder) placeholders.push(`${f}:${s.line}`);
924
+ else locations.push({ path: f, line: s.line, label: s.label, sha256: sha256(s.value) });
783
925
  }
784
926
  }
785
927
 
786
- if (!hits.length) return [ok('minweb.no-secrets', `${files.length} tracked files scanned, nothing found`)];
928
+ const skipped = placeholders.length
929
+ ? ` (${placeholders.length} placeholder${placeholders.length > 1 ? 's' : ''} skipped: ${placeholders.slice(0, 3).join(', ')}${placeholders.length > 3 ? ', ...' : ''})`
930
+ : '';
931
+ if (!locations.length) {
932
+ return [ok('minweb.no-secrets', `${files.length} tracked files scanned, nothing found${skipped}`)];
933
+ }
787
934
 
788
935
  return [{
789
936
  id: 'minweb.no-secrets',
790
937
  state: 'fail',
791
938
  blocking: true,
792
- detail: hits.slice(0, 5).join('; '),
939
+ locations,
940
+ detail: describeLocations(locations) + skipped,
793
941
  fix: [
794
942
  'ROTATE THE CREDENTIAL NOW. It is already in git history and blocking a deploy does not un-leak it.',
795
943
  'Then remove it from history (git filter-repo or BFG), then force-push.',
796
944
  'Then move the value into Vault or your host\'s environment settings.',
945
+ 'Only if a match is NOT a credential: accept that one location in .sws/acknowledged.yml by its path,',
946
+ 'narrowed with `sws digest <path>:<line>`, never the whole check.',
797
947
  ].join(' '),
798
948
  }];
799
949
  }
@@ -1299,18 +1449,13 @@ export function next({ root, html }) {
1299
1449
  : ok('next.no-tailwind-config', 'no tailwind JS config'));
1300
1450
 
1301
1451
  // metadataBase is the Next equivalent of Astro's `site`, and the same miss.
1302
- const layouts = [];
1303
- (function walk(d) {
1304
- if (!existsSync(d)) return;
1305
- for (const n of readdirSync(d)) {
1306
- const p = join(d, n);
1307
- if (statSync(p).isDirectory()) { if (n !== 'node_modules') walk(p); }
1308
- else if (/^layout\.(t|j)sx?$/.test(n)) layouts.push(p);
1309
- }
1310
- })(join(root, 'app'));
1452
+ // Next takes the App Router from app/ or, when that is absent, src/app/.
1453
+ const layouts = projectFiles(root)
1454
+ .filter((f) => /^(src\/)?app\/(.+\/)?layout\.(t|j)sx?$/.test(f))
1455
+ .map((f) => join(root, f));
1311
1456
 
1312
1457
  if (!layouts.length) {
1313
- out.push(dunno('next.metadata-base', 'no app/layout file found; App Router expected'));
1458
+ out.push(dunno('next.metadata-base', 'no layout file in app/ or src/app/; App Router expected'));
1314
1459
  } else {
1315
1460
  const hit = layouts.find((f) => /metadataBase/.test(read(f)));
1316
1461
  out.push(hit
@@ -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