diff --git a/.github/workflows/action-test.yml b/.github/workflows/action-test.yml index 0da97e8..f235589 100644 --- a/.github/workflows/action-test.yml +++ b/.github/workflows/action-test.yml @@ -74,6 +74,21 @@ jobs: out: out/real-dark.svg theme: dark + # Un usuario que no existe es un error permanente: falla aunque + # keep-on-error esté activada y haya un SVG previo, que queda intacto. + - name: Preparar un SVG previo para el usuario inexistente + env: + FIXTURE_PATH: ${{ steps.fixture.outputs.path }} + run: cp "$FIXTURE_PATH" out/nouser.svg + + - name: Un usuario inexistente falla con un error claro + id: nouser + continue-on-error: true + uses: ./ + with: + user: commitling-usuario-que-no-existe-0 + out: out/nouser.svg + # keep-on-error (activada por defecto) solo conserva el SVG ante fallos # transitorios (red, 5xx, límite de peticiones), que cubren los tests de # la CLI. Un 401 (token inválido) es permanente: debe fallar aunque haya @@ -120,6 +135,7 @@ jobs: INVALID_OUTCOME: ${{ steps.invalid.outcome }} UNAUTHORIZED_OUTCOME: ${{ steps.unauthorized.outcome }} BADKEEP_OUTCOME: ${{ steps.badkeep.outcome }} + NOUSER_OUTCOME: ${{ steps.nouser.outcome }} OWNER: ${{ github.repository_owner }} run: | set -euo pipefail @@ -130,6 +146,8 @@ jobs: test "$UNAUTHORIZED_OUTCOME" = failure || { echo 'un 401 debería fallar aunque haya SVG previo'; exit 1; } test "$BADKEEP_OUTCOME" = failure || { echo 'keep-on-error: quizas debería fallar'; exit 1; } test ! -e out/badkeep.svg + test "$NOUSER_OUTCOME" = failure || { echo 'un usuario inexistente debería fallar'; exit 1; } + cmp out/nouser.svg "$FIXTURE_PATH" || { echo 'el SVG previo del usuario inexistente cambió'; exit 1; } cmp out/keep.svg "$FIXTURE_PATH" || { echo 'el SVG previo cambió'; exit 1; } for f in "$FIXTURE_PATH" "$MUSHROOM_PATH" "$COMPACT_PATH" "$REAL_PATH"; do test -s "$f" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 62b18c1..c50e2a5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -73,11 +73,38 @@ jobs: run: | go run ./cmd/commitling gallery --out out/site test -s out/site/index.html - ls out/site/svg | wc -l + find out/site/svg -type f | wc -l - name: versión run: go run ./cmd/commitling version + # Every workflow that the web generator and `commitling workflow` can + # produce (the web builds the same bytes; a test compares them) must be + # a valid GitHub Actions workflow that uses @v1: actionlint (official + # binary, pinned SHA-256) also runs shellcheck on its `run:` script. + - name: workflows generados (actionlint) + if: runner.os == 'Linux' + env: + ACTIONLINT_VERSION: "1.7.12" + ACTIONLINT_SHA256: "8aca8db96f1b94770f1b0d72b6dddcb1ebb8123cb3712530b08cc387b349a3d8" + run: | + set -euo pipefail + go build -o "$RUNNER_TEMP/commitling" ./cmd/commitling + mkdir -p out/wf + "$RUNNER_TEMP/commitling" workflow > out/wf/base.yml 2>/dev/null + for sp in moss mushroom; do for th in light dark both; do for sz in full compact; do + "$RUNNER_TEMP/commitling" workflow --user octocat --species "$sp" --theme "$th" --size "$sz" > "out/wf/$sp-$th-$sz.yml" 2>/dev/null + done; done; done + if grep -L 'uses: BertMarti/commitling@v1$' out/wf/*.yml | grep .; then echo "sin @v1"; exit 1; fi + if grep -l 'commitling@main' out/wf/*.yml; then echo "con @main"; exit 1; fi + tgz="actionlint_${ACTIONLINT_VERSION}_linux_amd64.tar.gz" + curl -fsSLo "$RUNNER_TEMP/$tgz" "https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}/$tgz" + echo "${ACTIONLINT_SHA256} $RUNNER_TEMP/$tgz" | sha256sum -c - + tar -xzf "$RUNNER_TEMP/$tgz" -C "$RUNNER_TEMP" actionlint + command -v shellcheck + "$RUNNER_TEMP/actionlint" -color out/wf/*.yml .github/workflows/*.yml + echo "$(find out/wf -name "*.yml" | wc -l) workflows generados válidos" + # Security checks: known vulnerabilities in Go and its standard library # (govulncheck), static analysis (staticcheck, also for the wasm build) and # secrets in the whole history and the working tree (gitleaks, official diff --git a/AGENTS.md b/AGENTS.md index da987d7..1739de2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -62,6 +62,8 @@ Una mascota pixel-art **original** que vive en el README de tu perfil de GitHub. - **Nada de `${{ }}` dentro de un script `run:`** (ni en `action.yml` ni en los workflows): las entradas y contextos llegan por `env:`. Lo vigila `TestNoExpressionsInRunScripts`. - Workflows con `permissions` explícitos (Pages: `{}` arriba y lo justo por job) y `persist-credentials: false` en cada `checkout` (`TestWorkflowsAreLeastPrivilege`). - **CSP de la web** (`` en `index.html.tmpl`): no se admiten ` + diff --git a/internal/gallery/install.js b/internal/gallery/install.js new file mode 100644 index 0000000..f00fdda --- /dev/null +++ b/internal/gallery/install.js @@ -0,0 +1,177 @@ +// Workflow generator of «Instálalo en tu perfil». It builds in the browser, +// with no wasm, no network and no storage, the same text as generate.Install +// (a Go test compares both for every option) and fills the steps with direct +// links to GitHub. No HTML is built from what the person types: only +// textContent and validated logins in href. +(function (root) { + 'use strict'; + + var BaseWorkflow = 'name: commitling\n\n' + + 'on:\n' + + ' schedule:\n' + + ' - cron: "23 5 * * *" # cada día a las 05:23 UTC\n' + + ' workflow_dispatch:\n\n' + + 'permissions:\n' + + ' contents: write\n\n' + + 'jobs:\n' + + ' commitling:\n' + + ' runs-on: ubuntu-latest\n' + + ' steps:\n' + + ' - uses: actions/checkout@v7\n' + + ' - uses: BertMarti/commitling@v1\n' + + ' with:\n' + + ' out: commitling.svg\n' + + ' - name: Guardar la criatura si ha cambiado\n' + + ' run: |\n' + + ' git add commitling.svg\n' + + ' if git diff --cached --quiet; then\n' + + ' echo "Sin cambios."\n' + + ' exit 0\n' + + ' fi\n' + + ' git config user.name "github-actions[bot]"\n' + + ' git config user.email "41898282+github-actions[bot]@users.noreply.github.com"\n' + + ' git commit -m "chore: actualiza commitling"\n' + + ' if ! git push; then\n' + + ' echo "::error title=commitling::No se pudo guardar la criatura en el repositorio. Comprueba que este archivo tiene «permissions: contents: write» y, si la rama está protegida, deja que github-actions[bot] suba cambios."\n' + + ' exit 1\n' + + ' fi\n'; + + var ReadmeSnippet = '![commitling](./commitling.svg)'; + var ReadmePicture = '\n' + + ' \n' + + ' commitling\n' + + ''; + + function validLogin(s) { + return typeof s === 'string' && s.length >= 1 && s.length <= 39 && + s.charAt(0) !== '-' && !/[^A-Za-z0-9-]/.test(s); + } + + function normalizeUser(s) { + s = typeof s === 'string' ? s.trim() : ''; + if (s.charAt(0) === '@') s = s.slice(1); + // A pasted profile link: https://github.com/, with or without the + // scheme, a trailing slash, a path, a query or a fragment. + var match = s.match(/^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/?#]+)(?:[/?#].*)?$/i); + return match ? match[1] : s; + } + + // Only the canonical values of the radios are accepted (as Go checks them + // with SpeciesByName, ThemeByName and SizeByName); anything else is the + // default, so nothing unexpected can reach the YAML. + var ALLOWED = { species: ['moss', 'mushroom'], theme: ['light', 'dark', 'both'], size: ['full', 'compact'] }; + function option(kind, value) { + var v = typeof value === 'string' ? value.trim().toLowerCase() : ''; + return ALLOWED[kind].indexOf(v) >= 0 ? v : ALLOWED[kind][0]; + } + + function build(input) { + input = input || {}; + var user = normalizeUser(input.user); + if (!validLogin(user)) user = ''; + var species = option('species', input.species); + var theme = option('theme', input.theme); + var size = option('size', input.size); + var both = theme === 'both'; + var files = both ? ['commitling.svg', 'commitling-dark.svg'] : ['commitling.svg']; + + function step(stepTheme, out) { + var text = ' - uses: BertMarti/commitling@v1\n with:\n'; + if (user) text += ' user: "' + user + '"\n'; + if (species !== 'moss') text += ' species: mushroom\n'; + if (stepTheme === 'dark') text += ' theme: dark\n'; + if (size === 'compact') text += ' size: compact\n'; + return text + ' out: ' + out + '\n'; + } + + var steps = both ? step('light', files[0]) + step('dark', files[1]) : step(theme, files[0]); + var workflow = BaseWorkflow.replace( + ' - uses: BertMarti/commitling@v1\n with:\n out: commitling.svg\n', steps + ).replace('git add commitling.svg\n', 'git add ' + files.join(' ') + '\n'); + return { workflow: workflow, readme: both ? ReadmePicture : ReadmeSnippet, files: files }; + } + + function links(login) { + var encoded = encodeURIComponent(login); + var repo = 'https://github.com/' + encoded + '/' + encoded; + return { + newRepo: 'https://github.com/new?name=' + encoded + '&visibility=public', + newFile: function (workflow) { + return repo + '/new/main?filename=.github%2Fworkflows%2Fcommitling.yml&value=' + encodeURIComponent(workflow); + }, + actions: repo + '/actions/workflows/commitling.yml', + editReadme: repo + '/edit/main/README.md', + profile: 'https://github.com/' + encoded + }; + } + + root.commitlingInstall = { build: build, normalizeUser: normalizeUser, validLogin: validLogin, links: links }; + + if (typeof document === 'undefined') return; + var form = document.getElementById('ins-form'); + if (!form) return; + form.hidden = false; + // The form only feeds the code blocks: Enter in the user field must not + // send it (that would reload the page with ?user=… in the URL and history). + form.addEventListener('submit', function (e) { e.preventDefault(); }); + var userInput = document.getElementById('ins-user'); + var error = document.getElementById('ins-error'); + var workflowEl = document.getElementById('wf'); + var readmeEl = document.getElementById('rd'); + var repoEl = document.getElementById('ins-repo'); + var linkParagraphs = document.querySelectorAll('.ins-link'); + var noLinks = document.getElementById('ins-nolinks'); + + function checked(name, fallback) { + var radios = document.querySelectorAll('input[name="' + name + '"]'); + for (var i = 0; i < radios.length; i++) if (radios[i].checked) return radios[i].value; + return fallback; + } + + function recalculate() { + var login = normalizeUser(userInput.value); + var valid = login === '' || validLogin(login); + var result = build({ user: valid ? login : '', species: checked('ins-species', 'moss'), theme: checked('ins-theme', 'light'), size: checked('ins-size', 'full') }); + workflowEl.textContent = result.workflow; + readmeEl.textContent = result.readme; + repoEl.textContent = login && valid ? login + '/' + login : 'tu-usuario/tu-usuario'; + if (!valid) { + error.textContent = 'Escribe un usuario de GitHub válido: entre 1 y 39 letras, números o guiones, sin guion inicial.'; + userInput.setAttribute('aria-invalid', 'true'); + } else { + error.textContent = ''; + userInput.removeAttribute('aria-invalid'); + } + var show = valid && login !== ''; + for (var i = 0; i < linkParagraphs.length; i++) linkParagraphs[i].hidden = !show; + noLinks.hidden = show; + if (show) { + var urls = links(login); + document.getElementById('ins-new-repo').setAttribute('href', urls.newRepo); + document.getElementById('ins-new-file').setAttribute('href', urls.newFile(result.workflow)); + document.getElementById('ins-actions').setAttribute('href', urls.actions); + document.getElementById('ins-edit-readme').setAttribute('href', urls.editReadme); + document.getElementById('ins-profile').setAttribute('href', urls.profile); + } + } + + form.addEventListener('input', recalculate); + form.addEventListener('change', recalculate); + recalculate(); + var genForm = document.getElementById('gen-form'); + if (genForm) genForm.addEventListener('submit', function () { + var genUser = document.getElementById('gen-user'); + var login = normalizeUser(genUser && genUser.value); + // Only a valid name is carried over: the generator shows its own error. + if (!userInput.value && validLogin(login)) { + userInput.value = login; + var names = [['species', 'ins-species'], ['theme', 'ins-theme'], ['size', 'ins-size']]; + for (var i = 0; i < names.length; i++) { + var source = document.querySelector('input[name="' + names[i][0] + '"]:checked'); + var target = document.querySelector('input[name="' + names[i][1] + '"][value="' + (source ? source.value : '') + '"]'); + if (target) target.checked = true; + } + recalculate(); + } + }); +})(typeof window !== 'undefined' ? window : this); diff --git a/internal/gallery/install_test.go b/internal/gallery/install_test.go new file mode 100644 index 0000000..e8b8f1d --- /dev/null +++ b/internal/gallery/install_test.go @@ -0,0 +1,124 @@ +package gallery + +import ( + "encoding/json" + "os" + "os/exec" + "regexp" + "runtime" + "strings" + "testing" + + "github.com/BertMarti/commitling/internal/generate" +) + +// The workflow generator of «Instálalo en tu perfil» (install.js) builds in +// the browser, without wasm or network, the same text as generate.Install. +// Its behaviour is proved in Node (testdata/install.test.js); here it is +// compared, byte for byte, with Go for every option. + +func nodeOrSkip(t *testing.T) string { + t.Helper() + if runtime.GOOS == "js" { + t.Skip("cannot start node from a wasm test binary") + } + node, err := exec.LookPath("node") + if err != nil { + if os.Getenv("CI") != "" { + t.Fatal("node is not installed, and the CI must run the install test") + } + t.Skip("node is not installed") + } + return node +} + +func TestInstallBehaviourInNode(t *testing.T) { + node := nodeOrSkip(t) + dir := buildDir(t) + out, err := exec.Command(node, "testdata/install.test.js", dir+string(os.PathSeparator)+"install.js").CombinedOutput() + if err != nil { + t.Fatalf("install.test.js failed: %v\n%s", err, out) + } + if n := strings.Count("\n"+string(out), "\nok "); n < 10 { + t.Errorf("expected at least 10 scenarios, got %d:\n%s", n, out) + } +} + +func TestInstallJSMatchesGo(t *testing.T) { + node := nodeOrSkip(t) + dir := buildDir(t) + out, err := exec.Command(node, "testdata/install.test.js", dir+string(os.PathSeparator)+"install.js", "--dump").Output() + if err != nil { + t.Fatalf("install.test.js --dump failed: %v", err) + } + var cases []struct { + User, Species, Theme, Size string + Workflow, Readme string + Files []string + } + if err := json.Unmarshal(out, &cases); err != nil { + t.Fatalf("--dump is not JSON: %v\n%.300s", err, out) + } + if len(cases) != 4*2*3*2 { + t.Fatalf("%d cases, want 48", len(cases)) + } + for _, c := range cases { + want, err := generate.Install(generate.Options{User: c.User, Species: c.Species, Theme: c.Theme, Size: c.Size}) + if err != nil { + t.Fatalf("%+v: %v", c, err) + } + name := c.User + "/" + c.Species + "/" + c.Theme + "/" + c.Size + if c.Workflow != want.Workflow { + t.Errorf("%s: the workflow of install.js differs from Go:\n%s", name, c.Workflow) + } + if c.Readme != want.Readme || strings.Join(c.Files, " ") != strings.Join(want.Files, " ") { + t.Errorf("%s: readme %q files %v, want %q %v", name, c.Readme, c.Files, want.Readme, want.Files) + } + } +} + +// The section is a real form (hidden until the script runs: without it the +// page shows the base workflow), with the three themes, and the script is +// loaded from a file, touches no network and keeps nothing in storage. +func TestInstallSectionAndScript(t *testing.T) { + dir := buildDir(t) + page := readBuilt(t, dir, "index.html") + for _, want := range []string{ + `