@hivemagnus/hive-devtools 0.0.0-stage → 0.1.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.
@@ -0,0 +1,152 @@
1
+ #!/usr/bin/env bash
2
+ # Blocks private data from entering git history.
3
+ #
4
+ # hive-check-private-data [options] check every tracked file (CI and manual use)
5
+ # hive-check-private-data [options] --staged check files staged for commit (pre-commit hook)
6
+ # hive-check-private-data [options] --message FILE check a commit message (commit-msg hook)
7
+ #
8
+ # Options (repeatable where marked):
9
+ # --root DIR repository to check (default: the git top level of the current directory)
10
+ # --terms-file FILE private-terms denylist (default: <root>/.private-terms; a missing file is skipped)
11
+ # --forbid-dir NAME also forbid any path inside a directory with this name (repeatable)
12
+ # --allow REGEX exempt paths matching this extended regex from the forbidden-path rule (repeatable)
13
+ #
14
+ # Two layers:
15
+ # 1. Forbidden paths: env files, keys, certificates, databases, backups, runtime state and
16
+ # private agent notes (*.local.md) may never be committed.
17
+ # 2. Private terms: an optional, gitignored `.private-terms` file lists one extended regex per
18
+ # line (case-insensitive) for names that must never appear in the repo or in commit
19
+ # messages, such as personal hostnames, private network domains, usernames or private
20
+ # project names. Lines starting with # and blank lines are ignored. The file is local so
21
+ # the denylist itself never becomes public. Findings never print the matching text.
22
+ set -euo pipefail
23
+ shopt -s nocasematch
24
+
25
+ usage() {
26
+ echo 'usage: hive-check-private-data [--root DIR] [--terms-file FILE] [--forbid-dir NAME]... [--allow REGEX]... [--staged | --message FILE]' >&2
27
+ exit 2
28
+ }
29
+
30
+ MODE="tracked"
31
+ MESSAGE_FILE=""
32
+ ROOT_DIR=""
33
+ TERMS_FILE=""
34
+ # Keep this list identical to DEFAULT_FORBIDDEN_DIRS in lib/privacy-policy.mjs (a test checks it).
35
+ FORBIDDEN_DIRS=(certs backups state artifacts .ardent .magnus .cindertrace .hive-dev .ssh audit-logs terminal-audit)
36
+ ALLOWED=('\.env\.example$')
37
+ while [[ "$#" -gt 0 ]]; do
38
+ case "$1" in
39
+ --staged) MODE="staged"; shift ;;
40
+ --message) [[ "$#" -ge 2 ]] || usage; MODE="message"; MESSAGE_FILE="$2"; shift 2 ;;
41
+ --root) [[ "$#" -ge 2 ]] || usage; ROOT_DIR="$2"; shift 2 ;;
42
+ --terms-file) [[ "$#" -ge 2 ]] || usage; TERMS_FILE="$2"; shift 2 ;;
43
+ --forbid-dir)
44
+ [[ "$#" -ge 2 && "$2" =~ ^[A-Za-z0-9._-]{1,64}$ && "$2" != . && "$2" != .. ]] || {
45
+ echo 'private-data check: --forbid-dir needs a plain directory name' >&2; exit 2; }
46
+ FORBIDDEN_DIRS+=("$2"); shift 2 ;;
47
+ --allow) [[ "$#" -ge 2 && -n "$2" ]] || usage; ALLOWED+=("$2"); shift 2 ;;
48
+ *) usage ;;
49
+ esac
50
+ done
51
+
52
+ if [[ -z "$ROOT_DIR" ]]; then
53
+ ROOT_DIR="$(git rev-parse --show-toplevel 2>/dev/null)" || { echo 'private-data check: not inside a git repository; pass --root' >&2; exit 2; }
54
+ fi
55
+ ROOT_DIR="$(cd "$ROOT_DIR" && pwd)"
56
+ if [[ -n "$MESSAGE_FILE" ]]; then
57
+ [[ "$MESSAGE_FILE" = /* ]] || MESSAGE_FILE="$PWD/$MESSAGE_FILE"
58
+ fi
59
+ [[ -n "$TERMS_FILE" ]] || TERMS_FILE="$ROOT_DIR/.private-terms"
60
+ [[ "$TERMS_FILE" = /* ]] || TERMS_FILE="$PWD/$TERMS_FILE"
61
+ cd "$ROOT_DIR"
62
+
63
+ TERMS_PATTERN=""
64
+ if [[ -f "$TERMS_FILE" ]]; then
65
+ TERMS_PATTERN="$(grep -vE '^[[:space:]]*(#|$)' "$TERMS_FILE" | paste -sd '|' - || true)"
66
+ fi
67
+
68
+ if [[ -n "$TERMS_PATTERN" ]]; then
69
+ if grep -qiE -- "$TERMS_PATTERN" </dev/null; then :
70
+ elif [[ "$?" -gt 1 ]]; then
71
+ echo 'private-data check: invalid regular expression in the private-terms file' >&2
72
+ exit 2
73
+ fi
74
+ fi
75
+ for pattern in "${ALLOWED[@]}"; do
76
+ if grep -qE -- "$pattern" </dev/null; then :
77
+ elif [[ "$?" -gt 1 ]]; then
78
+ echo 'private-data check: invalid --allow regular expression' >&2
79
+ exit 2
80
+ fi
81
+ done
82
+
83
+ dirs=""
84
+ for name in "${FORBIDDEN_DIRS[@]}"; do dirs+="${dirs:+|}${name//./\\.}"; done
85
+ FORBIDDEN_PATHS='(^|/)\.env($|\.)|(^|/)\.npmrc$|\.(pem|key|crt|p12|pfx|db|sqlite|sqlite3|bundle)(-(wal|shm|journal))?$|(^|/)('"$dirs"')/|(^|/)[^/]+\.local\.md$|(^|/)\.private-terms$|(^|/)\.vscode/mcp\.json$'
86
+
87
+ failures=0
88
+ fail() {
89
+ printf 'private-data check: %s\n' "$1" >&2
90
+ failures=$((failures + 1))
91
+ }
92
+ # A path that itself contains a private term is never printed.
93
+ shown() {
94
+ if [[ -n "$TERMS_PATTERN" ]] && grep -qiE -- "$TERMS_PATTERN" <<< "$1"; then printf '(path redacted)'; else printf '%s' "$1"; fi
95
+ }
96
+ allowed() {
97
+ local pattern
98
+ for pattern in "${ALLOWED[@]}"; do [[ "$1" =~ $pattern ]] && return 0; done
99
+ return 1
100
+ }
101
+
102
+ if [[ "$MODE" == "message" ]]; then
103
+ [[ -f "$MESSAGE_FILE" ]] || { echo 'private-data check: the commit message file does not exist' >&2; exit 2; }
104
+ if [[ -n "$TERMS_PATTERN" ]] && grep -vE '^#' "$MESSAGE_FILE" | grep -qiE -- "$TERMS_PATTERN"; then
105
+ fail "commit message contains a private term"
106
+ fi
107
+ [[ "$failures" -eq 0 ]] || exit 1
108
+ exit 0
109
+ fi
110
+
111
+ if [[ "$MODE" == "staged" ]]; then
112
+ mapfile -d '' -t files < <(git diff --cached --name-only --diff-filter=ACMR -z)
113
+ else
114
+ mapfile -d '' -t files < <(git ls-files -z)
115
+ fi
116
+
117
+ for file in "${files[@]}"; do
118
+ [[ -n "$file" ]] || continue
119
+ if [[ "$file" =~ $FORBIDDEN_PATHS ]] && ! allowed "$file"; then
120
+ fail "forbidden file: $(shown "$file")"
121
+ fi
122
+ done
123
+
124
+ if [[ -n "$TERMS_PATTERN" && "${#files[@]}" -gt 0 ]]; then
125
+ index_file="$(mktemp)"
126
+ trap 'rm -f "$index_file"' EXIT
127
+ for file in "${files[@]}"; do
128
+ [[ -n "$file" ]] || continue
129
+ if [[ "$MODE" == "staged" ]]; then
130
+ git show ":$file" > "$index_file"
131
+ content_file="$index_file"
132
+ else
133
+ [[ -f "$file" ]] || continue
134
+ content_file="$file"
135
+ fi
136
+ display="$(shown "$file")"
137
+ if matches="$(grep -naiE -- "$TERMS_PATTERN" "$content_file" | cut -d: -f1)"; then
138
+ while IFS= read -r line; do
139
+ fail "private term in $display:$line [redacted]"
140
+ done <<< "$matches"
141
+ fi
142
+ if [[ "$display" != "$file" ]]; then
143
+ fail "private term in a file name: $display"
144
+ fi
145
+ done
146
+ fi
147
+
148
+ if [[ "$failures" -gt 0 ]]; then
149
+ echo "private-data check failed with $failures finding(s). Remove the data, or genericize it (example.com hosts, env vars)." >&2
150
+ exit 1
151
+ fi
152
+ echo "Private data check passed."
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env node
2
+ // hive-check-publish-environment [--environment NAME]
3
+ // Fails unless the GitHub environment (default npm-publish) of GITHUB_REPOSITORY has a required
4
+ // reviewer. Needs GH_TOKEN with actions:read; the token is sent only to the GitHub API.
5
+ import { checkPublishEnvironment } from '../lib/publish.mjs';
6
+
7
+ try {
8
+ const args = process.argv.slice(2);
9
+ let environment = 'npm-publish';
10
+ if (args.length === 2 && args[0] === '--environment') environment = args[1];
11
+ else if (args.length) throw new Error('Usage: hive-check-publish-environment [--environment NAME]');
12
+ await checkPublishEnvironment(process.env, fetch, { environment });
13
+ console.log(`npm publication environment ${environment} requires review.`);
14
+ } catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; }
@@ -0,0 +1,111 @@
1
+ #!/usr/bin/env bash
2
+ # Scan exact staged bytes, immutable outgoing history or build output with the pinned Gitleaks.
3
+ # Never prints secret values.
4
+ #
5
+ # hive-gitleaks [--root DIR] [--config FILE] --staged the exact git index (pre-commit hook)
6
+ # hive-gitleaks [--root DIR] [--config FILE] --history all reachable history (CI)
7
+ # hive-gitleaks [--root DIR] [--config FILE] --pre-push outgoing refs read from stdin (pre-push hook)
8
+ # hive-gitleaks [--root DIR] [--config FILE] --dir PATH... directories such as build output
9
+ #
10
+ # --root defaults to the git top level of the current directory; --config is relative to the root
11
+ # and defaults to .gitleaks.toml. In --staged mode the staged copy of the config is used.
12
+ set -euo pipefail
13
+ version=8.30.1
14
+ usage() {
15
+ echo 'Usage: hive-gitleaks [--root DIR] [--config FILE] --staged|--history|--pre-push|--dir PATH...' >&2
16
+ exit 2
17
+ }
18
+ root=""
19
+ config=".gitleaks.toml"
20
+ mode=""
21
+ directories=()
22
+ while [[ "$#" -gt 0 ]]; do
23
+ case "$1" in
24
+ --root) [[ "$#" -ge 2 ]] || usage; root="$2"; shift 2 ;;
25
+ --config) [[ "$#" -ge 2 ]] || usage; config="$2"; shift 2 ;;
26
+ --staged|--history|--pre-push) [[ -z "$mode" ]] || usage; mode="$1"; shift ;;
27
+ --dir)
28
+ [[ -z "$mode" && "$#" -ge 2 ]] || usage; mode=--dir; shift
29
+ while [[ "$#" -gt 0 && "$1" != --* ]]; do directories+=("$1"); shift; done
30
+ ;;
31
+ *) usage ;;
32
+ esac
33
+ done
34
+ mode="${mode:---staged}"
35
+ if [[ "$config" = /* || "$config" == *..* || -z "$config" ]]; then
36
+ echo 'The Gitleaks config must be a path inside the repository.' >&2
37
+ exit 2
38
+ fi
39
+ if [[ -z "$root" ]]; then
40
+ root="$(git rev-parse --show-toplevel 2>/dev/null)" || { echo 'Not inside a git repository; pass --root.' >&2; exit 2; }
41
+ fi
42
+ root="$(cd "$root" && pwd)"
43
+ binary="${XDG_CACHE_HOME:-$HOME/.cache}/hivemagnus-tools/gitleaks/$version/gitleaks"
44
+ if [[ ! -x "$binary" ]]; then
45
+ binary="$(command -v gitleaks || true)"
46
+ fi
47
+ if [[ -z "$binary" ]] || [[ "$("$binary" version)" != "$version" ]]; then
48
+ echo "Gitleaks $version is required. Run: hive-install-gitleaks (from @hivemagnus/hive-devtools)" >&2
49
+ exit 2
50
+ fi
51
+ cd "$root"
52
+ options=(--gitleaks-ignore-path /dev/null
53
+ --redact=100 --ignore-gitleaks-allow --no-banner --no-color --log-level=warn)
54
+ require_config() {
55
+ [[ -f "$1" ]] || { echo "Gitleaks config $config not found." >&2; exit 2; }
56
+ }
57
+ scan_history() {
58
+ git rev-parse --verify "$1^{commit}" >/dev/null
59
+ "$binary" git --config "$root/$config" "${options[@]}" --log-opts="$2" "$root"
60
+ }
61
+ require_full_history() {
62
+ if [[ "$(git rev-parse --is-shallow-repository)" == true ]]; then
63
+ echo "$1" >&2
64
+ exit 2
65
+ fi
66
+ }
67
+ case "$mode" in
68
+ --staged)
69
+ umask 077
70
+ temporary="$(mktemp -d)"
71
+ trap 'rm -rf "$temporary"' EXIT
72
+ # Export the index, including force-added ignored files. Working-tree edits,
73
+ # untracked files, .gitignore and partial staging cannot hide staged secrets.
74
+ git checkout-index --all --prefix="$temporary/"
75
+ if [[ ! -f "$temporary/$config" ]]; then
76
+ echo "Stage $config before running the staged scan." >&2
77
+ exit 2
78
+ fi
79
+ (cd "$temporary"; "$binary" dir --config "$temporary/$config" "${options[@]}" .)
80
+ ;;
81
+ --history)
82
+ require_config "$root/$config"
83
+ require_full_history 'Full history is required; fetch with depth 0 before scanning.'
84
+ scan_history HEAD HEAD
85
+ ;;
86
+ --pre-push)
87
+ require_config "$root/$config"
88
+ require_full_history 'Full history is required before pushing; fetch with depth 0.'
89
+ while read -r local_ref local_sha remote_ref remote_sha; do
90
+ [[ -n "$local_ref" && -n "$remote_ref" ]] || { echo 'Invalid pre-push input.' >&2; exit 2; }
91
+ [[ "$local_sha" =~ ^[0-9a-f]{40,64}$ && "$remote_sha" =~ ^[0-9a-f]{40,64}$ ]] || exit 2
92
+ [[ "$local_sha" =~ ^0+$ ]] && continue # Ref deletion carries no new content.
93
+ if [[ "$remote_sha" =~ ^0+$ ]]; then
94
+ scan_history "$local_sha" "$local_sha"
95
+ elif git cat-file -e "$remote_sha^{commit}" 2>/dev/null; then
96
+ scan_history "$local_sha" "$remote_sha..$local_sha"
97
+ else
98
+ # Unknown remote base: scan all reachable commits instead of skipping.
99
+ scan_history "$local_sha" "$local_sha"
100
+ fi
101
+ done
102
+ ;;
103
+ --dir)
104
+ require_config "$root/$config"
105
+ [[ "${#directories[@]}" -gt 0 ]] || { echo 'Name at least one directory to scan.' >&2; exit 2; }
106
+ for directory in "${directories[@]}"; do
107
+ [[ -d "$directory" ]] || { echo "Not a directory: $directory" >&2; exit 2; }
108
+ "$binary" dir --config "$root/$config" "${options[@]}" "$directory"
109
+ done
110
+ ;;
111
+ esac
@@ -0,0 +1,44 @@
1
+ #!/usr/bin/env bash
2
+ # Install the reviewed, checksum-verified Gitleaks release into the user cache, without a paid
3
+ # Action or elevated privileges. hive-gitleaks finds it there.
4
+ #
5
+ # hive-install-gitleaks
6
+ set -euo pipefail
7
+ version=8.30.1
8
+ case "$(uname -s)/$(uname -m)" in
9
+ Linux/x86_64) platform=linux_x64; checksum=551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb ;;
10
+ Linux/aarch64|Linux/arm64) platform=linux_arm64; checksum=e4a487ee7ccd7d3a7f7ec08657610aa3606637dab924210b3aee62570fb4b080 ;;
11
+ Darwin/x86_64) platform=darwin_x64; checksum=dfe101a4db2255fc85120ac7f3d25e4342c3c20cf749f2c20a18081af1952709 ;;
12
+ Darwin/arm64) platform=darwin_arm64; checksum=b40ab0ae55c505963e365f271a8d3846efbc170aa17f2607f13df610a9aeb6a5 ;;
13
+ *) echo 'Unsupported platform: install Gitleaks 8.30.1 manually on PATH.' >&2; exit 2 ;;
14
+ esac
15
+ cache="${XDG_CACHE_HOME:-$HOME/.cache}/hivemagnus-tools/gitleaks/$version"
16
+ if [[ -x "$cache/gitleaks" ]] && [[ "$("$cache/gitleaks" version)" == "$version" ]]; then
17
+ echo "Gitleaks $version is installed."
18
+ exit 0
19
+ fi
20
+ umask 077
21
+ temporary="$(mktemp -d)"
22
+ trap 'rm -rf "$temporary"' EXIT
23
+ curl --fail --silent --show-error --location --proto '=https' --tlsv1.2 \
24
+ "https://github.com/gitleaks/gitleaks/releases/download/v$version/gitleaks_${version}_${platform}.tar.gz" \
25
+ --output "$temporary/archive.tar.gz"
26
+ if command -v sha256sum >/dev/null 2>&1; then
27
+ actual="$(sha256sum "$temporary/archive.tar.gz")"
28
+ else
29
+ actual="$(shasum -a 256 "$temporary/archive.tar.gz")"
30
+ fi
31
+ if [[ "${actual%% *}" != "$checksum" ]]; then
32
+ echo 'Gitleaks archive checksum mismatch; refusing installation.' >&2
33
+ exit 2
34
+ fi
35
+ tar -xzf "$temporary/archive.tar.gz" -C "$temporary" gitleaks
36
+ chmod 755 "$temporary/gitleaks"
37
+ [[ "$("$temporary/gitleaks" version)" == "$version" ]]
38
+ mkdir -p "$cache"
39
+ # Move on the destination filesystem so readers never see a partial executable.
40
+ candidate="$(mktemp "$cache/.gitleaks.XXXXXX")"
41
+ cp "$temporary/gitleaks" "$candidate"
42
+ chmod 755 "$candidate"
43
+ mv -f "$candidate" "$cache/gitleaks"
44
+ echo "Installed Gitleaks $version."
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env node
2
+ // hive-publish-package [--root DIR] [--name NAME] [--tag-prefix PREFIX]
3
+ // Publishes the package in --root (default: the current directory) with provenance when its
4
+ // version is not on npm yet. DRY_RUN=true|false is required; a real publication must run from
5
+ // GITHUB_REF refs/tags/<PREFIX><version> (default prefix v) with npm trusted publishing.
6
+ import { resolve } from 'node:path';
7
+ import { publishPackage } from '../lib/publish.mjs';
8
+
9
+ const USAGE = 'Usage: DRY_RUN=true|false hive-publish-package [--root DIR] [--name NAME] [--tag-prefix PREFIX]';
10
+ try {
11
+ const args = process.argv.slice(2);
12
+ const options = { root: process.cwd(), tagPrefix: 'v' };
13
+ for (let index = 0; index < args.length; index += 2) {
14
+ const value = args[index + 1];
15
+ if (value === undefined) throw new Error(USAGE);
16
+ if (args[index] === '--root') options.root = resolve(value);
17
+ else if (args[index] === '--name') options.name = value;
18
+ else if (args[index] === '--tag-prefix') options.tagPrefix = value;
19
+ else throw new Error(USAGE);
20
+ }
21
+ if (!['true', 'false'].includes(process.env.DRY_RUN)) throw new Error('DRY_RUN must be true or false');
22
+ await publishPackage({ ...options, dryRun: process.env.DRY_RUN === 'true', ref: process.env.GITHUB_REF });
23
+ } catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; }
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env node
2
+ // Scans working and staged content for credentials and private infrastructure without
3
+ // printing any matching value.
4
+ //
5
+ // hive-scan-secrets [--staged] [--root DIR] [--secret-name NAME]... [--allow-home-user NAME]... [--exclude GLOB]...
6
+ //
7
+ // Without --staged it scans tracked and untracked, non-ignored files, then the index as well,
8
+ // so a sanitized working copy cannot hide a staged secret from the commit hook.
9
+ import { execFileSync, spawnSync } from 'node:child_process';
10
+ import { existsSync, readFileSync, realpathSync } from 'node:fs';
11
+ import { matchesGlob, resolve } from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
13
+ import { privateInfrastructureFindings, secretFindings } from '../lib/privacy-policy.mjs';
14
+
15
+ const USAGE = 'Usage: hive-scan-secrets [--staged] [--root DIR] [--secret-name NAME]... [--allow-home-user NAME]... [--exclude GLOB]...';
16
+
17
+ export function parseArguments(argv) {
18
+ const options = { staged: false, root: undefined, secretNames: [], homeUsers: [], exclude: [] };
19
+ for (let index = 0; index < argv.length; index++) {
20
+ const argument = argv[index];
21
+ const value = () => {
22
+ const next = argv[++index];
23
+ if (next === undefined || next === '') throw new Error(USAGE);
24
+ return next;
25
+ };
26
+ if (argument === '--staged') options.staged = true;
27
+ else if (argument === '--root') options.root = value();
28
+ else if (argument === '--secret-name') options.secretNames.push(value());
29
+ else if (argument === '--allow-home-user') options.homeUsers.push(value());
30
+ else if (argument === '--exclude') options.exclude.push(value());
31
+ else throw new Error(USAGE);
32
+ }
33
+ return options;
34
+ }
35
+
36
+ export function scan(options) {
37
+ const root = options.root ? resolve(options.root)
38
+ : execFileSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8' }).trim();
39
+ const git = (...args) => execFileSync('git', args, { cwd: root, maxBuffer: 64 * 1024 * 1024 });
40
+ const files = git(...(options.staged ? ['diff', '--cached', '--name-only', '--diff-filter=ACMR', '-z']
41
+ : ['ls-files', '--cached', '--others', '--exclude-standard', '-z'])).toString().split('\0').filter(Boolean);
42
+ let failures = 0;
43
+ for (const file of new Set(files)) {
44
+ // Globs match repository-relative paths (`fixtures/**`, `**/*.snap`).
45
+ if (options.exclude.some(pattern => matchesGlob(file, pattern))) continue;
46
+ // Tracked build output must be checked too; ignore rules exclude untracked build products.
47
+ if (!options.staged && !existsSync(resolve(root, file))) continue;
48
+ const content = (options.staged ? git('show', `:${file}`) : readFileSync(resolve(root, file))).toString();
49
+ for (const finding of [...secretFindings(content, options), ...privateInfrastructureFindings(content, options)]) {
50
+ console.error(`${file}:${finding.line}: ${finding.rule} [redacted]`);
51
+ failures++;
52
+ }
53
+ }
54
+ return { root, failures };
55
+ }
56
+
57
+ function main() {
58
+ const argv = process.argv.slice(2);
59
+ const options = parseArguments(argv);
60
+ const { root, failures } = scan(options);
61
+ let failed = failures > 0;
62
+ if (!options.staged) {
63
+ const result = spawnSync(process.execPath, [fileURLToPath(import.meta.url), ...argv, '--staged', '--root', root],
64
+ { stdio: 'inherit' });
65
+ if (result.status !== 0) failed = true;
66
+ }
67
+ if (failed) process.exitCode = 1;
68
+ else console.log(`Secret scan passed (${options.staged ? 'staged' : 'working'} files).`);
69
+ }
70
+
71
+ if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
72
+ try { main(); } catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 2; }
73
+ }
@@ -0,0 +1,100 @@
1
+ // GitHub Actions run with the workflow's token and secrets, and a tag or branch can be moved
2
+ // after review. Every `uses:` must therefore name an immutable revision:
3
+ // - owner/repo[/path]@<40-hex commit SHA> (actions and reusable workflows)
4
+ // - docker://image@sha256:<64-hex digest>
5
+ // - ./local/path (same repository and commit; exempt)
6
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
7
+ import { join, relative } from 'node:path';
8
+
9
+ const USES_KEY = /^\s*(?:-\s+)?(?:\{\s*)?uses:/;
10
+ const PINNED = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:\/[^@\s]+)?@[0-9a-f]{40}$/;
11
+ const DIGEST = /^docker:\/\/[^@\s]+@sha256:[0-9a-f]{64}$/;
12
+
13
+ /**
14
+ * Splits a `uses:` line into its reference and trailing comment, scanning by hand rather than
15
+ * with one backtracking regex. Returns undefined for a line it does not understand.
16
+ */
17
+ function parseUses(line, key) {
18
+ let rest = line.slice(key.length).trimStart();
19
+ const quote = rest[0] === '"' || rest[0] === "'" ? rest[0] : '';
20
+ if (quote) rest = rest.slice(1);
21
+ const end = rest.search(/[\s"'#,}]/);
22
+ const reference = end === -1 ? rest : rest.slice(0, end);
23
+ let after = end === -1 ? '' : rest.slice(end);
24
+ if (quote) {
25
+ if (!after.startsWith(quote)) return undefined;
26
+ after = after.slice(1);
27
+ }
28
+ after = after.trimStart().replace(/\r$/, '');
29
+ let comment = '';
30
+ if (after.startsWith(',') || after.startsWith('}')) {
31
+ const hash = after.indexOf('#'); // flow mapping: `{ uses: a/b@sha } # v1`
32
+ if (hash !== -1) comment = after.slice(hash);
33
+ } else if (after.startsWith('#')) comment = after;
34
+ else if (after !== '') return undefined;
35
+ return reference ? { reference, comment } : undefined;
36
+ }
37
+
38
+ /**
39
+ * Findings for one workflow or action file. With `requireVersionComment`, a pinned action also
40
+ * needs a trailing comment that names the version it resolves to (`# v4.2.1`, or a tag such
41
+ * as `# hive-devtools-v0.1.0`), so updates
42
+ * can be reviewed.
43
+ */
44
+ export function actionPinFindings(text, { requireVersionComment = false } = {}) {
45
+ const findings = [];
46
+ for (const [index, line] of text.split('\n').entries()) {
47
+ const key = USES_KEY.exec(line);
48
+ if (!key) continue;
49
+ const parsed = parseUses(line, key[0]);
50
+ if (!parsed) {
51
+ // Fail closed on a `uses:` this parser does not understand rather than skipping it.
52
+ findings.push({ line: index + 1, uses: line.trim().slice(0, 120), rule: 'unrecognised uses: syntax' });
53
+ continue;
54
+ }
55
+ const { reference, comment } = parsed;
56
+ if (reference.startsWith('./')) continue;
57
+ if (reference.startsWith('docker://')) {
58
+ if (!DIGEST.test(reference)) findings.push({ line: index + 1, uses: reference, rule: 'container image is not pinned to a sha256 digest' });
59
+ continue;
60
+ }
61
+ if (!PINNED.test(reference)) {
62
+ findings.push({ line: index + 1, uses: reference, rule: 'not pinned to a full commit SHA' });
63
+ } else if (requireVersionComment && !/^#\s*(?:[A-Za-z0-9._-]*-)?v?\d+(?:\.\d+)*/.test(comment)) {
64
+ findings.push({ line: index + 1, uses: reference, rule: 'pinned SHA has no version comment' });
65
+ }
66
+ }
67
+ return findings;
68
+ }
69
+
70
+ function walk(directory, files) {
71
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
72
+ const path = join(directory, entry.name);
73
+ if (entry.isDirectory()) walk(path, files);
74
+ else if (entry.isFile() && /\.ya?ml$/.test(entry.name)) files.push(path);
75
+ }
76
+ }
77
+
78
+ /** Workflow and action files of a repository: .github/workflows, .github/actions and a root action.yml. */
79
+ export function workflowFiles(root, paths = ['.github/workflows', '.github/actions', 'action.yml', 'action.yaml']) {
80
+ const files = [];
81
+ for (const path of paths) {
82
+ const full = join(root, path);
83
+ if (!existsSync(full)) continue;
84
+ if (statSync(full).isDirectory()) walk(full, files);
85
+ else files.push(full);
86
+ }
87
+ return files.sort();
88
+ }
89
+
90
+ /** Checks every workflow file under `root` and returns `file:line` findings. */
91
+ export function checkActionPins(root, options = {}) {
92
+ const findings = [];
93
+ const files = workflowFiles(root, options.paths);
94
+ for (const file of files) {
95
+ for (const finding of actionPinFindings(readFileSync(file, 'utf8'), options)) {
96
+ findings.push({ file: relative(root, file), ...finding });
97
+ }
98
+ }
99
+ return { files: files.length, findings };
100
+ }
@@ -0,0 +1,74 @@
1
+ #!/usr/bin/env node
2
+ // Dependency-free Node.js runtime preflight. This file imports only Node built-ins so it can
3
+ // also be streamed to a host before any deployment writes:
4
+ //
5
+ // ssh host 'node --input-type=module - --engines "^24.22.3 || ^26.13.1"' < lib/node-runtime.mjs
6
+ //
7
+ // hive-check-node-runtime [--package FILE] fail unless this Node satisfies the package's engines.node
8
+ // hive-check-node-runtime --engines RANGE fail unless this Node satisfies RANGE
9
+ // hive-check-node-runtime --print-range [--package FILE]
10
+ //
11
+ // Only `^X.Y.Z || ^X.Y.Z` ranges are accepted: each names a supported major and its patch floor.
12
+ import { readFileSync, realpathSync } from 'node:fs';
13
+ import { resolve } from 'node:path';
14
+ import { fileURLToPath } from 'node:url';
15
+
16
+ export function assertNodeVersion(version, range) {
17
+ const actual = /^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(version);
18
+ if (!actual || typeof range !== 'string') throw Error('A stable Node.js version and package engines range are required');
19
+ const allowed = range.split('||').map(part => {
20
+ const match = /^\^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(part.trim());
21
+ if (!match || Number(match[1]) < 1) throw Error('Unsupported package Node.js engines range');
22
+ return match.slice(1).map(Number);
23
+ });
24
+ const current = actual.slice(1).map(Number);
25
+ if (![...current, ...allowed.flat()].every(Number.isSafeInteger)) throw Error('Invalid Node.js version');
26
+ if (!allowed.some(minimum => current[0] === minimum[0] &&
27
+ (current[1] > minimum[1] || current[1] === minimum[1] && current[2] >= minimum[2]))) {
28
+ throw Error(`Node.js ${range} is required; found ${version}`);
29
+ }
30
+ }
31
+
32
+ /** Reads and validates engines.node from a package.json (default: ./package.json). */
33
+ export function packageNodeRange(file = resolve(process.cwd(), 'package.json')) {
34
+ const range = JSON.parse(readFileSync(file, 'utf8')).engines?.node;
35
+ // Validate syntax before the value is used in a remote shell argument.
36
+ if (typeof range !== 'string' || range !== range.trim() || range.length > 200 || !/^\^\d+\.\d+\.\d+(?: *\|\| *\^\d+\.\d+\.\d+)*$/.test(range)) {
37
+ throw Error('Package must declare a bounded Node.js engines range');
38
+ }
39
+ return range;
40
+ }
41
+
42
+ export function runNodeRuntimeCheck(args, version = process.versions.node) {
43
+ let packageFile;
44
+ let engines;
45
+ let print = false;
46
+ for (let index = 0; index < args.length; index++) {
47
+ const next = () => {
48
+ const value = args[++index];
49
+ if (value === undefined || value === '') throw Error('Use --print-range, --engines RANGE or --package FILE');
50
+ return value;
51
+ };
52
+ if (args[index] === '--print-range') print = true;
53
+ else if (args[index] === '--package') packageFile = resolve(next());
54
+ else if (args[index] === '--engines') engines = next();
55
+ else throw Error('Use --print-range, --engines RANGE or --package FILE');
56
+ }
57
+ if (print && engines !== undefined) throw Error('--print-range and --engines cannot be combined');
58
+ if (print) return packageNodeRange(packageFile);
59
+ assertNodeVersion(version, engines ?? packageNodeRange(packageFile));
60
+ return undefined;
61
+ }
62
+
63
+ export function isMain(url, argv1 = process.argv[1]) {
64
+ if (argv1 === '-') return true; // streamed on stdin
65
+ if (!argv1) return false;
66
+ try { return realpathSync(argv1) === fileURLToPath(url); } catch { return false; }
67
+ }
68
+
69
+ if (isMain(import.meta.url)) {
70
+ try {
71
+ const range = runNodeRuntimeCheck(process.argv.slice(2));
72
+ if (range !== undefined) console.log(range);
73
+ } catch (error) { console.error(error.message); process.exitCode = 1; }
74
+ }