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
package/src/cli.js CHANGED
@@ -3,20 +3,20 @@
3
3
  * actions-warden CLI entry point.
4
4
  *
5
5
  * Commands: audit, pin, upgrade, verify, report, org-scan, rules
6
- * Global flags: --format, --output, --output-path, --workflow, --token
6
+ * Common command flags include --format, --output, --output-path, and --workflow.
7
7
  *
8
8
  * Mutating operations (pin, upgrade) only write when --write is present.
9
9
  *
10
10
  * Exit codes:
11
- * 0 no findings / no errors
12
- * 1 findings reported (audit FAIL) or errors during pin/upgrade
13
- * 2 invalid arguments
11
+ * 0 completed with status OK (or displayed help/version)
12
+ * 1 completed with a structured FAIL result
13
+ * 2 invocation-level failure
14
14
  */
15
15
 
16
- import { realpath } from 'node:fs/promises';
17
- import { basename, dirname, join, resolve } from 'node:path';
16
+ import { stat } from 'node:fs/promises';
17
+ import { resolve } from 'node:path';
18
18
  import { createRequire } from 'node:module';
19
- import { Command, Option } from 'commander';
19
+ import { Command, CommanderError, InvalidArgumentError, Option } from 'commander';
20
20
 
21
21
  import { audit, renderAudit } from './commands/audit.js';
22
22
  import { pin, renderPin } from './commands/pin.js';
@@ -28,33 +28,80 @@ import { listRules } from './rules/index.js';
28
28
  import { format as fmt } from './lib/formatter.js';
29
29
  import { writeFileGuarded } from './lib/writer.js';
30
30
  import { serializeBaseline } from './lib/baseline.js';
31
- import { formatOrganizationProgress } from './lib/org-progress.js';
32
31
  import {
33
- AGENT_MODE_ENVIRONMENT_VARIABLE,
34
- createOrganizationAgentArtifacts,
35
- renderOrganizationAgentReceipt,
36
- resolveAgentMode,
37
- } from './lib/agent-mode.js';
32
+ createOrganizationProgressReporter,
33
+ isScanFailureReported,
34
+ } from './lib/org-progress.js';
35
+ import { redact } from './lib/redact.js';
36
+ import { resolveTargets } from './lib/targets.js';
37
+ import {
38
+ EXECUTION_CONTEXT_ENVIRONMENT_VARIABLE,
39
+ renderOrganizationScanReceipt,
40
+ resolveExecutionContext,
41
+ } from './lib/org-artifacts.js';
42
+ import { runOrganizationScan } from './lib/org-run.js';
43
+ import { SEVERITY_LEVELS, VISIBILITY_FILTERS } from './lib/org-schema.js';
44
+ import { writeOrganizationReportDirectory } from './lib/org-report-directory.js';
45
+ import {
46
+ assertDestinationsAreDistinct,
47
+ assertDestinationsDoNotReplaceControls,
48
+ assertDestinationsUseSafeNames,
49
+ validateWriteDestination,
50
+ } from './lib/destination.js';
38
51
 
39
52
  const program = new Command();
40
53
  const require = createRequire(import.meta.url);
41
54
  const { version } = require('../package.json');
55
+ const FIX_ID_RE = /^[0-9a-f]{16}$/i;
56
+ let structuredProgressContext = null;
42
57
  program
43
58
  .name('actions-warden')
44
59
  .description('Audit GitHub Actions across repositories and organizations; pin, verify, and upgrade dependencies.')
45
- .version(version);
46
-
47
- const formatOption = new Option('--format <fmt>', 'output format').choices(['toon', 'json', 'text', 'sarif']).default('toon');
48
- const outputOption = new Option('--output <dest>', 'output destination').choices(['stdout', 'file']).default('stdout');
49
-
50
- function addCommonOptions(cmd) {
51
- return cmd
52
- .option('-w, --workflow <pattern...>', 'workflow path or glob (repeatable)')
53
- .option('--cwd <dir>', 'working directory', process.cwd())
54
- .option('--token <token>', 'GitHub token (overrides GITHUB_TOKEN / GH_TOKEN)')
55
- .addOption(formatOption)
56
- .addOption(outputOption)
57
- .option('--output-path <path>', 'file path when --output=file');
60
+ .version(version)
61
+ .exitOverride(error => {
62
+ if (error.exitCode !== 0) error.exitCode = 2;
63
+ throw error;
64
+ });
65
+
66
+ function createFormatOption(defaultValue = 'toon') {
67
+ return new Option('--format <fmt>', 'output format')
68
+ .choices(['toon', 'json', 'text', 'csv', 'sarif', 'html'])
69
+ .default(defaultValue);
70
+ }
71
+
72
+ function createOutputOption(defaultValue = 'stdout') {
73
+ return new Option('--output <dest>', 'output destination')
74
+ .choices(['stdout', 'file'])
75
+ .default(defaultValue);
76
+ }
77
+
78
+ function createOutputPathOption() {
79
+ return new Option('--output-path <path>', 'report path (implies --output=file)')
80
+ .argParser(value => parseNonEmpty(value, '--output-path'))
81
+ .implies({ output: 'file' });
82
+ }
83
+
84
+ function createCwdOption() {
85
+ return new Option('--cwd <dir>', 'working directory')
86
+ .argParser(value => parseNonEmpty(value, '--cwd'))
87
+ .default(process.cwd(), 'current directory');
88
+ }
89
+
90
+ function createTokenOption() {
91
+ return new Option('--token <token>', 'GitHub token override (prefer GITHUB_TOKEN or GH_TOKEN)')
92
+ .argParser(value => parseNonEmpty(value, '--token'));
93
+ }
94
+
95
+ function addCommonOptions(cmd, { includeToken = true } = {}) {
96
+ const configured = cmd
97
+ .addOption(new Option('-w, --workflow <pattern...>', 'workflow path or glob (repeatable)')
98
+ .argParser((value, previous) => collectNonEmpty(value, previous, '--workflow')))
99
+ .addOption(createCwdOption());
100
+ if (includeToken) configured.addOption(createTokenOption());
101
+ return configured
102
+ .addOption(createFormatOption())
103
+ .addOption(createOutputOption())
104
+ .addOption(createOutputPathOption());
58
105
  }
59
106
 
60
107
  async function emit(payload, opts) {
@@ -71,22 +118,27 @@ async function emit(payload, opts) {
71
118
  process.stdout.write(payload);
72
119
  }
73
120
 
74
- addCommonOptions(program.command('audit'))
121
+ addCommonOptions(program.command('audit'), { includeToken: false })
75
122
  .description('Scan workflows for security findings')
76
- .addOption(new Option('--severity <level>', 'minimum severity').choices(['low', 'medium', 'high', 'critical']))
77
- .option('--explain', 'include plain-English remediation hint for each finding', false)
78
- .option('--config <path>', 'repository policy file (default: .actions-warden.yml)')
79
- .option('--ignore-config', 'do not load repository policy', false)
80
- .option('--baseline <path>', 'suppress findings recorded in a baseline')
81
- .option('--create-baseline <path>', 'write the current findings as a baseline')
123
+ .addOption(new Option('--severity <level>', 'minimum severity').choices(SEVERITY_LEVELS))
124
+ .option('--explain', 'include plain-English remediation hint for each finding')
125
+ .addOption(new Option('--config <path>', 'repository policy file (default: .actions-warden.yml)')
126
+ .argParser(value => parseNonEmpty(value, '--config'))
127
+ .conflicts('ignoreConfig'))
128
+ .addOption(new Option('--ignore-config', 'do not load repository policy').conflicts('config'))
129
+ .addOption(new Option('--baseline <path>', 'suppress findings recorded in a baseline')
130
+ .argParser(value => parseNonEmpty(value, '--baseline'))
131
+ .conflicts('createBaseline'))
132
+ .addOption(new Option('--create-baseline <path>', 'write the current findings as a baseline')
133
+ .argParser(value => parseNonEmpty(value, '--create-baseline'))
134
+ .conflicts('baseline'))
82
135
  .action(async (opts) => {
83
136
  const createBaseline = opts.createBaseline;
84
- if (createBaseline && opts.baseline) {
85
- throw new Error('--baseline and --create-baseline cannot be used together');
86
- }
87
- if (opts.ignoreConfig && opts.config) {
88
- throw new Error('--config and --ignore-config cannot be used together');
89
- }
137
+ const destinations = await preflightRepositoryCommand(opts, {
138
+ additionalDestinations: createBaseline
139
+ ? [{ option: '--create-baseline', path: createBaseline }]
140
+ : [],
141
+ });
90
142
  const result = await audit({
91
143
  cwd: opts.cwd,
92
144
  workflows: opts.workflow,
@@ -96,6 +148,10 @@ addCommonOptions(program.command('audit'))
96
148
  baseline: opts.baseline,
97
149
  ignoreBaseline: Boolean(createBaseline),
98
150
  });
151
+ await assertDestinationsDoNotReplaceControls(destinations, [
152
+ { label: 'active config', path: result.configPath },
153
+ ...(!createBaseline ? [{ label: 'active baseline', path: result.baseline.path }] : []),
154
+ ]);
99
155
  if (createBaseline) {
100
156
  await writeFileGuarded({
101
157
  path: resolve(opts.cwd, createBaseline),
@@ -111,6 +167,8 @@ addCommonOptions(program.command('audit'))
111
167
  },
112
168
  }], {
113
169
  status: 'OK',
170
+ title: 'Finding baseline created',
171
+ metadata: { path: createBaseline },
114
172
  json: {
115
173
  schemaVersion: '1.0',
116
174
  path: createBaseline,
@@ -129,15 +187,11 @@ addCommonOptions(program.command('audit'))
129
187
 
130
188
  addCommonOptions(program.command('pin'))
131
189
  .description('Pin tag/branch refs to immutable commit SHAs')
132
- .option('--write', 'apply changes (disables dry-run)', false)
133
- .option('--dry-run', 'explicitly keep dry-run mode (the default)', false)
134
- .option('--fix <id>', 'apply only the change with this id')
190
+ .addOption(new Option('--write', 'apply changes (disables dry-run)').conflicts('dryRun'))
191
+ .addOption(new Option('--dry-run', 'explicitly keep dry-run mode (the default)').conflicts('write'))
192
+ .addOption(new Option('--fix <id>', 'select only the 16-hex change id').argParser(parseFixId))
135
193
  .action(async (opts) => {
136
- if (opts.write && opts.dryRun) {
137
- process.stderr.write('error: --write and --dry-run cannot be used together\n');
138
- process.exitCode = 2;
139
- return;
140
- }
194
+ await preflightRepositoryCommand(opts);
141
195
  const dryRun = !opts.write;
142
196
  const result = await pin({
143
197
  cwd: opts.cwd,
@@ -153,24 +207,16 @@ addCommonOptions(program.command('pin'))
153
207
 
154
208
  addCommonOptions(program.command('upgrade'))
155
209
  .description('Upgrade pinned/tagged actions to a newer version')
156
- .option('--write', 'apply changes (disables dry-run)', false)
157
- .option('--dry-run', 'explicitly keep dry-run mode (the default)', false)
210
+ .addOption(new Option('--write', 'apply changes (disables dry-run)').conflicts('dryRun'))
211
+ .addOption(new Option('--dry-run', 'explicitly keep dry-run mode (the default)').conflicts('write'))
158
212
  .addOption(new Option('--mode <m>', 'upgrade scope').choices(['major', 'minor', 'patch']).default('minor'))
159
- .option('--min-age <days>', 'cooldown: only accept tags older than this many days', '7')
160
- .option('--fix <id>', 'apply only the change with this id')
213
+ .addOption(new Option('--min-age <days>', 'cooldown: only accept tags older than this many days')
214
+ .argParser(value => parseInteger(value, '--min-age', { min: 0 }))
215
+ .default(7))
216
+ .addOption(new Option('--fix <id>', 'select only the 16-hex change id').argParser(parseFixId))
161
217
  .action(async (opts) => {
162
- if (opts.write && opts.dryRun) {
163
- process.stderr.write('error: --write and --dry-run cannot be used together\n');
164
- process.exitCode = 2;
165
- return;
166
- }
218
+ await preflightRepositoryCommand(opts);
167
219
  const dryRun = !opts.write;
168
- const minAgeDays = Number.parseInt(opts.minAge, 10);
169
- if (Number.isNaN(minAgeDays) || minAgeDays < 0) {
170
- process.stderr.write('error: --min-age must be a non-negative integer\n');
171
- process.exitCode = 2;
172
- return;
173
- }
174
220
  const result = await upgrade({
175
221
  cwd: opts.cwd,
176
222
  workflows: opts.workflow,
@@ -178,7 +224,7 @@ addCommonOptions(program.command('upgrade'))
178
224
  token: opts.token,
179
225
  mode: opts.mode,
180
226
  fix: opts.fix,
181
- minAgeDays,
227
+ minAgeDays: opts.minAge,
182
228
  });
183
229
  const payload = renderUpgrade(result, { format: opts.format, dryRun, mode: opts.mode, cwd: opts.cwd });
184
230
  await emit(payload, opts);
@@ -188,23 +234,21 @@ addCommonOptions(program.command('upgrade'))
188
234
  addCommonOptions(program.command('report'))
189
235
  .description('Combined audit + pin (dry) + upgrade (dry) report')
190
236
  .addOption(new Option('--mode <m>', 'upgrade scope').choices(['major', 'minor', 'patch']).default('minor'))
191
- .addOption(new Option('--severity <level>', 'minimum audit severity').choices(['low', 'medium', 'high', 'critical']))
192
- .option('--explain', 'include remediation hints in audit findings', false)
193
- .option('--min-age <days>', 'cooldown for upgrades (days)', '7')
194
- .option('--offline', 'skip network calls (audit only)', false)
195
- .option('--config <path>', 'repository policy file (default: .actions-warden.yml)')
196
- .option('--ignore-config', 'do not load repository policy', false)
197
- .option('--baseline <path>', 'suppress audit findings recorded in a baseline')
237
+ .addOption(new Option('--severity <level>', 'minimum audit severity').choices(SEVERITY_LEVELS))
238
+ .option('--explain', 'include remediation hints in audit findings')
239
+ .addOption(new Option('--min-age <days>', 'cooldown for upgrades (days)')
240
+ .argParser(value => parseInteger(value, '--min-age', { min: 0 }))
241
+ .default(7))
242
+ .addOption(new Option('--offline', 'skip network calls (audit only)')
243
+ .conflicts(['token', 'mode', 'minAge']))
244
+ .addOption(new Option('--config <path>', 'repository policy file (default: .actions-warden.yml)')
245
+ .argParser(value => parseNonEmpty(value, '--config'))
246
+ .conflicts('ignoreConfig'))
247
+ .addOption(new Option('--ignore-config', 'do not load repository policy').conflicts('config'))
248
+ .addOption(new Option('--baseline <path>', 'suppress audit findings recorded in a baseline')
249
+ .argParser(value => parseNonEmpty(value, '--baseline')))
198
250
  .action(async (opts) => {
199
- const minAgeDays = Number.parseInt(opts.minAge, 10);
200
- if (Number.isNaN(minAgeDays) || minAgeDays < 0) {
201
- process.stderr.write('error: --min-age must be a non-negative integer\n');
202
- process.exitCode = 2;
203
- return;
204
- }
205
- if (opts.ignoreConfig && opts.config) {
206
- throw new Error('--config and --ignore-config cannot be used together');
207
- }
251
+ const destinations = await preflightRepositoryCommand(opts);
208
252
  const result = await report({
209
253
  cwd: opts.cwd,
210
254
  workflows: opts.workflow,
@@ -213,10 +257,14 @@ addCommonOptions(program.command('report'))
213
257
  severity: opts.severity,
214
258
  explain: Boolean(opts.explain),
215
259
  skipResolve: Boolean(opts.offline),
216
- minAgeDays,
260
+ minAgeDays: opts.minAge,
217
261
  configPath: opts.ignoreConfig ? false : opts.config,
218
262
  baseline: opts.baseline,
219
263
  });
264
+ await assertDestinationsDoNotReplaceControls(destinations, [
265
+ { label: 'active config', path: result.audit.configPath },
266
+ { label: 'active baseline', path: result.audit.baseline.path },
267
+ ]);
220
268
  const payload = renderReport(result, { format: opts.format, mode: opts.mode, cwd: opts.cwd });
221
269
  await emit(payload, opts);
222
270
  process.exitCode = result.status === 'OK' ? 0 : 1;
@@ -225,6 +273,7 @@ addCommonOptions(program.command('report'))
225
273
  addCommonOptions(program.command('verify'))
226
274
  .description('Verify pinned SHAs and version metadata against GitHub')
227
275
  .action(async (opts) => {
276
+ await preflightRepositoryCommand(opts);
228
277
  const result = await verify({
229
278
  cwd: opts.cwd,
230
279
  workflows: opts.workflow,
@@ -237,88 +286,242 @@ addCommonOptions(program.command('verify'))
237
286
 
238
287
  program.command('org-scan <organization>')
239
288
  .description('Scan workflow security across a GitHub organization')
240
- .option('-r, --repository <pattern...>', 'repository name or glob (repeatable)')
241
- .addOption(new Option('--visibility <visibility>', 'repository visibility').choices(['all', 'public', 'private', 'internal']).default('all'))
242
- .option('--include-archived', 'include archived repositories', false)
243
- .option('--include-disabled', 'include disabled repositories', false)
244
- .option('--include-forks', 'include forked repositories', false)
245
- .option('--max-repos <count>', 'scan at most this many repositories')
246
- .option('--concurrency <count>', 'concurrent repository scans (1-16)', '4')
247
- .addOption(new Option('--severity <level>', 'minimum severity').choices(['low', 'medium', 'high', 'critical']))
248
- .option('--explain', 'include plain-English remediation hint for each finding', false)
249
- .option('--config <path>', 'organization-wide policy file (default: .actions-warden.yml)')
250
- .option('--ignore-config', 'do not load organization-wide policy', false)
251
- .option('--baseline <path>', 'suppress findings recorded in an organization baseline')
252
- .option('--checkpoint <path>', 'create or replace a resumable scan checkpoint')
253
- .option('--resume <path>', 'resume from and update an existing checkpoint')
254
- .addOption(new Option('--progress <mode>', 'live progress on stderr').choices(['auto', 'always', 'never']).default('auto'))
289
+ .addOption(new Option('-r, --repository <pattern...>', 'repository name or glob (repeatable)')
290
+ .argParser((value, previous) => collectNonEmpty(value, previous, '--repository')))
291
+ .addOption(new Option('--visibility <visibility>', 'repository visibility').choices(VISIBILITY_FILTERS).default('all'))
292
+ .option('--include-archived', 'include archived repositories')
293
+ .option('--include-disabled', 'include disabled repositories')
294
+ .option('--include-forks', 'include forked repositories')
295
+ .addOption(new Option('--max-repos <count>', 'scan at most this many repositories')
296
+ .argParser(value => parseInteger(value, '--max-repos', { min: 1 })))
297
+ .addOption(new Option('--concurrency <count>', 'concurrent repository scans (1-16)')
298
+ .argParser(value => parseInteger(value, '--concurrency', { min: 1, max: 16 }))
299
+ .default(4))
300
+ .addOption(new Option('--severity <level>', 'minimum severity').choices(SEVERITY_LEVELS))
301
+ .option('--explain', 'include plain-English remediation hint for each finding')
302
+ .addOption(new Option('--config <path>', 'organization-wide policy file (default: .actions-warden.yml)')
303
+ .argParser(value => parseNonEmpty(value, '--config'))
304
+ .conflicts('ignoreConfig'))
305
+ .addOption(new Option('--ignore-config', 'do not load organization-wide policy').conflicts('config'))
306
+ .addOption(new Option('--baseline <path>', 'suppress findings recorded in an organization baseline')
307
+ .argParser(value => parseNonEmpty(value, '--baseline')))
308
+ .addOption(new Option('--checkpoint <path>', 'create or automatically resume a scan checkpoint')
309
+ .argParser(value => parseNonEmpty(value, '--checkpoint'))
310
+ .conflicts('resume'))
311
+ .addOption(new Option('--resume <path>', 'resume from and update an existing checkpoint')
312
+ .argParser(value => parseNonEmpty(value, '--resume'))
313
+ .conflicts('checkpoint'))
314
+ .addOption(new Option('--fresh', 'start fresh and replace the selected checkpoint')
315
+ .conflicts('resume'))
316
+ .addOption(new Option('--no-auto-checkpoint', 'disable the automatic scope-specific checkpoint'))
317
+ .addOption(new Option('--previous-report <path>', 'compare with a prior organization JSON report')
318
+ .argParser(value => parseNonEmpty(value, '--previous-report')))
319
+ .addOption(new Option('--progress <mode>', 'stderr progress: auto, plain, json, or none')
320
+ .choices(['auto', 'plain', 'json', 'none'])
321
+ .default('auto'))
322
+ .addOption(new Option('--report-dir <dir>', 'write compact JSON plus per-repository artifacts')
323
+ .argParser(value => parseNonEmpty(value, '--report-dir'))
324
+ .conflicts('outputPath'))
255
325
  .option('--agent-mode', 'use bounded AI-agent output and automatic artifacts')
256
326
  .option('--no-agent-mode', 'disable agent mode from the environment')
257
- .option('--cwd <dir>', 'working directory', process.cwd())
258
- .option('--token <token>', 'GitHub token (overrides GITHUB_TOKEN / GH_TOKEN)')
259
- .addOption(formatOption)
260
- .addOption(outputOption)
261
- .option('--output-path <path>', 'file path when --output=file')
327
+ .addOption(createCwdOption())
328
+ .addOption(createTokenOption())
329
+ .addOption(createFormatOption('json'))
330
+ .addOption(createOutputOption('file'))
331
+ .addOption(createOutputPathOption())
262
332
  .action(async (organization, opts, command) => {
263
- if (opts.ignoreConfig && opts.config) {
264
- throw new Error('--config and --ignore-config cannot be used together');
265
- }
266
- if (opts.checkpoint && opts.resume) {
267
- throw new Error('--checkpoint and --resume cannot be used together');
268
- }
269
- const concurrency = parsePositiveInteger(opts.concurrency, '--concurrency');
270
- const maxRepositories = opts.maxRepos === undefined
271
- ? undefined
272
- : parsePositiveInteger(opts.maxRepos, '--max-repos');
273
- const agentMode = resolveAgentMode({
333
+ await validateWorkingDirectory(opts.cwd);
334
+ assertMutuallyExclusiveFlags('--agent-mode', '--no-agent-mode');
335
+ const executionContext = resolveExecutionContext({
274
336
  optionValue: opts.agentMode,
275
337
  optionSource: command.getOptionValueSource('agentMode'),
276
- environmentValue: process.env[AGENT_MODE_ENVIRONMENT_VARIABLE],
338
+ environmentValue: process.env[EXECUTION_CONTEXT_ENVIRONMENT_VARIABLE],
277
339
  });
278
- const effective = { ...opts };
279
- if (agentMode) {
280
- if (command.getOptionValueSource('format') === 'default') effective.format = 'json';
281
- if (command.getOptionValueSource('output') === 'default') effective.output = 'file';
282
- if (command.getOptionValueSource('progress') === 'default') effective.progress = 'never';
340
+ const effective = resolveOrganizationScanOptions(opts, command);
341
+ let progressReporter;
342
+ const startedAt = new Date();
343
+ try {
344
+ const run = await runOrganizationScan({
345
+ ...organizationRunOptions(organization, effective),
346
+ scanOrganization,
347
+ openProgress: () => {
348
+ progressReporter = openOrganizationProgress({
349
+ organization,
350
+ effective,
351
+ command,
352
+ executionContext,
353
+ });
354
+ return progressReporter;
355
+ },
356
+ });
357
+ await writeOrganizationOutput({
358
+ run,
359
+ effective,
360
+ agentMode: executionContext === 'agent',
361
+ startedAt,
362
+ });
363
+ process.exitCode = run.result.status === 'OK' ? 0 : 1;
364
+ progressReporter?.close();
365
+ } catch (error) {
366
+ if (!structuredProgressContext) progressReporter?.close();
367
+ throw error;
368
+ }
369
+ });
370
+
371
+ program.command('rules')
372
+ .description('List available audit rules')
373
+ .addOption(createFormatOption())
374
+ .action((opts) => {
375
+ const rules = listRules();
376
+ const payload = fmt(opts.format, rules.map(r => ({ label: 'RULE', fields: r })), {
377
+ status: 'OK',
378
+ title: 'Audit rule catalog',
379
+ json: { schemaVersion: '1.0', rules, status: 'OK' },
380
+ });
381
+ process.stdout.write(payload);
382
+ });
383
+
384
+ program.parseAsync(process.argv).catch((err) => {
385
+ if (err instanceof CommanderError) {
386
+ process.exitCode = err.exitCode;
387
+ return;
388
+ }
389
+ if (isScanFailureReported(err)) {
390
+ // The scan adapter already emitted the terminal structured failure.
391
+ } else if (structuredProgressContext) {
392
+ structuredProgressContext.reporter.emit({
393
+ type: 'command-failed',
394
+ organization: structuredProgressContext.organization,
395
+ error: String(err?.message ?? err),
396
+ });
397
+ } else {
398
+ process.stderr.write(`error: ${cliErrorText(err)}\n`);
399
+ }
400
+ structuredProgressContext?.reporter.close();
401
+ process.exitCode = 2;
402
+ });
403
+
404
+ function cliErrorText(error) {
405
+ return [...redact(String(error?.message ?? error))]
406
+ .map(char => {
407
+ const code = char.charCodeAt(0);
408
+ return code < 32 || code === 127 ? ' ' : char;
409
+ })
410
+ .join('');
411
+ }
412
+
413
+ function parseNonEmpty(value, option) {
414
+ if (value.length === 0) {
415
+ throw new InvalidArgumentError(`${option} must be non-empty`);
416
+ }
417
+ return value;
418
+ }
419
+
420
+ function collectNonEmpty(value, previous, option) {
421
+ return [...(Array.isArray(previous) ? previous : []), parseNonEmpty(value, option)];
422
+ }
423
+
424
+ function parseInteger(value, option, { min, max = Number.MAX_SAFE_INTEGER }) {
425
+ if (!/^\d+$/.test(value)) {
426
+ throw new InvalidArgumentError(`${option} must be an integer`);
427
+ }
428
+ const parsed = Number(value);
429
+ if (!Number.isSafeInteger(parsed) || parsed < min || parsed > max) {
430
+ if (min === 0 && max === Number.MAX_SAFE_INTEGER) {
431
+ throw new InvalidArgumentError(`${option} must be a non-negative integer`);
283
432
  }
284
- const agentArtifacts = agentMode
285
- ? await createOrganizationAgentArtifacts({
286
- organization,
287
- cwd: effective.cwd,
288
- repositories: effective.repository,
289
- visibility: effective.visibility,
290
- includeArchived: Boolean(effective.includeArchived),
291
- includeDisabled: Boolean(effective.includeDisabled),
292
- includeForks: Boolean(effective.includeForks),
293
- maxRepositories,
294
- severity: effective.severity,
295
- explain: Boolean(effective.explain),
296
- configPath: effective.ignoreConfig ? false : effective.config,
297
- baseline: effective.baseline,
298
- reportFormat: effective.format,
299
- })
300
- : null;
301
- if (agentMode && effective.output === 'file' && !effective.outputPath) {
302
- effective.outputPath = agentArtifacts.reportPath;
433
+ if (min === 1 && max === Number.MAX_SAFE_INTEGER) {
434
+ throw new InvalidArgumentError(`${option} must be a positive integer`);
303
435
  }
304
- let checkpointPath = effective.resume ?? effective.checkpoint;
305
- let resume = Boolean(effective.resume);
306
- if (agentMode && !checkpointPath) {
307
- checkpointPath = agentArtifacts.checkpointPath;
308
- resume = agentArtifacts.resume;
436
+ throw new InvalidArgumentError(`${option} must be an integer from ${min} to ${max}`);
437
+ }
438
+ return parsed;
439
+ }
440
+
441
+ function parseFixId(value) {
442
+ if (!FIX_ID_RE.test(value)) {
443
+ throw new InvalidArgumentError('--fix must be a 16-character hexadecimal change id');
444
+ }
445
+ return value.toLowerCase();
446
+ }
447
+
448
+ async function preflightRepositoryCommand(opts, { additionalDestinations = [] } = {}) {
449
+ await validateWorkingDirectory(opts.cwd);
450
+ const outputDestination = await validateOutputDestination(opts);
451
+ const destinations = outputDestination ? [outputDestination] : [];
452
+ for (const destination of additionalDestinations) {
453
+ destinations.push(await validateWriteDestination({
454
+ ...destination,
455
+ cwd: opts.cwd,
456
+ }));
457
+ }
458
+ await assertDestinationsAreDistinct(destinations);
459
+ await assertDestinationsUseSafeNames(destinations, opts.cwd);
460
+ if (destinations.length > 0) {
461
+ const workflows = await resolveTargets({ workflows: opts.workflow, cwd: opts.cwd });
462
+ await assertDestinationsDoNotReplaceControls(
463
+ destinations,
464
+ workflows.map(path => ({ label: 'selected workflow', path })),
465
+ );
466
+ }
467
+ return destinations;
468
+ }
469
+
470
+ async function validateWorkingDirectory(cwd) {
471
+ if (typeof cwd !== 'string' || cwd.length === 0 || cwd.includes('\0')) {
472
+ throw new Error('--cwd must be an existing directory');
473
+ }
474
+ let metadata;
475
+ try {
476
+ metadata = await stat(resolve(cwd));
477
+ } catch (error) {
478
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR') {
479
+ throw new Error('--cwd must be an existing directory');
480
+ }
481
+ throw error;
482
+ }
483
+ if (!metadata.isDirectory()) throw new Error('--cwd must be an existing directory');
484
+ }
485
+
486
+ function assertOutputPathUsesFile(opts) {
487
+ if (opts.outputPath && opts.output !== 'file') {
488
+ throw new Error('--output-path cannot be used with --output=stdout');
489
+ }
490
+ }
491
+
492
+ async function validateOutputDestination(opts) {
493
+ assertOutputPathUsesFile(opts);
494
+ if (opts.output !== 'file') return null;
495
+ if (!opts.outputPath) throw new Error('--output-path is required when --output=file');
496
+ return validateWriteDestination({
497
+ option: '--output-path',
498
+ path: opts.outputPath,
499
+ cwd: opts.cwd ?? process.cwd(),
500
+ });
501
+ }
502
+
503
+ function resolveOrganizationScanOptions(opts, command) {
504
+ const effective = { ...opts };
505
+ if (effective.reportDir) {
506
+ if (command.getOptionValueSource('format') === 'cli' && effective.format !== 'json') {
507
+ throw new Error('--report-dir supports only --format=json');
309
508
  }
310
- if (
311
- checkpointPath
312
- && effective.output === 'file'
313
- && effective.outputPath
314
- && await samePath(
315
- resolve(effective.cwd, checkpointPath),
316
- resolve(effective.cwd, effective.outputPath),
317
- )
318
- ) {
319
- throw new Error('checkpoint and report output paths must be different');
509
+ if (command.getOptionValueSource('output') === 'cli' && effective.output !== 'file') {
510
+ throw new Error('--report-dir cannot be used with --output=stdout');
320
511
  }
321
- const result = await scanOrganization({
512
+ effective.format = 'json';
513
+ effective.output = 'file';
514
+ }
515
+ if (effective.previousReport && effective.format === 'sarif') {
516
+ throw new Error('--previous-report cannot be used with --format=sarif');
517
+ }
518
+ assertOutputPathUsesFile(effective);
519
+ return effective;
520
+ }
521
+
522
+ function organizationRunOptions(organization, effective) {
523
+ return {
524
+ scan: {
322
525
  organization,
323
526
  cwd: effective.cwd,
324
527
  token: effective.token,
@@ -327,74 +530,78 @@ program.command('org-scan <organization>')
327
530
  includeArchived: Boolean(effective.includeArchived),
328
531
  includeDisabled: Boolean(effective.includeDisabled),
329
532
  includeForks: Boolean(effective.includeForks),
330
- maxRepositories,
331
- concurrency,
533
+ maxRepositories: effective.maxRepos,
534
+ concurrency: effective.concurrency,
332
535
  severity: effective.severity,
333
536
  explain: Boolean(effective.explain),
334
537
  configPath: effective.ignoreConfig ? false : effective.config,
335
538
  baseline: effective.baseline,
336
- checkpointPath,
337
- resume,
338
- onProgress: progressEnabled(effective.progress)
339
- ? event => {
340
- const message = formatOrganizationProgress(event);
341
- if (message) process.stderr.write(message);
342
- }
343
- : undefined,
539
+ },
540
+ format: effective.format,
541
+ output: effective.output,
542
+ outputPath: effective.outputPath,
543
+ reportDirectory: effective.reportDir,
544
+ checkpointPath: effective.checkpoint,
545
+ resumePath: effective.resume,
546
+ fresh: Boolean(effective.fresh),
547
+ autoCheckpoint: effective.autoCheckpoint !== false,
548
+ previousReportPath: effective.previousReport,
549
+ labels: { output: '--output-path', checkpoint: '--checkpoint', resume: '--resume' },
550
+ };
551
+ }
552
+
553
+ function openOrganizationProgress({ organization, effective, command, executionContext }) {
554
+ const reporter = createOrganizationProgressReporter({
555
+ mode: effective.progress,
556
+ context: command.getOptionValueSource('progress') === 'cli' ? 'auto' : executionContext,
557
+ stream: process.stderr,
558
+ });
559
+ if (reporter.mode === 'json') structuredProgressContext = { organization, reporter };
560
+ return reporter;
561
+ }
562
+
563
+ async function writeOrganizationOutput({ run, effective, agentMode, startedAt }) {
564
+ const { result } = run;
565
+ let reportPath = run.reportPath;
566
+ let reportDirectoryPath;
567
+ let manifestPath;
568
+ if (run.reportDirectory) {
569
+ const directoryResult = await writeOrganizationReportDirectory({
570
+ result,
571
+ path: effective.reportDir,
572
+ cwd: effective.cwd,
344
573
  });
574
+ reportPath = directoryResult.reportPath;
575
+ reportDirectoryPath = directoryResult.directory;
576
+ manifestPath = directoryResult.manifestPath;
577
+ } else {
345
578
  const payload = renderOrganizationScan(result, {
346
579
  format: effective.format,
347
580
  cwd: effective.cwd,
348
581
  });
349
- await emit(payload, effective);
350
- if (agentMode && effective.output === 'file') {
351
- process.stdout.write(renderOrganizationAgentReceipt({
352
- result,
353
- reportPath: effective.outputPath,
354
- reportFormat: effective.format,
355
- checkpointPath,
356
- resumed: resume,
357
- }));
358
- }
359
- process.exitCode = result.status === 'OK' ? 0 : 1;
360
- });
361
-
362
- program.command('rules')
363
- .description('List available audit rules')
364
- .addOption(formatOption)
365
- .action((opts) => {
366
- const rules = listRules();
367
- const payload = fmt(opts.format, rules.map(r => ({ label: 'RULE', fields: r })), {
368
- status: 'OK',
369
- json: { schemaVersion: '1.0', rules, status: 'OK' },
370
- });
371
- process.stdout.write(payload);
372
- });
373
-
374
- program.parseAsync(process.argv).catch((err) => {
375
- process.stderr.write(`error: ${err.message}\n`);
376
- process.exitCode = 2;
377
- });
378
-
379
- function parsePositiveInteger(value, option) {
380
- if (!/^\d+$/.test(value) || Number.parseInt(value, 10) < 1) {
381
- throw new Error(`${option} must be a positive integer`);
582
+ await emit(payload, { ...effective, outputPath: run.reportPath });
382
583
  }
383
- return Number.parseInt(value, 10);
584
+ if (effective.output !== 'file') return;
585
+ process.stdout.write(renderOrganizationScanReceipt({
586
+ result,
587
+ startedAt,
588
+ finishedAt: new Date(),
589
+ reportPath,
590
+ reportFormat: effective.format,
591
+ checkpointPath: run.checkpointPath,
592
+ resumed: run.resumed,
593
+ repositoriesReused: run.repositoriesReused,
594
+ reportLayout: run.reportDirectory ? 'directory' : 'single',
595
+ reportDirectory: reportDirectoryPath,
596
+ manifestPath,
597
+ kind: agentMode ? 'actions-warden-agent-receipt' : 'actions-warden-org-scan-receipt',
598
+ }));
384
599
  }
385
600
 
386
- function progressEnabled(mode) {
387
- return mode === 'always' || (mode === 'auto' && Boolean(process.stderr.isTTY));
601
+ function assertMutuallyExclusiveFlags(left, right) {
602
+ const args = process.argv.slice(2);
603
+ if (args.includes(left) && args.includes(right)) {
604
+ throw new Error(`${left} and ${right} cannot be used together`);
605
+ }
388
606
  }
389
607
 
390
- async function samePath(left, right) {
391
- const [leftParent, rightParent] = await Promise.all([
392
- realpath(dirname(left)),
393
- realpath(dirname(right)),
394
- ]);
395
- const leftTarget = join(leftParent, basename(left));
396
- const rightTarget = join(rightParent, basename(right));
397
- return process.platform === 'win32'
398
- ? leftTarget.toLowerCase() === rightTarget.toLowerCase()
399
- : leftTarget === rightTarget;
400
- }