vouchington-tooling 0.79.0 → 0.80.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +50 -0
- package/dist/cli/index.mjs +3 -0
- package/dist/cli/parse-forwarded-commands.d.mts +1 -1
- package/dist/cli/parse-forwarded-commands.mjs +1 -0
- package/dist/cli/parse.d.mts +3 -0
- package/dist/cli/usage-text.d.mts +1 -1
- package/dist/cli/usage-text.mjs +2 -0
- package/dist/runner-policy/cli.d.mts +6 -0
- package/dist/runner-policy/cli.mjs +45 -0
- package/dist/runner-policy/config.d.mts +3 -0
- package/dist/runner-policy/config.mjs +97 -0
- package/dist/runner-policy/discover.d.mts +9 -0
- package/dist/runner-policy/discover.mjs +34 -0
- package/dist/runner-policy/evaluate.d.mts +7 -0
- package/dist/runner-policy/evaluate.mjs +61 -0
- package/dist/runner-policy/index.d.mts +6 -0
- package/dist/runner-policy/index.mjs +4 -0
- package/dist/runner-policy/matrix.d.mts +13 -0
- package/dist/runner-policy/matrix.mjs +45 -0
- package/dist/runner-policy/rules.d.mts +6 -0
- package/dist/runner-policy/rules.mjs +87 -0
- package/dist/runner-policy/types.d.mts +38 -0
- package/dist/runner-policy/types.mjs +1 -0
- package/dist/runner-policy/workflow.d.mts +24 -0
- package/dist/runner-policy/workflow.mjs +37 -0
- package/package.json +6 -1
- package/scripts/__pycache__/run_bounded_process.cpython-314.pyc +0 -0
package/README.md
CHANGED
|
@@ -86,6 +86,7 @@ vouchington harness-assert-gates HARNESS_DISPATCH_ENABLED HARNESS_SHEPHERD_ENABL
|
|
|
86
86
|
echo '[{"login":"octocat","type":"User"}]' | vouchington gha-collaborator-trust owner/repo --allow-bot github-actions[bot]
|
|
87
87
|
vouchington nuget-central-version trusted.props candidate.props metadata.json out.props
|
|
88
88
|
vouchington verify-workflow-secrets --repo owner/name --inventory .github/workflows/workflow-secrets-inventory.mts
|
|
89
|
+
vouchington runner-policy --config .github/runner-policy.json --root .github/workflows
|
|
89
90
|
vouchington tmux up --config tmux.json --no-attach
|
|
90
91
|
vouchington tmux name my-topic
|
|
91
92
|
vouchington tmux read-title
|
|
@@ -704,6 +705,7 @@ import { runAstGrepExamples } from 'vouchington-tooling/ast-grep-examples'
|
|
|
704
705
|
import { astGrepPackPaths } from 'vouchington-tooling/ast-grep-pack'
|
|
705
706
|
import { validateNugetUpdate } from 'vouchington-tooling/nuget-central-version'
|
|
706
707
|
import { runVerifyWorkflowSecretsCli } from 'vouchington-tooling/workflow-secrets-drift'
|
|
708
|
+
import { evaluateRunnerPolicy } from 'vouchington-tooling/runner-policy'
|
|
707
709
|
import { launchSession, loadTmuxConfig } from 'vouchington-tooling/tmux'
|
|
708
710
|
import { runDeadCodeGate } from 'vouchington-tooling/dead-code'
|
|
709
711
|
import { normalizeSwiftSource } from 'vouchington-tooling/swift-semantic-equal'
|
|
@@ -1444,3 +1446,51 @@ const { result, error } = await withPostgresQueryFailureForTest(
|
|
|
1444
1446
|
The package's own tests start a throwaway cluster with `initdb`/`pg_ctl` found through
|
|
1445
1447
|
`POSTGRES_BIN_DIR`, `PATH` or a standard install location. They skip where no server can run and
|
|
1446
1448
|
fail under `CI`.
|
|
1449
|
+
|
|
1450
|
+
## Runner policy
|
|
1451
|
+
|
|
1452
|
+
`vouchington runner-policy [--config <file>] [--root <directory>]` checks GitHub Actions runner
|
|
1453
|
+
policy for a consumer's workflows. `--config` defaults to `.github/runner-policy.json` and `--root`
|
|
1454
|
+
to `.github/workflows` (only `*.yml` / `*.yaml` files directly under the root are read). It prints
|
|
1455
|
+
each violation and exits 1 on any violation, 0 when clean, and 2 on a usage error. The library
|
|
1456
|
+
subpath `vouchington-tooling/runner-policy` exports the pure
|
|
1457
|
+
`evaluateRunnerPolicy(inputs: {path, text}[], config)` plus `parseRunnerPolicyConfig`,
|
|
1458
|
+
`discoverWorkflows` and `loadRunnerPolicyConfig`. A workflow is identified by its path relative to
|
|
1459
|
+
the root (for example `checks.yml`).
|
|
1460
|
+
|
|
1461
|
+
```json
|
|
1462
|
+
{
|
|
1463
|
+
"allowedLabels": ["runner-small", "runner-large"],
|
|
1464
|
+
"requiredJobs": [{ "workflow": "ci.yml", "job": "gate", "runsOn": "runner-large" }],
|
|
1465
|
+
"exactLabelJobs": [{ "label": "runner-arm", "jobs": ["ci.yml#build", "ci.yml#test"] }],
|
|
1466
|
+
"restrictedLabels": [
|
|
1467
|
+
{
|
|
1468
|
+
"label": "runner-small",
|
|
1469
|
+
"forbidServices": true,
|
|
1470
|
+
"forbiddenActions": {
|
|
1471
|
+
"prefixes": ["docker/"],
|
|
1472
|
+
"contains": ["/docker/"],
|
|
1473
|
+
"exact": ["./.github/actions/setup-db"]
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
]
|
|
1477
|
+
}
|
|
1478
|
+
```
|
|
1479
|
+
|
|
1480
|
+
Only `allowedLabels` (non-empty) is required; unknown keys are rejected and every config problem is
|
|
1481
|
+
reported at once. Policies:
|
|
1482
|
+
|
|
1483
|
+
- `allowedLabels`: every non-delegate job's `runs-on` must be a literal string in the set, or
|
|
1484
|
+
`${{ matrix.<field> }}` resolving from `strategy.matrix.<field>` plus `strategy.matrix.include[].<field>`
|
|
1485
|
+
to a non-empty candidate list whose members are all in the set. Missing `runs-on`, unresolved or
|
|
1486
|
+
expression matrices, other computed expressions, array label sets and object forms are rejected.
|
|
1487
|
+
- Jobs with `uses:` (reusable-workflow delegates) must not set `runs-on`.
|
|
1488
|
+
- `requiredJobs`: each job must exist in its workflow and use exactly the literal `runsOn`.
|
|
1489
|
+
- `exactLabelJobs`: the `workflow#job` entries running on `label` (literally or through any matrix
|
|
1490
|
+
candidate) must equal `jobs`; missing and extra entries are both reported.
|
|
1491
|
+
- `restrictedLabels`: jobs using `label` literally must not declare non-empty `services`
|
|
1492
|
+
(`forbidServices`, default `true`) nor use a step `uses` value matching `forbiddenActions`
|
|
1493
|
+
`prefixes`, `contains` substrings or `exact` values.
|
|
1494
|
+
|
|
1495
|
+
The check fails closed: no discovered workflows, a missing root, an unreadable config or workflow,
|
|
1496
|
+
a YAML parse error, or a config entry naming an undiscovered workflow is a failure, never a pass.
|
package/dist/cli/index.mjs
CHANGED
|
@@ -16,6 +16,7 @@ import { runScript } from "./commands/spawn-script.mjs";
|
|
|
16
16
|
import { runNugetCentralVersionCommand } from "./commands/nuget-central-version.mjs";
|
|
17
17
|
import { runDeadCodeCli } from "../dead-code/cli.mjs";
|
|
18
18
|
import { runVerifyWorkflowSecretsCli } from "../workflow-secrets-drift/cli.mjs";
|
|
19
|
+
import { runRunnerPolicyCli } from "../runner-policy/cli.mjs";
|
|
19
20
|
import { runVitestBlobManifestCommand } from "./commands/vitest-blob-manifest.mjs";
|
|
20
21
|
import { runVitestReportAttemptCommand } from "./commands/vitest-report-attempt.mjs";
|
|
21
22
|
import { runPrepareVitestReportsCommand } from "./commands/prepare-vitest-reports.mjs";
|
|
@@ -83,6 +84,8 @@ export function runCli(argv = process.argv) {
|
|
|
83
84
|
return runNugetCentralVersionCommand(parsed.args);
|
|
84
85
|
case 'verify-workflow-secrets':
|
|
85
86
|
return runVerifyWorkflowSecretsCli(parsed.args);
|
|
87
|
+
case 'runner-policy':
|
|
88
|
+
return runRunnerPolicyCli(parsed.args);
|
|
86
89
|
case 'dead-code':
|
|
87
90
|
return runDeadCodeCli(parsed.args);
|
|
88
91
|
case 'swift-semantic-equal':
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
declare const FORWARDED: readonly ["with-host-lock", "host-storage", "pnpm-install", "vitest-blob-manifest", "vitest-report-attempt", "prepare-vitest-reports", "nuget-central-version", "verify-workflow-secrets", "dead-code", "swift-semantic-equal", "post-review", "stage-review-payload", "retrospective-transcript", "retrospective-facts", "agent-blackboard", "mcp", "hook", "worktree", "transient-retry", "sandbox-command-audit", "cloc", "coverage-scope-check", "trivy-policy", "docker-image-mirror", "workspace-registry-check", "storybook-browser-runner", "tmux"];
|
|
1
|
+
declare const FORWARDED: readonly ["with-host-lock", "host-storage", "pnpm-install", "vitest-blob-manifest", "vitest-report-attempt", "prepare-vitest-reports", "nuget-central-version", "verify-workflow-secrets", "runner-policy", "dead-code", "swift-semantic-equal", "post-review", "stage-review-payload", "retrospective-transcript", "retrospective-facts", "agent-blackboard", "mcp", "hook", "worktree", "transient-retry", "sandbox-command-audit", "cloc", "coverage-scope-check", "trivy-policy", "docker-image-mirror", "workspace-registry-check", "storybook-browser-runner", "tmux"];
|
|
2
2
|
type Name = (typeof FORWARDED)[number];
|
|
3
3
|
type ForwardedCommand = {
|
|
4
4
|
[K in Name]: {
|
package/dist/cli/parse.d.mts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const USAGE = "Usage: vouchington <command> [options]\n\nCommands:\n runner-port-policy Print or validate a runner port policy\n with-host-lock Run a command under a host-wide lock\n host-storage Check free space on caller-supplied paths\n gha-runtime-audit Audit successful GitHub Actions job runtimes\n require-up-to-date Require HEAD to include a fetched remote branch\n fresh-base Classify the worktree against a remote base branch\n gitleaks-directory-scan Scan a directory with Gitleaks\n ast-grep-examples Run AST-grep rule examples\n ast-grep-pack Print shipped unconditional AST-grep pack paths as JSON\n gha-workspace-policy Check GitHub Actions workspace safety policy\n gha-output Write a collision-safe multiline GITHUB_OUTPUT record\n gha-needs-results Fail if required GitHub Actions job results failed\n download-with-diagnostics Download a URL and report HTTP status on failure\n download-optional-run-artifacts Download optional artifacts from the current run\n host-pressure-diagnostics Print a bounded host memory/OOM/PSI snapshot\n allocate-browser-safe-ports Allocate Fetch-safe localhost ports\n diagnose-port-collision Capture bounded localhost port diagnostics\n prepare-trivy-db Download the Trivy vulnerability database\n gha-artifacts-cleanup Delete classified GitHub Actions artifacts\n agent-issue-labels Map changed paths to labels; create missing repository labels\n http-origin Validate an optional HTTP(S) origin\n vitest-blob-manifest Stamp a vitest-blob-manifest:v1 identity file\n vitest-report-attempt Write or read a Vitest report-attempt marker\n prepare-vitest-reports Validate and select Vitest report JSON files\n pnpm-install Install a pnpm workspace with retry and release-age fail-fast\n check-cache-size Measure a path and decide whether to save a GHA cache\n make-shard-matrix Emit a [1..N] GitHub Actions shard matrix\n load-runner-env Overlay a runner env file onto GITHUB_ENV with injection guards\n clean-workspace Reset a persistent-runner workspace with a fork-PR trust gate\n install-github-release Download a checksum-verified GitHub Release binary\n run-with-timeout Run a command with GNU timeout or a Perl fallback\n lint-links Two-pass lychee: internal links fail, external warn\n materialize-pr-context Dump PR title/body/files/diff/comments and #N crawl\n wait-for-apt-locks Wait until apt/dpkg lock files are free\n install-playwright-chromium-arm64 Install Playwright Chromium from browsers.json\n ghcr-package-retention Delete old GHCR package versions (KEEP_MIN or --main-history)\n harness-admission-lane Compute a GITHUB_RUN_ID admission lane for fleet fan-out\n harness-assert-gates Fail if any named HARNESS_*_ENABLED gate is enabled\n gha-collaborator-trust Classify authors as write-access collaborators or not\n nuget-central-version Validate a Directory.Packages.props PackageVersion delta\n verify-workflow-secrets Check a secret inventory against live repository and environment secrets\n dead-code Gate unused code against a committed jscpd baseline\n swift-semantic-equal Compare Swift sources ignoring comments and whitespace\n post-review Post one COMMENT review from a staged payload file\n stage-review-payload Validate a review payload file into a staging directory\n retrospective-transcript Format facts from Claude-compatible, Codex, or Grok transcripts\n link-skill Link one packaged skill into an explicit consumer directory\n retrospective-facts Gather immutable facts for a retrospective\n agent-blackboard Probe an Agent Blackboard deployment, classify distill sessions, manage snapshots\n mcp Serve the agent-blackboard journal tools over stdio (MCP)\n hook Run a repository policy module as a pre/post tool-use hook\n worktree Reclaim finished git worktrees (dry run unless --yes)\n tmux Run configured dev windows in tmux; name panes; agent reminders\n story-coverage Check component exports are imported by stories\n transient-retry Rerun a failed GitHub Actions run when an injected rule matches\n sandbox-command-audit Audit agent transcripts for sandbox escalations and denials\n cloc Count tracked lines of code by category and service with scc\n coverage-scope-check Check positive-threshold coverage rules against the Vitest scope\n trivy-policy Check tracked Trivy workflow scans and the exception registry\n docker-image-mirror Require tracked Docker images to come from a Docker Hub mirror\n workspace-registry-check Check syncpack, pnpm workspace and CI path-filter registries against tracked manifests\n storybook-browser-runner Run the Storybook Vitest browser project with cache, retry and watchdog\n\nOptions:\n -h, --help Show this help\n -v, --version Print the package version\n\nrunner-port-policy\n (no args) Print the shipped policy as JSON\n --file <path> Validate and print a policy file\n --reserved <port> Print true if the port is reserved\n\nwith-host-lock\n --name <family>\n [--slots <n>]\n --timeout-seconds <n>\n [--command-timeout-seconds <n>]\n [--failure-diagnostics <absolute-script>]\n [--on-acquire-timeout fail|run-unlocked]\n -- <command> [args...]\n\nhost-storage --path <path> [--path <path>...] [--minimum-free-bytes <bytes>] [--pnpm-store] [--docker-root] [--docker-desktop-path <path>] [--discovery-timeout-ms <ms>]\n\ngha-runtime-audit\n [--repository owner/name] Default GITHUB_REPOSITORY\n [--branch main]\n [--median-threshold-floor <seconds>] Off unless set. Must be below the ceiling\n [--median-threshold-ceiling <seconds>] Default 360. Flags a five-sample median above this\n --pr-workflow <name|/regex/> Repeatable\n --push-workflow <name|/regex/> Repeatable\n\nrequire-up-to-date --remote <name> --branch <name>\nfresh-base [--remote <name>] [--branch <name>] [--skip-fetch]\ngitleaks-directory-scan --config <path> [--directory <path>]\nast-grep-examples --rules <directory> --config <path>\nast-grep-pack\ngha-workspace-policy [--root <directory>] [--workflow-directory <directory>] [--action-directory <directory>]\n\ngha-output <name>\ngha-needs-results [label]\ndownload-with-diagnostics <url> <destination> [-- curl-args...]\ndownload-optional-run-artifacts (--name <name>... | --pattern <pattern>) --dir <directory>\nhost-pressure-diagnostics\nallocate-browser-safe-ports <count> [--policy path] [--forbidden-ports path]\ndiagnose-port-collision [--ports \"2200 2216\"] [--output-dir PATH]\nprepare-trivy-db\ngha-artifacts-cleanup run --run-id <id> [--keep-pattern glob] [--delete-pattern glob] [--patterns-file json]\ngha-artifacts-cleanup sweep --older-than-hours <n> [--keep-pattern glob] [--delete-pattern glob] [--patterns-file json]\nagent-issue-labels labels-from-paths [--labeler <path>] <path>...\nagent-issue-labels ensure-labels [--repo owner/name] [--policy-file json] [--update] <label>...\nhttp-origin [--field NAME] [value]\nvitest-blob-manifest <suite> [reports-directory]\nvitest-report-attempt <write DIRECTORY SUITE|read ROOT>\nprepare-vitest-reports [primary-directory] [fallback-directory] [output-directory]\npnpm-install --runner-lifecycle persistent|ephemeral|ephemeral-full --install-scripts true|false\ncheck-cache-size <path> <max-bytes> <label>\nmake-shard-matrix <total>\nload-runner-env\nclean-workspace\ninstall-github-release --repo owner/name --version X --asset 'name-{platform}.tar.gz' --bin name [--tag-prefix PREFIX] [--expected-sha256 SHA256] [--no-checksum] [--checksums-asset NAME] [--version-flag FLAG] [--bin-dir DIR]\nrun-with-timeout <timeout-seconds> <kill-after-seconds> <command...>\nlint-links [--offline] [--config PATH] [--glob PATTERN] [files...]\nmaterialize-pr-context\nwait-for-apt-locks\ninstall-playwright-chromium-arm64 [name:archive...]\nghcr-package-retention [--main-history] [--apply|--dry-run] [<url-encoded-package>...]\nharness-admission-lane <lanes>\nharness-assert-gates <gate>...\ngha-collaborator-trust <owner/repo> [--allow-bot <login>]... < authors.json\nnuget-central-version <trusted-props> <candidate-props> <metadata-json> <output-props>\nverify-workflow-secrets [--repo OWNER/NAME] [--confirm NAME,...] [--inventory MODULE] [--export NAME] [--branch NAME]\ndead-code --baseline PATH [--seed|--update] [--config PATH] [--binary PATH] [--repo-root PATH] [--entry GLOB]... [--snapshot-ignore GLOB]... [--exclude GLOB]...\nswift-semantic-equal <base> <head> <file.swift>\npost-review\nstage-review-payload optional|required <source> <destination>\nretrospective-transcript [--session-id ID] [--jsonl PATH] [--projects-dir PATH] [--codex-sessions-dir PATH] [--grok-sessions-dir PATH]\nlink-skill <name> --source-root <skills-dir> --target-root <consumer-skills-dir> Link a packaged or repository-local skill\nretrospective-facts (--pr NUMBER | --branch NAME | --no-pr) [--repo OWNER/NAME] [--raw]\nagent-blackboard probe\nagent-blackboard session-start [--skip-env NAME] [--setup-hint TEXT] [--docs-path PATH] [--restore-hint TEXT] [--timeout-ms N] (SessionStart hook; payload on stdin)\nagent-blackboard distill classify <partition.jsonl> --retro-cutoff ISO8601 --session-cutoff ISO8601\nagent-blackboard snapshot partition --snapshot PATH --checksum SHA256 --counts '{\"sessions\":N,\"entries\":N,\"records\":N,\"bytes\":N}'\nagent-blackboard snapshot cleanup [--snapshot PATH] [--partition-directory PATH --receipt JSON]\nmcp\n (no args) Serve journal_append, journal_entries, outbox_status, outbox_flush,\n session_ensure, retrospective_check, retrospective_save,\n pr_validate, pr_create, pr_update,\n snapshot_export, snapshot_partition, snapshot_cleanup, and session_archive over stdio.\n Needs the optional @modelcontextprotocol/sdk peer (and zod).\n Launch it from inside the repository's git worktree.\n\nhook pre-tool-use|post-tool-use --harness claude|codex|cursor|grok --policy <module> [--root <dir>] [--automation-env NAME]...\n Reads the harness hook payload on stdin. <module> default-exports a policy object (or a function\n of the hook context returning one) with a command rule table, post-tool-use checkers, and an\n optional reminder. pre-tool-use exits 2 to block, and also when the policy cannot load.\n post-tool-use is advisory and always exits 0. --root defaults to the working directory.\n Each --automation-env NAME (repeatable) marks the run unattended when that environment variable\n is set, non-empty, and not 0 or false; CI markers and claude -p are always unattended.\n\nworktree reclaim [--yes] [--json] [--max-worktrees N] [--timeout-ms N] [--pr-limit N] [--after PATH]\n Dry run by default. Removes clean, fully pushed worktrees whose same-repository PR for the\n branch is merged or closed at exactly HEAD, using git worktree remove (never forced).\n Skips the main checkout, the current worktree, and locked, bare or detached worktrees.\n\ntransient-retry --rules <module> [--repo owner/name] [--token-env NAME] [--dry-run] <run-id>\n Loads a module exporting \"rules\" (and optionally \"limits\"), evaluates them against the failed run,\n and reruns only on a match. Exits 0 on rerun, 2 when none is warranted, 1 on error.\n\nsandbox-command-audit --rules <module> [--settings-path <file>] [--repo-root <dir>]... [--worktree-glob <glob>]... [--projects-dir <dir>] [--codex-sessions-dir <dir>] [--session-id <id>] [--limit N] [--since DAYS] [--json] [--raw]\n Scans Claude and Codex transcripts scoped to this repository (git roots plus any --worktree-glob\n layouts) and reports Bash escalations, denials and permission failures by command prefix.\n <module> exports an object (default or \"rules\") with loadPolicy({ settingsPath, cwd }), which\n returns { covers(list, commandOrPrefix) } for the allow/deny/excluded lists or { error }, and\n optionally classifyFailure(command, text, source), limits and worktreeGlobs. Transcript roots\n default to CLAUDE_CONFIG_DIR/projects and CODEX_HOME/sessions. --raw prints full command text.\n\ncloc --config <file> [--scc-bin <path>] [--json]\n Counts git-tracked lines with scc (SCC_BIN or --scc-bin, else \"scc\"), classified into\n source/tests/tooling and by service, and prints an aligned table (--json: rows). <file> is a .json\n file or a module whose default (or \"config\") export is the layout: services [{ name, match }],\n defaultService, categories, testPatterns, toolingPatterns, countedRoots, countedRootFiles,\n excludedDirs, ignoredDirs, sccBin, missingSccHint.\n\ncoverage-scope-check [--rules <path>] [--scope-file <json>] [--include <glob>]... [--exclude <glob>]...\n Fails (exit 1) when a git-tracked file that a coverage rules file (default .coverage-rules.yml)\n gives a patch_coverage_min above 0, and its scope does not ignore, is outside the collector's\n scope. The collector scope is the repeated --include/--exclude globs plus, optionally, the\n include/exclude string arrays of a --scope-file JSON written from the Vitest coverage config.\n At least one include glob is required.\n\ntrivy-policy [--root <dir>] [--ignore-file <path>] [--findings-exit-code-env <NAME>] [--cleanup-url-prefix <url>] [--min-gates N] [--min-sboms N] [--max-expiry-days N]\n Reads git-tracked workflows, composite actions and shell scripts and prints each violation (exit 1).\n Every Trivy package scan must be an auditable CLI run block (no action, wrapper, substitution or\n background). Vulnerability gates need --scanners vuln, --pkg-types os, --severity CRITICAL,HIGH,\n --ignore-unfixed, --skip-db-update, --quiet, table output to a file, --ignorefile <ignore-file>\n (default .trivyignore.yaml) and --exit-code \"$<NAME>\" (default TRIVY_FINDINGS_EXIT_CODE).\n CycloneDX SBOM scans must be unfiltered with --exit-code 0. At least --min-gates gates and\n --min-sboms SBOM scans (default 2 each) must exist. The tracked ignore registry needs purl-exact OS\n packages, a \"Not exploitable: ... Cleanup: <issue URL>\" statement (URL must start with\n --cleanup-url-prefix when given) and an expired_at between tomorrow and --max-expiry-days (30).\n\ndocker-image-mirror [--root <dir>] [--mirror <host>] [--allow-registry <prefix>]... [--require-digest]\n [--allow-ref-expression <text>]...\n Prints each Docker Hub image in git-tracked workflows, composite actions and Dockerfiles (exit 1):\n run, pull and create commands, containers, services, docker:// references, buildx drivers, FROM,\n COPY --from and # syntax. Images must name a registry host; --mirror (default mirror.gcr.io) is\n the host the message tells you to use. --allow-registry (repeatable) instead requires every image,\n including FROM and COPY --from, to start with one of the prefixes; a reference that expands a\n variable passes only when its literal text before the variable starts with a prefix. --require-digest\n requires @sha256: plus 64 lowercase hex characters. Stage aliases and scratch stay exempt.\n --allow-ref-expression (repeatable) is an audited escape hatch for dynamic job outputs: a reference\n whose raw text exactly equals the value is accepted. Images the same file builds locally are exempt.\n\nworkspace-registry-check [--root <dir>] [--syncpack-config <path>] [--workspace-file <path>]\n [--path-filters <path>] [--tooling-group <name>] [--trigger-only-glob <glob>] [--runtime-prefix <prefix>]\n Reconciles git-tracked package.json manifests with the syncpack \"source\" globs (default\n .syncpackrc.json), the pnpm \"packages\" globs (pnpm-workspace.yaml) and the dorny/paths-filter groups\n (.github/ci-path-filters.yml) and prints one line per violation (exit 1). The --tooling-group group\n (default tooling) must reach every manifest and wildcard workspace glob, and its --trigger-only-glob\n (default **/package.json) does not count as registering a manifest. Each group named with\n --runtime-prefix (default runtime-) must mirror the primary group of the same name.\n\nstorybook-browser-runner --project <name> [--command <cmd>] [--result-file <path>]... [--completion-file <path>] [--coverage-arg=<arg>]... [--optimize-deps-config <path>] [--env-prefix <PREFIX>] [--progress-prefix <text>] [-- <argv>...]\n Spawns <cmd> (default pnpm) in its own process group with <argv> (default \"exec vitest run\n --project <name>\") plus the coverage args (default --coverage) and supervises it: a Vite optimizer\n cache, retries on known Vite and browser start-up flakes, and stall, hang and session-budget\n watchdogs. --result-file paths are removed before each attempt and --completion-file is the one\n whose appearance is recorded. Tuned by <PREFIX>_STARTUP_ATTEMPTS, _OPTIMIZER_STALL_MS, _HANG_MS,\n _SESSION_BUDGET_MS, _DIAGNOSTICS_FILE, _PERSISTENT_CACHE, _PERSISTENT_CACHE_DIR and _COVERAGE\n (PREFIX defaults to STORYBOOK_BROWSER). Exits with the resolved test exit code.\n\ntmux up --config <file> [--root <dir>] [--no-attach] [-v|--verbose]\ntmux name [--socket PATH --pane %ID --worktree PATH] <name> | read-title | post-tool | agent-reminder <event>\n Environment: TMUX_TARGET_BIN, TMUX_TARGET_ROOT, TMUX_NAME_COMMAND, AGENT_TMUX_SOCKET/PANE/WORKTREE.\n\nstory-coverage --root <dir> --component-root <rel> --story-root <rel> --source-extension <ext> --component-extension <ext> --marker <regex> --story-pattern <regex> [--alias <prefix>=<path>] [--exclusions <json>] [--exclusions-label <text>]\n";
|
|
1
|
+
export declare const USAGE = "Usage: vouchington <command> [options]\n\nCommands:\n runner-port-policy Print or validate a runner port policy\n with-host-lock Run a command under a host-wide lock\n host-storage Check free space on caller-supplied paths\n gha-runtime-audit Audit successful GitHub Actions job runtimes\n require-up-to-date Require HEAD to include a fetched remote branch\n fresh-base Classify the worktree against a remote base branch\n gitleaks-directory-scan Scan a directory with Gitleaks\n ast-grep-examples Run AST-grep rule examples\n ast-grep-pack Print shipped unconditional AST-grep pack paths as JSON\n gha-workspace-policy Check GitHub Actions workspace safety policy\n gha-output Write a collision-safe multiline GITHUB_OUTPUT record\n gha-needs-results Fail if required GitHub Actions job results failed\n download-with-diagnostics Download a URL and report HTTP status on failure\n download-optional-run-artifacts Download optional artifacts from the current run\n host-pressure-diagnostics Print a bounded host memory/OOM/PSI snapshot\n allocate-browser-safe-ports Allocate Fetch-safe localhost ports\n diagnose-port-collision Capture bounded localhost port diagnostics\n prepare-trivy-db Download the Trivy vulnerability database\n gha-artifacts-cleanup Delete classified GitHub Actions artifacts\n agent-issue-labels Map changed paths to labels; create missing repository labels\n http-origin Validate an optional HTTP(S) origin\n vitest-blob-manifest Stamp a vitest-blob-manifest:v1 identity file\n vitest-report-attempt Write or read a Vitest report-attempt marker\n prepare-vitest-reports Validate and select Vitest report JSON files\n pnpm-install Install a pnpm workspace with retry and release-age fail-fast\n check-cache-size Measure a path and decide whether to save a GHA cache\n make-shard-matrix Emit a [1..N] GitHub Actions shard matrix\n load-runner-env Overlay a runner env file onto GITHUB_ENV with injection guards\n clean-workspace Reset a persistent-runner workspace with a fork-PR trust gate\n install-github-release Download a checksum-verified GitHub Release binary\n run-with-timeout Run a command with GNU timeout or a Perl fallback\n lint-links Two-pass lychee: internal links fail, external warn\n materialize-pr-context Dump PR title/body/files/diff/comments and #N crawl\n wait-for-apt-locks Wait until apt/dpkg lock files are free\n install-playwright-chromium-arm64 Install Playwright Chromium from browsers.json\n ghcr-package-retention Delete old GHCR package versions (KEEP_MIN or --main-history)\n harness-admission-lane Compute a GITHUB_RUN_ID admission lane for fleet fan-out\n harness-assert-gates Fail if any named HARNESS_*_ENABLED gate is enabled\n gha-collaborator-trust Classify authors as write-access collaborators or not\n nuget-central-version Validate a Directory.Packages.props PackageVersion delta\n verify-workflow-secrets Check a secret inventory against live repository and environment secrets\n runner-policy Check workflow runner labels and jobs against a config\n dead-code Gate unused code against a committed jscpd baseline\n swift-semantic-equal Compare Swift sources ignoring comments and whitespace\n post-review Post one COMMENT review from a staged payload file\n stage-review-payload Validate a review payload file into a staging directory\n retrospective-transcript Format facts from Claude-compatible, Codex, or Grok transcripts\n link-skill Link one packaged skill into an explicit consumer directory\n retrospective-facts Gather immutable facts for a retrospective\n agent-blackboard Probe an Agent Blackboard deployment, classify distill sessions, manage snapshots\n mcp Serve the agent-blackboard journal tools over stdio (MCP)\n hook Run a repository policy module as a pre/post tool-use hook\n worktree Reclaim finished git worktrees (dry run unless --yes)\n tmux Run configured dev windows in tmux; name panes; agent reminders\n story-coverage Check component exports are imported by stories\n transient-retry Rerun a failed GitHub Actions run when an injected rule matches\n sandbox-command-audit Audit agent transcripts for sandbox escalations and denials\n cloc Count tracked lines of code by category and service with scc\n coverage-scope-check Check positive-threshold coverage rules against the Vitest scope\n trivy-policy Check tracked Trivy workflow scans and the exception registry\n docker-image-mirror Require tracked Docker images to come from a Docker Hub mirror\n workspace-registry-check Check syncpack, pnpm workspace and CI path-filter registries against tracked manifests\n storybook-browser-runner Run the Storybook Vitest browser project with cache, retry and watchdog\n\nOptions:\n -h, --help Show this help\n -v, --version Print the package version\n\nrunner-port-policy\n (no args) Print the shipped policy as JSON\n --file <path> Validate and print a policy file\n --reserved <port> Print true if the port is reserved\n\nwith-host-lock\n --name <family>\n [--slots <n>]\n --timeout-seconds <n>\n [--command-timeout-seconds <n>]\n [--failure-diagnostics <absolute-script>]\n [--on-acquire-timeout fail|run-unlocked]\n -- <command> [args...]\n\nhost-storage --path <path> [--path <path>...] [--minimum-free-bytes <bytes>] [--pnpm-store] [--docker-root] [--docker-desktop-path <path>] [--discovery-timeout-ms <ms>]\n\ngha-runtime-audit\n [--repository owner/name] Default GITHUB_REPOSITORY\n [--branch main]\n [--median-threshold-floor <seconds>] Off unless set. Must be below the ceiling\n [--median-threshold-ceiling <seconds>] Default 360. Flags a five-sample median above this\n --pr-workflow <name|/regex/> Repeatable\n --push-workflow <name|/regex/> Repeatable\n\nrequire-up-to-date --remote <name> --branch <name>\nfresh-base [--remote <name>] [--branch <name>] [--skip-fetch]\ngitleaks-directory-scan --config <path> [--directory <path>]\nast-grep-examples --rules <directory> --config <path>\nast-grep-pack\ngha-workspace-policy [--root <directory>] [--workflow-directory <directory>] [--action-directory <directory>]\n\ngha-output <name>\ngha-needs-results [label]\ndownload-with-diagnostics <url> <destination> [-- curl-args...]\ndownload-optional-run-artifacts (--name <name>... | --pattern <pattern>) --dir <directory>\nhost-pressure-diagnostics\nallocate-browser-safe-ports <count> [--policy path] [--forbidden-ports path]\ndiagnose-port-collision [--ports \"2200 2216\"] [--output-dir PATH]\nprepare-trivy-db\ngha-artifacts-cleanup run --run-id <id> [--keep-pattern glob] [--delete-pattern glob] [--patterns-file json]\ngha-artifacts-cleanup sweep --older-than-hours <n> [--keep-pattern glob] [--delete-pattern glob] [--patterns-file json]\nagent-issue-labels labels-from-paths [--labeler <path>] <path>...\nagent-issue-labels ensure-labels [--repo owner/name] [--policy-file json] [--update] <label>...\nhttp-origin [--field NAME] [value]\nvitest-blob-manifest <suite> [reports-directory]\nvitest-report-attempt <write DIRECTORY SUITE|read ROOT>\nprepare-vitest-reports [primary-directory] [fallback-directory] [output-directory]\npnpm-install --runner-lifecycle persistent|ephemeral|ephemeral-full --install-scripts true|false\ncheck-cache-size <path> <max-bytes> <label>\nmake-shard-matrix <total>\nload-runner-env\nclean-workspace\ninstall-github-release --repo owner/name --version X --asset 'name-{platform}.tar.gz' --bin name [--tag-prefix PREFIX] [--expected-sha256 SHA256] [--no-checksum] [--checksums-asset NAME] [--version-flag FLAG] [--bin-dir DIR]\nrun-with-timeout <timeout-seconds> <kill-after-seconds> <command...>\nlint-links [--offline] [--config PATH] [--glob PATTERN] [files...]\nmaterialize-pr-context\nwait-for-apt-locks\ninstall-playwright-chromium-arm64 [name:archive...]\nghcr-package-retention [--main-history] [--apply|--dry-run] [<url-encoded-package>...]\nharness-admission-lane <lanes>\nharness-assert-gates <gate>...\ngha-collaborator-trust <owner/repo> [--allow-bot <login>]... < authors.json\nnuget-central-version <trusted-props> <candidate-props> <metadata-json> <output-props>\nverify-workflow-secrets [--repo OWNER/NAME] [--confirm NAME,...] [--inventory MODULE] [--export NAME] [--branch NAME]\nrunner-policy [--config FILE] [--root DIR]\ndead-code --baseline PATH [--seed|--update] [--config PATH] [--binary PATH] [--repo-root PATH] [--entry GLOB]... [--snapshot-ignore GLOB]... [--exclude GLOB]...\nswift-semantic-equal <base> <head> <file.swift>\npost-review\nstage-review-payload optional|required <source> <destination>\nretrospective-transcript [--session-id ID] [--jsonl PATH] [--projects-dir PATH] [--codex-sessions-dir PATH] [--grok-sessions-dir PATH]\nlink-skill <name> --source-root <skills-dir> --target-root <consumer-skills-dir> Link a packaged or repository-local skill\nretrospective-facts (--pr NUMBER | --branch NAME | --no-pr) [--repo OWNER/NAME] [--raw]\nagent-blackboard probe\nagent-blackboard session-start [--skip-env NAME] [--setup-hint TEXT] [--docs-path PATH] [--restore-hint TEXT] [--timeout-ms N] (SessionStart hook; payload on stdin)\nagent-blackboard distill classify <partition.jsonl> --retro-cutoff ISO8601 --session-cutoff ISO8601\nagent-blackboard snapshot partition --snapshot PATH --checksum SHA256 --counts '{\"sessions\":N,\"entries\":N,\"records\":N,\"bytes\":N}'\nagent-blackboard snapshot cleanup [--snapshot PATH] [--partition-directory PATH --receipt JSON]\nmcp\n (no args) Serve journal_append, journal_entries, outbox_status, outbox_flush,\n session_ensure, retrospective_check, retrospective_save,\n pr_validate, pr_create, pr_update,\n snapshot_export, snapshot_partition, snapshot_cleanup, and session_archive over stdio.\n Needs the optional @modelcontextprotocol/sdk peer (and zod).\n Launch it from inside the repository's git worktree.\n\nhook pre-tool-use|post-tool-use --harness claude|codex|cursor|grok --policy <module> [--root <dir>] [--automation-env NAME]...\n Reads the harness hook payload on stdin. <module> default-exports a policy object (or a function\n of the hook context returning one) with a command rule table, post-tool-use checkers, and an\n optional reminder. pre-tool-use exits 2 to block, and also when the policy cannot load.\n post-tool-use is advisory and always exits 0. --root defaults to the working directory.\n Each --automation-env NAME (repeatable) marks the run unattended when that environment variable\n is set, non-empty, and not 0 or false; CI markers and claude -p are always unattended.\n\nworktree reclaim [--yes] [--json] [--max-worktrees N] [--timeout-ms N] [--pr-limit N] [--after PATH]\n Dry run by default. Removes clean, fully pushed worktrees whose same-repository PR for the\n branch is merged or closed at exactly HEAD, using git worktree remove (never forced).\n Skips the main checkout, the current worktree, and locked, bare or detached worktrees.\n\ntransient-retry --rules <module> [--repo owner/name] [--token-env NAME] [--dry-run] <run-id>\n Loads a module exporting \"rules\" (and optionally \"limits\"), evaluates them against the failed run,\n and reruns only on a match. Exits 0 on rerun, 2 when none is warranted, 1 on error.\n\nsandbox-command-audit --rules <module> [--settings-path <file>] [--repo-root <dir>]... [--worktree-glob <glob>]... [--projects-dir <dir>] [--codex-sessions-dir <dir>] [--session-id <id>] [--limit N] [--since DAYS] [--json] [--raw]\n Scans Claude and Codex transcripts scoped to this repository (git roots plus any --worktree-glob\n layouts) and reports Bash escalations, denials and permission failures by command prefix.\n <module> exports an object (default or \"rules\") with loadPolicy({ settingsPath, cwd }), which\n returns { covers(list, commandOrPrefix) } for the allow/deny/excluded lists or { error }, and\n optionally classifyFailure(command, text, source), limits and worktreeGlobs. Transcript roots\n default to CLAUDE_CONFIG_DIR/projects and CODEX_HOME/sessions. --raw prints full command text.\n\ncloc --config <file> [--scc-bin <path>] [--json]\n Counts git-tracked lines with scc (SCC_BIN or --scc-bin, else \"scc\"), classified into\n source/tests/tooling and by service, and prints an aligned table (--json: rows). <file> is a .json\n file or a module whose default (or \"config\") export is the layout: services [{ name, match }],\n defaultService, categories, testPatterns, toolingPatterns, countedRoots, countedRootFiles,\n excludedDirs, ignoredDirs, sccBin, missingSccHint.\n\ncoverage-scope-check [--rules <path>] [--scope-file <json>] [--include <glob>]... [--exclude <glob>]...\n Fails (exit 1) when a git-tracked file that a coverage rules file (default .coverage-rules.yml)\n gives a patch_coverage_min above 0, and its scope does not ignore, is outside the collector's\n scope. The collector scope is the repeated --include/--exclude globs plus, optionally, the\n include/exclude string arrays of a --scope-file JSON written from the Vitest coverage config.\n At least one include glob is required.\n\ntrivy-policy [--root <dir>] [--ignore-file <path>] [--findings-exit-code-env <NAME>] [--cleanup-url-prefix <url>] [--min-gates N] [--min-sboms N] [--max-expiry-days N]\n Reads git-tracked workflows, composite actions and shell scripts and prints each violation (exit 1).\n Every Trivy package scan must be an auditable CLI run block (no action, wrapper, substitution or\n background). Vulnerability gates need --scanners vuln, --pkg-types os, --severity CRITICAL,HIGH,\n --ignore-unfixed, --skip-db-update, --quiet, table output to a file, --ignorefile <ignore-file>\n (default .trivyignore.yaml) and --exit-code \"$<NAME>\" (default TRIVY_FINDINGS_EXIT_CODE).\n CycloneDX SBOM scans must be unfiltered with --exit-code 0. At least --min-gates gates and\n --min-sboms SBOM scans (default 2 each) must exist. The tracked ignore registry needs purl-exact OS\n packages, a \"Not exploitable: ... Cleanup: <issue URL>\" statement (URL must start with\n --cleanup-url-prefix when given) and an expired_at between tomorrow and --max-expiry-days (30).\n\ndocker-image-mirror [--root <dir>] [--mirror <host>] [--allow-registry <prefix>]... [--require-digest]\n [--allow-ref-expression <text>]...\n Prints each Docker Hub image in git-tracked workflows, composite actions and Dockerfiles (exit 1):\n run, pull and create commands, containers, services, docker:// references, buildx drivers, FROM,\n COPY --from and # syntax. Images must name a registry host; --mirror (default mirror.gcr.io) is\n the host the message tells you to use. --allow-registry (repeatable) instead requires every image,\n including FROM and COPY --from, to start with one of the prefixes; a reference that expands a\n variable passes only when its literal text before the variable starts with a prefix. --require-digest\n requires @sha256: plus 64 lowercase hex characters. Stage aliases and scratch stay exempt.\n --allow-ref-expression (repeatable) is an audited escape hatch for dynamic job outputs: a reference\n whose raw text exactly equals the value is accepted. Images the same file builds locally are exempt.\n\nworkspace-registry-check [--root <dir>] [--syncpack-config <path>] [--workspace-file <path>]\n [--path-filters <path>] [--tooling-group <name>] [--trigger-only-glob <glob>] [--runtime-prefix <prefix>]\n Reconciles git-tracked package.json manifests with the syncpack \"source\" globs (default\n .syncpackrc.json), the pnpm \"packages\" globs (pnpm-workspace.yaml) and the dorny/paths-filter groups\n (.github/ci-path-filters.yml) and prints one line per violation (exit 1). The --tooling-group group\n (default tooling) must reach every manifest and wildcard workspace glob, and its --trigger-only-glob\n (default **/package.json) does not count as registering a manifest. Each group named with\n --runtime-prefix (default runtime-) must mirror the primary group of the same name.\n\nstorybook-browser-runner --project <name> [--command <cmd>] [--result-file <path>]... [--completion-file <path>] [--coverage-arg=<arg>]... [--optimize-deps-config <path>] [--env-prefix <PREFIX>] [--progress-prefix <text>] [-- <argv>...]\n Spawns <cmd> (default pnpm) in its own process group with <argv> (default \"exec vitest run\n --project <name>\") plus the coverage args (default --coverage) and supervises it: a Vite optimizer\n cache, retries on known Vite and browser start-up flakes, and stall, hang and session-budget\n watchdogs. --result-file paths are removed before each attempt and --completion-file is the one\n whose appearance is recorded. Tuned by <PREFIX>_STARTUP_ATTEMPTS, _OPTIMIZER_STALL_MS, _HANG_MS,\n _SESSION_BUDGET_MS, _DIAGNOSTICS_FILE, _PERSISTENT_CACHE, _PERSISTENT_CACHE_DIR and _COVERAGE\n (PREFIX defaults to STORYBOOK_BROWSER). Exits with the resolved test exit code.\n\ntmux up --config <file> [--root <dir>] [--no-attach] [-v|--verbose]\ntmux name [--socket PATH --pane %ID --worktree PATH] <name> | read-title | post-tool | agent-reminder <event>\n Environment: TMUX_TARGET_BIN, TMUX_TARGET_ROOT, TMUX_NAME_COMMAND, AGENT_TMUX_SOCKET/PANE/WORKTREE.\n\nstory-coverage --root <dir> --component-root <rel> --story-root <rel> --source-extension <ext> --component-extension <ext> --marker <regex> --story-pattern <regex> [--alias <prefix>=<path>] [--exclusions <json>] [--exclusions-label <text>]\n";
|
package/dist/cli/usage-text.mjs
CHANGED
|
@@ -43,6 +43,7 @@ Commands:
|
|
|
43
43
|
gha-collaborator-trust Classify authors as write-access collaborators or not
|
|
44
44
|
nuget-central-version Validate a Directory.Packages.props PackageVersion delta
|
|
45
45
|
verify-workflow-secrets Check a secret inventory against live repository and environment secrets
|
|
46
|
+
runner-policy Check workflow runner labels and jobs against a config
|
|
46
47
|
dead-code Gate unused code against a committed jscpd baseline
|
|
47
48
|
swift-semantic-equal Compare Swift sources ignoring comments and whitespace
|
|
48
49
|
post-review Post one COMMENT review from a staged payload file
|
|
@@ -129,6 +130,7 @@ harness-assert-gates <gate>...
|
|
|
129
130
|
gha-collaborator-trust <owner/repo> [--allow-bot <login>]... < authors.json
|
|
130
131
|
nuget-central-version <trusted-props> <candidate-props> <metadata-json> <output-props>
|
|
131
132
|
verify-workflow-secrets [--repo OWNER/NAME] [--confirm NAME,...] [--inventory MODULE] [--export NAME] [--branch NAME]
|
|
133
|
+
runner-policy [--config FILE] [--root DIR]
|
|
132
134
|
dead-code --baseline PATH [--seed|--update] [--config PATH] [--binary PATH] [--repo-root PATH] [--entry GLOB]... [--snapshot-ignore GLOB]... [--exclude GLOB]...
|
|
133
135
|
swift-semantic-equal <base> <head> <file.swift>
|
|
134
136
|
post-review
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export declare const USAGE = "Usage: vouchington runner-policy [--config <file>] [--root <directory>]";
|
|
2
|
+
export interface RunnerPolicyCliOptions {
|
|
3
|
+
output?: Pick<Console, 'error' | 'log'>;
|
|
4
|
+
}
|
|
5
|
+
/** Exit codes: 0 clean, 1 violations or fail-closed input error, 2 usage error. */
|
|
6
|
+
export declare function runRunnerPolicyCli(argv: readonly string[], options?: RunnerPolicyCliOptions): Promise<number>;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { parseArgs } from 'node:util';
|
|
2
|
+
import { DEFAULT_CONFIG_PATH, DEFAULT_WORKFLOW_ROOT, discoverWorkflows, loadRunnerPolicyConfig, } from "./discover.mjs";
|
|
3
|
+
import { evaluateRunnerPolicy, formatRunnerPolicyViolation } from "./evaluate.mjs";
|
|
4
|
+
export const USAGE = 'Usage: vouchington runner-policy [--config <file>] [--root <directory>]';
|
|
5
|
+
/** Exit codes: 0 clean, 1 violations or fail-closed input error, 2 usage error. */
|
|
6
|
+
export async function runRunnerPolicyCli(argv, options = {}) {
|
|
7
|
+
const { output = console } = options;
|
|
8
|
+
let values;
|
|
9
|
+
try {
|
|
10
|
+
;
|
|
11
|
+
({ values } = parseArgs({
|
|
12
|
+
args: [...argv],
|
|
13
|
+
options: {
|
|
14
|
+
config: { type: 'string', default: DEFAULT_CONFIG_PATH },
|
|
15
|
+
root: { type: 'string', default: DEFAULT_WORKFLOW_ROOT },
|
|
16
|
+
},
|
|
17
|
+
strict: true,
|
|
18
|
+
}));
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
output.error(`${USAGE}\n${error.message}`);
|
|
22
|
+
return 2;
|
|
23
|
+
}
|
|
24
|
+
const empty = ['config', 'root'].find((key) => values[key].trim() === '');
|
|
25
|
+
if (empty !== undefined) {
|
|
26
|
+
output.error(`${USAGE}\n--${empty} requires a non-empty value`);
|
|
27
|
+
return 2;
|
|
28
|
+
}
|
|
29
|
+
try {
|
|
30
|
+
const config = await loadRunnerPolicyConfig(values.config);
|
|
31
|
+
const inputs = await discoverWorkflows(values.root);
|
|
32
|
+
const violations = evaluateRunnerPolicy(inputs, config);
|
|
33
|
+
if (violations.length === 0) {
|
|
34
|
+
output.log(`runner-policy: ${String(inputs.length)} workflow file(s) conform`);
|
|
35
|
+
return 0;
|
|
36
|
+
}
|
|
37
|
+
output.error(`runner-policy: ${String(violations.length)} violation(s)\n` +
|
|
38
|
+
violations.map((violation) => ` - ${formatRunnerPolicyViolation(violation)}`).join('\n'));
|
|
39
|
+
return 1;
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
output.error(`runner-policy failed: ${error.message}`);
|
|
43
|
+
return 1;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
2
|
+
function checkKeys(value, allowed, where, problems) {
|
|
3
|
+
for (const key of Object.keys(value)) {
|
|
4
|
+
if (!allowed.includes(key))
|
|
5
|
+
problems.push(`${where}: unknown key "${key}"`);
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
function stringList(value, where, problems, minimum = 0) {
|
|
9
|
+
const ok = Array.isArray(value) &&
|
|
10
|
+
value.length >= minimum &&
|
|
11
|
+
value.every((item) => typeof item === 'string' && item.trim() !== '');
|
|
12
|
+
if (!ok) {
|
|
13
|
+
problems.push(`${where}: must be ${minimum > 0 ? 'a non-empty' : 'an'} array of non-empty strings`);
|
|
14
|
+
}
|
|
15
|
+
return ok ? value : [];
|
|
16
|
+
}
|
|
17
|
+
function nonEmptyString(value, key, where, problems) {
|
|
18
|
+
const field = value[key];
|
|
19
|
+
if (typeof field === 'string' && field.trim() !== '')
|
|
20
|
+
return field;
|
|
21
|
+
problems.push(`${where}.${key}: must be a non-empty string`);
|
|
22
|
+
return '';
|
|
23
|
+
}
|
|
24
|
+
const jobReference = /^[^#\s]+#[^#\s]+$/;
|
|
25
|
+
function parseRequired(raw, where, problems) {
|
|
26
|
+
checkKeys(raw, ['workflow', 'job', 'runsOn'], where, problems);
|
|
27
|
+
return {
|
|
28
|
+
workflow: nonEmptyString(raw, 'workflow', where, problems),
|
|
29
|
+
job: nonEmptyString(raw, 'job', where, problems),
|
|
30
|
+
runsOn: nonEmptyString(raw, 'runsOn', where, problems),
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
function parseExact(raw, where, problems) {
|
|
34
|
+
checkKeys(raw, ['label', 'jobs'], where, problems);
|
|
35
|
+
const jobs = stringList(raw.jobs, `${where}.jobs`, problems);
|
|
36
|
+
for (const job of jobs) {
|
|
37
|
+
if (!jobReference.test(job))
|
|
38
|
+
problems.push(`${where}.jobs: "${job}" must look like workflow#job`);
|
|
39
|
+
}
|
|
40
|
+
if (new Set(jobs).size !== jobs.length)
|
|
41
|
+
problems.push(`${where}.jobs: entries must be unique`);
|
|
42
|
+
return { label: nonEmptyString(raw, 'label', where, problems), jobs };
|
|
43
|
+
}
|
|
44
|
+
function parseActions(raw, where, problems) {
|
|
45
|
+
if (raw !== undefined && !isRecord(raw)) {
|
|
46
|
+
problems.push(`${where}: must be an object`);
|
|
47
|
+
return { prefixes: [], contains: [], exact: [] };
|
|
48
|
+
}
|
|
49
|
+
const record = raw ?? {};
|
|
50
|
+
checkKeys(record, ['prefixes', 'contains', 'exact'], where, problems);
|
|
51
|
+
const list = (key) => record[key] === undefined ? [] : stringList(record[key], `${where}.${key}`, problems);
|
|
52
|
+
return { prefixes: list('prefixes'), contains: list('contains'), exact: list('exact') };
|
|
53
|
+
}
|
|
54
|
+
function parseRestricted(raw, where, problems) {
|
|
55
|
+
checkKeys(raw, ['label', 'forbidServices', 'forbiddenActions'], where, problems);
|
|
56
|
+
if (raw.forbidServices !== undefined && typeof raw.forbidServices !== 'boolean') {
|
|
57
|
+
problems.push(`${where}.forbidServices: must be a boolean`);
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
label: nonEmptyString(raw, 'label', where, problems),
|
|
61
|
+
forbidServices: raw.forbidServices !== false,
|
|
62
|
+
forbiddenActions: parseActions(raw.forbiddenActions, `${where}.forbiddenActions`, problems),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
function entries(raw, key, problems, parse) {
|
|
66
|
+
const value = raw[key];
|
|
67
|
+
if (value === undefined)
|
|
68
|
+
return [];
|
|
69
|
+
if (!Array.isArray(value)) {
|
|
70
|
+
problems.push(`${key}: must be an array`);
|
|
71
|
+
return [];
|
|
72
|
+
}
|
|
73
|
+
return value.flatMap((item, index) => {
|
|
74
|
+
const where = `${key}[${String(index)}]`;
|
|
75
|
+
if (isRecord(item))
|
|
76
|
+
return [parse(item, where, problems)];
|
|
77
|
+
problems.push(`${where}: must be an object`);
|
|
78
|
+
return [];
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
/** Validates an untrusted parsed-JSON config; throws one error listing every problem. */
|
|
82
|
+
export function parseRunnerPolicyConfig(raw) {
|
|
83
|
+
if (!isRecord(raw))
|
|
84
|
+
throw new Error('runner-policy config must be a JSON object');
|
|
85
|
+
const problems = [];
|
|
86
|
+
checkKeys(raw, ['allowedLabels', 'requiredJobs', 'exactLabelJobs', 'restrictedLabels'], 'config', problems);
|
|
87
|
+
const config = {
|
|
88
|
+
allowedLabels: stringList(raw.allowedLabels, 'allowedLabels', problems, 1),
|
|
89
|
+
requiredJobs: entries(raw, 'requiredJobs', problems, parseRequired),
|
|
90
|
+
exactLabelJobs: entries(raw, 'exactLabelJobs', problems, parseExact),
|
|
91
|
+
restrictedLabels: entries(raw, 'restrictedLabels', problems, parseRestricted),
|
|
92
|
+
};
|
|
93
|
+
if (problems.length > 0) {
|
|
94
|
+
throw new Error(`invalid runner-policy config:\n${problems.map((p) => ` - ${p}`).join('\n')}`);
|
|
95
|
+
}
|
|
96
|
+
return config;
|
|
97
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { RunnerPolicyConfig, WorkflowInput } from './types.mts';
|
|
2
|
+
export declare const DEFAULT_WORKFLOW_ROOT = ".github/workflows";
|
|
3
|
+
export declare const DEFAULT_CONFIG_PATH = ".github/runner-policy.json";
|
|
4
|
+
/**
|
|
5
|
+
* Reads every `*.yml` / `*.yaml` file directly under `root` (workflow directories are flat).
|
|
6
|
+
* Throws when the root is missing or not a directory, or when any file cannot be read.
|
|
7
|
+
*/
|
|
8
|
+
export declare function discoverWorkflows(root: string): Promise<WorkflowInput[]>;
|
|
9
|
+
export declare function loadRunnerPolicyConfig(file: string): Promise<RunnerPolicyConfig>;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { readdir, readFile, stat } from 'node:fs/promises';
|
|
2
|
+
import { join, resolve } from 'node:path';
|
|
3
|
+
import { parseRunnerPolicyConfig } from "./config.mjs";
|
|
4
|
+
export const DEFAULT_WORKFLOW_ROOT = '.github/workflows';
|
|
5
|
+
export const DEFAULT_CONFIG_PATH = '.github/runner-policy.json';
|
|
6
|
+
/**
|
|
7
|
+
* Reads every `*.yml` / `*.yaml` file directly under `root` (workflow directories are flat).
|
|
8
|
+
* Throws when the root is missing or not a directory, or when any file cannot be read.
|
|
9
|
+
*/
|
|
10
|
+
export async function discoverWorkflows(root) {
|
|
11
|
+
const directory = resolve(root);
|
|
12
|
+
const info = await stat(directory).catch(() => undefined);
|
|
13
|
+
if (info === undefined || !info.isDirectory()) {
|
|
14
|
+
throw new Error(`workflow root "${root}" does not exist or is not a directory`);
|
|
15
|
+
}
|
|
16
|
+
const entries = await readdir(directory, { withFileTypes: true });
|
|
17
|
+
const names = entries
|
|
18
|
+
.filter((entry) => entry.isFile() && /\.ya?ml$/.test(entry.name))
|
|
19
|
+
.map((entry) => entry.name)
|
|
20
|
+
.sort();
|
|
21
|
+
return Promise.all(names.map(async (path) => ({ path, text: await readFile(join(directory, path), 'utf8') })));
|
|
22
|
+
}
|
|
23
|
+
export async function loadRunnerPolicyConfig(file) {
|
|
24
|
+
let raw;
|
|
25
|
+
try {
|
|
26
|
+
raw = JSON.parse(await readFile(resolve(file), 'utf8'));
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
throw new Error(`cannot read runner-policy config "${file}": ${error.message}`, {
|
|
30
|
+
cause: error,
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
return parseRunnerPolicyConfig(raw);
|
|
34
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { RunnerPolicyConfig, RunnerPolicyViolation, WorkflowInput } from './types.mts';
|
|
2
|
+
/**
|
|
3
|
+
* Evaluates every configured runner policy over supplied workflow files. Fails closed: empty
|
|
4
|
+
* input, unparseable workflows and config entries naming undiscovered workflows are violations.
|
|
5
|
+
*/
|
|
6
|
+
export declare function evaluateRunnerPolicy(inputs: readonly WorkflowInput[], config: RunnerPolicyConfig): RunnerPolicyViolation[];
|
|
7
|
+
export declare function formatRunnerPolicyViolation(violation: RunnerPolicyViolation): string;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { resolveRunsOn } from "./matrix.mjs";
|
|
2
|
+
import { exactSetViolations, requiredJobViolations, restrictedViolations, } from "./rules.mjs";
|
|
3
|
+
import { parseWorkflowInput } from "./workflow.mjs";
|
|
4
|
+
function allowedLabelViolations(workflows, allowed) {
|
|
5
|
+
const out = [];
|
|
6
|
+
for (const [workflow, parsed] of workflows) {
|
|
7
|
+
for (const [job, body] of parsed.jobs) {
|
|
8
|
+
const base = { workflow, job };
|
|
9
|
+
if (body.uses !== undefined) {
|
|
10
|
+
if (body['runs-on'] !== undefined) {
|
|
11
|
+
out.push({
|
|
12
|
+
...base,
|
|
13
|
+
policy: 'reusable-delegate',
|
|
14
|
+
message: 'reusable-workflow delegate must not set runs-on',
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
continue;
|
|
18
|
+
}
|
|
19
|
+
const resolved = resolveRunsOn(body);
|
|
20
|
+
const policy = 'allowed-labels';
|
|
21
|
+
if (resolved.kind === 'invalid') {
|
|
22
|
+
out.push({ ...base, policy, message: resolved.reason });
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
const labels = resolved.kind === 'literal' ? [resolved.label] : resolved.candidates;
|
|
26
|
+
for (const label of labels.filter((candidate) => !allowed.includes(candidate))) {
|
|
27
|
+
out.push({ ...base, policy, message: `runs-on label "${label}" is not allowed` });
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return out;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Evaluates every configured runner policy over supplied workflow files. Fails closed: empty
|
|
35
|
+
* input, unparseable workflows and config entries naming undiscovered workflows are violations.
|
|
36
|
+
*/
|
|
37
|
+
export function evaluateRunnerPolicy(inputs, config) {
|
|
38
|
+
if (inputs.length === 0) {
|
|
39
|
+
return [{ policy: 'discovery', message: 'no workflow files were discovered' }];
|
|
40
|
+
}
|
|
41
|
+
const violations = [];
|
|
42
|
+
const workflows = new Map();
|
|
43
|
+
for (const input of inputs) {
|
|
44
|
+
const parsed = parseWorkflowInput(input);
|
|
45
|
+
if (parsed.ok)
|
|
46
|
+
workflows.set(input.path, parsed.workflow);
|
|
47
|
+
else
|
|
48
|
+
violations.push({ policy: 'parse', workflow: input.path, message: parsed.message });
|
|
49
|
+
}
|
|
50
|
+
return [
|
|
51
|
+
...violations,
|
|
52
|
+
...allowedLabelViolations(workflows, config.allowedLabels),
|
|
53
|
+
...requiredJobViolations(config.requiredJobs, workflows),
|
|
54
|
+
...exactSetViolations(config.exactLabelJobs, workflows),
|
|
55
|
+
...restrictedViolations(config.restrictedLabels, workflows),
|
|
56
|
+
];
|
|
57
|
+
}
|
|
58
|
+
export function formatRunnerPolicyViolation(violation) {
|
|
59
|
+
const where = [violation.workflow, violation.job].filter(Boolean).join('#');
|
|
60
|
+
return `${where === '' ? '' : `${where}: `}${violation.message} [${violation.policy}]`;
|
|
61
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { runRunnerPolicyCli, USAGE } from './cli.mts';
|
|
2
|
+
export type { RunnerPolicyCliOptions } from './cli.mts';
|
|
3
|
+
export { parseRunnerPolicyConfig } from './config.mts';
|
|
4
|
+
export { DEFAULT_CONFIG_PATH, DEFAULT_WORKFLOW_ROOT, discoverWorkflows, loadRunnerPolicyConfig, } from './discover.mts';
|
|
5
|
+
export { evaluateRunnerPolicy, formatRunnerPolicyViolation } from './evaluate.mts';
|
|
6
|
+
export type { ExactLabelJobs, ForbiddenActions, RequiredJob, RestrictedLabel, RunnerPolicyConfig, RunnerPolicyName, RunnerPolicyViolation, WorkflowInput, } from './types.mts';
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { runRunnerPolicyCli, USAGE } from "./cli.mjs";
|
|
2
|
+
export { parseRunnerPolicyConfig } from "./config.mjs";
|
|
3
|
+
export { DEFAULT_CONFIG_PATH, DEFAULT_WORKFLOW_ROOT, discoverWorkflows, loadRunnerPolicyConfig, } from "./discover.mjs";
|
|
4
|
+
export { evaluateRunnerPolicy, formatRunnerPolicyViolation } from "./evaluate.mjs";
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type WorkflowJob } from './workflow.mts';
|
|
2
|
+
export type RunsOnResolution = {
|
|
3
|
+
kind: 'literal';
|
|
4
|
+
label: string;
|
|
5
|
+
} | {
|
|
6
|
+
kind: 'matrix';
|
|
7
|
+
candidates: string[];
|
|
8
|
+
} | {
|
|
9
|
+
kind: 'invalid';
|
|
10
|
+
reason: string;
|
|
11
|
+
};
|
|
12
|
+
/** Resolves a non-delegate job's `runs-on` to literal label(s), or explains why it cannot. */
|
|
13
|
+
export declare function resolveRunsOn(job: WorkflowJob): RunsOnResolution;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { isRecord } from "./workflow.mjs";
|
|
2
|
+
const matrixExpression = /^\$\{\{\s*matrix\.([A-Za-z_][A-Za-z0-9_-]*)\s*\}\}$/;
|
|
3
|
+
const invalid = (reason) => ({ kind: 'invalid', reason });
|
|
4
|
+
const candidateText = (value) => typeof value === 'string' ? value : JSON.stringify(value);
|
|
5
|
+
function matrixCandidates(job, field) {
|
|
6
|
+
const matrix = isRecord(job.strategy) ? job.strategy.matrix : undefined;
|
|
7
|
+
if (!isRecord(matrix)) {
|
|
8
|
+
return invalid(`matrix.${field} cannot be resolved: strategy.matrix is not a mapping`);
|
|
9
|
+
}
|
|
10
|
+
const candidates = [];
|
|
11
|
+
const declared = matrix[field];
|
|
12
|
+
if (declared !== undefined) {
|
|
13
|
+
if (!Array.isArray(declared))
|
|
14
|
+
return invalid(`matrix.${field} is not an array of labels`);
|
|
15
|
+
candidates.push(...declared);
|
|
16
|
+
}
|
|
17
|
+
if (matrix.include !== undefined) {
|
|
18
|
+
if (!Array.isArray(matrix.include))
|
|
19
|
+
return invalid('matrix.include is not an array');
|
|
20
|
+
for (const entry of matrix.include) {
|
|
21
|
+
if (isRecord(entry) && entry[field] !== undefined)
|
|
22
|
+
candidates.push(entry[field]);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
if (candidates.length === 0)
|
|
26
|
+
return invalid(`matrix.${field} resolves to no candidates`);
|
|
27
|
+
return { kind: 'matrix', candidates: candidates.map(candidateText) };
|
|
28
|
+
}
|
|
29
|
+
/** Resolves a non-delegate job's `runs-on` to literal label(s), or explains why it cannot. */
|
|
30
|
+
export function resolveRunsOn(job) {
|
|
31
|
+
const runsOn = job['runs-on'];
|
|
32
|
+
if (runsOn === undefined || runsOn === null)
|
|
33
|
+
return invalid('runs-on is missing');
|
|
34
|
+
if (Array.isArray(runsOn))
|
|
35
|
+
return invalid('runs-on must not be an array of labels');
|
|
36
|
+
if (typeof runsOn !== 'string') {
|
|
37
|
+
return invalid(`runs-on must be a literal string, got ${typeof runsOn} form`);
|
|
38
|
+
}
|
|
39
|
+
const field = matrixExpression.exec(runsOn)?.[1];
|
|
40
|
+
if (field !== undefined)
|
|
41
|
+
return matrixCandidates(job, field);
|
|
42
|
+
if (runsOn.includes('${{'))
|
|
43
|
+
return invalid(`runs-on is a computed expression: ${runsOn}`);
|
|
44
|
+
return { kind: 'literal', label: runsOn };
|
|
45
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { ExactLabelJobs, RequiredJob, RestrictedLabel, RunnerPolicyViolation } from './types.mts';
|
|
2
|
+
import { type ParsedWorkflow } from './workflow.mts';
|
|
3
|
+
export type Workflows = ReadonlyMap<string, ParsedWorkflow>;
|
|
4
|
+
export declare function requiredJobViolations(required: readonly RequiredJob[], workflows: Workflows): RunnerPolicyViolation[];
|
|
5
|
+
export declare function exactSetViolations(rules: readonly ExactLabelJobs[], workflows: Workflows): RunnerPolicyViolation[];
|
|
6
|
+
export declare function restrictedViolations(rules: readonly RestrictedLabel[], workflows: Workflows): RunnerPolicyViolation[];
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { resolveRunsOn } from "./matrix.mjs";
|
|
2
|
+
import { hasNonEmptyServices, stepUses } from "./workflow.mjs";
|
|
3
|
+
const missingWorkflow = (policy, workflow) => ({
|
|
4
|
+
policy,
|
|
5
|
+
workflow,
|
|
6
|
+
message: `configured workflow "${workflow}" was not discovered`,
|
|
7
|
+
});
|
|
8
|
+
export function requiredJobViolations(required, workflows) {
|
|
9
|
+
return required.flatMap(({ workflow, job, runsOn }) => {
|
|
10
|
+
const parsed = workflows.get(workflow);
|
|
11
|
+
if (parsed === undefined)
|
|
12
|
+
return [missingWorkflow('required-jobs', workflow)];
|
|
13
|
+
const found = parsed.jobs.get(job);
|
|
14
|
+
const base = { policy: 'required-jobs', workflow, job };
|
|
15
|
+
if (found === undefined)
|
|
16
|
+
return [{ ...base, message: 'required job is missing' }];
|
|
17
|
+
const resolved = resolveRunsOn(found);
|
|
18
|
+
if (resolved.kind === 'literal' && resolved.label === runsOn)
|
|
19
|
+
return [];
|
|
20
|
+
return [{ ...base, message: `required job must use literal runs-on "${runsOn}"` }];
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
/** Labels a job runs on: a literal label, every resolvable matrix candidate, or none. */
|
|
24
|
+
function jobLabels(job) {
|
|
25
|
+
const resolved = resolveRunsOn(job);
|
|
26
|
+
if (resolved.kind === 'literal')
|
|
27
|
+
return [resolved.label];
|
|
28
|
+
return resolved.kind === 'matrix' ? resolved.candidates : [];
|
|
29
|
+
}
|
|
30
|
+
export function exactSetViolations(rules, workflows) {
|
|
31
|
+
return rules.flatMap(({ label, jobs }) => {
|
|
32
|
+
const out = [];
|
|
33
|
+
for (const workflow of new Set(jobs.map((entry) => entry.slice(0, entry.indexOf('#'))))) {
|
|
34
|
+
if (!workflows.has(workflow))
|
|
35
|
+
out.push(missingWorkflow('exact-label-jobs', workflow));
|
|
36
|
+
}
|
|
37
|
+
const actual = new Set();
|
|
38
|
+
for (const [workflow, parsed] of workflows) {
|
|
39
|
+
for (const [id, job] of parsed.jobs) {
|
|
40
|
+
if (job.uses === undefined && jobLabels(job).includes(label))
|
|
41
|
+
actual.add(`${workflow}#${id}`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const expected = new Set(jobs);
|
|
45
|
+
const entry = (policyJob, message) => {
|
|
46
|
+
const split = policyJob.indexOf('#');
|
|
47
|
+
const workflow = policyJob.slice(0, split);
|
|
48
|
+
const job = policyJob.slice(split + 1);
|
|
49
|
+
return { policy: 'exact-label-jobs', workflow, job, message };
|
|
50
|
+
};
|
|
51
|
+
for (const job of expected) {
|
|
52
|
+
if (!actual.has(job))
|
|
53
|
+
out.push(entry(job, `expected to run on "${label}" but does not`));
|
|
54
|
+
}
|
|
55
|
+
for (const job of actual) {
|
|
56
|
+
if (!expected.has(job))
|
|
57
|
+
out.push(entry(job, `runs on "${label}" but is not in the exact set`));
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
export function restrictedViolations(rules, workflows) {
|
|
63
|
+
const out = [];
|
|
64
|
+
for (const { label, forbidServices, forbiddenActions } of rules) {
|
|
65
|
+
for (const [workflow, parsed] of workflows) {
|
|
66
|
+
for (const [id, job] of parsed.jobs) {
|
|
67
|
+
const resolved = resolveRunsOn(job);
|
|
68
|
+
if (job.uses !== undefined || resolved.kind !== 'literal' || resolved.label !== label) {
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
const base = { policy: 'restricted-label', workflow, job: id };
|
|
72
|
+
if (forbidServices && hasNonEmptyServices(job)) {
|
|
73
|
+
out.push({ ...base, message: `"${label}" jobs must not declare services` });
|
|
74
|
+
}
|
|
75
|
+
for (const action of stepUses(job)) {
|
|
76
|
+
const matched = forbiddenActions.prefixes.some((prefix) => action.startsWith(prefix)) ||
|
|
77
|
+
forbiddenActions.contains.some((part) => action.includes(part)) ||
|
|
78
|
+
forbiddenActions.exact.includes(action);
|
|
79
|
+
if (matched) {
|
|
80
|
+
out.push({ ...base, message: `"${label}" jobs must not use action "${action}"` });
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/** One workflow file supplied to the evaluator; `path` is relative to the discovery root. */
|
|
2
|
+
export interface WorkflowInput {
|
|
3
|
+
path: string;
|
|
4
|
+
text: string;
|
|
5
|
+
}
|
|
6
|
+
export interface RequiredJob {
|
|
7
|
+
workflow: string;
|
|
8
|
+
job: string;
|
|
9
|
+
runsOn: string;
|
|
10
|
+
}
|
|
11
|
+
export interface ForbiddenActions {
|
|
12
|
+
prefixes: readonly string[];
|
|
13
|
+
contains: readonly string[];
|
|
14
|
+
exact: readonly string[];
|
|
15
|
+
}
|
|
16
|
+
export interface RestrictedLabel {
|
|
17
|
+
label: string;
|
|
18
|
+
forbidServices: boolean;
|
|
19
|
+
forbiddenActions: ForbiddenActions;
|
|
20
|
+
}
|
|
21
|
+
export interface ExactLabelJobs {
|
|
22
|
+
label: string;
|
|
23
|
+
/** `workflow#job` entries. */
|
|
24
|
+
jobs: readonly string[];
|
|
25
|
+
}
|
|
26
|
+
export interface RunnerPolicyConfig {
|
|
27
|
+
allowedLabels: readonly string[];
|
|
28
|
+
requiredJobs: readonly RequiredJob[];
|
|
29
|
+
exactLabelJobs: readonly ExactLabelJobs[];
|
|
30
|
+
restrictedLabels: readonly RestrictedLabel[];
|
|
31
|
+
}
|
|
32
|
+
export type RunnerPolicyName = 'discovery' | 'parse' | 'allowed-labels' | 'reusable-delegate' | 'required-jobs' | 'exact-label-jobs' | 'restricted-label';
|
|
33
|
+
export interface RunnerPolicyViolation {
|
|
34
|
+
policy: RunnerPolicyName;
|
|
35
|
+
workflow?: string;
|
|
36
|
+
job?: string;
|
|
37
|
+
message: string;
|
|
38
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { WorkflowInput } from './types.mts';
|
|
2
|
+
export interface WorkflowJob {
|
|
3
|
+
uses?: unknown;
|
|
4
|
+
'runs-on'?: unknown;
|
|
5
|
+
services?: unknown;
|
|
6
|
+
strategy?: unknown;
|
|
7
|
+
steps?: unknown;
|
|
8
|
+
}
|
|
9
|
+
export interface ParsedWorkflow {
|
|
10
|
+
path: string;
|
|
11
|
+
jobs: Map<string, WorkflowJob>;
|
|
12
|
+
}
|
|
13
|
+
export type ParseResult = {
|
|
14
|
+
ok: true;
|
|
15
|
+
workflow: ParsedWorkflow;
|
|
16
|
+
} | {
|
|
17
|
+
ok: false;
|
|
18
|
+
message: string;
|
|
19
|
+
};
|
|
20
|
+
export declare const isRecord: (value: unknown) => value is Record<string, unknown>;
|
|
21
|
+
export declare function parseWorkflowInput(input: WorkflowInput): ParseResult;
|
|
22
|
+
/** `uses` values of a job's steps; non-string values are ignored. */
|
|
23
|
+
export declare function stepUses(job: WorkflowJob): string[];
|
|
24
|
+
export declare function hasNonEmptyServices(job: WorkflowJob): boolean;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { parse } from 'yaml';
|
|
2
|
+
export const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
3
|
+
export function parseWorkflowInput(input) {
|
|
4
|
+
let document;
|
|
5
|
+
try {
|
|
6
|
+
document = parse(input.text);
|
|
7
|
+
}
|
|
8
|
+
catch (error) {
|
|
9
|
+
return { ok: false, message: `cannot parse YAML: ${error.message.split('\n')[0]}` };
|
|
10
|
+
}
|
|
11
|
+
if (!isRecord(document) || !isRecord(document.jobs)) {
|
|
12
|
+
return { ok: false, message: 'workflow has no jobs mapping' };
|
|
13
|
+
}
|
|
14
|
+
const jobs = new Map();
|
|
15
|
+
for (const [id, job] of Object.entries(document.jobs)) {
|
|
16
|
+
if (!isRecord(job))
|
|
17
|
+
return { ok: false, message: `job "${id}" is not a mapping` };
|
|
18
|
+
jobs.set(id, job);
|
|
19
|
+
}
|
|
20
|
+
return { ok: true, workflow: { path: input.path, jobs } };
|
|
21
|
+
}
|
|
22
|
+
/** `uses` values of a job's steps; non-string values are ignored. */
|
|
23
|
+
export function stepUses(job) {
|
|
24
|
+
if (!Array.isArray(job.steps))
|
|
25
|
+
return [];
|
|
26
|
+
return job.steps.flatMap((step) => isRecord(step) && typeof step.uses === 'string' ? [step.uses] : []);
|
|
27
|
+
}
|
|
28
|
+
export function hasNonEmptyServices(job) {
|
|
29
|
+
const { services } = job;
|
|
30
|
+
if (services === undefined || services === null || services === '')
|
|
31
|
+
return false;
|
|
32
|
+
if (Array.isArray(services))
|
|
33
|
+
return services.length > 0;
|
|
34
|
+
if (isRecord(services))
|
|
35
|
+
return Object.keys(services).length > 0;
|
|
36
|
+
return true;
|
|
37
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vouchington-tooling",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.80.1",
|
|
4
4
|
"description": "Vouchington CLI and extractable tooling libraries.",
|
|
5
5
|
"homepage": "https://github.com/vouchington/vouchington-tooling/tree/main/packages/vouchington-tooling#readme",
|
|
6
6
|
"bugs": {
|
|
@@ -356,6 +356,11 @@
|
|
|
356
356
|
"import": "./dist/tmux/index.mjs",
|
|
357
357
|
"default": "./dist/tmux/index.mjs"
|
|
358
358
|
},
|
|
359
|
+
"./runner-policy": {
|
|
360
|
+
"types": "./dist/runner-policy/index.d.mts",
|
|
361
|
+
"import": "./dist/runner-policy/index.mjs",
|
|
362
|
+
"default": "./dist/runner-policy/index.mjs"
|
|
363
|
+
},
|
|
359
364
|
"./workflow-secrets-drift": {
|
|
360
365
|
"types": "./dist/workflow-secrets-drift/index.d.mts",
|
|
361
366
|
"import": "./dist/workflow-secrets-drift/index.mjs",
|
|
Binary file
|