From 1ffc28619213aab196d8123e1b4e2c38eab3878d Mon Sep 17 00:00:00 2001 From: Stuart Clark Date: Sun, 15 Nov 2026 23:01:04 +0000 Subject: [PATCH 01/54] chore: add linters, commit hooks and the private-host check ESLint, Prettier, cspell, markdownlint, knip and commitlint, run by the committed hooks. The private-host check and the attribution check come from the Druxt module template. --- .cspell-project-words.txt | 29 +++++ .cspell.json | 23 ++++ .githooks/commit-msg | 7 ++ .githooks/pre-commit | 9 ++ .gitlab/scripts/check-attribution.sh | 158 ++++++++++++++++++++++++ .gitlab/scripts/install-vale.sh | 134 ++++++++++++++++++++ .gitlab/scripts/lint-prose.sh | 178 +++++++++++++++++++++++++++ .markdownlint-cli2.jsonc | 21 ++++ .prettierignore | 14 +++ .prettierrc.json | 23 ++++ .yamllint | 10 ++ CLAUDE.md | 3 + commitlint.config.mjs | 46 +++++++ eslint.config.mjs | 27 ++++ knip.jsonc | 13 ++ scripts/lint-private-refs.mjs | 178 +++++++++++++++++++++++++++ scripts/postinstall.mjs | 35 ++++++ test/private-refs.test.ts | 92 ++++++++++++++ vitest.config.ts | 22 ++++ 19 files changed, 1022 insertions(+) create mode 100644 .cspell-project-words.txt create mode 100644 .cspell.json create mode 100755 .githooks/commit-msg create mode 100755 .githooks/pre-commit create mode 100755 .gitlab/scripts/check-attribution.sh create mode 100755 .gitlab/scripts/install-vale.sh create mode 100755 .gitlab/scripts/lint-prose.sh create mode 100644 .markdownlint-cli2.jsonc create mode 100644 .prettierignore create mode 100644 .prettierrc.json create mode 100644 .yamllint create mode 100644 CLAUDE.md create mode 100644 commitlint.config.mjs create mode 100644 eslint.config.mjs create mode 100644 knip.jsonc create mode 100644 scripts/lint-private-refs.mjs create mode 100644 scripts/postinstall.mjs create mode 100644 test/private-refs.test.ts create mode 100644 vitest.config.ts diff --git a/.cspell-project-words.txt b/.cspell-project-words.txt new file mode 100644 index 0000000..0aa2846 --- /dev/null +++ b/.cspell-project-words.txt @@ -0,0 +1,29 @@ +# Words this project uses that the standard dictionaries do not carry. +# Add a term here rather than switching the check off for a file. +actionlint +automerge +citty +clack +commitlint +consola +corepack +cspell +DDEV +druxt +Druxt +druxtjs +giget +gitleaks +interruptible +knip +Ksection +Lando +lndo +markdownlint +mise +Nuxt +nuxt +nvmrc +vitest +yamllint +opencode diff --git a/.cspell.json b/.cspell.json new file mode 100644 index 0000000..274dc6a --- /dev/null +++ b/.cspell.json @@ -0,0 +1,23 @@ +{ + "files": ["**/*.{js,mjs,ts,json,jsonc,md,yml,yaml}"], + "dictionaryDefinitions": [ + { + "name": "project-words", + "path": "./.cspell-project-words.txt" + } + ], + "dictionaries": ["project-words", "bash", "misc", "node", "softwareTerms"], + "ignorePaths": [ + ".git/", + "node_modules/", + "**/node_modules/", + "**/dist/", + "coverage/", + "reports/", + "**/CHANGELOG.md", + "package-lock.json", + ".vale/", + "packages/cli/starters/" + ], + "useGitignore": true +} diff --git a/.githooks/commit-msg b/.githooks/commit-msg new file mode 100755 index 0000000..6735462 --- /dev/null +++ b/.githooks/commit-msg @@ -0,0 +1,7 @@ +#!/usr/bin/env sh +# Conventional Commits, checked before the commit exists. +# +# This repository squash-merges, so the merge request or pull request title +# becomes the commit subject too. A prose title breaks the next push to the +# target branch for everyone, not only its author. +exec npx --no -- commitlint --edit "$1" diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100755 index 0000000..36b3ad4 --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,9 @@ +#!/usr/bin/env sh +# The fast half of CI: every linter, the type check, then the unit tests. +# +# The end-to-end test is not here. It downloads a real starter over the +# network, and a hook that needs the network gets bypassed with --no-verify. +set -e +npm run --silent lint +npm run --silent typecheck +npm test --silent diff --git a/.gitlab/scripts/check-attribution.sh b/.gitlab/scripts/check-attribution.sh new file mode 100755 index 0000000..857b430 --- /dev/null +++ b/.gitlab/scripts/check-attribution.sh @@ -0,0 +1,158 @@ +#!/usr/bin/env bash +# Rejects AI authorship claims in commits, the merge request description and +# tracked files. The work is the author's; a tool takes no credit for it. +# +# Usage: check-attribution.sh [--files-only] [] +# +# Commits: the range ..HEAD. Without an argument the base is read from +# ATTRIBUTION_BASE_SHA, then CI_MERGE_REQUEST_DIFF_BASE_SHA, then +# CI_COMMIT_BEFORE_SHA. With none of those only HEAD is read. +# +# Description: MERGE_REQUEST_DESCRIPTION, then CI_MERGE_REQUEST_DESCRIPTION. +# When GITLAB_API_TOKEN, CI_API_V4_URL, CI_PROJECT_ID and CI_MERGE_REQUEST_IID +# are all set the description is fetched instead, because the variable is cut +# at 2700 characters and a footer sits at the end. On a merge request pipeline +# with no description from either source the check refuses: passing over a +# description it never read is not a pass. +# +# Files: every tracked text file, whatever the range. +# +# Exit codes: 0 clean, 1 attribution found, 2 cannot run. +# +# The rejected strings are assembled from fragments below, so this file passes +# its own scan. Keep them that way. + +set -uo pipefail + +files_only=0 +base="" +for arg in "$@"; do + case "$arg" in + --files-only) files_only=1 ;; + -h|--help) sed -n '2,22p' "$0"; exit 0 ;; + *) base="$arg" ;; + esac +done + +if ! git rev-parse --show-toplevel >/dev/null 2>&1; then + echo "[ERROR] not inside a git repository; nothing to check." >&2 + exit 2 +fi + +# Tool names that must not appear as an author, co-author or generator. +tools='claude|anthropic|copilot|chatgpt|openai|gemini|codex|cursor|aider|devin|windsurf|opencode|glm' + +# Each alternative in pieces: the trailer key, the footer, the session link +# and the noreply address are the four shapes seen in practice. +trailer='co-authored'"-by:.*(${tools})" +footer="generated (with|by).*(${tools}|\\bai\\b)" +session='claude-'"session:|claude\\.ai/code/session" +address='noreply'"@anthropic\\.com" +pattern="(${trailer})|(${footer})|(${session})|(${address})" + +failures=0 +report() { + echo "[FAIL] $1" + failures=$((failures + 1)) +} + +# --- commits ----------------------------------------------------------------- + +commits_checked=0 +if [ "$files_only" -eq 0 ]; then + if [ -z "$base" ]; then + base="${ATTRIBUTION_BASE_SHA:-${CI_MERGE_REQUEST_DIFF_BASE_SHA:-}}" + fi + if [ -z "$base" ] && [ -n "${CI_COMMIT_BEFORE_SHA:-}" ] \ + && [ "$CI_COMMIT_BEFORE_SHA" != "0000000000000000000000000000000000000000" ]; then + base="$CI_COMMIT_BEFORE_SHA" + fi + + # An all-zero sha is what GitHub passes as the previous commit of a first + # push, and what GitLab passes as CI_COMMIT_BEFORE_SHA for a new branch. + case "$base" in 0000000000000000000000000000000000000000) base="" ;; esac + + if [ -n "$base" ]; then + if ! git cat-file -e "${base}^{commit}" 2>/dev/null; then + echo "[ERROR] base ${base} is not a commit in this repository." >&2 + exit 2 + fi + shas="$(git rev-list "${base}..HEAD")" + else + shas="$(git rev-parse HEAD)" + fi + + for sha in $shas; do + commits_checked=$((commits_checked + 1)) + short="$(git rev-parse --short "$sha")" + while IFS= read -r line; do + [ -n "$line" ] && report "commit ${short}: ${line}" + done < <(git log -1 --format=%B "$sha" | grep -iE "$pattern" || true) + done +fi + +# --- merge request description ----------------------------------------------- + +description_checked=0 +if [ "$files_only" -eq 0 ]; then + description="" + have_description=0 + + if [ -n "${GITLAB_API_TOKEN:-}" ] && [ -n "${CI_API_V4_URL:-}" ] \ + && [ -n "${CI_PROJECT_ID:-}" ] && [ -n "${CI_MERGE_REQUEST_IID:-}" ]; then + url="${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/merge_requests/${CI_MERGE_REQUEST_IID}" + payload="$(curl -sSf --header "PRIVATE-TOKEN: ${GITLAB_API_TOKEN}" "$url" 2>/dev/null || true)" + if [ -n "$payload" ]; then + if command -v python3 >/dev/null 2>&1; then + description="$(printf '%s' "$payload" | python3 -c 'import json,sys; print(json.load(sys.stdin).get("description") or "")')" + elif command -v node >/dev/null 2>&1; then + description="$(printf '%s' "$payload" | node -e 'let d="";process.stdin.on("data",c=>d+=c).on("end",()=>process.stdout.write(JSON.parse(d).description||""))')" + fi + have_description=1 + fi + fi + + if [ "$have_description" -eq 0 ]; then + if [ -n "${MERGE_REQUEST_DESCRIPTION+x}" ]; then + description="$MERGE_REQUEST_DESCRIPTION" + have_description=1 + elif [ -n "${CI_MERGE_REQUEST_DESCRIPTION+x}" ]; then + description="$CI_MERGE_REQUEST_DESCRIPTION" + have_description=1 + if [ "${#description}" -ge 2700 ]; then + echo "[WARN] CI_MERGE_REQUEST_DESCRIPTION is cut at 2700 characters; set GITLAB_API_TOKEN so the full description is read." >&2 + fi + elif [ -n "${CI_MERGE_REQUEST_IID:-}" ]; then + echo "[ERROR] merge request pipeline, but the description is not available." >&2 + echo " GitLab exposes it as CI_MERGE_REQUEST_DESCRIPTION (16.0 and later); other platforms pass MERGE_REQUEST_DESCRIPTION." >&2 + exit 2 + fi + fi + + if [ "$have_description" -eq 1 ]; then + description_checked=1 + while IFS= read -r line; do + [ -n "$line" ] && report "merge request description: ${line}" + done < <(printf '%s\n' "$description" | grep -iE "$pattern" || true) + fi +fi + +# --- tracked files ----------------------------------------------------------- + +files_checked="$(git ls-files | wc -l | tr -d ' ')" +while IFS= read -r line; do + [ -n "$line" ] && report "$line" +done < <(git grep -nIiE "$pattern" -- . || true) + +# --- verdict ----------------------------------------------------------------- + +scope="${files_checked} tracked files" +if [ "$files_only" -eq 0 ]; then + scope="${commits_checked} commits, $([ "$description_checked" -eq 1 ] && echo 'the merge request description' || echo 'no description'), ${scope}" +fi + +if [ "$failures" -gt 0 ]; then + echo "[FAIL] ${failures} attribution line(s) across ${scope}. The work is the author's; remove the credit." + exit 1 +fi +echo "[PASS] no AI attribution in ${scope}." diff --git a/.gitlab/scripts/install-vale.sh b/.gitlab/scripts/install-vale.sh new file mode 100755 index 0000000..10dd246 --- /dev/null +++ b/.gitlab/scripts/install-vale.sh @@ -0,0 +1,134 @@ +#!/usr/bin/env bash +# Installs a pinned Vale and the ai-tells style package, both checksum-verified. +# +# Usage: install-vale.sh [] +# +# Why not `vale sync`: it fetches whatever the package URL serves and verifies +# nothing. Here the version and its checksum move together, so a bump is a +# reviewed change rather than something that happens inside a job. +# +# Environment: +# VALE_VERSION pinned below. Overriding it requires VALE_SHA256 too, +# because the pinned checksums are for the pinned version. +# VALE_SHA256 expected checksum of the Vale archive for this platform. +# AI_TELLS_VERSION pinned below. Same rule: override both or neither. +# AI_TELLS_SHA256 expected checksum of the style package archive. +# +# Exit codes: 0 installed or already present, 1 checksum mismatch, 2 cannot run. + +set -euo pipefail + +bin_dir="${1:?usage: install-vale.sh []}" +styles_dir="${2:-}" + +pinned_vale="3.17.1" +pinned_ai_tells="1.31.0" +pinned_ai_tells_sha256="bc1267248f13e65928475c439ad7ae1bf806a20d09254c08d7d8c4a9c8b811f0" + +vale_version="${VALE_VERSION:-$pinned_vale}" +ai_tells_version="${AI_TELLS_VERSION:-$pinned_ai_tells}" + +case "$(uname -s)-$(uname -m)" in + Linux-x86_64) + asset="Linux_64-bit" + pinned_vale_sha256="db947f89f2292e6a0381a61de155f6a5f5cb4cb460ca178ea412ef605559cefd" ;; + Linux-aarch64|Linux-arm64) + asset="Linux_arm64" + pinned_vale_sha256="92d91ebf9ee69ec077379be95cd09e6710ab33d3d5bab66bb482e66ebc80dc23" ;; + Darwin-x86_64) + asset="macOS_64-bit" + pinned_vale_sha256="b37ab999dfd1414d041bd2e94ced103292d634da76f954c385bf789dc7f5f939" ;; + Darwin-arm64) + asset="macOS_arm64" + pinned_vale_sha256="80cacf85ef23f53cfdd77355ec41a6ef99aec136f15dfb3517723482f35593f9" ;; + *) + echo "Unsupported platform: $(uname -s) $(uname -m)" >&2 + exit 2 ;; +esac + +if [ "$vale_version" != "$pinned_vale" ] && [ -z "${VALE_SHA256:-}" ]; then + echo "VALE_VERSION=${vale_version} is not the pinned ${pinned_vale}; set VALE_SHA256 for it." >&2 + exit 2 +fi +if [ "$ai_tells_version" != "$pinned_ai_tells" ] && [ -z "${AI_TELLS_SHA256:-}" ]; then + echo "AI_TELLS_VERSION=${ai_tells_version} is not the pinned ${pinned_ai_tells}; set AI_TELLS_SHA256 for it." >&2 + exit 2 +fi +vale_sha256="${VALE_SHA256:-$pinned_vale_sha256}" +ai_tells_sha256="${AI_TELLS_SHA256:-$pinned_ai_tells_sha256}" + +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT + +# `sha256sum` on Linux, `shasum` on macOS. Either way the comparison is +# exact, and a mismatch removes the download so nothing later can run it. +verify() { + local file="$1" expected="$2" actual + if command -v sha256sum >/dev/null 2>&1; then + actual="$(sha256sum "$file" | cut -d' ' -f1)" + else + actual="$(shasum -a 256 "$file" | cut -d' ' -f1)" + fi + if [ "$actual" != "$expected" ]; then + echo "checksum mismatch for $(basename "$file"): expected ${expected}, got ${actual}; refusing to install it." >&2 + rm -f "$file" + return 1 + fi +} + +fetch() { + curl -sSfL --retry 3 -o "$2" "$1" +} + +# --- Vale -------------------------------------------------------------------- + +if [ -x "$bin_dir/vale" ] && "$bin_dir/vale" --version 2>/dev/null | grep -q "$vale_version"; then + echo "vale ${vale_version} already installed in ${bin_dir}" +else + archive="$work/vale.tar.gz" + fetch "https://github.com/errata-ai/vale/releases/download/v${vale_version}/vale_${vale_version}_${asset}.tar.gz" "$archive" + verify "$archive" "$vale_sha256" || exit 1 + tar -xzf "$archive" -C "$work" vale + mkdir -p "$bin_dir" + install -m 0755 "$work/vale" "$bin_dir/vale" + echo "vale ${vale_version} installed in ${bin_dir}" +fi + +# --- ai-tells ---------------------------------------------------------------- + +if [ -z "$styles_dir" ]; then + exit 0 +fi + +marker="$styles_dir/ai-tells/.installed-version" +if [ -f "$marker" ] && [ "$(cat "$marker")" = "$ai_tells_version" ]; then + echo "ai-tells ${ai_tells_version} already installed in ${styles_dir}" + exit 0 +fi + +zip="$work/ai-tells.zip" +fetch "https://github.com/tbhb/vale-ai-tells/releases/download/v${ai_tells_version}/ai-tells.zip" "$zip" +verify "$zip" "$ai_tells_sha256" || exit 1 + +# The package is a zip. Not every image has unzip, and every image that runs +# this has one of the others. +if command -v unzip >/dev/null 2>&1; then + unzip -q -o "$zip" -d "$work/unpacked" +elif command -v python3 >/dev/null 2>&1; then + python3 -m zipfile -e "$zip" "$work/unpacked" +elif command -v bsdtar >/dev/null 2>&1; then + mkdir -p "$work/unpacked" && bsdtar -xf "$zip" -C "$work/unpacked" +else + echo "No unzip, python3 or bsdtar available to unpack the style package." >&2 + exit 2 +fi + +if [ ! -d "$work/unpacked/ai-tells/styles/ai-tells" ]; then + echo "The style package did not contain styles/ai-tells; its layout has changed." >&2 + exit 2 +fi +mkdir -p "$styles_dir" +rm -rf "$styles_dir/ai-tells" +cp -R "$work/unpacked/ai-tells/styles/ai-tells" "$styles_dir/ai-tells" +printf '%s\n' "$ai_tells_version" > "$marker" +echo "ai-tells ${ai_tells_version} installed in ${styles_dir}" diff --git a/.gitlab/scripts/lint-prose.sh b/.gitlab/scripts/lint-prose.sh new file mode 100755 index 0000000..1985c91 --- /dev/null +++ b/.gitlab/scripts/lint-prose.sh @@ -0,0 +1,178 @@ +#!/usr/bin/env bash +# Lints prose with Vale: the markdown a change touches, the commit messages in +# its range, and the merge request description. All three are content someone +# wrote for this repository, and the project voice applies to all of it. +# +# Usage: lint-prose.sh [--all] [] +# +# Markdown: files added or modified in ..HEAD; with --all, every tracked +# markdown file. Without an argument the base is read from PROSE_BASE_SHA, +# then CI_MERGE_REQUEST_DIFF_BASE_SHA, then CI_COMMIT_BEFORE_SHA. With none of +# those the files and message of HEAD alone are read. +# +# Description: MERGE_REQUEST_DESCRIPTION, then CI_MERGE_REQUEST_DESCRIPTION. +# A merge request pipeline with neither is refused, as check-attribution.sh +# does and for the same reason. +# +# Environment: +# VALE_BIN path to vale; PATH otherwise. See install-vale.sh. +# PROSE_LINT_GLOB passed to `vale --glob` for the repository's markdown, +# to keep fixtures and vendored prose out. Never applied +# to commit messages or the description: those are never +# fixtures. +# +# Before any input is read, an em-dash is written to a file outside the tree +# and linted. If that does not fire, the .vale.ini has no section covering the +# generated inputs and the run would pass by linting nothing, so it refuses. +# +# Exit codes: 0 clean, 1 findings, 2 cannot run. + +set -uo pipefail + +all=0 +base="" +for arg in "$@"; do + case "$arg" in + --all) all=1 ;; + -h|--help) sed -n '2,28p' "$0"; exit 0 ;; + *) base="$arg" ;; + esac +done + +root="$(git rev-parse --show-toplevel 2>/dev/null)" || { + echo "[ERROR] not inside a git repository; nothing to lint." >&2 + exit 2 +} + +# VALE_BIN, then PATH, then the repository's own .vale/bin, which is where +# install-vale.sh puts it when a repository installs it for itself. +vale="${VALE_BIN:-$(command -v vale 2>/dev/null || true)}" +if [ -z "$vale" ] && [ -x "$root/.vale/bin/vale" ]; then + vale="$root/.vale/bin/vale" +fi +if [ -z "$vale" ] || [ ! -x "$vale" ]; then + echo "[ERROR] vale is not installed. Run install-vale.sh .vale/bin .vale/styles in the repository root, or put vale on PATH." >&2 + exit 2 +fi + +ini="$root/.vale.ini" +if [ ! -f "$ini" ]; then + echo "[ERROR] no .vale.ini at ${root}; there is no project voice to apply." >&2 + exit 2 +fi + +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT + +# --- canary ------------------------------------------------------------------ + +mkdir -p "$work/canary" +printf 'Canary text %s with a dash.\n' "$(printf '\xe2\x80\x94')" > "$work/canary/canary.md" +canary_out="$(cd "$work/canary" && "$vale" --config "$ini" --output=line canary.md 2>&1)" +canary_rc=$? +if [ "$canary_rc" -eq 0 ] || ! printf '%s' "$canary_out" | grep -q 'canary.md:'; then + echo "[ERROR] canary did not fire: .vale.ini applies no em-dash rule to files outside the tree, so commit messages and the description would be linted by nothing." >&2 + echo " Add a section such as [*.md] with BasedOnStyles = ai-tells. Vale said:" >&2 + printf '%s\n' "$canary_out" | sed 's/^/ /' >&2 + exit 2 +fi + +# --- range ------------------------------------------------------------------- + +if [ -z "$base" ]; then + base="${PROSE_BASE_SHA:-${CI_MERGE_REQUEST_DIFF_BASE_SHA:-}}" +fi +if [ -z "$base" ] && [ -n "${CI_COMMIT_BEFORE_SHA:-}" ] \ + && [ "$CI_COMMIT_BEFORE_SHA" != "0000000000000000000000000000000000000000" ]; then + base="$CI_COMMIT_BEFORE_SHA" +fi +case "$base" in 0000000000000000000000000000000000000000) base="" ;; esac +if [ -n "$base" ] && ! git cat-file -e "${base}^{commit}" 2>/dev/null; then + echo "[ERROR] base ${base} is not a commit in this repository." >&2 + exit 2 +fi + +findings=0 + +# --- commit messages and the description ------------------------------------- + +inputs="$work/inputs" +mkdir -p "$inputs/commits" + +if [ -n "$base" ]; then + shas="$(git rev-list "${base}..HEAD")" +else + shas="$(git rev-parse HEAD)" +fi +commits=0 +for sha in $shas; do + commits=$((commits + 1)) + git log -1 --format=%B "$sha" > "$inputs/commits/$(git rev-parse --short "$sha").md" +done + +description_state="no description" +if [ -n "${MERGE_REQUEST_DESCRIPTION+x}" ]; then + printf '%s\n' "$MERGE_REQUEST_DESCRIPTION" > "$inputs/merge-request.md" + description_state="the merge request description" +elif [ -n "${CI_MERGE_REQUEST_DESCRIPTION+x}" ]; then + printf '%s\n' "$CI_MERGE_REQUEST_DESCRIPTION" > "$inputs/merge-request.md" + description_state="the merge request description" +elif [ -n "${CI_MERGE_REQUEST_IID:-}" ]; then + echo "[ERROR] merge request pipeline, but the description is not available." >&2 + echo " GitLab exposes it as CI_MERGE_REQUEST_DESCRIPTION (16.0 and later); other platforms pass MERGE_REQUEST_DESCRIPTION." >&2 + exit 2 +fi + +generated=() +for f in "$inputs"/commits/*.md "$inputs/merge-request.md"; do + [ -f "$f" ] && generated+=("${f#"$inputs"/}") +done +if [ "${#generated[@]}" -gt 0 ]; then + out="$(cd "$inputs" && "$vale" --config "$ini" --output=line "${generated[@]}" 2>&1)" + rc=$? + if [ -n "$out" ]; then + printf '%s\n' "$out" + fi + if [ "$rc" -ne 0 ]; then + findings=$((findings + 1)) + fi +fi + +# --- the repository's markdown ----------------------------------------------- + +markdown=() +if [ "$all" -eq 1 ]; then + mapfile -d '' -t markdown < <(git -C "$root" ls-files -z -- '*.md') +elif [ -n "$base" ]; then + mapfile -d '' -t markdown < <(git -C "$root" diff -z --name-only --diff-filter=AMR "$base" HEAD -- '*.md') +else + mapfile -d '' -t markdown < <(git -C "$root" diff-tree -z --no-commit-id -r --name-only --diff-filter=AMR HEAD -- '*.md') +fi +existing=() +for f in "${markdown[@]}"; do + [ -f "$root/$f" ] && existing+=("$f") +done + +if [ "${#existing[@]}" -gt 0 ]; then + glob=() + if [ -n "${PROSE_LINT_GLOB:-}" ]; then + glob=(--glob="$PROSE_LINT_GLOB") + fi + out="$(cd "$root" && "$vale" --config "$ini" --output=line "${glob[@]}" "${existing[@]}" 2>&1)" + rc=$? + if [ -n "$out" ]; then + printf '%s\n' "$out" + fi + if [ "$rc" -ne 0 ]; then + findings=$((findings + 1)) + fi +fi + +# --- verdict ----------------------------------------------------------------- + +scope="${commits} commit message(s), ${description_state}, ${#existing[@]} markdown file(s)" +if [ "$findings" -gt 0 ]; then + echo "[FAIL] prose findings across ${scope}." + exit 1 +fi +echo "[PASS] prose clean across ${scope}." diff --git a/.markdownlint-cli2.jsonc b/.markdownlint-cli2.jsonc new file mode 100644 index 0000000..9d5f5eb --- /dev/null +++ b/.markdownlint-cli2.jsonc @@ -0,0 +1,21 @@ +{ + // MD013 (line length) is off: prose reflows, and a hard wrap in Markdown + // shows up as a diff on every edit to the paragraph, not the sentence. + // MD024 is scoped to siblings so a changelog can repeat "Fixed" per release. + // MD041 is off: a changeset starts with front matter, not a heading. + "config": { + "default": true, + "MD013": false, + "MD024": { "siblings_only": true }, + "MD041": false + }, + "ignores": [ + "node_modules/**", + "**/node_modules/**", + "**/dist/**", + "coverage/**", + ".vale/**", + "**/CHANGELOG.md", + ".changeset/**" + ] +} diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..58399a0 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,14 @@ +node_modules/ +dist/ +coverage/ +reports/ +package-lock.json +CHANGELOG.md +.vale/ +packages/cli/starters/ + +# Pipeline definitions are owned by yamllint, not prettier. The two disagree on +# comment spacing, and letting both format these files means each run of one +# undoes the other. +.gitlab-ci.yml +.github/workflows/ diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 0000000..0b5f863 --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,23 @@ +{ + "printWidth": 80, + "semi": false, + "singleQuote": true, + "trailingComma": "es5", + "tabWidth": 2, + "overrides": [ + { + "files": ["*.jsonc", "tsconfig*.json"], + "options": { + "parser": "jsonc", + "trailingComma": "none" + } + }, + { + "files": ["*.md"], + "options": { + "printWidth": 100, + "proseWrap": "preserve" + } + } + ] +} diff --git a/.yamllint b/.yamllint new file mode 100644 index 0000000..cc245ab --- /dev/null +++ b/.yamllint @@ -0,0 +1,10 @@ +--- +extends: default +rules: + # 200, not 80: pipeline scripts carry long commands, and wrapping them makes + # them harder to read rather than easier. + line-length: + max: 200 + level: warning + truthy: + check-keys: false diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..3f07d74 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,3 @@ +# Claude Code + +@AGENTS.md diff --git a/commitlint.config.mjs b/commitlint.config.mjs new file mode 100644 index 0000000..300421c --- /dev/null +++ b/commitlint.config.mjs @@ -0,0 +1,46 @@ +// Conventional Commits, unmodified, plus one project rule. +// +// The type list is deliberately the stock one. A repository-specific vocabulary +// means a contributor who has worked on another Druxt repository guesses wrong, +// and the value of the convention is that it is the same everywhere. +// +// no-ai-attribution: the work is the author's. A co-author trailer naming a +// coding assistant, a generated-with footer or a session link hands ownership +// to a tool. .gitlab/scripts/check-attribution.sh runs the same check over the +// merge request range and every tracked file in CI; this is the local half, +// run by the commit-msg hook. The pattern is assembled from pieces so that this +// file passes its own scan. +const tools = + 'claude|anthropic|copilot|chatgpt|openai|gemini|codex|cursor|aider|devin|windsurf|opencode|glm' +const attribution = new RegExp( + [ + 'co-authored' + `-by:.*(${tools})`, + `generated (with|by).*(${tools}|\\bai\\b)`, + 'claude-' + 'session:', + 'claude\\.ai/code/session', + 'noreply' + '@anthropic\\.com', + ].join('|'), + 'i' +) + +export default { + extends: ['@commitlint/config-conventional'], + plugins: [ + { + rules: { + 'no-ai-attribution': ({ raw }) => { + const hit = raw.match(attribution) + return [ + !hit, + hit + ? `AI attribution is not allowed: "${hit[0].trim()}". The work is the author's.` + : '', + ] + }, + }, + }, + ], + rules: { + 'no-ai-attribution': [2, 'always'], + }, +} diff --git a/eslint.config.mjs b/eslint.config.mjs new file mode 100644 index 0000000..60af4ad --- /dev/null +++ b/eslint.config.mjs @@ -0,0 +1,27 @@ +import js from '@eslint/js' +import prettier from 'eslint-config-prettier' +import globals from 'globals' +import tseslint from 'typescript-eslint' + +export default tseslint.config( + { + ignores: [ + '**/dist/**', + '**/node_modules/**', + 'coverage/**', + 'reports/**', + '.vale/**', + 'packages/cli/starters/**', + ], + }, + js.configs.recommended, + ...tseslint.configs.recommended, + prettier, + { + languageOptions: { + ecmaVersion: 2023, + sourceType: 'module', + globals: globals.node, + }, + } +) diff --git a/knip.jsonc b/knip.jsonc new file mode 100644 index 0000000..2a2c97d --- /dev/null +++ b/knip.jsonc @@ -0,0 +1,13 @@ +{ + "$schema": "https://unpkg.com/knip@6/schema.json", + "workspaces": { + ".": { + "entry": ["scripts/*.mjs", "test/**/*.test.ts"], + "project": ["scripts/**/*.mjs", "test/**/*.ts"] + }, + "packages/*": { + "entry": ["src/index.ts", "src/bin.ts", "test/**/*.test.ts"], + "project": ["src/**/*.ts", "test/**/*.ts"] + } + } +} diff --git a/scripts/lint-private-refs.mjs b/scripts/lint-private-refs.mjs new file mode 100644 index 0000000..a325555 --- /dev/null +++ b/scripts/lint-private-refs.mjs @@ -0,0 +1,178 @@ +/** + * Fail if a tracked file points at a host only the author can reach. + * + * This repository is public, and the starter registry it carries is read by + * every copy of the CLI, so a private URL here reaches everyone who runs it. + * + * The rule is the shape of the host, not a list of known hostnames - + * anything resolvable only inside a LAN. localhost, loopback and the + * DDEV and Lando development domains are how a site runs locally, so + * they are the exceptions. + * + * Known gap: this matches host shape, so it catches `scheme://host/...` + * and scp-style git remotes. It cannot catch an internal project or + * repository name written as prose, which has no shape to match. A + * green run here is not a statement about that class. + */ + +import { execFileSync } from 'node:child_process' +import fs from 'node:fs' +import path from 'node:path' +import { fileURLToPath, pathToFileURL } from 'node:url' + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') + +/** Development hosts that are meant to be here. */ +const ALLOWED = [ + /^localhost$/i, + /^127\./, + /^::1$/, + /\.ddev\.site$/i, + /\.lndo\.site$/i, +] + +/** Hosts nobody outside the author's network can resolve. */ +const PRIVATE_HOST = [ + /^[a-z0-9-]+(\.[a-z0-9-]+)*\.(local|internal|lan|home|corp|intranet)$/i, + /^10\.\d{1,3}\.\d{1,3}\.\d{1,3}$/, + /^192\.168\.\d{1,3}\.\d{1,3}$/, + /^172\.(1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}$/, + /^f[cd][0-9a-f]{2}:/i, + /^fe[89ab][0-9a-f]:/i, +] + +/** + * Scheme, then the authority's host. + * + * Userinfo has to be stepped over rather than captured, because a git + * remote usually carries it - `https://oauth2:TOKEN@host/path` - and + * capturing `oauth2` instead of the host let the whole URL through. + */ +// The bracket class takes dots as well as hex: an IPv4-mapped literal such as +// [::ffff:10.0.0.8] is a bracketed host that carries an RFC1918 address. +const URL_HOST = + /(?:[a-z][a-z0-9+.-]*:\/\/(?:[^/@\s]*@)?|\bgit@)(\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9._-]+)/g + +/** + * The IPv4 address inside an IPv4-mapped IPv6 literal, else the host as given. + * + * A mapped address has four spellings, compressed or expanded, with the last + * 32 bits written as dotted decimal or as two hex groups. Matching the dotted + * spelling alone let `[0:0:0:0:0:ffff:0a00:0008]` name a private endpoint that + * every pattern below then read as a public one. + */ +export function mappedToIpv4(host) { + if (!/^[0-9a-f:.]+$/i.test(host) || !host.includes(':')) return host + + // A trailing dotted quad occupies the last two groups. Rewriting it as hex + // first means the zero-fill below only ever counts groups. + const text = host.replace( + /(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/, + (_, a, b, c, d) => + [((+a << 8) | +b).toString(16), ((+c << 8) | +d).toString(16)].join(':') + ) + + const [head, tail] = text.split('::') + const left = head ? head.split(':') : [] + const right = tail === undefined ? [] : tail ? tail.split(':') : [] + const groups = + tail === undefined + ? left + : left.concat(Array(8 - left.length - right.length).fill('0'), right) + + if (groups.length !== 8 || groups.some((g) => !/^[0-9a-f]{1,4}$/i.test(g))) { + return host + } + const value = groups.map((g) => parseInt(g, 16)) + if (!value.slice(0, 5).every((g) => g === 0) || value[5] !== 0xffff) { + return host + } + return [value[6] >> 8, value[6] & 0xff, value[7] >> 8, value[7] & 0xff].join( + '.' + ) +} + +/** Every private host referenced by `text`, with the line it sits on. */ +export function findPrivateRefs(text) { + const found = [] + text.split('\n').forEach((line, index) => { + for (const match of line.matchAll(URL_HOST)) { + const host = mappedToIpv4( + match[1].replace(/^\[|\]$/g, '').replace(/[.:]+$/, '') + ) + if (ALLOWED.some((pattern) => pattern.test(host))) { + continue + } + if (PRIVATE_HOST.some((pattern) => pattern.test(host))) { + found.push({ line: index + 1, host }) + } + } + }) + return found +} + +/** Tracked files, which is the set that actually gets published. */ +export function trackedFiles(root = ROOT) { + return execFileSync('git', ['-C', root, 'ls-files', '-z'], { + encoding: 'utf8', + }) + .split('\0') + .filter(Boolean) +} + +/** + * The rule's own source and test state private hosts on purpose - the + * patterns here, the examples there. Nothing else gets an exemption: + * an opt-out marker anyone could paste would eventually be pasted over + * a real leak. + */ +const SELF = ['scripts/lint-private-refs.mjs', 'test/private-refs.test.ts'] + +export function lintPrivateRefs(root = ROOT) { + const problems = [] + for (const file of trackedFiles(root)) { + if (SELF.includes(file)) { + continue + } + const absolute = path.join(root, file) + let text + try { + text = fs.readFileSync(absolute, 'utf8') + } catch { + continue + } + if (text.includes('\0')) { + continue + } + for (const hit of findPrivateRefs(text)) { + problems.push(`${file}:${hit.line}: ${hit.host}`) + } + } + return problems +} + +export function main(root = ROOT) { + const problems = lintPrivateRefs(root) + if (problems.length > 0) { + console.error( + [ + '', + 'These tracked files reference a host that only resolves on a private network:', + '', + ...problems.map((problem) => ` ${problem}`), + '', + 'This repository is public. Replace the reference with a public one,', + 'or describe the thing without a URL.', + '', + ].join('\n') + ) + process.exit(1) + } + console.log('No private hosts referenced by tracked files.') +} + +if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) { + // An explicit root keeps the tests honest: they run the real command + // against a throwaway repository rather than this one. + main(process.argv[2] ? path.resolve(process.argv[2]) : ROOT) +} diff --git a/scripts/postinstall.mjs b/scripts/postinstall.mjs new file mode 100644 index 0000000..213e635 --- /dev/null +++ b/scripts/postinstall.mjs @@ -0,0 +1,35 @@ +/** + * Point git at the committed hooks directory. + * + * The hooks live in .githooks/ and are activated with + * `git config core.hooksPath`, which is a per-clone setting rather than + * something the repository carries. Without this step a fresh clone has the + * hooks on disk and none of them running, which is worse than having no hooks + * at all: the repository looks protected and is not. + * + * A committed directory, not husky: it is the same in every Druxt repository, + * including the ones with no package.json, and costs no dependency. + * + * Quiet on failure. A CI install runs this too, and there is nothing to gain + * from failing an install because a hook could not be configured in a + * container that will never make a commit. + */ + +import { execFileSync } from 'node:child_process' + +try { + execFileSync('git', ['rev-parse', '--git-dir'], { stdio: 'ignore' }) +} catch { + // Not a git checkout: a published tarball, or a vendored copy. Nothing to do. + process.exit(0) +} + +try { + execFileSync('git', ['config', 'core.hooksPath', '.githooks'], { + stdio: 'ignore', + }) + console.log('Git hooks enabled from .githooks/') +} catch (error) { + console.warn(`Could not enable git hooks: ${error.message}`) + console.warn('Run `npm run hooks:install` by hand if you intend to commit.') +} diff --git a/test/private-refs.test.ts b/test/private-refs.test.ts new file mode 100644 index 0000000..8be6658 --- /dev/null +++ b/test/private-refs.test.ts @@ -0,0 +1,92 @@ +import { execFileSync } from 'node:child_process' +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterEach, describe, expect, test } from 'vitest' +import { findPrivateRefs } from '../scripts/lint-private-refs.mjs' + +const SCRIPT = fileURLToPath( + new URL('../scripts/lint-private-refs.mjs', import.meta.url) +) + +const hostsIn = (text: string) => findPrivateRefs(text).map((ref) => ref.host) + +// The hosts below are private on purpose. The rule exempts this file by path, +// which is why it can state them plainly. +describe('findPrivateRefs', () => { + test('finds a private host by name', () => { + expect(hostsIn('see http://gitlab.example.local/x')).toEqual([ + 'gitlab.example.local', + ]) + }) + + test('finds RFC1918 addresses', () => { + expect(hostsIn('http://10.0.0.8/ http://192.168.1.1/')).toEqual([ + '10.0.0.8', + '192.168.1.1', + ]) + expect(hostsIn('http://172.16.0.1/')).toEqual(['172.16.0.1']) + }) + + test('finds an RFC1918 address inside an IPv4-mapped IPv6 literal', () => { + expect(hostsIn('https://[::ffff:10.0.0.8]/x')).toEqual(['10.0.0.8']) + expect(hostsIn('https://[::ffff:0a00:0008]/x')).toEqual(['10.0.0.8']) + expect(hostsIn('https://[0:0:0:0:0:ffff:10.0.0.8]/x')).toEqual(['10.0.0.8']) + expect(hostsIn('http://[::ffff:c0a8:0101]/')).toEqual(['192.168.1.1']) + }) + + test('finds a link-local IPv6 address', () => { + expect(hostsIn('http://[fe80::1]/')).toEqual(['fe80::1']) + }) + + test('leaves public hosts alone', () => { + expect(hostsIn('https://druxtjs.org/docs')).toEqual([]) + expect(hostsIn('http://[2001:db8::1]/')).toEqual([]) + expect(hostsIn('http://[::ffff:8.8.8.8]/')).toEqual([]) + }) + + test('leaves the local development hosts alone', () => { + expect(hostsIn('http://localhost:3000/ http://127.0.0.1:8888/')).toEqual([]) + expect(hostsIn('http://[::1]/ https://example.ddev.site/')).toEqual([]) + }) + + test('reads the host, not the userinfo a git remote carries', () => { + expect(hostsIn('https://oauth2:token@gitlab.example.local/a')).toEqual([ + 'gitlab.example.local', + ]) + }) +}) + +describe('the lint:private command', () => { + let repo: string | undefined + + afterEach(() => { + if (repo) rmSync(repo, { recursive: true, force: true }) + }) + + const repoWith = (content: string) => { + repo = mkdtempSync(join(tmpdir(), 'drx-private-')) + execFileSync('git', ['init', '-q', repo]) + writeFileSync(join(repo, 'README.md'), content) + execFileSync('git', ['-C', repo, 'add', 'README.md']) + return repo + } + + const run = (root: string) => { + try { + execFileSync(process.execPath, [SCRIPT, root], { stdio: 'pipe' }) + return 0 + } catch (error) { + return (error as { status: number }).status + } + } + + test('passes a repository with public references only', () => { + expect(run(repoWith('See https://druxtjs.org.\n'))).toBe(0) + }) + + test('fails a repository whose tracked file names a private host', () => { + expect(run(repoWith('See http://gitlab.example.local/x.\n'))).toBe(1) + }) +}) diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 0000000..733ce78 --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,22 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + resolve: { + // create-druxt imports the CLI by its package name. The tests read the + // CLI's sources, so they do not depend on a build having run. + alias: { + '@druxt/cli': fileURLToPath( + new URL('./packages/cli/src/index.ts', import.meta.url) + ), + }, + }, + test: { + include: ['packages/*/test/**/*.test.ts', 'test/**/*.test.ts'], + coverage: { + provider: 'v8', + include: ['packages/*/src/**/*.ts', 'scripts/lint-private-refs.mjs'], + reporter: ['text', 'lcov'], + }, + }, +}) From 8fc88722b7d4cac02538a5ed7e2427f95f9b3c15 Mon Sep 17 00:00:00 2001 From: Stuart Clark Date: Sun, 15 Nov 2026 23:04:10 +0000 Subject: [PATCH 02/54] feat(cli): validate a starter registry entry An entry is giget's own format with a druxt object: the release line, the layout, the parts, what the site requires, the date it was last maintained and whether it is the default. Validation names the first field that is wrong. --- packages/cli/src/errors.ts | 27 +++++ packages/cli/src/layouts.ts | 24 +++++ packages/cli/src/parts.ts | 56 ++++++++++ packages/cli/src/registry/entry.ts | 124 +++++++++++++++++++++++ packages/cli/test/helpers/entry.ts | 35 +++++++ packages/cli/test/registry/entry.test.ts | 112 ++++++++++++++++++++ 6 files changed, 378 insertions(+) create mode 100644 packages/cli/src/errors.ts create mode 100644 packages/cli/src/layouts.ts create mode 100644 packages/cli/src/parts.ts create mode 100644 packages/cli/src/registry/entry.ts create mode 100644 packages/cli/test/helpers/entry.ts create mode 100644 packages/cli/test/registry/entry.test.ts diff --git a/packages/cli/src/errors.ts b/packages/cli/src/errors.ts new file mode 100644 index 0000000..ef3e6ee --- /dev/null +++ b/packages/cli/src/errors.ts @@ -0,0 +1,27 @@ +/** What went wrong, for a caller reading `--json` output. */ +export type DrxErrorCode = + | 'usage' + | 'not-available' + | 'registry' + | 'invalid-entry' + | 'unknown-starter' + | 'unknown-source' + | 'directory-not-empty' + | 'config' + | 'download' + | 'install' + | 'cancelled' + +/** + * A failure the user can act on. Its message is printed as it is, with no + * stack trace, and the process exits non-zero. + */ +export class DrxError extends Error { + readonly code: DrxErrorCode + + constructor(code: DrxErrorCode, message: string) { + super(message) + this.name = 'DrxError' + this.code = code + } +} diff --git a/packages/cli/src/layouts.ts b/packages/cli/src/layouts.ts new file mode 100644 index 0000000..ce61241 --- /dev/null +++ b/packages/cli/src/layouts.ts @@ -0,0 +1,24 @@ +import { DrxError } from './errors.js' + +/** + * How the parts of a site are put together: one repository, a repository per + * part, or a parent repository with each part as a submodule. + */ +export const LAYOUTS = ['monorepo', 'split', 'workspace'] as const +export type Layout = (typeof LAYOUTS)[number] + +/** The layouts `init` can create. */ +export const AVAILABLE_LAYOUTS: readonly Layout[] = ['monorepo'] + +export function isLayout(value: unknown): value is Layout { + return LAYOUTS.includes(value as Layout) +} + +export function assertLayoutAvailable(layout: Layout): void { + if (!AVAILABLE_LAYOUTS.includes(layout)) { + throw new DrxError( + 'not-available', + `The ${layout} layout is not available yet. Use --layout ${AVAILABLE_LAYOUTS.join(' or ')}.` + ) + } +} diff --git a/packages/cli/src/parts.ts b/packages/cli/src/parts.ts new file mode 100644 index 0000000..07fe3d3 --- /dev/null +++ b/packages/cli/src/parts.ts @@ -0,0 +1,56 @@ +export const ROLES = ['frontend', 'backend'] as const +export type Role = (typeof ROLES)[number] + +/** + * One side of a site. The role says what it is for and the kind says what it + * is built with. The kind is a plain string, so a new one needs an adapter + * and no change to this type. + */ +export interface Part { + role: Role + kind: string + /** Relative to the project root, with forward slashes. */ + path: string +} + +export function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +export function isNonEmptyString(value: unknown): value is string { + return typeof value === 'string' && value.trim() !== '' +} + +/** True for a path that stays inside the directory it is resolved against. */ +function isInsidePath(value: unknown): value is string { + if (!isNonEmptyString(value)) return false + if (value.startsWith('/') || /^[a-z]:/i.test(value)) return false + return !value.split(/[\\/]/).includes('..') +} + +/** + * The first problem with a list of parts, as "