Files
msd-core/scripts/base64-scan.sh
Tom Boucher 463cffd894 chore(#604): rename get-shit-done/ runtime directory to gsd-core/ (#615)
* chore(#604): rename get-shit-done/ runtime directory to gsd-core/

Renames the installed runtime directory `get-shit-done/` to `gsd-core/` so the
on-disk name matches the package (`@opengsd/gsd-core`), repo, and binary
(`gsd-tools`). The npm package name and binary are unchanged; npx/npm consumers
are unaffected.

Mechanical (bulk, ~90% of the diff):
- `git mv get-shit-done gsd-core`
- Swept path/identifier references across the repo via
  `perl -pe 's/get-shit-done(?!-\w)/gsd-core/g'`. The negative lookahead
  preserves the five legitimate slug variants that are NOT the directory:
  get-shit-done-{OLD,cc,classic,cli,redux} (old package/repo names).
- Build/manifest wiring: package.json (bin, files, coverage globs),
  tsconfig.build.json (outDir), ~86 .gitignore build-output entries,
  stryker.config.mjs, scan-ignore files, install.js path strings.
- Frozen (not rewritten): CHANGELOG.md history; translated docs
  (README.<locale>.md and docs/{ja-JP,ko-KR,pt-BR,zh-CN}/).

New logic (review here):
- src/installer-migrations/003-rename-get-shit-done-to-gsd-core.cts: a proper
  ADR-0008 installer migration. On upgrade it walks the legacy
  `~/.claude/get-shit-done/` tree, classifies each file via the prior install
  manifest, and emits remove-managed / backup-and-remove for managed files
  while PRESERVING unknown user-added files. Symlink-safe (skips a symlinked
  root and symlinked entries; bounds-checks every path under configDir). The
  framework rolls back on install failure. Emptied dirs may remain (framework
  has no recursive dir-removal primitive) — documented.
- scripts/lint-legacy-dir-name.cjs: CI regression guard forbidding the bare
  `get-shit-done` directory token (split token to avoid self-match; case-
  insensitive; `(?!-\w)` lookahead allows the slug variants; allowlists
  CHANGELOG, translated docs, and `gsd-allow-legacy-name` marker lines).
  Wired into the lint-tests CI job.
- Restored scripts/lint-package-identity-drift.cjs detection regexes (the
  mechanical sweep had wrongly rewritten the old-name patterns it exists to
  detect) and marked them as intentional legacy references.
- TDD tests for the migration and the guard; do.md slash-command guard regex
  tightened so a `/gsd-core/bin` path segment is not mistaken for a command;
  changeset + docs/installer-migrations.md row added.

Breaking: the installed runtime path moves `~/.claude/get-shit-done/` ->
`~/.claude/gsd-core/`. Migration 003 removes the stale legacy dir's managed
files (preserving user files) on upgrade. Users with custom hooks/configs
hardcoding the old path must update them.

Closes #604

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#604): unsweep pending changesets + allowlist injection-example docs

CI fixes for the rename PR:
- Do not sweep pending .changeset/*.md (ephemeral release-note fragments,
  like CHANGELOG); reverted those body edits so 5 pre-existing malformed
  fragments (missing type/pr) no longer enter the PR diff and trip docs-lint.
  Allowlisted .changeset/ in the legacy-name guard accordingly.
- Allowlisted TEST-EXAMPLES.md and docs/explanation/security-model.md in
  prompt-injection-scan.sh: they contain intentional injection examples /
  security-model prose; the path-reference rewrites are kept.

CodeQL alerts on this PR are pre-existing (alert lines unchanged by this PR;
none in the new migration/guard) and are out of scope for the rename.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#604): resolve CodeQL alerts surfaced on this PR

The rename diff touched files carrying pre-existing CodeQL findings; per the
no-pre-existing-dismissal rule, fixing every surfaced alert rather than waving
them off. All behavior-preserving:

- scripts/ci-test-scope.cjs: build the config-path match from string
  .includes() instead of a RegExp over an arg-derived value (js/regex-injection).
- src/profile-output.cts: escape backslashes before pipe-escaping desc/safeName
  so the table-cell escape is complete (js/incomplete-sanitization).
- tests/{bug-2643,bug-2808,docs-parity-live-registry}: two-pass HTML-comment
  strip so a bare/unclosed `<!--` cannot survive (js/incomplete-multi-character-sanitization).
- tests/inline-plan-threshold: drop the no-op `\s`->`\s` identity replace,
  keep the meaningful POSIX-class conversion (js/identity-replacement).

Verified: build:lib green; the touched test files + ci-test-scope + profile-output
suites pass; lint:legacy-name clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#604): correctly resolve remaining CodeQL alerts (regex-injection + sanitization)

The prior commit's fixes for two alerts were ineffective:
- ci-test-scope.cjs js/regex-injection: the alert is the CLI-arg-derived `file`
  reaching static regex `.test(file)` calls (not the config rule). Removed ALL
  regex over file/t — startsWith/includes/=== string checks + an isWindowsHint
  helper — so there is no regex sink for the tainted value.
- js/incomplete-multi-character-sanitization (3 test files): a single
  `.replace(/<!--...-->/g,'')` can let `<!--` re-form. Replaced with a fixpoint
  loop (replace until stable) plus a final bare-opener strip.

Verified: no regex over file/t remains; ci-test-scope + the 3 test suites pass;
lint:legacy-name clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#604): make ci-test-scope + comment-strippers regex-free to clear CodeQL

CodeQL flags the regex PATTERNS syntactically (regex-injection on the
--files arg split; incomplete-multi-character-sanitization on the <!--...-->
replace), so loop fixes do not satisfy it. Made these paths regex-free:
- ci-test-scope.cjs splitFiles: char-by-char separator tokenizer (no /[,\\s]+/).
- 3 test files: indexOf/slice HTML-comment stripper (no .replace(/<!--/)).
Behavior preserved; ci-test-scope + the 3 suites pass; guard clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#604): unblock security base64 scan on the large rename diff

The security job hit its 10m timeout: base64-scan.sh choked on the binary
test fixture tests/feat-3594-parser-property-style.test.cjs (embedded NUL/
non-UTF8 bytes -> thousands of bogus blobs + "ignored null byte" warnings),
and the ~800-file rename diff is slow to scan regardless.

- scripts/base64-scan.sh: skip binary-by-content files (grep -Iq .) — they
  can't carry base64-obfuscated *text* and feeding NUL bytes through the
  per-line scanner is pathologically slow. collect_files already filtered
  binary *extensions*; this catches binary *content* in text extensions.
- .github/workflows/security-scan.yml: raise the security job timeout 10m->30m
  to accommodate very large diffs (the scan itself is unchanged).

Verified locally: scan skips the fixture, 0 "ignored null byte" warnings,
0 findings, exit 0.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#604): sweep get-shit-done refs introduced by merging next

The branch was updated with next (#614/#384/#618 etc.), which reference the
get-shit-done/ dir (still named that on next). Swept the stale references in
the merged files to gsd-core so the rename stays consistent and lint:legacy-name
passes:
- commands/gsd/discuss-phase.md (runtime-launcher shim paths)
- src/core.cts (getAgentsDir layout comments)
- tests/bug-384-agents-runtime-aware.test.cjs (require path to runtime lib)

Verified: guard 0 violations; build green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#604): exclude gsd-core/ path segments from bug-3683 command cross-ref invariant

The #614 runtime-launcher shim added to discuss-phase.md references
`${_GSD_RUNTIME_ROOT}/gsd-core/bin/...`. bug-3683's REF_PATTERN excluded path-y
refs only via lookbehind, but `}` precedes `/gsd-core/` in the shim, so it
mis-read the directory path as a dangling `/gsd-core` command ref (same class as
the #604 bug-2954 fix). Added a trailing `(?![\w-]*\/)` so `/gsd-<x>/...` path
segments are not treated as slash-command references.

Verified locally on BOTH platforms before pushing:
- mac (node 26) full suite: 0 failures
- gsd-test-runner (linux, node22 image) full suite: 0 failures
- bug-3683 + bug-2954 pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#604): lazily resolve findProjectRoot in gsd-tools (harden flaky CI)

CI intermittently failed state.test's gsd-tools subprocess with
"findProjectRoot is not a function" (flip-flopping across legs; not reproducible
on mac full suite, gsd-test linux full suite, test:unit, or state.test x8).
findProjectRoot is a re-export from core.cjs (sourced from project-root.cjs);
binding it via destructure at module-load can be undefined under a load-ordering
edge. Resolve it lazily at call time via a small wrapper so the lookup happens
after core.cjs is fully initialized.

Verified green on BOTH platforms before pushing:
- mac (node 26) full suite: 0 failures
- gsd-test-runner (linux, node22) full suite: 0 failures
- state.test.cjs: 106/106; gsd-tools loads cleanly.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#604): allowlist verification-patterns.md placeholder examples in secret scan

The rename git-mv'd references/verification-patterns.md into gsd-core/, pulling
it into the secret-scan diff. It documents stub/placeholder RED-FLAG env-var
examples (illustrative Stripe test-key / database-URL / API-key placeholders) —
not real credentials. Added it to .secretscanignore with the strict annotation,
mirroring the existing gsd-core/workflows/plan-phase.md exception.

Verified locally: secret-scan-lint --strict OK; secret-scan --diff origin/next
exits 0 with 0 findings.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 18:35:29 -04:00

352 lines
12 KiB
Bash
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env bash
# base64-scan.sh — Detect base64-obfuscated prompt injection in source files
#
# Extracts base64 blobs >= 40 chars, decodes them, and checks decoded content
# against the same injection patterns used by prompt-injection-scan.sh.
#
# Usage:
# scripts/base64-scan.sh --diff origin/main # CI mode: scan changed files
# scripts/base64-scan.sh --file path/to/file # Scan a single file
# scripts/base64-scan.sh --dir agents/ # Scan all files in a directory
#
# Exit codes:
# 0 = clean
# 1 = findings detected
# 2 = usage error
set -euo pipefail
# ── Locale hardening (#116) ───────────────────────────────────────────────────
# BSD tr (macOS) treats input bytes as multi-byte characters under any UTF-8
# locale. When the input to `tr -cd '[:print:]'` contains bytes that are not
# valid UTF-8 start sequences (e.g. lone continuation bytes 0x80–0x9F), BSD tr
# emits "Illegal byte sequence" to stderr and exits non-zero. Setting LC_ALL=C
# forces the C locale throughout the script so every byte 0x00–0xFF is a valid
# character — no multi-byte interpretation, no illegal-byte errors.
#
# This is safe for our use-case: all injection patterns are ASCII; base64 -d
# and grep -E POSIX classes ([:space:], [:print:]) behave correctly in C locale.
#
# Source: `man tr` on macOS 26.5 — ENVIRONMENT section states LC_ALL / LC_CTYPE
# control character interpretation; BSD tr rejects invalid multi-byte sequences.
# Empirically verified: `printf '\x80\x81hello' | LC_ALL=C tr -cd '[:print:]'`
# exits 0 and strips the high bytes cleanly.
export LC_ALL=C
MIN_BLOB_LENGTH=40
# Lines longer than this byte count are skipped with a partial-scan warning.
# This prevents `grep -oE` from spending unbounded time on e.g. minified JS or
# single-line binary blobs. 1 MiB is large enough for any realistic text file
# line but small enough to bound blob-extraction cost.
MAX_LINE_BYTES=1048576
# -- Portable timeout wrapper (#116) ------------------------------------------
# macOS does not ship GNU coreutils timeout. We probe for it (or gtimeout
# from homebrew coreutils), falling back to perl alarm(N)+exec.
# Exit codes: GNU timeout uses 124 on timeout; perl SIGALRM produces 142.
# Both are treated as timeout exits by is_timeout_exit() below.
# Usage: run_with_timeout <seconds> <command> [args...]
_TIMEOUT_CMD=""
# shellcheck disable=SC2329 # intentionally defined for use by callers; not called in main loop
_init_timeout_cmd() {
if [[ -n "$_TIMEOUT_CMD" ]]; then return; fi
if command -v timeout >/dev/null 2>&1; then
_TIMEOUT_CMD="timeout"
elif command -v gtimeout >/dev/null 2>&1; then
_TIMEOUT_CMD="gtimeout"
else
_TIMEOUT_CMD="perl_alarm"
fi
}
# shellcheck disable=SC2329 # intentionally defined for use by callers; not called in main loop
run_with_timeout() {
local secs="$1"; shift
_init_timeout_cmd
case "$_TIMEOUT_CMD" in
timeout|gtimeout)
"$_TIMEOUT_CMD" "$secs" "$@"
;;
perl_alarm)
# perl sets SIGALRM after N seconds, then exec()s the command.
# Exit 142 (SIGALRM) when timed out.
perl -e '
my $secs = shift @ARGV;
alarm($secs);
exec(@ARGV) or die "exec: $!\n";
' -- "$secs" "$@"
;;
esac
}
# is_timeout_exit: returns 0 (true) if rc indicates a timeout kill.
# shellcheck disable=SC2329 # intentionally defined for use by callers; not called in main loop
is_timeout_exit() { [[ "$1" -eq 124 || "$1" -eq 142 ]]; }
# ─── Injection Patterns (decoded content) ────────────────────────────────────
# Subset of patterns — if someone base64-encoded something, check for the
# most common injection indicators.
DECODED_PATTERNS=(
'ignore[[:space:]]+(all[[:space:]]+)?previous[[:space:]]+instructions'
'you[[:space:]]+are[[:space:]]+now[[:space:]]+'
'system[[:space:]]+prompt'
'</?system>'
'</?assistant>'
'\[SYSTEM\]'
'\[INST\]'
'<<SYS>>'
'override[[:space:]]+(system|safety|security)'
'pretend[[:space:]]+(you|to)[[:space:]]'
'act[[:space:]]+as[[:space:]]+(a|an|if)'
'jailbreak'
'bypass[[:space:]]+(safety|content|security)'
'eval[[:space:]]*\('
'exec[[:space:]]*\('
'rm[[:space:]]+-rf'
'curl[[:space:]].*\|[[:space:]]*sh'
'wget[[:space:]].*\|[[:space:]]*sh'
)
# ─── Ignorelist ──────────────────────────────────────────────────────────────
IGNOREFILE=".base64scanignore"
IGNORED_PATTERNS=()
load_ignorelist() {
if [[ -f "$IGNOREFILE" ]]; then
while IFS= read -r line; do
# Skip comments and empty lines
[[ "$line" =~ ^[[:space:]]*# ]] && continue
[[ -z "${line// }" ]] && continue
IGNORED_PATTERNS+=("$line")
done < "$IGNOREFILE"
fi
}
is_ignored() {
local blob="$1"
if [[ ${#IGNORED_PATTERNS[@]} -eq 0 ]]; then
return 1
fi
for pattern in "${IGNORED_PATTERNS[@]}"; do
if [[ "$blob" == "$pattern" ]]; then
return 0
fi
done
return 1
}
# ─── Skip Rules ──────────────────────────────────────────────────────────────
should_skip_file() {
local file="$1"
# Skip binary files
case "$file" in
*.png|*.jpg|*.jpeg|*.gif|*.ico|*.woff|*.woff2|*.ttf|*.eot|*.otf) return 0 ;;
*.zip|*.tar|*.gz|*.bz2|*.xz|*.7z) return 0 ;;
*.pdf|*.doc|*.docx|*.xls|*.xlsx) return 0 ;;
esac
# Skip lockfiles and node_modules
case "$file" in
*/node_modules/*) return 0 ;;
*/package-lock.json) return 0 ;;
*/yarn.lock) return 0 ;;
*/pnpm-lock.yaml) return 0 ;;
esac
# Skip the scan scripts themselves and test files
case "$file" in
*/base64-scan.sh) return 0 ;;
*/security-scan.test.cjs) return 0 ;;
esac
# Skip scanner fixture directories — they contain deliberate injection samples
case "$file" in
tests/fixtures/*) return 0 ;;
esac
return 1
}
is_data_uri() {
local context="$1"
# data:image/png;base64,... or data:application/font-woff;base64,...
echo "$context" | grep -qE 'data:[a-zA-Z]+/[a-zA-Z0-9.+-]+;base64,' 2>/dev/null
}
# ─── File Collection ─────────────────────────────────────────────────────────
collect_files() {
local mode="$1"
shift
case "$mode" in
--diff)
local base="${1:-origin/main}"
git diff --name-only --diff-filter=ACMR "$base"...HEAD 2>/dev/null \
| grep -vE '\.(png|jpg|jpeg|gif|ico|woff|woff2|ttf|eot|otf|zip|tar|gz|pdf)$' || true
;;
--file)
if [[ -f "$1" ]]; then
echo "$1"
else
echo "Error: file not found: $1" >&2
exit 2
fi
;;
--dir)
local dir="$1"
if [[ ! -d "$dir" ]]; then
echo "Error: directory not found: $dir" >&2
exit 2
fi
find "$dir" -type f ! -path '*/node_modules/*' ! -path '*/.git/*' ! -path '*/dist/*' \
! -name '*.png' ! -name '*.jpg' ! -name '*.gif' ! -name '*.woff*' 2>/dev/null || true
;;
--stdin)
cat
;;
*)
echo "Usage: $0 --diff [base] | --file <path> | --dir <path> | --stdin" >&2
exit 2
;;
esac
}
# ─── Scanner ─────────────────────────────────────────────────────────────────
extract_and_check_blobs() {
local file="$1"
local found=0
local line_num=0
# Skip binary-by-content files (e.g. adversarial parser fixtures with embedded
# non-UTF8 / NUL bytes). They cannot meaningfully carry base64-obfuscated *text*,
# and feeding NUL bytes through the per-line scanner spawns thousands of bogus
# `base64 -d` subprocesses (the "ignored null byte" warnings) — slow enough to
# blow the job timeout on a large diff. `grep -Iq .` treats a binary file as
# non-matching, so this skips it with a coverage notice (collect_files already
# filters binary *extensions*; this catches binary *content* in text extensions).
if ! LC_ALL=C grep -Iq . "$file" 2>/dev/null; then
echo "SKIP: $file (binary content — base64 text scan not applicable)" >&2
return 0
fi
while IFS= read -r line; do
line_num=$((line_num + 1))
# Guard: skip lines that exceed MAX_LINE_BYTES. Very long lines (e.g. a
# minified JS bundle stored as one line, or a binary file with no newlines)
# would cause `grep -oE` to spend unbounded time. We emit a partial-scan
# warning to stderr so the caller can see coverage was reduced.
if [[ ${#line} -gt $MAX_LINE_BYTES ]]; then
echo "SKIP: $file line $line_num (${#line} bytes > ${MAX_LINE_BYTES} limit — partial scan)" >&2
continue
fi
# Skip data URIs — legitimate base64 usage
if is_data_uri "$line"; then
continue
fi
# Extract base64-like blobs (alphanumeric + / + = padding, >= MIN_BLOB_LENGTH)
local blobs
blobs=$(echo "$line" | grep -oE '[A-Za-z0-9+/]{'"$MIN_BLOB_LENGTH"',}={0,3}' 2>/dev/null || true)
if [[ -z "$blobs" ]]; then
continue
fi
while IFS= read -r blob; do
[[ -z "$blob" ]] && continue
# Check ignorelist
if [[ ${#IGNORED_PATTERNS[@]} -gt 0 ]] && is_ignored "$blob"; then
continue
fi
# Try to decode — if it fails, not valid base64
local decoded
decoded=$(echo "$blob" | base64 -d 2>/dev/null || echo "")
if [[ -z "$decoded" ]]; then
continue
fi
# Check if decoded content is mostly printable text (not random binary)
local total_chars=${#decoded}
if [[ $total_chars -eq 0 ]]; then
continue
fi
# Count printable ASCII characters
local printable_count
printable_count=$(echo -n "$decoded" | tr -cd '[:print:]' | wc -c | tr -d ' ')
# Skip if less than 70% printable (likely binary data, not obfuscated text)
if [[ $((printable_count * 100 / total_chars)) -lt 70 ]]; then
continue
fi
# Scan decoded content against injection patterns
for pattern in "${DECODED_PATTERNS[@]}"; do
if echo "$decoded" | grep -iqE "$pattern" 2>/dev/null; then
if [[ $found -eq 0 ]]; then
echo "FAIL: $file"
found=1
fi
echo " line $line_num: base64 blob decodes to suspicious content"
echo " blob: ${blob:0:60}..."
echo " decoded: ${decoded:0:120}"
echo " matched: $pattern"
break
fi
done
done <<< "$blobs"
done < "$file"
return $found
}
# ─── Main ────────────────────────────────────────────────────────────────────
main() {
if [[ $# -eq 0 ]]; then
echo "Usage: $0 --diff [base] | --file <path> | --dir <path>" >&2
exit 2
fi
load_ignorelist
local mode="$1"
shift
local files
files=$(collect_files "$mode" "$@")
if [[ -z "$files" ]]; then
echo "base64-scan: no files to scan"
exit 0
fi
local total=0
local failed=0
while IFS= read -r file; do
[[ -z "$file" ]] && continue
if should_skip_file "$file"; then
continue
fi
total=$((total + 1))
if ! extract_and_check_blobs "$file"; then
failed=$((failed + 1))
fi
done <<< "$files"
echo ""
echo "base64-scan: scanned $total files, $failed with findings"
if [[ $failed -gt 0 ]]; then
exit 1
fi
exit 0
}
main "$@"