actions-warden 0.4.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 (76) hide show
  1. package/AGENTS.md +46 -8
  2. package/CONTRIBUTING.md +6 -2
  3. package/README.md +171 -61
  4. package/RELEASING.md +3 -2
  5. package/SECURITY.md +15 -5
  6. package/docs/AI-AGENTS.md +109 -29
  7. package/docs/CLI.md +284 -60
  8. package/docs/CONFIGURATION.md +34 -11
  9. package/docs/DEVELOPMENT.md +97 -24
  10. package/docs/GITHUB-ACTION.md +157 -27
  11. package/docs/JAVASCRIPT-API.md +172 -8
  12. package/docs/OUTPUTS.md +399 -36
  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 +78 -35
  35. package/src/action.js +351 -174
  36. package/src/cli.js +191 -177
  37. package/src/commands/audit.js +17 -30
  38. package/src/commands/org-scan.js +451 -280
  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 +137 -96
  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/paths.js +18 -1
  69. package/src/lib/redact.js +58 -7
  70. package/src/lib/resolver.js +66 -9
  71. package/src/lib/types.js +137 -0
  72. package/src/rules/pull-request-target-checkout.js +5 -0
  73. package/src/rules/unpinned-action.js +2 -3
  74. package/src/rules/workflow-structure.js +2 -4
  75. package/src/version.js +1 -1
  76. package/src/lib/agent-mode.js +0 -174
@@ -0,0 +1,251 @@
1
+ /**
2
+ * Guarded directory layout for large organization JSON reports.
3
+ *
4
+ * The aggregate is intentionally compact. Complete repository evidence is
5
+ * stored in independently hashed JSON files, and a manifest written last makes
6
+ * the current artifact set explicit. Existing unrelated files are preserved.
7
+ */
8
+
9
+ import { createHash } from 'node:crypto';
10
+ import { lstat, mkdir, readdir, realpath } from 'node:fs/promises';
11
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path';
12
+ import { canonicalPath } from './identity.js';
13
+ import { renderJson } from './formatter.js';
14
+ import { buildOrganizationReport } from './org-report.js';
15
+ import { writeFileGuarded } from './writer.js';
16
+
17
+ const AGGREGATE_FILENAME = 'organization-report.json';
18
+ const COMPARISON_FILENAME = 'organization-comparison.json';
19
+ const MANIFEST_FILENAME = 'manifest.json';
20
+ const REPOSITORIES_DIRECTORY = 'repositories';
21
+
22
+ /**
23
+ * Validate a future organization report directory without creating it.
24
+ * Existing path components and owned entries must be real directories/files,
25
+ * never symbolic links.
26
+ */
27
+ export async function validateOrganizationReportDirectory({ path, cwd = process.cwd() }) {
28
+ const directory = await resolveGuardedDirectory({ path, cwd, create: false });
29
+ await validateExistingLayout(directory);
30
+ return directory;
31
+ }
32
+
33
+ /**
34
+ * Write a compact aggregate, complete per-repository JSON artifacts, optional
35
+ * comparison evidence, and a final integrity manifest.
36
+ */
37
+ export async function writeOrganizationReportDirectory({
38
+ result,
39
+ path,
40
+ cwd = process.cwd(),
41
+ }) {
42
+ const directory = await resolveGuardedDirectory({ path, cwd, create: true });
43
+ await validateExistingLayout(directory);
44
+ const repositoriesDirectory = join(directory, REPOSITORIES_DIRECTORY);
45
+ await ensureDirectory(repositoriesDirectory);
46
+
47
+ const complete = buildOrganizationReport(result, { cwd });
48
+ const repositoryArtifacts = [];
49
+ const compactRepositories = [];
50
+ for (const repositoryResult of complete.repositories) {
51
+ const artifactName = repositoryArtifactName(repositoryResult.repository);
52
+ const artifactPath = join(repositoriesDirectory, artifactName);
53
+ const relativePath = `${REPOSITORIES_DIRECTORY}/${artifactName}`;
54
+ const content = renderJson({
55
+ schemaVersion: '1.0',
56
+ kind: 'actions-warden-org-scan-repository',
57
+ organization: complete.organization,
58
+ analysis: complete.analysis,
59
+ scope: complete.scope,
60
+ repository: repositoryResult,
61
+ status: repositoryResult.status,
62
+ });
63
+ await writeFileGuarded({ path: artifactPath, content, dryRun: false, cwd });
64
+ const artifact = integrity(relativePath, content);
65
+ repositoryArtifacts.push({
66
+ repository: repositoryResult.repository.fullName,
67
+ ...artifact,
68
+ });
69
+ compactRepositories.push({
70
+ repository: repositoryResult.repository,
71
+ revision: repositoryResult.revision,
72
+ summary: repositoryResult.summary,
73
+ status: repositoryResult.status,
74
+ files: repositoryResult.files.length,
75
+ findings: repositoryResult.findings.length,
76
+ errors: repositoryResult.errors.length,
77
+ artifact,
78
+ });
79
+ }
80
+
81
+ let comparisonArtifact;
82
+ if (complete.comparison) {
83
+ const content = renderJson(complete.comparison);
84
+ await writeFileGuarded({
85
+ path: join(directory, COMPARISON_FILENAME),
86
+ content,
87
+ dryRun: false,
88
+ cwd,
89
+ });
90
+ comparisonArtifact = integrity(COMPARISON_FILENAME, content);
91
+ }
92
+
93
+ const aggregate = {
94
+ schemaVersion: '1.0',
95
+ kind: 'actions-warden-org-scan-directory',
96
+ organization: complete.organization,
97
+ analysis: complete.analysis,
98
+ scope: complete.scope,
99
+ coverage: complete.coverage,
100
+ repositories: compactRepositories,
101
+ summary: complete.summary,
102
+ baseline: complete.baseline,
103
+ configPath: complete.configPath,
104
+ ...(complete.comparison ? {
105
+ comparison: {
106
+ summary: complete.comparison.summary,
107
+ artifact: comparisonArtifact,
108
+ },
109
+ } : {}),
110
+ status: complete.status,
111
+ };
112
+ const aggregateContent = renderJson(aggregate);
113
+ await writeFileGuarded({
114
+ path: join(directory, AGGREGATE_FILENAME),
115
+ content: aggregateContent,
116
+ dryRun: false,
117
+ cwd,
118
+ });
119
+ const aggregateArtifact = integrity(AGGREGATE_FILENAME, aggregateContent);
120
+ const manifest = {
121
+ schemaVersion: '1.0',
122
+ kind: 'actions-warden-org-scan-manifest',
123
+ organization: complete.organization,
124
+ analysis: complete.analysis,
125
+ report: aggregateArtifact,
126
+ repositories: repositoryArtifacts,
127
+ ...(comparisonArtifact ? { comparison: comparisonArtifact } : {}),
128
+ status: complete.status,
129
+ };
130
+ await writeFileGuarded({
131
+ path: join(directory, MANIFEST_FILENAME),
132
+ content: renderJson(manifest),
133
+ dryRun: false,
134
+ cwd,
135
+ });
136
+
137
+ return {
138
+ directory: canonicalPath(directory, cwd),
139
+ reportPath: canonicalPath(join(directory, AGGREGATE_FILENAME), cwd),
140
+ manifestPath: canonicalPath(join(directory, MANIFEST_FILENAME), cwd),
141
+ repositories: repositoryArtifacts.length,
142
+ };
143
+ }
144
+
145
+ async function resolveGuardedDirectory({ path, cwd, create }) {
146
+ if (typeof path !== 'string' || !path || path.includes('\0')) {
147
+ throw new Error('--report-dir must be a non-empty path');
148
+ }
149
+ const requestedRoot = resolve(cwd);
150
+ const requested = resolve(requestedRoot, path);
151
+ if (!isAbsolute(path) && isOutside(relative(requestedRoot, requested))) {
152
+ throw new Error(`refusing to write outside working directory: ${path}`);
153
+ }
154
+ const root = await realpath(requestedRoot);
155
+ const lexicalRelative = relative(requestedRoot, requested);
156
+ if (isOutside(lexicalRelative)) {
157
+ throw new Error(`refusing to write outside working directory: ${path}`);
158
+ }
159
+ if (lexicalRelative === '') {
160
+ throw new Error('--report-dir must be a dedicated subdirectory inside the working directory');
161
+ }
162
+ let cursor = root;
163
+ for (const segment of lexicalRelative.split(sep).filter(Boolean)) {
164
+ cursor = join(cursor, segment);
165
+ try {
166
+ const metadata = await lstat(cursor);
167
+ if (metadata.isSymbolicLink() || !metadata.isDirectory()) {
168
+ throw new Error(`organization report path is not a regular directory: ${cursor}`);
169
+ }
170
+ } catch (error) {
171
+ if (error.code !== 'ENOENT') throw error;
172
+ if (create) await mkdir(cursor, { mode: 0o700 });
173
+ }
174
+ }
175
+ // Keep the caller's lexical root for stable workspace-relative receipt
176
+ // paths. Every component above was still checked through the real root.
177
+ return requested;
178
+ }
179
+
180
+ async function validateExistingLayout(directory) {
181
+ try {
182
+ const metadata = await lstat(directory);
183
+ if (metadata.isSymbolicLink() || !metadata.isDirectory()) {
184
+ throw new Error(`organization report path is not a regular directory: ${directory}`);
185
+ }
186
+ } catch (error) {
187
+ if (error.code === 'ENOENT') return;
188
+ throw error;
189
+ }
190
+ for (const name of [AGGREGATE_FILENAME, COMPARISON_FILENAME, MANIFEST_FILENAME]) {
191
+ await validateOptionalFile(join(directory, name));
192
+ }
193
+ const repositoriesDirectory = join(directory, REPOSITORIES_DIRECTORY);
194
+ try {
195
+ const metadata = await lstat(repositoriesDirectory);
196
+ if (metadata.isSymbolicLink() || !metadata.isDirectory()) {
197
+ throw new Error(`organization report repositories path is unsafe: ${repositoriesDirectory}`);
198
+ }
199
+ const entries = await readdir(repositoriesDirectory, { withFileTypes: true });
200
+ if (entries.some(entry => entry.isSymbolicLink() || !entry.isFile())) {
201
+ throw new Error(`organization report repositories contain an unsafe entry: ${repositoriesDirectory}`);
202
+ }
203
+ } catch (error) {
204
+ if (error.code !== 'ENOENT') throw error;
205
+ }
206
+ }
207
+
208
+ async function validateOptionalFile(path) {
209
+ try {
210
+ const metadata = await lstat(path);
211
+ if (metadata.isSymbolicLink() || !metadata.isFile()) {
212
+ throw new Error(`organization report artifact is not a regular file: ${path}`);
213
+ }
214
+ } catch (error) {
215
+ if (error.code !== 'ENOENT') throw error;
216
+ }
217
+ }
218
+
219
+ async function ensureDirectory(path) {
220
+ try {
221
+ const metadata = await lstat(path);
222
+ if (metadata.isSymbolicLink() || !metadata.isDirectory()) {
223
+ throw new Error(`organization report path is not a regular directory: ${path}`);
224
+ }
225
+ } catch (error) {
226
+ if (error.code !== 'ENOENT') throw error;
227
+ await mkdir(path, { mode: 0o700 });
228
+ }
229
+ }
230
+
231
+ function repositoryArtifactName(repository) {
232
+ const name = String(repository?.name ?? 'repository').toLowerCase();
233
+ const safeName = /^[a-z0-9_.-]+$/.test(name) ? name : 'repository';
234
+ const hash = createHash('sha256')
235
+ .update(String(repository?.fullName ?? '').toLowerCase())
236
+ .digest('hex')
237
+ .slice(0, 16);
238
+ return `${safeName}.${hash}.json`;
239
+ }
240
+
241
+ function integrity(path, content) {
242
+ return {
243
+ path,
244
+ bytes: Buffer.byteLength(content),
245
+ sha256: createHash('sha256').update(content).digest('hex'),
246
+ };
247
+ }
248
+
249
+ function isOutside(value) {
250
+ return value === '..' || value.startsWith(`..${sep}`) || isAbsolute(value);
251
+ }
@@ -0,0 +1,223 @@
1
+ // @ts-check
2
+ /**
3
+ * Canonical organization report document.
4
+ *
5
+ * The public JSON document is assembled once here. Every serialization,
6
+ * comparison, and report-directory artifact is derived from it so the formats
7
+ * cannot drift apart.
8
+ */
9
+
10
+ import { canonicalPath } from './identity.js';
11
+ import { redactDeep } from './redact.js';
12
+ import { listRules } from '../rules/index.js';
13
+
14
+ /**
15
+ * Build the plain, credential-redacted public document for an organization
16
+ * scan result. Paths are repository-relative to `cwd` and the value is safe to
17
+ * serialize with `JSON.stringify`.
18
+ *
19
+ * @param {import('./types.js').OrganizationScanResult & {comparison?: Record<string, any>}} result
20
+ * Value returned by `scanOrganization`.
21
+ * @param {{cwd?: string, comparison?: Record<string, any>}} [options]
22
+ * @returns {import('./types.js').OrganizationReport}
23
+ */
24
+ export function buildOrganizationReport(result, {
25
+ cwd = process.cwd(),
26
+ comparison = result.comparison,
27
+ } = {}) {
28
+ const report = {
29
+ schemaVersion: '1.0',
30
+ organization: result.organization,
31
+ analysis: result.analysis,
32
+ scope: result.scope,
33
+ coverage: result.coverage,
34
+ repositories: result.repositories.map(repositoryResult => ({
35
+ repository: repositoryResult.repository,
36
+ revision: repositoryResult.revision,
37
+ files: repositoryResult.files,
38
+ fileDetails: repositoryResult.fileDetails,
39
+ findings: repositoryResult.findings.map(finding => normalizeFinding(finding, cwd)),
40
+ errors: repositoryResult.errors,
41
+ summary: repositoryResult.summary,
42
+ status: repositoryResult.status,
43
+ })),
44
+ findings: result.findings.map(finding => normalizeFinding(finding, cwd)),
45
+ errors: result.errors,
46
+ summary: result.summary,
47
+ baseline: {
48
+ ...result.baseline,
49
+ path: result.baseline.path ? canonicalPath(result.baseline.path, cwd) : null,
50
+ },
51
+ configPath: result.configPath ? canonicalPath(result.configPath, cwd) : null,
52
+ ...(comparison ? { comparison } : {}),
53
+ status: result.status,
54
+ };
55
+ return JSON.parse(JSON.stringify(redactDeep(report)));
56
+ }
57
+
58
+ /**
59
+ * Project a report document into the labeled records shared by the TOON, text,
60
+ * CSV, SARIF, and HTML renderers, together with the HTML title and metadata.
61
+ *
62
+ * @param {ReturnType<typeof buildOrganizationReport>} report
63
+ * @param {{format: 'toon'|'text'|'csv'|'sarif'|'html'}} options
64
+ * @returns {{records: Array<{label: string, fields: Record<string, unknown>}>,
65
+ * title: string, metadata: Record<string, unknown>}}
66
+ */
67
+ export function organizationReportRecords(report, { format }) {
68
+ const records = [];
69
+ if (format === 'sarif') {
70
+ for (const rule of listRules()) records.push({ label: 'RULE', fields: rule });
71
+ }
72
+ for (const repositoryResult of report.repositories) {
73
+ appendRepositoryRecords(records, repositoryResult, format);
74
+ }
75
+ records.push({
76
+ label: 'COVERAGE',
77
+ fields: {
78
+ complete: report.coverage.complete,
79
+ enumerationComplete: report.coverage.enumerationComplete,
80
+ selectedRepositoriesComplete: report.coverage.selectedRepositoriesComplete,
81
+ eligibleRepositoriesComplete: report.coverage.eligibleRepositoriesComplete,
82
+ limitedByMaxRepositories: report.coverage.limitedByMaxRepositories,
83
+ repositoriesOmittedByLimit: report.coverage.repositoriesOmittedByLimit,
84
+ incompleteRepositories: report.coverage.incompleteRepositories.length,
85
+ },
86
+ });
87
+ if (report.comparison) appendComparisonRecords(records, report.comparison);
88
+ records.push({
89
+ label: 'SUMMARY',
90
+ fields: { organization: report.organization, ...report.summary },
91
+ });
92
+ return {
93
+ records,
94
+ title: `Organization scan: ${report.organization}`,
95
+ metadata: reportMetadata(report),
96
+ };
97
+ }
98
+
99
+ /**
100
+ * @param {import('./types.js').ReportRecord[]} records
101
+ * @param {import('./types.js').RepositoryResult} repositoryResult
102
+ * @param {string} format
103
+ */
104
+ function appendRepositoryRecords(records, repositoryResult, format) {
105
+ records.push({
106
+ label: 'REPOSITORY',
107
+ fields: {
108
+ repo: repositoryResult.repository.fullName,
109
+ visibility: repositoryResult.repository.visibility,
110
+ branch: repositoryResult.revision.branch,
111
+ commit: repositoryResult.revision.commitSha,
112
+ files: repositoryResult.files.length,
113
+ findings: repositoryResult.findings.length,
114
+ errors: repositoryResult.errors.length,
115
+ status: repositoryResult.status,
116
+ ...(format === 'sarif' ? { url: repositoryResult.repository.htmlUrl } : {}),
117
+ },
118
+ });
119
+ for (const detail of repositoryResult.fileDetails) {
120
+ records.push({
121
+ label: 'FILE',
122
+ fields: {
123
+ repo: repositoryResult.repository.fullName,
124
+ path: detail.path,
125
+ status: detail.status,
126
+ findings: detail.findings,
127
+ blobSha: detail.blobSha,
128
+ bytes: detail.bytes,
129
+ permalink: detail.permalink,
130
+ },
131
+ });
132
+ }
133
+ for (const finding of repositoryResult.findings) {
134
+ records.push({
135
+ label: 'FINDING',
136
+ fields: {
137
+ id: finding.id,
138
+ ...finding.fields,
139
+ repo: finding.repository,
140
+ file: finding.file,
141
+ path: finding.path,
142
+ line: finding.line,
143
+ url: finding.url,
144
+ permalink: finding.permalink,
145
+ ...(finding.explain ? { explain: finding.explain } : {}),
146
+ ...(format === 'sarif' && finding.fingerprint
147
+ ? { fingerprint: finding.fingerprint }
148
+ : {}),
149
+ },
150
+ });
151
+ }
152
+ for (const error of repositoryResult.errors) {
153
+ records.push({
154
+ label: 'ERROR',
155
+ fields: {
156
+ repo: error.repository,
157
+ file: error.path ? `${error.repository}/${error.path}` : undefined,
158
+ path: error.path,
159
+ permalink: error.permalink,
160
+ msg: error.error,
161
+ },
162
+ });
163
+ }
164
+ }
165
+
166
+ /**
167
+ * @param {import('./types.js').ReportRecord[]} records
168
+ * @param {Record<string, any>} comparison
169
+ */
170
+ function appendComparisonRecords(records, comparison) {
171
+ records.push({ label: 'COMPARISON', fields: comparison.summary });
172
+ for (const [change, findings] of Object.entries(comparison.findings)) {
173
+ for (const finding of findings) {
174
+ records.push({
175
+ label: `${change.toUpperCase()}_FINDING`,
176
+ fields: {
177
+ ...finding.fields,
178
+ id: finding.id,
179
+ change,
180
+ type: finding.ruleId,
181
+ sev: finding.severity,
182
+ repo: finding.repository,
183
+ file: finding.file,
184
+ path: finding.path,
185
+ line: finding.line,
186
+ url: finding.url,
187
+ permalink: finding.permalink,
188
+ explain: finding.explain,
189
+ },
190
+ });
191
+ }
192
+ }
193
+ }
194
+
195
+ /** @param {import('./types.js').OrganizationReport} report */
196
+ function reportMetadata(report) {
197
+ return {
198
+ organization: report.organization,
199
+ analysisGeneration: report.analysis.generation,
200
+ visibility: report.scope.visibility,
201
+ repositoryFilters: report.scope.repositories.length > 0
202
+ ? report.scope.repositories.join(', ')
203
+ : 'all eligible repositories',
204
+ includeArchived: report.scope.includeArchived,
205
+ includeDisabled: report.scope.includeDisabled,
206
+ includeForks: report.scope.includeForks,
207
+ maxRepositories: report.scope.maxRepositories ?? 'none',
208
+ severity: report.scope.severity ?? 'all levels',
209
+ baseline: report.baseline.path ?? 'none',
210
+ coverageComplete: report.coverage.complete,
211
+ };
212
+ }
213
+
214
+ /**
215
+ * @param {import('./types.js').OrganizationFinding} finding
216
+ * @param {string} cwd
217
+ */
218
+ function normalizeFinding(finding, cwd) {
219
+ return {
220
+ ...finding,
221
+ file: canonicalPath(finding.file, cwd),
222
+ };
223
+ }