@blundergoat/gruff-ts 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 (77) hide show
  1. package/CHANGELOG.md +123 -1
  2. package/CONTRIBUTING.md +32 -25
  3. package/README.md +55 -46
  4. package/SECURITY.md +18 -30
  5. package/UPGRADING.md +101 -0
  6. package/bin/gruff-ts +3 -0
  7. package/docs/README.md +11 -13
  8. package/docs/agent-hook.md +33 -24
  9. package/docs/ci-integration.md +38 -24
  10. package/docs/configuration.md +173 -71
  11. package/docs/dashboard.md +12 -13
  12. package/docs/output-formats.md +100 -25
  13. package/docs/philosophy.md +2 -2
  14. package/docs/reports-and-ci.md +14 -157
  15. package/docs/rules.md +140 -106
  16. package/package.json +10 -8
  17. package/src/analyser.ts +886 -282
  18. package/src/baseline-file.ts +867 -0
  19. package/src/baseline-identity.ts +463 -0
  20. package/src/baseline-options.ts +139 -34
  21. package/src/baseline.ts +85 -55
  22. package/src/blocks.ts +579 -364
  23. package/src/changed-regions.ts +414 -65
  24. package/src/check-ignore.ts +28 -13
  25. package/src/class-rules.ts +461 -302
  26. package/src/cli-program.ts +956 -166
  27. package/src/cli.ts +9 -2
  28. package/src/comment-rules.ts +277 -414
  29. package/src/comment-scanner.ts +363 -44
  30. package/src/complexity-metrics.ts +320 -0
  31. package/src/config-load-error.ts +17 -8
  32. package/src/config-parse.ts +291 -98
  33. package/src/config-preservation.ts +81 -26
  34. package/src/config.ts +778 -210
  35. package/src/constants.ts +7 -6
  36. package/src/context-doc-rules.ts +188 -61
  37. package/src/dashboard.ts +88 -23
  38. package/src/dead-code-rules.ts +153 -74
  39. package/src/discovery.ts +521 -148
  40. package/src/doc-rules.ts +592 -147
  41. package/src/duplicate-test-group-rules.ts +359 -0
  42. package/src/findings-helpers.ts +240 -89
  43. package/src/findings.ts +48 -24
  44. package/src/fixture-purpose-rules.ts +226 -48
  45. package/src/github-actions-event-guards.ts +331 -0
  46. package/src/github-actions-rules.ts +336 -106
  47. package/src/hook-contract.ts +708 -211
  48. package/src/init-config.ts +169 -114
  49. package/src/inline-suppressions.ts +340 -0
  50. package/src/limit-band.ts +56 -0
  51. package/src/line-rules.ts +331 -419
  52. package/src/migrate-config.ts +670 -0
  53. package/src/naming-pushers.ts +33 -107
  54. package/src/parsed-script.ts +1206 -0
  55. package/src/pillar-summary.ts +56 -40
  56. package/src/profiles.ts +97 -71
  57. package/src/project-config-rules.ts +335 -146
  58. package/src/project-rules.ts +237 -115
  59. package/src/public-exports.ts +284 -0
  60. package/src/report-html.ts +217 -85
  61. package/src/report-renderers.ts +864 -195
  62. package/src/rule-list.ts +166 -46
  63. package/src/rules.ts +100 -104
  64. package/src/safety-rules.ts +191 -132
  65. package/src/scoring.ts +255 -52
  66. package/src/security-flow-rules.ts +930 -109
  67. package/src/selectors.ts +169 -0
  68. package/src/sensitive-data-rules.ts +502 -375
  69. package/src/sensitive-exclusions.ts +435 -0
  70. package/src/source-text.ts +380 -148
  71. package/src/static-analysis-redundant-rules.ts +298 -41
  72. package/src/test-block-rules.ts +422 -228
  73. package/src/text-scans.ts +67 -9
  74. package/src/types.ts +222 -71
  75. package/tsconfig.json +2 -1
  76. package/src/process-exec-metadata.ts +0 -153
  77. package/src/test-fixtures.ts +0 -668
@@ -1,5 +1,9 @@
1
- // GitHub Actions workflow security heuristics, path-gated to committed workflow files.
1
+ // Audits committed GitHub Actions workflow YAML files for supply-chain and pull-request security risks.
2
+ //
3
+ // Path-gated to `.github/workflows/*.yml` and `.yaml` so regular YAML config files never emit CI findings.
4
+ // Checks unpinned third-party actions, remote-shell pipes, unsafe `pull_request_target` checkouts, and secret exposure on PR triggers.
2
5
  import type { SourceFile } from "./discovery.ts";
6
+ import { unreachableWorkflowSecretLines } from "./github-actions-event-guards.ts";
3
7
  import { makeFinding } from "./findings.ts";
4
8
  import type { Finding } from "./types.ts";
5
9
 
@@ -22,11 +26,6 @@ interface WorkflowFindingInput {
22
26
  metadata: Record<string, unknown>;
23
27
  }
24
28
 
25
- // Shared indentation state for YAML block scans; deleting `indent` exits the current block.
26
- interface IndentedBlockState {
27
- indent?: number;
28
- }
29
-
30
29
  // Active `run: |` / `run: >` block scalar. The start line is the finding anchor, while `lines`
31
30
  // holds the shell body after YAML indentation has been stripped by `workflowLines`.
32
31
  interface RunBlockState {
@@ -41,38 +40,63 @@ interface WorkflowCommand {
41
40
  line: WorkflowLine;
42
41
  }
43
42
 
43
+ // GitHub's 2026-07-12 workflow table defines the current write-capable keys below.
44
+ // `repository-projects` remains so users scanning legacy Enterprise workflows still see the risk.
44
45
  const WRITE_PERMISSION_SCOPES = new Set([
45
46
  "actions",
47
+ "artifact-metadata",
48
+ "attestations",
46
49
  "checks",
50
+ "code-quality",
47
51
  "contents",
48
52
  "deployments",
53
+ "discussions",
54
+ "id-token",
49
55
  "issues",
50
56
  "packages",
57
+ "pages",
51
58
  "pull-requests",
52
59
  "repository-projects",
53
60
  "security-events",
54
61
  "statuses",
55
62
  ]);
56
63
 
57
- // Stable rule contract: workflow-only checks ignore non-workflow YAML so example docs avoid findings.
64
+ /**
65
+ * Checks YAML workflow source when `file` has a GitHub workflow display path, keeping example YAML outside workflows exempt.
66
+ * Under the stable rule contract, non-workflow paths leave `findings` unchanged.
67
+ *
68
+ * @param file - Source file descriptor whose `displayPath` gates analysis.
69
+ * @param source - Raw YAML file contents to inspect for workflow security findings.
70
+ * @param findings - Findings array that receives appended workflow security warnings.
71
+ * @returns Nothing. Appends any workflow findings to `findings` and leaves other paths unchanged.
72
+ */
58
73
  function analyseGithubActionsRules(file: SourceFile, source: string, findings: Finding[]): void {
59
74
  if (!isGithubWorkflowPath(file.displayPath)) {
60
75
  return;
61
76
  }
62
77
  const lines = workflowLines(source);
63
78
  analysePullRequestTarget(file, lines, findings);
64
- analyseBroadPermissions(file, lines, findings);
65
79
  analyseUnpinnedActions(file, lines, findings);
66
80
  analyseRemoteShell(file, lines, findings);
67
81
  analyseSecretsInPullRequest(file, lines, findings);
68
82
  }
69
83
 
70
- // Matches committed GitHub Actions workflow locations and nothing under docs or examples.
84
+ /**
85
+ * Checks whether a display path names a YAML file directly under the root `.github/workflows` directory, ignoring case.
86
+ *
87
+ * @param displayPath - Relative repository path to test against the workflow directory pattern.
88
+ * @returns `true` when `displayPath` is a `.yml` or `.yaml` file directly inside `.github/workflows`.
89
+ */
71
90
  function isGithubWorkflowPath(displayPath: string): boolean {
72
91
  return /^\.github\/workflows\/[^/]+\.ya?ml$/i.test(displayPath);
73
92
  }
74
93
 
75
- // Normalizes raw YAML lines into a small record while preserving indentation for block-state scans.
94
+ /**
95
+ * Normalizes raw YAML lines into structured records while preserving leading-space indentation for block-state scans.
96
+ *
97
+ * @param source - Raw YAML workflow text split on LF or CRLF line endings.
98
+ * @returns Normalized line records with stripped inline comments, trimmed text, 1-based line numbers, and space indentation.
99
+ */
76
100
  function workflowLines(source: string): WorkflowLine[] {
77
101
  return source.split(/\r?\n/).map((raw, index) => {
78
102
  const text = stripInlineComment(raw);
@@ -81,19 +105,37 @@ function workflowLines(source: string): WorkflowLine[] {
81
105
  });
82
106
  }
83
107
 
84
- // Removes common YAML inline comments without attempting to parse quoted scalars.
108
+ /**
109
+ * Removes common YAML inline comments starting at `" #"` without attempting to parse quoted scalars.
110
+ *
111
+ * @param line - Single raw YAML line to strip.
112
+ * @returns Substring before the first `" #"`, or `line` unchanged when none is present.
113
+ */
85
114
  function stripInlineComment(line: string): string {
86
115
  const comment = line.indexOf(" #");
87
116
  return comment === -1 ? line : line.slice(0, comment);
88
117
  }
89
118
 
90
- // Counts spaces only; workflow YAML should not rely on tabs for indentation.
119
+ /**
120
+ * Counts leading ASCII spaces on a line because workflow YAML should only use spaces, never tabs, for indentation.
121
+ *
122
+ * @param line - Raw YAML line whose leading indentation is measured.
123
+ * @returns Number of leading space characters at the start of `line`.
124
+ */
91
125
  function leadingSpaceCount(line: string): number {
92
126
  const match = line.match(/^ */);
93
127
  return match?.[0].length ?? 0;
94
128
  }
95
129
 
96
- // Stable finding contract: reports pull_request_target only when trusted-context risk is visible nearby.
130
+ /**
131
+ * Checks workflow lines for a `pull_request_target` event paired with a trusted-context risk signal anywhere in the workflow.
132
+ * Uses `file` and the first matching event line to emit a stable finding anchor.
133
+ *
134
+ * @param file - Workflow source file descriptor used for the finding path.
135
+ * @param lines - Normalized workflow lines to scan for the event and risk signals.
136
+ * @param findings - Findings array that receives the warning when both conditions match.
137
+ * @returns Nothing. Appends a `pull_request_target` warning to `findings` when both exist.
138
+ */
97
139
  function analysePullRequestTarget(file: SourceFile, lines: readonly WorkflowLine[], findings: Finding[]): void {
98
140
  const eventLine = lines.find((line) => hasPullRequestTargetEvent(line));
99
141
  if (!eventLine || !hasPullRequestTargetRiskContext(lines)) {
@@ -111,17 +153,33 @@ function analysePullRequestTarget(file: SourceFile, lines: readonly WorkflowLine
111
153
  );
112
154
  }
113
155
 
114
- // Detects the event token in compact or expanded YAML event forms.
156
+ /**
157
+ * Checks whether a nonblank, noncomment workflow line contains the whole `pull_request_target` token using the line's text alone.
158
+ *
159
+ * @param line - Normalized workflow line to inspect.
160
+ * @returns `true` when `line` is not blank or a comment and matches the `pull_request_target` word token.
161
+ */
115
162
  function hasPullRequestTargetEvent(line: WorkflowLine): boolean {
116
163
  return !isCommentOrBlank(line) && /\bpull_request_target\b/.test(line.trimmed);
117
164
  }
118
165
 
119
- // Separates the boolean gate from metadata collection so the event-alone case stays quiet.
166
+ /**
167
+ * Checks whether workflow lines contain any recognized risk signal so an event-only workflow produces no `pull_request_target` warning.
168
+ *
169
+ * @param lines - Normalized workflow lines to scan for risk indicators.
170
+ * @returns `true` when at least one risk context label is detected in `lines`.
171
+ */
120
172
  function hasPullRequestTargetRiskContext(lines: readonly WorkflowLine[]): boolean {
121
173
  return pullRequestTargetRiskContext(lines).length > 0;
122
174
  }
123
175
 
124
- // Collects stable risk labels used in metadata and tests.
176
+ /**
177
+ * Scans workflow lines for checkout steps, `run` steps, secret references, and broad write permissions.
178
+ * Produces unique risk labels in stable sorted order for finding metadata.
179
+ *
180
+ * @param lines - Normalized workflow lines to inspect.
181
+ * @returns Sorted unique risk context labels; an empty array means no risk signal was recognized.
182
+ */
125
183
  function pullRequestTargetRiskContext(lines: readonly WorkflowLine[]): string[] {
126
184
  const contexts = new Set<string>();
127
185
  for (const line of lines) {
@@ -144,66 +202,12 @@ function pullRequestTargetRiskContext(lines: readonly WorkflowLine[]): string[]
144
202
  return [...contexts].sort();
145
203
  }
146
204
 
147
- // Stable permissions contract: helpers keep YAML block state explicit because nested scopes affect anchors.
148
- function analyseBroadPermissions(file: SourceFile, lines: readonly WorkflowLine[], findings: Finding[]): void {
149
- const state: IndentedBlockState = {};
150
- for (const line of lines) {
151
- const scope = broadPermissionScope(line, state);
152
- if (scope) {
153
- pushBroadPermissionFinding(file, findings, line, scope);
154
- }
155
- }
156
- }
157
-
158
- // Reports one finding per broad permission scope; stable scope symbols keep remediation targeted.
159
- function pushBroadPermissionFinding(file: SourceFile, findings: Finding[], line: WorkflowLine, scope: string): void {
160
- findings.push(
161
- workflowFinding(file, {
162
- ruleId: "security.github-actions-broad-permissions",
163
- message: `Workflow grants broad write permission \`${scope}\`.`,
164
- line: line.lineNumber,
165
- symbol: scope,
166
- remediation: "Reduce workflow permissions to read-only by default and grant write scopes only to trusted jobs.",
167
- metadata: { permission: scope },
168
- }),
169
- );
170
- }
171
-
172
- // Returns the broad permission scope for either inline permissions or an active permissions block.
173
- function broadPermissionScope(line: WorkflowLine, state: IndentedBlockState): string | undefined {
174
- if (isCommentOrBlank(line)) {
175
- return undefined;
176
- }
177
- closeBlockWhenOutdented(state, line);
178
- const inline = line.trimmed.match(/^permissions:\s*(write-all)\b/i);
179
- if (inline?.[1]) {
180
- return "write-all";
181
- }
182
- if (/^permissions:\s*$/i.test(line.trimmed)) {
183
- state.indent = line.indent;
184
- return undefined;
185
- }
186
- if (state.indent === undefined || line.indent <= state.indent) {
187
- return undefined;
188
- }
189
- return scopedWritePermission(line);
190
- }
191
-
192
- // Clears YAML block state once the scanner reaches a sibling or parent indentation level.
193
- function closeBlockWhenOutdented(state: IndentedBlockState, line: WorkflowLine): void {
194
- if (state.indent !== undefined && line.indent <= state.indent) {
195
- delete state.indent;
196
- }
197
- }
198
-
199
- // Extracts selected write scopes that are broad enough to matter for workflow security.
200
- function scopedWritePermission(line: WorkflowLine): string | undefined {
201
- const scoped = line.trimmed.match(/^([a-z-]+):\s*write\b/i);
202
- const scope = scoped?.[1] ?? "";
203
- return WRITE_PERMISSION_SCOPES.has(scope) ? scope : undefined;
204
- }
205
-
206
- // Lightweight permission signal used by the pull_request_target risk-context gate.
205
+ /**
206
+ * Checks whether a line signals `write-all` permissions or a `write` grant for a recognized scope in the `pull_request_target` risk check.
207
+ *
208
+ * @param line - Normalized workflow line whose trimmed text is matched against permission rules.
209
+ * @returns `true` when `line` declares `permissions: write-all` or `<scope>: write` for a known write scope.
210
+ */
207
211
  function broadPermissionSignal(line: WorkflowLine): boolean {
208
212
  if (/^permissions:\s*write-all\b/i.test(line.trimmed)) {
209
213
  return true;
@@ -212,7 +216,14 @@ function broadPermissionSignal(line: WorkflowLine): boolean {
212
216
  return WRITE_PERMISSION_SCOPES.has(scoped?.[1] ?? "");
213
217
  }
214
218
 
215
- // Stable supply-chain contract: reports third-party action refs unless pinned to a full commit SHA.
219
+ /**
220
+ * Scans workflow lines for third-party action references whose refs fall outside the stable pinning contract of 40 hexadecimal characters.
221
+ *
222
+ * @param file - Workflow source file descriptor used for warning paths.
223
+ * @param lines - Normalized workflow lines to inspect for `uses:` entries.
224
+ * @param findings - Findings array that receives a warning for each unpinned third-party action.
225
+ * @returns Nothing. Appends warnings to `findings` for refs not pinned to a 40-character hexadecimal SHA.
226
+ */
216
227
  function analyseUnpinnedActions(file: SourceFile, lines: readonly WorkflowLine[], findings: Finding[]): void {
217
228
  for (const line of lines) {
218
229
  const action = thirdPartyActionUse(line);
@@ -232,7 +243,13 @@ function analyseUnpinnedActions(file: SourceFile, lines: readonly WorkflowLine[]
232
243
  }
233
244
  }
234
245
 
235
- // Parses `uses:` entries while exempting GitHub-owned and local reusable actions.
246
+ /**
247
+ * Extracts the action path, owner, and ref from a recognized external `uses:` entry.
248
+ * Local paths and owners `actions` or `github` are skipped because they are exempt from third-party pin checks.
249
+ *
250
+ * @param line - Normalized workflow line to parse for an external action reference.
251
+ * @returns Parsed `{ action, owner, ref }` object, or `undefined` when absent, unsupported, local, or exempt.
252
+ */
236
253
  function thirdPartyActionUse(line: WorkflowLine): { action: string; owner: string; ref: string } | undefined {
237
254
  if (isCommentOrBlank(line)) {
238
255
  return undefined;
@@ -250,12 +267,25 @@ function thirdPartyActionUse(line: WorkflowLine): { action: string; owner: strin
250
267
  return { action, owner, ref };
251
268
  }
252
269
 
253
- // Full 40-character SHAs are the stable pinning target for third-party actions.
270
+ /**
271
+ * Checks whether an action ref is exactly 40 hexadecimal characters, the required commit-pin form for third-party actions.
272
+ *
273
+ * @param ref - Action version, branch, tag, or commit SHA string after `@`.
274
+ * @returns `true` when `ref` consists of exactly 40 hexadecimal characters.
275
+ */
254
276
  function isPinnedToFullSha(ref: string): boolean {
255
277
  return /^[0-9a-f]{40}$/i.test(ref);
256
278
  }
257
279
 
258
- // Stable run-step contract: helpers separate YAML block state from shell matching to preserve anchors.
280
+ /**
281
+ * Checks `run` commands extracted from workflow lines for a remote download piped to a shell.
282
+ * YAML block parsing preserves a stable source anchor for each command.
283
+ *
284
+ * @param file - Workflow source file descriptor used for the report path.
285
+ * @param lines - Normalized workflow lines to extract `run` commands from.
286
+ * @param findings - Findings array that receives a warning for each matching remote-shell command.
287
+ * @returns Nothing. Appends matching remote-shell warnings to `findings`.
288
+ */
259
289
  function analyseRemoteShell(file: SourceFile, lines: readonly WorkflowLine[], findings: Finding[]): void {
260
290
  for (const command of runCommands(lines)) {
261
291
  if (isRemoteShellCommand(command.command)) {
@@ -264,7 +294,14 @@ function analyseRemoteShell(file: SourceFile, lines: readonly WorkflowLine[], fi
264
294
  }
265
295
  }
266
296
 
267
- // Reports workflow-specific remote-shell findings at the risky command line for stable anchors.
297
+ /**
298
+ * Appends a workflow remote-shell warning for a matched `run` command using a stable source anchor.
299
+ *
300
+ * @param file - Workflow source file descriptor used for the finding path.
301
+ * @param findings - Findings array that receives the new warning.
302
+ * @param line - Workflow line anchoring the matched `run` step in the report.
303
+ * @returns Nothing. Appends one remote-shell finding to `findings`.
304
+ */
268
305
  function pushRemoteShellFinding(file: SourceFile, findings: Finding[], line: WorkflowLine): void {
269
306
  findings.push(
270
307
  workflowFinding(file, {
@@ -278,8 +315,13 @@ function pushRemoteShellFinding(file: SourceFile, findings: Finding[], line: Wor
278
315
  );
279
316
  }
280
317
 
281
- // Extracts both inline `run: command` values and multiline block-scalar bodies. The returned order
282
- // follows workflow source order so multiple remote-shell findings remain deterministic.
318
+ /**
319
+ * Collects inline and block-scalar `run` commands with their source lines in workflow source order.
320
+ * Block bodies use trimmed lines so remote-shell findings stay deterministic.
321
+ *
322
+ * @param lines - Normalized workflow lines to scan for `run:` entries and block bodies.
323
+ * @returns Extracted `run` commands paired with their anchor lines, or an empty list if none are recognized.
324
+ */
283
325
  function runCommands(lines: readonly WorkflowLine[]): WorkflowCommand[] {
284
326
  const commands: WorkflowCommand[] = [];
285
327
  const state: RunBlockState = { lines: [] };
@@ -294,16 +336,29 @@ function runCommands(lines: readonly WorkflowLine[]): WorkflowCommand[] {
294
336
  return commands;
295
337
  }
296
338
 
297
- // Ends a block scalar when YAML indentation returns to the parent/sibling level. The current line
298
- // is then processed again by the caller as a possible next command.
339
+ /**
340
+ * Flushes an active `run` block when indentation drops to or below the block header level, allowing the caller to inspect `line` next.
341
+ * Leaves `state` and `commands` unchanged when no block is closed.
342
+ *
343
+ * @param line - Current workflow line whose indentation may close the active block.
344
+ * @param state - Mutable run-block accumulator cleared when the active block closes.
345
+ * @param commands - Command list that receives the flushed block command when a start line is present.
346
+ * @returns Nothing. Appends any closed block command to `commands` and resets `state`.
347
+ */
299
348
  function flushClosedRunBlock(line: WorkflowLine, state: RunBlockState, commands: WorkflowCommand[]): void {
300
349
  if (state.indent !== undefined && line.indent <= state.indent) {
301
350
  flushRunBlock(state, commands);
302
351
  }
303
352
  }
304
353
 
305
- // Captures a line belonging to the active run block. The normalized trimmed text is enough for the
306
- // remote-shell heuristic because it only needs command tokens and pipe placement.
354
+ /**
355
+ * Appends a line's trimmed text to `state.lines` when indented deeper than the active `run` key, leaving `state` unchanged otherwise.
356
+ * The remote-shell check uses this normalized text, which can omit content after a space and hash.
357
+ *
358
+ * @param line - Normalized workflow line to test against the active run-block indentation.
359
+ * @param state - Mutable run-block state holding the active `indent` and accumulated `lines`.
360
+ * @returns `true` when `line` belongs to the active block and was captured; `false` otherwise.
361
+ */
307
362
  function runBlockLine(line: WorkflowLine, state: RunBlockState): boolean {
308
363
  if (state.indent === undefined || line.indent <= state.indent) {
309
364
  return false;
@@ -312,8 +367,15 @@ function runBlockLine(line: WorkflowLine, state: RunBlockState): boolean {
312
367
  return true;
313
368
  }
314
369
 
315
- // Starts a new `run` block or records an inline command. Blank and comment-only lines are ignored
316
- // here because they cannot carry a workflow step key.
370
+ /**
371
+ * Parses a line as a `run` entry, either initializing block-scalar collection in `state` or appending an inline command to `commands`.
372
+ * Blank, comment-only, and non-`run` lines leave `state` and `commands` unchanged.
373
+ *
374
+ * @param line - Normalized workflow line to inspect for a `run:` prefix.
375
+ * @param state - Mutable run-block state reset when `line` starts a block scalar.
376
+ * @param commands - Command list that receives inline `run` commands.
377
+ * @returns Nothing. Mutates `state` for block scalars or appends inline commands to `commands`.
378
+ */
317
379
  function startOrPushRunCommand(line: WorkflowLine, state: RunBlockState, commands: WorkflowCommand[]): void {
318
380
  if (isCommentOrBlank(line)) {
319
381
  return;
@@ -331,8 +393,14 @@ function startOrPushRunCommand(line: WorkflowLine, state: RunBlockState, command
331
393
  }
332
394
  }
333
395
 
334
- // Emits the pending block-scalar command and clears all mutable state. Missing `startLine` is
335
- // treated as empty state so partially initialized blocks cannot throw.
396
+ /**
397
+ * Emits any pending `run` block command from `state` to `commands` and clears `state`.
398
+ * Missing `indent` or `startLine` skips command emission while still resetting `state`.
399
+ *
400
+ * @param state - Mutable run-block state whose pending lines, `indent`, and `startLine` are cleared.
401
+ * @param commands - Command list that receives the joined block command when active.
402
+ * @returns Nothing. Appends the pending block command to `commands` when complete and resets `state`.
403
+ */
336
404
  function flushRunBlock(state: RunBlockState, commands: WorkflowCommand[]): void {
337
405
  if (state.indent !== undefined && state.startLine) {
338
406
  commands.push({ command: state.lines.join("\n"), line: state.startLine });
@@ -342,59 +410,221 @@ function flushRunBlock(state: RunBlockState, commands: WorkflowCommand[]): void
342
410
  state.lines = [];
343
411
  }
344
412
 
345
- // Recognizes YAML block scalar headers including chomping/indent indicators such as `|-`, `>2`, or `|+4`.
413
+ /**
414
+ * Checks whether a `run` value matches a YAML block scalar header pattern, including forms such as `|-`, `>2`, or `|+4`.
415
+ *
416
+ * @param command - Inline string following `run:` on the header line.
417
+ * @returns `true` when `command` is a block scalar indicator (`|` or `>`) with optional chomping or indent modifiers.
418
+ */
346
419
  function isRunBlockScalar(command: string): boolean {
347
420
  return /^[|>](?:[+-]?\d*|\d*[+-]?)?\s*$/.test(command);
348
421
  }
349
422
 
350
- // Mirrors package script remote-installer semantics for curl/wget piped to a shell.
423
+ /**
424
+ * Checks whether command text matches a `curl` or `wget` HTTP(S) download piped to `sh`, `bash`, or `zsh`, with optional `sudo`.
425
+ *
426
+ * @param command - Shell command text extracted from an inline or block-scalar `run` step.
427
+ * @returns `true` when `command` pipes an HTTP or HTTPS `curl` or `wget` fetch into a shell.
428
+ */
351
429
  function isRemoteShellCommand(command: string): boolean {
352
430
  return /\b(?:curl|wget)\b[^|]*https?:\/\/[^|]*\|\s*(?:sudo\s+)?(?:sh|bash|zsh)\b/i.test(command);
353
431
  }
354
432
 
355
- // Stable secret-exposure contract: reports secrets.NAME only when the workflow is pull-request triggered.
433
+ /**
434
+ * Checks workflow lines for named secret references only when the workflow declares `pull_request_target`.
435
+ * Under the stable rule contract, skips `GITHUB_TOKEN` and lines identified as unreachable for this event.
436
+ *
437
+ * @param file - Workflow source file descriptor used for finding paths.
438
+ * @param lines - Normalized workflow lines to check for triggers and secret references.
439
+ * @param findings - Findings array that receives at most one secret warning per line.
440
+ * @returns Nothing. Appends matching secret findings to `findings`.
441
+ */
356
442
  function analyseSecretsInPullRequest(file: SourceFile, lines: readonly WorkflowLine[], findings: Finding[]): void {
357
- if (!hasPullRequestStyleEvent(lines)) {
443
+ if (!declaredWorkflowEvents(lines).has("pull_request_target")) {
358
444
  return;
359
445
  }
446
+ const unreachable = unreachableWorkflowSecretLines(lines.map((line) => line.raw).join("\n"), ["pull_request_target"]);
360
447
  for (const line of lines) {
361
448
  const secretName = secretReference(line);
362
- if (!secretName) {
449
+ if (!secretName || unreachable.has(line.lineNumber)) {
363
450
  continue;
364
451
  }
365
452
  findings.push(
366
453
  workflowFinding(file, {
367
454
  ruleId: "security.github-actions-secrets-in-pr",
368
- message: `Pull request workflow references secret \`${secretName}\`.`,
455
+ message: `pull_request_target workflow references secret \`${secretName}\`.`,
369
456
  line: line.lineNumber,
370
457
  symbol: secretName,
371
458
  remediation: "Avoid exposing secrets to pull request workflows unless the code path is trusted and tightly gated.",
372
- metadata: { event: "pull_request", secretName },
459
+ metadata: { event: "pull_request_target", secretName },
373
460
  }),
374
461
  );
375
462
  }
376
463
  }
377
464
 
378
- // Treats pull_request and pull_request_target as PR-style contexts for secret exposure checks.
379
- function hasPullRequestStyleEvent(lines: readonly WorkflowLine[]): boolean {
380
- return lines.some((line) => !isCommentOrBlank(line) && /\bpull_request(?:_target)?\b/.test(line.trimmed));
465
+ /**
466
+ * Reads recognized event names from the top-level `on` key so `pull_request_target` secret checks only fire on workflows that declare that trigger.
467
+ * Supports scalar, inline/multiline flow, and indented/indentless block sequences because YAML allows all four forms for `on:`.
468
+ *
469
+ * @param lines - Normalized workflow lines to scan for top-level `on` declarations.
470
+ * @returns Set of recognized trigger event names, or an empty set when none are declared so the `pull_request_target` secret check is skipped.
471
+ */
472
+ function declaredWorkflowEvents(lines: readonly WorkflowLine[]): Set<string> {
473
+ const events = new Set<string>();
474
+ const state: OnBlockState = { inOnBlock: false, eventIndent: undefined, flowDepth: 0 };
475
+ for (const line of lines) {
476
+ if (!isCommentOrBlank(line)) {
477
+ consumeWorkflowEventLine(line, events, state);
478
+ }
479
+ }
480
+ return events;
481
+ }
482
+
483
+ // Mutable parser state tracked while walking lines under a workflow's top-level `on:` trigger declaration.
484
+ interface OnBlockState {
485
+ inOnBlock: boolean;
486
+ eventIndent: number | undefined;
487
+ flowDepth: number;
488
+ }
489
+
490
+ /**
491
+ * Updates trigger-event state from one non-blank workflow line because YAML allows multiline flow arrays and indentless sequence items under `on:`.
492
+ *
493
+ * @param line - Normalized non-comment workflow line being scanned.
494
+ * @param events - Mutable trigger-event set updated in place.
495
+ * @param state - Mutable `on:` block tracking state updated in place.
496
+ * @returns Nothing. Adds any recognized event names from `line` into `events`.
497
+ */
498
+ function consumeWorkflowEventLine(line: WorkflowLine, events: Set<string>, state: OnBlockState): void {
499
+ // Multiline flow declarations like `on: [\n pull_request_target,\n issues\n]` keep collecting until outer flow depth returns to zero.
500
+ if (state.flowDepth > 0) {
501
+ const cleaned = stripInlineComment(line.trimmed).trim();
502
+ addFlowEvents(events, cleaned);
503
+ state.flowDepth = Math.max(0, state.flowDepth + flowDelimiterDelta(cleaned));
504
+ return;
505
+ }
506
+ // Indentless block sequence items (`on:\n- pull_request_target`) sit at indent 0 and belong to the active `on:` block.
507
+ if (line.indent === 0 && !(state.inOnBlock && line.trimmed.startsWith("-"))) {
508
+ const onKey = line.trimmed.match(/^["']?on["']?\s*:\s*(.*)$/);
509
+ const inlineValue = onKey ? stripInlineComment(onKey[1] ?? "").trim() : "";
510
+ state.inOnBlock = onKey !== null && inlineValue === "";
511
+ state.eventIndent = undefined;
512
+ if (onKey && !state.inOnBlock) {
513
+ addFlowEvents(events, inlineValue);
514
+ state.flowDepth = inlineValue.startsWith("[") || inlineValue.startsWith("{")
515
+ ? Math.max(0, flowDelimiterDelta(inlineValue))
516
+ : 0;
517
+ }
518
+ return;
519
+ }
520
+ if (!state.inOnBlock) {
521
+ return;
522
+ }
523
+ consumeNestedOnEventLine(line, events, state);
524
+ }
525
+
526
+ /**
527
+ * Extracts trigger events from a line indented under top-level `on:`, supporting both block entries and nested flow collections.
528
+ *
529
+ * @param line - Normalized non-comment workflow line nested under `on:`.
530
+ * @param events - Mutable trigger-event set updated in place.
531
+ * @param state - Mutable `on:` block tracking state updated in place.
532
+ * @returns Nothing. Adds recognized event names from `line` into `events` and updates flow state when nested flow syntax starts.
533
+ */
534
+ function consumeNestedOnEventLine(line: WorkflowLine, events: Set<string>, state: OnBlockState): void {
535
+ // The first nested line fixes the event level; deeper lines configure one event, such as its branches.
536
+ state.eventIndent ??= line.indent;
537
+ // Deeper lines configure one event, such as its branch filter, and never name a new event.
538
+ if (line.indent !== state.eventIndent) {
539
+ return;
540
+ }
541
+ const cleaned = stripInlineComment(line.trimmed).trim();
542
+ // Flow sequences or mappings nested under `on:` (e.g. `on:\n [push, pull_request_target]`) declare events directly.
543
+ if (cleaned.startsWith("[") || cleaned.startsWith("{")) {
544
+ addFlowEvents(events, cleaned);
545
+ state.flowDepth = Math.max(0, flowDelimiterDelta(cleaned));
546
+ state.inOnBlock = false;
547
+ return;
548
+ }
549
+ const event = cleaned.match(/^(?:-\s*)?["']?([A-Za-z_]+)["']?\s*(?::|$)/)?.[1];
550
+ // A line naming an event, such as `push:` or `- pull_request`, adds it to the workflow's triggers.
551
+ if (event) {
552
+ events.add(event);
553
+ }
554
+ }
555
+
556
+ /**
557
+ * Counts net flow-collection bracket nesting (`[`/`{` minus `]`/`}`) on one YAML line so nested flow maps do not close `on:` early.
558
+ *
559
+ * @param text - Trimmed YAML flow text with inline comments already stripped.
560
+ * @returns Positive count for unclosed openers, zero for balanced delimiters, or negative when closers exceed openers.
561
+ */
562
+ function flowDelimiterDelta(text: string): number {
563
+ let delta = 0;
564
+ for (const character of text) {
565
+ if (character === "[" || character === "{") {
566
+ delta += 1;
567
+ } else if (character === "]" || character === "}") {
568
+ delta -= 1;
569
+ }
570
+ }
571
+ return delta;
572
+ }
573
+
574
+ /**
575
+ * Parses event names from a scalar or simple flow sequence or mapping declaration and adds non-empty names to `events`.
576
+ *
577
+ * @param events - Mutable event set that receives parsed trigger names.
578
+ * @param declaration - Inline value following top-level `on:` after stripping inline comments.
579
+ * @returns Nothing. Adds recognized non-empty event names to `events`.
580
+ */
581
+ function addFlowEvents(events: Set<string>, declaration: string): void {
582
+ for (const flowEntry of declaration.replace(/^[[{]/, "").replace(/[\]}]$/, "").split(",")) {
583
+ const event = (flowEntry.split(":")[0] ?? "").trim().replace(/^["']|["']$/g, "");
584
+ if (event) {
585
+ events.add(event);
586
+ }
587
+ }
381
588
  }
382
589
 
383
- // Extracts the secret symbol while keeping the raw expression out of finding metadata.
590
+ /**
591
+ * Extracts the first case-sensitive `secrets.NAME` identifier on a line while excluding `GITHUB_TOKEN`.
592
+ * Returning the name alone keeps the raw expression out of finding metadata.
593
+ *
594
+ * @param line - Normalized workflow line whose trimmed text is scanned for secret expressions.
595
+ * @returns First non-`GITHUB_TOKEN` secret name, or `undefined` for blank, comment-only, or unmatched lines.
596
+ */
384
597
  function secretReference(line: WorkflowLine): string | undefined {
385
598
  if (isCommentOrBlank(line)) {
386
599
  return undefined;
387
600
  }
388
- const match = line.trimmed.match(/\bsecrets\.([A-Za-z_][A-Za-z0-9_]*)\b/);
389
- return match?.[1];
601
+ // Excluding GITHUB_TOKEN does not end the search because a later reference on the same line can name another secret.
602
+ for (const match of line.trimmed.matchAll(/\bsecrets\.([A-Za-z_][A-Za-z0-9_]*)\b/g)) {
603
+ if (match[1] !== "GITHUB_TOKEN") {
604
+ return match[1];
605
+ }
606
+ }
607
+ return undefined;
390
608
  }
391
609
 
392
- // Skips blank/comment-only YAML lines before applying simple text heuristics.
610
+ /**
611
+ * Checks whether a line's trimmed YAML text is empty or comment-only so callers can skip it during text heuristics.
612
+ *
613
+ * @param line - Normalized workflow line to test.
614
+ * @returns `true` when `line.trimmed` is empty or starts with `#`.
615
+ */
393
616
  function isCommentOrBlank(line: WorkflowLine): boolean {
394
617
  return line.trimmed.length === 0 || line.trimmed.startsWith("#");
395
618
  }
396
619
 
397
- // Centralizes workflow finding metadata so every rule emits the same pillar/severity contract.
620
+ /**
621
+ * Builds a workflow security warning using a stable finding contract across workflow rules.
622
+ * Omits `symbol` when `input` supplies none or an empty string.
623
+ *
624
+ * @param file - Workflow source file descriptor providing `displayPath` for the report path.
625
+ * @param input - Rule identifier, message, source line, optional symbol, remediation, and metadata payload.
626
+ * @returns Constructed security warning `Finding` ready to append to results.
627
+ */
398
628
  function workflowFinding(file: SourceFile, input: WorkflowFindingInput): Finding {
399
629
  return makeFinding({
400
630
  ruleId: input.ruleId,