actions-warden 0.3.0 → 0.6.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.
Files changed (78) hide show
  1. package/AGENTS.md +60 -12
  2. package/CONTRIBUTING.md +6 -2
  3. package/README.md +180 -58
  4. package/RELEASING.md +3 -2
  5. package/SECURITY.md +23 -8
  6. package/docs/AI-AGENTS.md +125 -29
  7. package/docs/CLI.md +346 -69
  8. package/docs/CONFIGURATION.md +34 -11
  9. package/docs/DEVELOPMENT.md +114 -18
  10. package/docs/GITHUB-ACTION.md +163 -29
  11. package/docs/JAVASCRIPT-API.md +177 -11
  12. package/docs/OUTPUTS.md +408 -40
  13. package/docs/README.md +1 -1
  14. package/examples/README.md +21 -0
  15. package/examples/baseline-adoption/README.md +79 -0
  16. package/examples/baseline-adoption/github-actions.yml +56 -0
  17. package/examples/baseline-adoption/policy.yml +7 -0
  18. package/examples/ci-violation-reporting/README.md +82 -0
  19. package/examples/ci-violation-reporting/github-actions.yml +55 -0
  20. package/examples/ci-violation-reporting/policy.yml +7 -0
  21. package/examples/ci-violation-reporting/violating-workflow.yml +17 -0
  22. package/examples/csv-reporting/README.md +50 -0
  23. package/examples/csv-reporting/github-actions.yml +59 -0
  24. package/examples/html-organization-report/README.md +35 -0
  25. package/examples/html-organization-report/github-actions.yml +61 -0
  26. package/examples/notifications/README.md +67 -0
  27. package/examples/notifications/github-actions.yml +163 -0
  28. package/examples/org-scan.yml +24 -5
  29. package/examples/sarif-code-scanning/README.md +42 -0
  30. package/examples/sarif-code-scanning/github-actions.yml +66 -0
  31. package/examples/upgrade-pr.yml +1 -1
  32. package/llms.txt +14 -5
  33. package/package.json +8 -4
  34. package/skills/actions-warden/SKILL.md +91 -39
  35. package/src/action.js +353 -187
  36. package/src/cli.js +416 -209
  37. package/src/commands/audit.js +17 -30
  38. package/src/commands/org-scan.js +452 -286
  39. package/src/commands/pin.js +9 -5
  40. package/src/commands/report.js +7 -2
  41. package/src/commands/upgrade.js +9 -5
  42. package/src/commands/verify.js +24 -4
  43. package/src/index.js +5 -1
  44. package/src/lib/action-summary.js +656 -0
  45. package/src/lib/annotations.js +4 -6
  46. package/src/lib/baseline.js +11 -1
  47. package/src/lib/config.js +10 -5
  48. package/src/lib/destination.js +98 -0
  49. package/src/lib/execution.js +5 -1
  50. package/src/lib/formats/csv.js +125 -0
  51. package/src/lib/formats/html.js +394 -0
  52. package/src/lib/formats/json.js +17 -0
  53. package/src/lib/formats/sarif.js +229 -0
  54. package/src/lib/formats/text.js +30 -0
  55. package/src/lib/formats/toon.js +50 -0
  56. package/src/lib/formatter.js +25 -192
  57. package/src/lib/github-org.js +208 -102
  58. package/src/lib/org-artifacts.js +211 -0
  59. package/src/lib/org-checkpoint.js +159 -35
  60. package/src/lib/org-progress.js +182 -4
  61. package/src/lib/org-report-comparison.js +505 -0
  62. package/src/lib/org-report-directory.js +251 -0
  63. package/src/lib/org-report.js +223 -0
  64. package/src/lib/org-run.js +305 -0
  65. package/src/lib/org-schema.js +89 -0
  66. package/src/lib/org-source-links.js +39 -0
  67. package/src/lib/parser.js +5 -0
  68. package/src/lib/path-equality.js +30 -0
  69. package/src/lib/paths.js +18 -1
  70. package/src/lib/redact.js +58 -7
  71. package/src/lib/resolver.js +66 -9
  72. package/src/lib/types.js +137 -0
  73. package/src/lib/writer.js +3 -0
  74. package/src/rules/pull-request-target-checkout.js +5 -0
  75. package/src/rules/unpinned-action.js +2 -3
  76. package/src/rules/workflow-structure.js +2 -4
  77. package/src/version.js +1 -1
  78. package/src/lib/agent-mode.js +0 -175
@@ -0,0 +1,394 @@
1
+ // @ts-check
2
+ /**
3
+ * Self-contained, deterministic HTML report with client-side search and filters.
4
+ */
5
+
6
+ import { redact, redactDeep } from '../redact.js';
7
+
8
+ /**
9
+ * @typedef {{label: string, fields: Record<string, string>}} HtmlRecord
10
+ * @typedef {{rule: string, severity: string, count: number}} RuleCount
11
+ */
12
+
13
+ const MAX_HTML_REPORT_BYTES = 32 * 1024 * 1024;
14
+
15
+ const HTML_STYLES = ` :root { color-scheme: light dark; --bg: #f6f8fa; --panel: #fff; --text: #1f2328; --muted: #59636e; --border: #d0d7de; --accent: #0969da; --ok: #1a7f37; --fail: #cf222e; --critical: #82071e; --high: #cf222e; --medium: #9a6700; --low: #0969da; }
16
+ @media (prefers-color-scheme: dark) { :root { --bg: #0d1117; --panel: #161b22; --text: #e6edf3; --muted: #8d96a0; --border: #30363d; --accent: #58a6ff; --ok: #3fb950; --fail: #f85149; --critical: #ff7b72; --high: #f85149; --medium: #d29922; --low: #58a6ff; } }
17
+ * { box-sizing: border-box; }
18
+ body { margin: 0; background: var(--bg); color: var(--text); font: 14px/1.5 ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
19
+ main { width: min(1600px, 100%); margin: 0 auto; padding: 24px; }
20
+ h1, h2, h3 { line-height: 1.25; }
21
+ h1 { margin: 0; font-size: clamp(24px, 4vw, 36px); }
22
+ h2 { margin: 0 0 16px; font-size: 20px; }
23
+ h3 { margin: 0 0 12px; font-size: 16px; }
24
+ .header { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 20px; }
25
+ .eyebrow, .muted { color: var(--muted); }
26
+ .eyebrow { margin: 0 0 4px; font-size: 12px; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; }
27
+ .panel { margin: 16px 0; padding: 18px; overflow: hidden; background: var(--panel); border: 1px solid var(--border); border-radius: 10px; box-shadow: 0 1px 0 rgb(31 35 40 / 4%); }
28
+ .status, .badge { display: inline-flex; align-items: center; border-radius: 999px; font-weight: 700; white-space: nowrap; }
29
+ .status { padding: 7px 12px; font-size: 13px; }
30
+ .badge { padding: 2px 8px; font-size: 12px; background: color-mix(in srgb, var(--muted) 14%, transparent); }
31
+ .status-ok, .badge-ok, .badge-resolved { color: var(--ok); background: color-mix(in srgb, var(--ok) 14%, transparent); }
32
+ .status-fail, .badge-fail, .badge-new, .badge-unknown { color: var(--fail); background: color-mix(in srgb, var(--fail) 14%, transparent); }
33
+ .badge-critical { color: var(--critical); background: color-mix(in srgb, var(--critical) 14%, transparent); }
34
+ .badge-high { color: var(--high); background: color-mix(in srgb, var(--high) 14%, transparent); }
35
+ .badge-medium { color: var(--medium); background: color-mix(in srgb, var(--medium) 14%, transparent); }
36
+ .badge-low, .badge-unchanged { color: var(--low); background: color-mix(in srgb, var(--low) 14%, transparent); }
37
+ .callout { border-left: 4px solid var(--fail); }
38
+ .callout strong { display: block; margin-bottom: 4px; }
39
+ .metrics { display: grid; grid-template-columns: repeat(auto-fit, minmax(145px, 1fr)); gap: 10px; }
40
+ .metric { min-width: 0; padding: 12px; background: var(--bg); border: 1px solid var(--border); border-radius: 8px; }
41
+ .metric-name { display: block; overflow-wrap: anywhere; color: var(--muted); font-size: 12px; }
42
+ .metric-value { display: block; margin-top: 3px; overflow-wrap: anywhere; font-size: 20px; font-weight: 700; }
43
+ .filters { display: grid; grid-template-columns: minmax(220px, 2fr) repeat(3, minmax(140px, 1fr)); gap: 10px; }
44
+ label { display: grid; gap: 4px; color: var(--muted); font-size: 12px; font-weight: 600; }
45
+ input, select { width: 100%; min-height: 38px; padding: 7px 9px; color: var(--text); background: var(--panel); border: 1px solid var(--border); border-radius: 6px; font: inherit; }
46
+ input:focus, select:focus { outline: 2px solid var(--accent); outline-offset: 1px; }
47
+ .filter-count { margin: 10px 0 0; color: var(--muted); }
48
+ .table-wrap { overflow: auto; border: 1px solid var(--border); border-radius: 8px; }
49
+ table { width: 100%; border-collapse: collapse; font-size: 13px; }
50
+ th, td { padding: 9px 11px; vertical-align: top; text-align: left; border-bottom: 1px solid var(--border); overflow-wrap: anywhere; }
51
+ th { position: sticky; top: 0; z-index: 1; color: var(--muted); background: var(--panel); font-size: 11px; letter-spacing: .04em; text-transform: uppercase; }
52
+ tbody tr:last-child td { border-bottom: 0; }
53
+ tbody tr:hover { background: color-mix(in srgb, var(--accent) 6%, transparent); }
54
+ code { font: 12px/1.45 ui-monospace, SFMono-Regular, Consolas, "Liberation Mono", monospace; white-space: pre-wrap; }
55
+ a { color: var(--accent); text-decoration-thickness: .08em; text-underline-offset: .15em; }
56
+ [hidden] { display: none !important; }
57
+ footer { margin: 24px 0 8px; color: var(--muted); font-size: 12px; text-align: center; }
58
+ @media (max-width: 800px) { main { padding: 14px; } .header { align-items: stretch; flex-direction: column; } .filters { grid-template-columns: 1fr; } }
59
+ @media print { :root { color-scheme: light; } body { background: #fff; color: #000; } main { width: 100%; padding: 0; } .filters-panel { display: none; } .panel { break-inside: avoid; box-shadow: none; } th { position: static; } }`;
60
+
61
+ const HTML_SCRIPT = ` (() => {
62
+ const rows = [...document.querySelectorAll('[data-record]')];
63
+ const search = document.querySelector('#filter-search');
64
+ const label = document.querySelector('#filter-label');
65
+ const severity = document.querySelector('#filter-severity');
66
+ const repository = document.querySelector('#filter-repository');
67
+ const count = document.querySelector('#filter-count');
68
+ if (!search || !label || !severity || !repository || !count) return;
69
+ const apply = () => {
70
+ const query = search.value.trim().toLocaleLowerCase();
71
+ let visible = 0;
72
+ for (const row of rows) {
73
+ const matches = (!query || row.dataset.search.includes(query))
74
+ && (!label.value || row.dataset.label === label.value)
75
+ && (!severity.value || row.dataset.severity === severity.value)
76
+ && (!repository.value || row.dataset.repository === repository.value);
77
+ row.hidden = !matches;
78
+ if (matches) visible += 1;
79
+ }
80
+ for (const section of document.querySelectorAll('[data-record-section]')) {
81
+ section.hidden = !section.querySelector('[data-record]:not([hidden])');
82
+ }
83
+ count.textContent = String(visible) + ' of ' + String(rows.length) + ' records shown';
84
+ };
85
+ for (const control of [search, label, severity, repository]) {
86
+ control.addEventListener(control === search ? 'input' : 'change', apply);
87
+ }
88
+ apply();
89
+ })();`;
90
+
91
+ /**
92
+ * Render a deterministic, self-contained HTML report with client-side search
93
+ * and filters. Dynamic values are redacted and escaped before entering markup;
94
+ * no report data is interpolated into executable JavaScript.
95
+ *
96
+ * @param {Array<{label: string, fields: Record<string, unknown>}>} records
97
+ * @param {{status?: 'OK'|'FAIL', title?: string,
98
+ * metadata?: Record<string, unknown>}} [options]
99
+ * @returns {string}
100
+ */
101
+ export function renderHtml(records, options = {}) {
102
+ const normalized = normalizeHtmlRecords(redactDeep(records));
103
+ const status = redact(String(options.status ?? 'UNKNOWN'));
104
+ const title = redact(String(options.title ?? 'actions-warden report'));
105
+ const metadata = normalizeFields(redactDeep(options.metadata ?? {}));
106
+ const summary = [...normalized].reverse().find(record => record.label === 'SUMMARY');
107
+ const detailRecords = normalized.filter(record => record.label !== 'SUMMARY');
108
+ const groups = groupRecords(detailRecords);
109
+ const findings = normalized.filter(record => record.label === 'FINDING');
110
+ const ruleCounts = summarizeHtmlRules(findings);
111
+ const labels = [...new Set(detailRecords.map(record => record.label))].sort();
112
+ const severities = [...new Set(detailRecords
113
+ .map(record => record.fields.sev ?? record.fields.severity)
114
+ .filter(Boolean)
115
+ .map(String))].sort(severitySort);
116
+ const repositories = [...new Set(detailRecords
117
+ .map(recordRepository)
118
+ .filter(Boolean))].sort((left, right) => left.localeCompare(right));
119
+ const incomplete = Number(summary?.fields.errors ?? 0) > 0
120
+ || Number(summary?.fields.repositoriesFailed ?? 0) > 0
121
+ || detailRecords.some(record => record.label === 'ERROR')
122
+ || detailRecords.some(record => (
123
+ record.label === 'UNKNOWN_FINDING'
124
+ || (record.label === 'COMPARISON' && record.fields.complete === 'false')
125
+ || (record.label === 'COVERAGE' && record.fields.complete === 'false')
126
+ ))
127
+ || findings.some(record => (
128
+ record.fields.type === 'parse-error' || record.fields.ruleId === 'parse-error'
129
+ ));
130
+
131
+ const document = `<!doctype html>
132
+ <html lang="en">
133
+ <head>
134
+ <meta charset="utf-8">
135
+ <meta name="viewport" content="width=device-width, initial-scale=1">
136
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data:">
137
+ <title>${escapeHtml(title)}</title>
138
+ <style>
139
+ ${HTML_STYLES}
140
+ </style>
141
+ </head>
142
+ <body>
143
+ <main>
144
+ <header class="header">
145
+ <div><p class="eyebrow">actions-warden report</p><h1>${escapeHtml(title)}</h1></div>
146
+ <span class="status ${statusClass(status)}">${escapeHtml(status)}</span>
147
+ </header>
148
+ ${incomplete ? `<section class="panel callout"><strong>Coverage is incomplete</strong><span>One or more repositories or files could not be fully inspected. Review operational errors before treating absent findings as clean.</span></section>` : ''}
149
+ ${renderHtmlMetadata(metadata)}
150
+ ${renderHtmlSummary(summary?.fields)}
151
+ ${renderHtmlRuleBreakdown(ruleCounts)}
152
+ ${detailRecords.length > 0 ? renderHtmlFilters({ labels, severities, repositories, total: detailRecords.length }) : ''}
153
+ ${[...groups.entries()].map(([label, values]) => renderHtmlGroup(label, values)).join('\n ')}
154
+ <footer>Generated deterministically by actions-warden. The saved report may contain sensitive repository names, paths, and findings.</footer>
155
+ </main>
156
+ <script>
157
+ ${HTML_SCRIPT}
158
+ </script>
159
+ </body>
160
+ </html>
161
+ `;
162
+ const bytes = Buffer.byteLength(document);
163
+ if (bytes > MAX_HTML_REPORT_BYTES) {
164
+ throw new Error(
165
+ `HTML report exceeds ${MAX_HTML_REPORT_BYTES} bytes; use JSON, SARIF, or a narrower scope`,
166
+ );
167
+ }
168
+ return document;
169
+ }
170
+
171
+ /**
172
+ * @param {unknown} records
173
+ * @returns {HtmlRecord[]}
174
+ */
175
+ function normalizeHtmlRecords(records) {
176
+ if (!Array.isArray(records)) return [];
177
+ return records.map(record => ({
178
+ label: redact(String(record?.label ?? 'RECORD')),
179
+ fields: normalizeFields(record?.fields),
180
+ }));
181
+ }
182
+
183
+ /**
184
+ * @param {unknown} fields
185
+ * @returns {Record<string, string>}
186
+ */
187
+ function normalizeFields(fields) {
188
+ if (!fields || typeof fields !== 'object' || Array.isArray(fields)) return {};
189
+ return Object.fromEntries(Object.entries(fields)
190
+ .filter(([, value]) => value !== null && value !== undefined && value !== '')
191
+ .map(([key, value]) => [redact(String(key)), htmlValue(value)]));
192
+ }
193
+
194
+ /**
195
+ * @param {unknown} value
196
+ * @returns {string}
197
+ */
198
+ function htmlValue(value) {
199
+ if (typeof value === 'string') return redact(value);
200
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value);
201
+ return redact(JSON.stringify(value));
202
+ }
203
+
204
+ /**
205
+ * @param {HtmlRecord[]} records
206
+ * @returns {Map<string, HtmlRecord[]>}
207
+ */
208
+ function groupRecords(records) {
209
+ const groups = new Map();
210
+ for (const record of records) {
211
+ if (!groups.has(record.label)) groups.set(record.label, []);
212
+ groups.get(record.label).push(record);
213
+ }
214
+ return groups;
215
+ }
216
+
217
+ /**
218
+ * @param {HtmlRecord[]} findings
219
+ * @returns {RuleCount[]}
220
+ */
221
+ function summarizeHtmlRules(findings) {
222
+ const counts = new Map();
223
+ for (const finding of findings) {
224
+ const rule = String(finding.fields.type ?? finding.fields.ruleId ?? 'unknown');
225
+ const severity = String(finding.fields.sev ?? finding.fields.severity ?? 'unknown');
226
+ const key = `${severity}\0${rule}`;
227
+ const current = counts.get(key) ?? { rule, severity, count: 0 };
228
+ current.count += 1;
229
+ counts.set(key, current);
230
+ }
231
+ return [...counts.values()].sort((left, right) => (
232
+ severitySort(left.severity, right.severity)
233
+ || right.count - left.count
234
+ || left.rule.localeCompare(right.rule)
235
+ ));
236
+ }
237
+
238
+ /** @param {Record<string, string>} metadata */
239
+ function renderHtmlMetadata(metadata) {
240
+ const entries = Object.entries(metadata);
241
+ if (entries.length === 0) return '';
242
+ return `<section class="panel"><h2>Report scope</h2><div class="metrics">${entries.map(([name, value]) => (
243
+ `<div class="metric"><span class="metric-name">${escapeHtml(humanize(name))}</span><span class="metric-value"><code>${escapeHtml(value)}</code></span></div>`
244
+ )).join('')}</div></section>`;
245
+ }
246
+
247
+ /** @param {Record<string, string>|undefined} fields */
248
+ function renderHtmlSummary(fields) {
249
+ if (!fields || Object.keys(fields).length === 0) return '';
250
+ return `<section class="panel"><h2>Summary</h2><div class="metrics">${Object.entries(fields)
251
+ .map(([name, value]) => (
252
+ `<div class="metric"><span class="metric-name">${escapeHtml(humanize(name))}</span><span class="metric-value">${escapeHtml(value)}</span></div>`
253
+ )).join('')}</div></section>`;
254
+ }
255
+
256
+ /** @param {RuleCount[]} rows */
257
+ function renderHtmlRuleBreakdown(rows) {
258
+ if (rows.length === 0) return '';
259
+ return `<section class="panel"><h2>Rule breakdown</h2><div class="table-wrap"><table><thead><tr><th>Severity</th><th>Rule</th><th>Findings</th></tr></thead><tbody>${rows.map(row => (
260
+ `<tr><td>${renderBadge(row.severity)}</td><td><code>${escapeHtml(row.rule)}</code></td><td>${row.count}</td></tr>`
261
+ )).join('')}</tbody></table></div></section>`;
262
+ }
263
+
264
+ /**
265
+ * @param {{labels: string[], severities: string[], repositories: string[],
266
+ * total: number}} filters
267
+ */
268
+ function renderHtmlFilters({ labels, severities, repositories, total }) {
269
+ return `<section class="panel filters-panel"><h2>Filter records</h2><div class="filters"><label>Search<input id="filter-search" type="search" placeholder="Repository, rule, file, action, or message"></label><label>Record type<select id="filter-label"><option value="">All types</option>${optionMarkup(labels)}</select></label><label>Severity<select id="filter-severity"><option value="">All severities</option>${optionMarkup(severities)}</select></label><label>Repository<select id="filter-repository"><option value="">All repositories</option>${optionMarkup(repositories)}</select></label></div><p class="filter-count" id="filter-count">${total} of ${total} records shown</p></section>`;
270
+ }
271
+
272
+ /** @param {string[]} values */
273
+ function optionMarkup(values) {
274
+ return values.map(value => (
275
+ `<option value="${escapeHtml(String(value).toLocaleLowerCase())}">${escapeHtml(value)}</option>`
276
+ )).join('');
277
+ }
278
+
279
+ /**
280
+ * @param {string} label
281
+ * @param {HtmlRecord[]} records
282
+ */
283
+ function renderHtmlGroup(label, records) {
284
+ const columns = [...new Set(records.flatMap(record => Object.keys(record.fields)))];
285
+ const rows = records.map(record => {
286
+ const severity = String(record.fields.sev ?? record.fields.severity ?? '').toLocaleLowerCase();
287
+ const repository = recordRepository(record).toLocaleLowerCase();
288
+ const search = `${record.label} ${Object.values(record.fields).join(' ')}`.toLocaleLowerCase();
289
+ return `<tr data-record data-label="${escapeHtml(record.label.toLocaleLowerCase())}" data-severity="${escapeHtml(severity)}" data-repository="${escapeHtml(repository)}" data-search="${escapeHtml(search)}">${columns.map(column => (
290
+ `<td>${renderHtmlCell(column, record.fields[column])}</td>`
291
+ )).join('')}</tr>`;
292
+ }).join('');
293
+ const heading = `${recordGroupTitle(label)} (${records.length})`;
294
+ return `<section class="panel" data-record-section><h2>${escapeHtml(heading)}</h2><div class="table-wrap"><table><thead><tr>${columns.map(column => `<th>${escapeHtml(humanize(column))}</th>`).join('')}</tr></thead><tbody>${rows}</tbody></table></div></section>`;
295
+ }
296
+
297
+ /** @param {string} label */
298
+ function recordGroupTitle(label) {
299
+ const names = new Map([
300
+ ['REPOSITORY', 'Repository breakdown'],
301
+ ['FILE', 'Scanned files'],
302
+ ['FINDING', 'Findings'],
303
+ ['ERROR', 'Operational errors'],
304
+ ['WARNING', 'Warnings'],
305
+ ['COMPARISON', 'Comparison summary'],
306
+ ['NEW_FINDING', 'New findings'],
307
+ ['RESOLVED_FINDING', 'Resolved findings'],
308
+ ['UNCHANGED_FINDING', 'Unchanged findings'],
309
+ ['UNKNOWN_FINDING', 'Unknown-resolution findings'],
310
+ ]);
311
+ return names.get(label) ?? humanize(label);
312
+ }
313
+
314
+ /**
315
+ * @param {string} key
316
+ * @param {string|undefined} value
317
+ */
318
+ function renderHtmlCell(key, value) {
319
+ if (value === undefined) return '';
320
+ if (['severity', 'sev', 'status', 'change'].includes(key)) return renderBadge(value);
321
+ if ((key === 'url' || key === 'permalink') && safeHttpsUrl(value)) {
322
+ return `<a href="${escapeHtml(value)}" target="_blank" rel="noopener noreferrer">${escapeHtml(value)}</a>`;
323
+ }
324
+ return `<code>${escapeHtml(value)}</code>`;
325
+ }
326
+
327
+ /** @param {unknown} value */
328
+ function renderBadge(value) {
329
+ const text = String(value);
330
+ const normalized = text.toLocaleLowerCase();
331
+ const known = new Set([
332
+ 'critical', 'high', 'medium', 'low', 'ok', 'fail',
333
+ 'new', 'resolved', 'unchanged', 'unknown',
334
+ ]);
335
+ const className = known.has(normalized) ? ` badge-${normalized}` : '';
336
+ return `<span class="badge${className}">${escapeHtml(text)}</span>`;
337
+ }
338
+
339
+ /** @param {HtmlRecord} record */
340
+ function recordRepository(record) {
341
+ const explicit = record.fields.repo ?? record.fields.repository;
342
+ return explicit ? String(explicit) : '';
343
+ }
344
+
345
+ /** @param {unknown} value */
346
+ function safeHttpsUrl(value) {
347
+ try {
348
+ return new URL(String(value)).protocol === 'https:';
349
+ } catch {
350
+ return false;
351
+ }
352
+ }
353
+
354
+ /** @param {string} status */
355
+ function statusClass(status) {
356
+ if (status.toLocaleLowerCase() === 'ok') return 'status-ok';
357
+ if (status.toLocaleLowerCase() === 'fail') return 'status-fail';
358
+ return '';
359
+ }
360
+
361
+ /**
362
+ * @param {unknown} left
363
+ * @param {unknown} right
364
+ */
365
+ function severitySort(left, right) {
366
+ const order = new Map([
367
+ ['critical', 0],
368
+ ['high', 1],
369
+ ['medium', 2],
370
+ ['low', 3],
371
+ ]);
372
+ return (order.get(String(left).toLocaleLowerCase()) ?? 4)
373
+ - (order.get(String(right).toLocaleLowerCase()) ?? 4);
374
+ }
375
+
376
+ /** @param {unknown} value */
377
+ function humanize(value) {
378
+ const source = String(value);
379
+ return (/^[A-Z0-9_-]+$/.test(source) ? source.toLocaleLowerCase() : source)
380
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
381
+ .replaceAll('_', ' ')
382
+ .replaceAll('-', ' ')
383
+ .replace(/^./, first => first.toLocaleUpperCase());
384
+ }
385
+
386
+ /** @param {unknown} value */
387
+ function escapeHtml(value) {
388
+ return String(value)
389
+ .replaceAll('&', '&amp;')
390
+ .replaceAll('<', '&lt;')
391
+ .replaceAll('>', '&gt;')
392
+ .replaceAll('"', '&quot;')
393
+ .replaceAll("'", '&#39;');
394
+ }
@@ -0,0 +1,17 @@
1
+ // @ts-check
2
+ /**
3
+ * Recursively redacted, 2-space-indented JSON serialization.
4
+ */
5
+
6
+ import { redactDeep } from '../redact.js';
7
+
8
+ /**
9
+ * Render recursively redacted JSON with 2-space indentation. Object key order
10
+ * follows the caller-provided value.
11
+ *
12
+ * @param {unknown} payload
13
+ * @returns {string}
14
+ */
15
+ export function renderJson(payload) {
16
+ return JSON.stringify(redactDeep(payload), null, 2) + '\n';
17
+ }
@@ -0,0 +1,229 @@
1
+ // @ts-check
2
+ /**
3
+ * SARIF 2.1.0 serialization for GitHub code scanning.
4
+ *
5
+ * Local commands produce one run. An organization scan produces one run per
6
+ * repository, so each run's locations are repository-relative and its version
7
+ * control provenance names that repository's URL, commit, and branch.
8
+ */
9
+
10
+ import { renderJson } from './json.js';
11
+
12
+ const SARIF_SCHEMA = 'https://json.schemastore.org/sarif-2.1.0.json';
13
+ const RESULT_LABELS = new Set(['FINDING', 'ERROR', 'WARNING', 'PIN', 'UPGRADE']);
14
+
15
+ // GitHub maps a score of over 9.0 to critical, 7.0-8.9 to high, 4.0-6.9 to medium,
16
+ // and 0.1-3.9 to low, so critical uses 9.5 rather than the ambiguous boundary 9.0.
17
+ const SECURITY_SEVERITY = new Map([
18
+ ['critical', '9.5'],
19
+ ['high', '7.0'],
20
+ ['medium', '4.0'],
21
+ ['low', '1.0'],
22
+ ]);
23
+
24
+ /**
25
+ * @typedef {import('../types.js').ReportRecord} ReportRecord
26
+ * @typedef {{id: string, shortDescription: {text: string},
27
+ * defaultConfiguration: {level: string}, properties?: Record<string, string>}} RuleDescriptor
28
+ */
29
+
30
+ /**
31
+ * Render records as SARIF 2.1.0 for GitHub code scanning. Records that contain
32
+ * `REPOSITORY` entries yield one run per repository; otherwise there is one run.
33
+ * Every rule descriptor with a known severity carries `security-severity`.
34
+ *
35
+ * @param {ReportRecord[]} records
36
+ * @param {{status?: string}} [options]
37
+ */
38
+ export function renderSarif(records, options = {}) {
39
+ const catalog = catalogRules(records);
40
+ const groups = repositoryGroups(records);
41
+ const runs = groups.length > 0
42
+ ? groups.map(group => buildRun(catalog, group.records, options, group.repository))
43
+ : [buildRun(catalog, records, options, null)];
44
+ return renderJson({ $schema: SARIF_SCHEMA, version: '2.1.0', runs });
45
+ }
46
+
47
+ /**
48
+ * @param {ReportRecord[]} records
49
+ * @returns {Map<string, RuleDescriptor>}
50
+ */
51
+ function catalogRules(records) {
52
+ const rules = new Map();
53
+ for (const record of records) {
54
+ if (record.label !== 'RULE') continue;
55
+ const id = String(record.fields.id ?? 'actions-warden');
56
+ rules.set(id, ruleDescriptor({
57
+ id,
58
+ text: String(record.fields.description ?? id),
59
+ level: sarifLevel(String(record.fields.severity ?? 'low')),
60
+ severity: String(record.fields.severity ?? ''),
61
+ }));
62
+ }
63
+ return rules;
64
+ }
65
+
66
+ /**
67
+ * Split records into one group per `REPOSITORY` record, keeping everything that
68
+ * follows it until the next repository.
69
+ *
70
+ * @param {ReportRecord[]} records
71
+ * @returns {Array<{repository: Record<string, unknown>, records: ReportRecord[]}>}
72
+ */
73
+ function repositoryGroups(records) {
74
+ /** @type {Array<{repository: Record<string, unknown>, records: ReportRecord[]}>} */
75
+ const groups = [];
76
+ for (const record of records) {
77
+ if (record.label === 'REPOSITORY') {
78
+ groups.push({ repository: record.fields, records: [] });
79
+ } else if (groups.length > 0) {
80
+ groups.at(-1)?.records.push(record);
81
+ }
82
+ }
83
+ return groups;
84
+ }
85
+
86
+ /**
87
+ * @param {Map<string, RuleDescriptor>} catalog
88
+ * @param {ReportRecord[]} records
89
+ * @param {{status?: string}} options
90
+ * @param {Record<string, unknown>|null} repository
91
+ */
92
+ function buildRun(catalog, records, options, repository) {
93
+ const rules = new Map(catalog);
94
+ const results = [];
95
+ for (const record of records) {
96
+ if (!RESULT_LABELS.has(record.label)) continue;
97
+ const ruleId = String(record.fields.type ?? `actions-warden/${record.label.toLowerCase()}`);
98
+ if (!rules.has(ruleId)) rules.set(ruleId, syntheticRule(ruleId, record));
99
+ results.push(buildResult(record, ruleId, repository !== null));
100
+ }
101
+ return {
102
+ tool: {
103
+ driver: {
104
+ name: 'actions-warden',
105
+ informationUri: 'https://github.com/chiz0me/actions-warden',
106
+ rules: [...rules.values()],
107
+ },
108
+ },
109
+ ...(repository ? versionControlProvenance(repository) : {}),
110
+ invocations: [{
111
+ executionSuccessful: options.status !== 'ERROR',
112
+ }],
113
+ results,
114
+ };
115
+ }
116
+
117
+ /**
118
+ * @param {string} ruleId
119
+ * @param {ReportRecord} record
120
+ * @returns {RuleDescriptor}
121
+ */
122
+ function syntheticRule(ruleId, record) {
123
+ const fields = record.fields;
124
+ return ruleDescriptor({
125
+ id: ruleId,
126
+ text: ruleId,
127
+ level: record.label === 'ERROR' ? 'error' : sarifLevel(String(fields.sev ?? 'low')),
128
+ // Only findings carry a security severity; operational errors, warnings, and
129
+ // change plans are not security alerts.
130
+ severity: record.label === 'FINDING' ? String(fields.sev ?? '') : '',
131
+ });
132
+ }
133
+
134
+ /**
135
+ * @param {{id: string, text: string, level: string, severity: string}} descriptor
136
+ * @returns {RuleDescriptor}
137
+ */
138
+ function ruleDescriptor({ id, text, level, severity }) {
139
+ const score = SECURITY_SEVERITY.get(severity);
140
+ return {
141
+ id,
142
+ shortDescription: { text },
143
+ defaultConfiguration: { level },
144
+ ...(score ? { properties: { 'security-severity': score } } : {}),
145
+ };
146
+ }
147
+
148
+ /**
149
+ * @param {ReportRecord} record
150
+ * @param {string} ruleId
151
+ * @param {boolean} repositoryRelative Use the repo-relative `path` for locations.
152
+ */
153
+ function buildResult(record, ruleId, repositoryRelative) {
154
+ const fields = record.fields;
155
+ const location = repositoryRelative ? (fields.path ?? fields.file) : fields.file;
156
+ const file = location ? String(location) : null;
157
+ const line = Number(fields.line);
158
+ return {
159
+ ruleId,
160
+ level: resultLevel(record),
161
+ message: {
162
+ text: String(fields.explain ?? fields.msg ?? summarizeFields(record.label, fields)),
163
+ },
164
+ ...(file ? {
165
+ locations: [{
166
+ physicalLocation: {
167
+ artifactLocation: { uri: file.replace(/\\/g, '/') },
168
+ ...(Number.isInteger(line) && line > 0
169
+ ? { region: { startLine: line } }
170
+ : {}),
171
+ },
172
+ }],
173
+ } : {}),
174
+ ...(fields.id ? {
175
+ partialFingerprints: {
176
+ // GitHub code scanning recognizes this key and uses the suffix to
177
+ // distinguish multiple results with the same semantic fingerprint.
178
+ primaryLocationLineHash: `${fields.fingerprint ?? fields.id}:1`,
179
+ 'actions-warden/id': String(fields.id),
180
+ ...(fields.fingerprint
181
+ ? { 'actions-warden/semantic': String(fields.fingerprint) }
182
+ : {}),
183
+ },
184
+ } : {}),
185
+ };
186
+ }
187
+
188
+ /** @param {ReportRecord} record */
189
+ function resultLevel(record) {
190
+ if (record.label === 'ERROR') return 'error';
191
+ if (record.label === 'WARNING') return 'warning';
192
+ return sarifLevel(String(record.fields.sev ?? (record.label === 'FINDING' ? 'warning' : 'low')));
193
+ }
194
+
195
+ /**
196
+ * @param {Record<string, unknown>} repository The REPOSITORY record's fields.
197
+ * @returns {{versionControlProvenance?: Array<Record<string, string>>}}
198
+ */
199
+ function versionControlProvenance(repository) {
200
+ if (!repository.url) return {};
201
+ return {
202
+ versionControlProvenance: [{
203
+ repositoryUri: String(repository.url),
204
+ ...(repository.commit ? { revisionId: String(repository.commit) } : {}),
205
+ ...(repository.branch ? { branch: String(repository.branch) } : {}),
206
+ }],
207
+ };
208
+ }
209
+
210
+ /** @param {string} severity */
211
+ function sarifLevel(severity) {
212
+ if (severity === 'critical' || severity === 'high' || severity === 'error') return 'error';
213
+ if (severity === 'medium' || severity === 'warning') return 'warning';
214
+ return 'note';
215
+ }
216
+
217
+ /**
218
+ * @param {string} label
219
+ * @param {Record<string, unknown>} fields
220
+ */
221
+ function summarizeFields(label, fields) {
222
+ const details = Object.entries(fields)
223
+ .filter(([key, value]) => (
224
+ !['id', 'file', 'line', 'path', 'permalink'].includes(key) && value != null && value !== ''
225
+ ))
226
+ .map(([key, value]) => `${key}=${String(value)}`)
227
+ .join(' ');
228
+ return `${label}: ${details}`;
229
+ }
@@ -0,0 +1,30 @@
1
+ // @ts-check
2
+ /**
3
+ * Plain-text, one-record-per-line serialization for human-readable logs.
4
+ */
5
+
6
+ import { redact } from '../redact.js';
7
+
8
+ /**
9
+ * Render plain text (human-readable summary).
10
+ *
11
+ * @param {Array<{label: string, fields: Record<string, unknown>}>} records
12
+ * @param {{status?: 'OK'|'FAIL'}} [options]
13
+ * @returns {string}
14
+ */
15
+ export function renderText(records, options = {}) {
16
+ const lines = records.map(r => {
17
+ const kv = Object.entries(r.fields)
18
+ .filter(([, v]) => v !== null && v !== undefined && v !== '')
19
+ .map(([k, v]) => `${k}=${escapeText(redact(String(v)))}`)
20
+ .join(' ');
21
+ return `[${r.label}] ${kv}`;
22
+ });
23
+ if (options.status) lines.push(`==> ${options.status}`);
24
+ return lines.join('\n') + '\n';
25
+ }
26
+
27
+ /** @param {string} value */
28
+ function escapeText(value) {
29
+ return JSON.stringify(value).slice(1, -1);
30
+ }