diff --git a/.claude/skills/publicar-version/SKILL.md b/.claude/skills/publicar-version/SKILL.md index 2160545..a529866 100644 --- a/.claude/skills/publicar-version/SKILL.md +++ b/.claude/skills/publicar-version/SKILL.md @@ -12,5 +12,6 @@ Las etiquetas (`vX.Y.Z`), las releases y mover la etiqueta móvil `v1` las hace 3. **CHANGELOG.md**: mueve lo de «Sin publicar» a `## [X.Y.Z] - AAAA-MM-DD` con Añadido / Cambiado / Corregido en español y actualiza los enlaces de comparación del final (`[Sin publicar]` → `vX.Y.Z...HEAD` y una línea `[X.Y.Z]`). 4. **Docs**: README (solo lo de usuario), `docs/USO.md`, `docs/DESARROLLO.md`, `AGENTS.md` si cambian reglas, `MEMORY.md` (estado, decisiones con fecha, registro de sesiones) y `PLAN.md`. 5. **Cabecera del README** (solo si cambian los sprites): genera la galería (`go run ./cmd/commitling gallery --out out/site`) y rehaz `docs/img/banner.svg` copiando el grupo `` de `svg/{seed,sprout,sapling,shrub}-happy.svg` y `svg/ancient-radiant.svg`, cada uno dentro de `` (la animación va en el grupo interior, nunca en el que lleva `transform`, o la animación CSS lo anula). -6. **Comprueba**: `gofmt -l .`, `go vet ./...`, `GOFLAGS=-p=2 go test ./...`, el subagente `guardian-compatibilidad` y, si tocaste la web, la skill `probar-web`. -7. **Notas para Alberto** en el PR: «tras fusionar: release `vX.Y.Z` con las notas del CHANGELOG y, si es compatible, mover `v1` a ella». +6. **Binario precompilado (opcional)**: si quieres que la Action descargue el binario en vez de compilar, el último commit antes de la etiqueta debe incluir `release/checksums.txt` (`scripts/build-release.sh out/rel --write`, con la versión de Go de `go.mod`). El workflow `release.yml` sube los binarios al publicar la release. Si no lo haces, no pasa nada: la Action compila como siempre. Si vuelves a tocar código después, regenéralo o el CI fallará. +7. **Comprueba**: `gofmt -l .`, `go vet ./...`, `GOFLAGS=-p=2 go test ./...`, el subagente `guardian-compatibilidad` y, si tocaste la web, la skill `probar-web`. +8. **Notas para Alberto** en el PR: «tras fusionar: release `vX.Y.Z` con las notas del CHANGELOG y, si es compatible, mover `v1` a ella». diff --git a/.github/workflows/action-test.yml b/.github/workflows/action-test.yml index f235589..d3a4581 100644 --- a/.github/workflows/action-test.yml +++ b/.github/workflows/action-test.yml @@ -17,7 +17,7 @@ jobs: action: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false @@ -38,6 +38,15 @@ jobs: species: mushroom out: out/mushroom.svg + - name: Action con la especie cactus (sin red) + id: cactus + uses: ./ + with: + user: "" + fixture: testdata/events.json + species: cactus + out: out/cactus.svg + - name: Action con la tarjeta compacta (sin red) id: compact uses: ./ @@ -129,6 +138,7 @@ jobs: env: FIXTURE_PATH: ${{ steps.fixture.outputs.path }} MUSHROOM_PATH: ${{ steps.mushroom.outputs.path }} + CACTUS_PATH: ${{ steps.cactus.outputs.path }} COMPACT_PATH: ${{ steps.compact.outputs.path }} BADSIZE_OUTCOME: ${{ steps.badsize.outcome }} REAL_PATH: ${{ steps.real.outputs.path }} @@ -149,7 +159,7 @@ jobs: 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 + for f in "$FIXTURE_PATH" "$MUSHROOM_PATH" "$CACTUS_PATH" "$COMPACT_PATH" "$REAL_PATH"; do test -s "$f" head -c 120 "$f"; echo grep -q '' "$f" @@ -160,5 +170,85 @@ jobs: grep -q 'Retoño' "$FIXTURE_PATH" grep -q 'Seta' "$MUSHROOM_PATH" if grep -q 'Retoño' "$MUSHROOM_PATH"; then echo 'la especie hongo no se aplicó'; exit 1; fi + grep -q 'Cactus' "$CACTUS_PATH" + if grep -q 'Retoño' "$CACTUS_PATH"; then echo 'la especie cactus no se aplicó'; exit 1; fi grep -q "@$OWNER" "$REAL_PATH" grep -q '#2b2724' "$REAL_PATH" + + # The precompiled binary path of the Action (release/checksums.txt plus a + # release download), tested against a local server that plays the role of + # the release: a binary that matches is used without compiling; a tampered + # one or a missing release fall back to go run with the same SVG. + binario: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: go.mod + cache: false + + - name: Binarios reproducibles y release falsa en 127.0.0.1 + run: | + set -euo pipefail + scripts/build-release.sh "$RUNNER_TEMP/rel" + version="$(sed -n 's/^var version = "\(.*\)"$/\1/p' cmd/commitling/main.go)" + mkdir -p release "$RUNNER_TEMP/www/v$version" + cp "$RUNNER_TEMP/rel/checksums.txt" release/checksums.txt + cp "$RUNNER_TEMP"/rel/commitling_* "$RUNNER_TEMP/www/v$version/" + nohup python3 -m http.server 8765 --bind 127.0.0.1 --directory "$RUNNER_TEMP/www" > "$RUNNER_TEMP/http.log" 2>&1 & + for _ in $(seq 1 20); do curl -fsS -o /dev/null http://127.0.0.1:8765/ && break; sleep 0.5; done + echo "COMMITLING_RELEASE_URL=http://127.0.0.1:8765" >> "$GITHUB_ENV" + echo "CL_VERSION=$version" >> "$GITHUB_ENV" + go run ./cmd/commitling render --fixture testdata/events.json --species cactus --out out/expected.svg + + - name: Action con el binario precompilado + id: prebuilt + uses: ./ + with: + user: "" + fixture: testdata/events.json + species: cactus + out: out/prebuilt.svg + + - name: Se usó el binario y el SVG es el mismo + run: | + set -euo pipefail + test -x "$RUNNER_TEMP/commitling-bin/commitling_${CL_VERSION}_linux_amd64" + grep -q "GET /v${CL_VERSION}/commitling_${CL_VERSION}_linux_amd64 " "$RUNNER_TEMP/http.log" + cmp out/prebuilt.svg out/expected.svg + + - name: Binario manipulado en la release + run: | + set -euo pipefail + rm -rf "$RUNNER_TEMP/commitling-bin" + printf '#!/bin/sh\necho manipulado\n' > "$RUNNER_TEMP/www/v${CL_VERSION}/commitling_${CL_VERSION}_linux_amd64" + + - name: Action con el binario manipulado (se descarta) + uses: ./ + with: + user: "" + fixture: testdata/events.json + species: cactus + out: out/tampered.svg + + - name: Sin release publicada + run: echo "COMMITLING_RELEASE_URL=http://127.0.0.1:8765/no-existe" >> "$GITHUB_ENV" + + - name: Action sin release (compila con Go) + uses: ./ + with: + user: "" + fixture: testdata/events.json + species: cactus + out: out/norelease.svg + + - name: Comprobar las alternativas + run: | + set -euo pipefail + test ! -e "$RUNNER_TEMP/commitling-bin/commitling_${CL_VERSION}_linux_amd64" || { echo 'el binario manipulado no se borró'; exit 1; } + cmp out/tampered.svg out/expected.svg + cmp out/norelease.svg out/expected.svg diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c50e2a5..4b0cfa9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,11 +24,11 @@ jobs: run: shell: bash steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: actions/setup-go@v7 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: go-version-file: go.mod cache: false @@ -78,6 +78,23 @@ jobs: - name: versión run: go run ./cmd/commitling version + # The Action trusts release/checksums.txt: if it is committed, it must + # still be what this tree compiles to (reproducible build), or the + # Action would refuse the release binaries. + - name: binarios de release reproducibles + if: runner.os == 'Linux' + run: | + if [ -f release/checksums.txt ]; then + scripts/build-release.sh out/rel --check + else + scripts/build-release.sh out/rel + echo "Sin release/checksums.txt: la Action compila con go run (los SHA-256 de arriba son los de este commit)." + fi + # The environment cannot change the bytes (build-release.sh resets + # GOFLAGS and GOEXPERIMENT; -tags would be recorded in the binary). + GOFLAGS=-tags=zzz scripts/build-release.sh out/rel-env + diff -u out/rel/checksums.txt out/rel-env/checksums.txt + # 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 @@ -92,7 +109,7 @@ jobs: 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 + for sp in moss mushroom cactus; 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 @@ -118,12 +135,12 @@ jobs: GOVULNCHECK_VERSION: "v1.9.0" STATICCHECK_VERSION: "2026.2.2" steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 persist-credentials: false - - uses: actions/setup-go@v7 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: go-version-file: go.mod cache: false diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 63fe969..59f3a38 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -23,11 +23,11 @@ jobs: permissions: contents: read steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: actions/setup-go@v7 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: go-version-file: go.mod cache: false @@ -63,7 +63,7 @@ jobs: "$cl" render --fixture testdata/events.json --theme dark --out "site/live/$LIVE_USER-dark.svg" fi - - uses: actions/upload-pages-artifact@v5 + - uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0 with: path: site @@ -78,4 +78,4 @@ jobs: url: ${{ steps.deployment.outputs.page_url }} steps: - id: deployment - uses: actions/deploy-pages@v5 + uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..3541e7d --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,71 @@ +name: Release + +# Uploads the precompiled binaries to a release when it is published. It only +# runs then (nothing here creates releases or moves tags). The binaries are +# rebuilt from the tag with scripts/build-release.sh and must match the +# release/checksums.txt committed in that tag: that file is what the Action +# trusts. Without it, nothing is uploaded and the Action keeps compiling with +# go run. +on: + release: + types: [published] + +permissions: {} + +concurrency: + group: release-${{ github.event.release.tag_name }} + cancel-in-progress: false + +jobs: + binaries: + name: binarios + runs-on: ubuntu-latest + permissions: + contents: write + env: + TAG: ${{ github.event.release.tag_name }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.event.release.tag_name }} + persist-credentials: false + + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: go.mod + cache: false + + - name: Comprobar la versión y release/checksums.txt + id: check + run: | + set -euo pipefail + version="$(sed -n 's/^var version = "\(.*\)"$/\1/p' cmd/commitling/main.go)" + if [ "$TAG" != "v$version" ]; then + echo "::error::La etiqueta $TAG no coincide con la versión de la CLI (v$version)." + exit 1 + fi + if [ ! -f release/checksums.txt ]; then + echo "::warning::$TAG no tiene release/checksums.txt: no se suben binarios y la Action seguirá compilando con go run." + echo "upload=false" >> "$GITHUB_OUTPUT" + exit 0 + fi + echo "upload=true" >> "$GITHUB_OUTPUT" + + - name: Compilar y verificar los binarios + if: steps.check.outputs.upload == 'true' + run: scripts/build-release.sh "$RUNNER_TEMP/dist" --check + + - name: Subir los binarios a la release + if: steps.check.outputs.upload == 'true' + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + run: | + set -euo pipefail + gh release upload "$TAG" "$RUNNER_TEMP"/dist/commitling_* "$RUNNER_TEMP/dist/checksums.txt" --clobber + { + echo "### Binarios de $TAG" + echo '```' + cat "$RUNNER_TEMP/dist/checksums.txt" + echo '```' + } >> "$GITHUB_STEP_SUMMARY" diff --git a/AGENTS.md b/AGENTS.md index 1739de2..30943ec 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -53,7 +53,7 @@ Una mascota pixel-art **original** que vive en el README de tu perfil de GitHub. - **Lo que entra en el wasm no puede importar `encoding/json`, `fmt`, `reflect`, `regexp`, `net/http`, `os` ni plantillas** (`TestWasmPackagesAvoidHeavyImports` lee los imports de `events`, `generate`, `render`, `stats`, `creature` y `cmd/wasm`; el CI falla si el wasm pasa de 3 MB). Texto: `strconv` y concatenación; errores: `errors.New`; eventos: `internal/events/scan.go` (lector a mano que sigue a `encoding/json`; `scan_test.go` lo compara con él, y ahí sí se puede importar `encoding/json`). `Event.Payload` es `[]byte`. CLI, galería y cliente HTTP (`internal/github`, `gallery`, `og`) pueden usar lo que quieran: no entran en el wasm. - Medir antes de optimizar: `go tool nm` no lee wasm; el desglose por paquete sale de leer las secciones de código y de nombres de un wasm sin recortar (ver `docs/specs/v0.7.md`). Pesos (Go 1.27, `-trimpath -ldflags="-s -w"`): 4.624.571 B (1.261.906 gzip) en v0.6.0 y 2.569.892 B (735.538 gzip) en v0.7.0; el resto es el `runtime` de Go. - Cualquier reescritura que toque `render` o `generate` se comprueba con las huellas (`testdata/golden/full-sha256.txt`: 96 tarjetas de v0.5.0 y `favicon.svg`) y comparando la galería entera y la CLI con las de `main` (`diff -r`). -- Generador y límite de la API: `generator.js` valida el login con la regla de `events.ValidLogin` (un test compara la regexp de JS con la función de Go), cachea los eventos 10 min en `sessionStorage` (`commitling:events:`; todo con `try/catch`; no hay más almacenamiento, ni `localStorage` ni cookies) y, con un 403 o 429, enseña `generate.FetchError` (hora local de `X-RateLimit-Reset`) y el botón «Ver demo» (`#gen-demo-alt`). +- Generador y límite de la API: `generator.js` valida el login con la regla de `events.ValidLogin` (un test compara la regexp de JS con la función de Go), cachea los eventos 10 min en `sessionStorage` (`commitling:events:`; todo con `try/catch`; sin cookies; el único `localStorage` es `commitling:theme` de `theme.js`) y, con un 403 o 429, enseña `generate.FetchError` (hora local de `X-RateLimit-Reset`) y el botón «Ver demo» (`#gen-demo-alt`). - Tests de comportamiento del generador en Node: `node internal/gallery/testdata/generator.test.js ` (DOM, `fetch`, `sessionStorage` y wasm simulados, sin dependencias); lo lanza `TestGeneratorBehaviourInNode`, que en el CI falla si no hay `node` y en otros sitios se salta. - El lector de CSS de los tests (`css_test.go`) ignora comentarios y cadenas y entiende `@media` y `@supports`; sigue siendo un lector mínimo, no un analizador completo. @@ -68,6 +68,13 @@ Una mascota pixel-art **original** que vive en el README de tu perfil de GitHub. - Cabecera del README: `docs/img/banner.svg` se generó con los `` de los SVG reales de la galería (fases contento y árbol radiante) a escala 0,6; si cambian los sprites, regénerala igual (receta en `.claude/skills/publicar-version/SKILL.md`). - En la Raspberry Pi de Alberto (4 núcleos, compartida): `GOFLAGS=-p=2` y nunca dos builds a la vez. +## Fase 3 (25-26/10/2026) +- **Tercera especie `cactus`** (`internal/creature/cactus.go`). La receta de `CONTRIBUTING.md` está al día (también OG, `install.js`, CI y tests). Las especies existentes no pueden cambiar ni un byte: compara la galería con la de `main` (`diff -r`). +- **Selector de tema** (`internal/gallery/theme.js`, en `` sin `defer` para no parpadear): `data-theme` en ``, cambia el `media` de los `` y de `theme-color` (original en `data-media`). `localStorage` `commitling:theme` con lista cerrada (`light`, `dark`); «Sistema» borra la clave. CSS: oscuro en `@media (prefers-color-scheme:dark){:root:not([data-theme=light])…}` y `:root[data-theme=dark]`. Test en Node: `node internal/gallery/testdata/theme.test.js internal/gallery/theme.js`. +- **Trusted Types**: la CSP lleva `require-trusted-types-for 'script'; trusted-types commitling`. La única política es la de `generator.js` (`scriptURL`), que solo acepta `wasm_exec.js`. Nada de `innerHTML`/`eval`/`script.src` con cadenas: si hace falta un sumidero nuevo, pasa por esa política y por `TestPageHasStrictCSP`. +- **Acciones por SHA** con `# vX.Y.Z` (`TestThirdPartyActionsArePinnedBySHA`); dependabot actualiza ambos. Los workflows que genera la web para las personas usuarias siguen con `actions/checkout@v7` (legibles; son suyos). +- **Binario precompilado** (inactivo): paso `bin` de `action.yml`, `scripts/build-release.sh`, `.github/workflows/release.yml`, job `binario` de `action-test.yml`. Solo se activa con `release/checksums.txt` en el árbol de la etiqueta (ver `docs/DESARROLLO.md`). Si ese archivo existe, todo cambio de código exige regenerarlo (`--write`) o el CI falla. + ## Reglas de contenido - El personaje es **diseño propio**. Prohibido imitar criaturas de videojuegos, anime o marcas. - Las reglas de fase y ánimo están documentadas en el README y son deterministas (mismos datos, mismo SVG). diff --git a/CHANGELOG.md b/CHANGELOG.md index ee430a8..3e9d4f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,17 +6,20 @@ El formato sigue [Keep a Changelog](https://keepachangelog.com/es-ES/1.1.0/) y e ## [Sin publicar] -## [0.8.0] - 2026-10-24 +## [0.8.0] - 2026-10-26 -Versión «Blindada»: seguridad, documentación, accesibilidad y una instalación guiada. **La interfaz de `action.yml` no cambia** (mismas entradas, misma salida `path`, mismos archivos) y las tarjetas SVG son byte a byte las de v0.7.0 (las 96 huellas de v0.5.0 pasan). +Versión «Blindada»: seguridad, documentación, accesibilidad, una instalación guiada y una tercera especie. **La interfaz de `action.yml` no cambia** (mismas entradas, misma salida `path`, mismos archivos) y las tarjetas SVG del brote de musgo y del hongo son byte a byte las de v0.7.0 (las 96 huellas de v0.5.0 pasan). ### Añadido +- **Tercera especie: el cactus** (`species: cactus`), de diseño propio: un cactus con ojos en su maceta de barro que pasa por **Yema**, **Bolita**, **Cactus**, **Cactus con brazos** y **Cactus centenario**, con las mismas reglas, ánimos y accesorios. Sale en la galería (claro, oscuro y compacta), en los dos generadores de la web, en `--species` y en la imagen de vista previa. +- **Selector de tema de la web** (Sistema · Claro · Oscuro) en la cabecera: cambia la página y todas las tarjetas sin recargar, se aplica antes de pintar (sin parpadeo) y se recuerda en el navegador con la clave `commitling:theme` (solo `light` o `dark`; «Sistema» la borra y cualquier otro valor se ignora). Sin JavaScript, la web sigue al sistema como antes. +- **Binario precompilado preparado** (inactivo hasta que una release lo active): `scripts/build-release.sh` compila los binarios de forma reproducible, `release.yml` los sube al publicar una release y la Action los usa en vez de compilar **solo** si el SHA-256 coincide con el `release/checksums.txt` de su propio árbol; si no, compila con Go como siempre. - **Generador del workflow en la web** («Instálalo en tu perfil»): escribes tu usuario (o pegas el enlace de tu perfil), eliges especie, tema (claro, oscuro o **automático**, con las dos tarjetas y un ``) y tamaño, y copias el `.github/workflows/commitling.yml` y el fragmento del README ya rellenos. Seis pasos explicados para quien nunca ha usado Actions (repositorio de perfil, crear el archivo, permisos, primera ejecución con «Run workflow», README y resultado), enlaces directos a cada paso en GitHub (incluido «Abrir GitHub con el archivo ya relleno») y una lista «Si algo falla» con cada mensaje y qué hacer. Funciona sin red y sin wasm (`install.js`), no guarda nada y produce byte a byte lo mismo que `generate.Install` (test en Node y Go). - **`commitling workflow`** (alias `init`): imprime ese mismo workflow (`--user`, `--species`, `--theme light|dark|both`, `--size`) y dice qué pegar en el README. - **Mensajes de error que dicen qué hacer**, en español: usuario inexistente (404), token rechazado (401), acceso denegado (403), límite de peticiones (con la hora UTC a la que se restablece y si había token) y caídas de GitHub (5xx); el login no válido explica por qué («quita la @ del principio»…). Dentro de GitHub Actions el error sale también como anotación `::error` en el resumen de la ejecución. - El workflow de ejemplo explica en el propio log por qué falla el `git push` («No se pudo guardar la criatura en el repositorio»: `permissions: contents: write` o rama protegida). El paso se llama ahora «Guardar la criatura si ha cambiado». -- CI: los 13 workflows que pueden generarse se validan con **actionlint** (con shellcheck) y deben usar `@v1`; la prueba de la Action comprueba que un usuario inexistente falla. +- CI: los 19 workflows que pueden generarse se validan con **actionlint** (con shellcheck) y deben usar `@v1`; la prueba de la Action comprueba que un usuario inexistente falla. - **Content-Security-Policy estricta en la web**: solo scripts propios (más `'wasm-unsafe-eval'` para el generador), conexiones solo a la propia web y a `api.github.com`, sin `object`, `base` ni formularios externos; `referrer` `strict-origin-when-cross-origin` y `theme-color` para claro y oscuro. El script de los botones «Copiar» y el aviso de criatura en vivo no disponible pasan a `page.js` (antes eran un ` @@ -40,6 +41,14 @@ Instalar Código + diff --git a/internal/gallery/install.js b/internal/gallery/install.js index f00fdda..ba3c4f7 100644 --- a/internal/gallery/install.js +++ b/internal/gallery/install.js @@ -59,7 +59,7 @@ // 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'] }; + var ALLOWED = { species: ['moss', 'mushroom', 'cactus'], 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]; @@ -78,7 +78,7 @@ 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 (species !== 'moss') text += ' species: ' + species + '\n'; if (stepTheme === 'dark') text += ' theme: dark\n'; if (size === 'compact') text += ' size: compact\n'; return text + ' out: ' + out + '\n'; diff --git a/internal/gallery/install_test.go b/internal/gallery/install_test.go index e8b8f1d..ca76b09 100644 --- a/internal/gallery/install_test.go +++ b/internal/gallery/install_test.go @@ -59,8 +59,8 @@ func TestInstallJSMatchesGo(t *testing.T) { 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)) + if len(cases) != 4*3*3*2 { + t.Fatalf("%d cases, want 72", len(cases)) } for _, c := range cases { want, err := generate.Install(generate.Options{User: c.User, Species: c.Species, Theme: c.Theme, Size: c.Size}) diff --git a/internal/gallery/style.css b/internal/gallery/style.css index 94523fe..61e449a 100644 --- a/internal/gallery/style.css +++ b/internal/gallery/style.css @@ -6,8 +6,10 @@ color-scheme:light dark; } @media (prefers-color-scheme:dark){ - :root{--paper:#2b2724;--ink:#f3efe6;--line:#4a433d;--muted:#a39a8e;--accent:#ee6e55;--code:#34302c} + :root:not([data-theme=light]){--paper:#2b2724;--ink:#f3efe6;--line:#4a433d;--muted:#a39a8e;--accent:#ee6e55;--code:#34302c} } +:root[data-theme=light]{color-scheme:light} +:root[data-theme=dark]{--paper:#2b2724;--ink:#f3efe6;--line:#4a433d;--muted:#a39a8e;--accent:#ee6e55;--code:#34302c;color-scheme:dark} *{box-sizing:border-box} html{background:var(--paper)} body{margin:0;background:var(--paper);color:var(--ink); @@ -30,6 +32,11 @@ h4{font-size:15px;margin:32px 0 14px} p{margin:0 0 14px;max-width:68ch} .lead{font-size:17px;margin:0} nav{margin-top:14px;display:flex;flex-wrap:wrap;gap:6px 18px;font-size:14px} +.theme-pick{border:0;margin:18px 0 0;padding:0;display:flex;flex-wrap:wrap;align-items:center;gap:6px 10px;font-size:13px;min-width:0} +.theme-pick legend{font-weight:700;padding:0} +.theme-pick .opts{gap:5px} +.theme-pick .opt label{padding:4px 8px} +.theme-pick[hidden]{display:none} section{padding:56px 0;border-top:2px dashed var(--line)} .gen{display:grid;grid-template-columns:minmax(0,320px) minmax(0,1fr);gap:28px 40px;align-items:start} .gen-form{display:grid;grid-template-columns:minmax(0,1fr);gap:20px} diff --git a/internal/gallery/testdata/generator.test.js b/internal/gallery/testdata/generator.test.js index b3ae5d0..f7df814 100644 --- a/internal/gallery/testdata/generator.test.js +++ b/internal/gallery/testdata/generator.test.js @@ -91,6 +91,7 @@ function loadPage(storage, opts = {}) { return storage; }, }); + if (opts.trustedTypes) sandbox.trustedTypes = opts.trustedTypes; sandbox.window = sandbox; function stub() { @@ -312,6 +313,31 @@ const tests = { assert.equal(p.error(), ''); }, + async 'Trusted Types: wasm_exec.js goes through the «commitling» policy, created once'() { + const created = []; + const trustedTypes = { + createPolicy(name, rules) { + created.push(name); + return { createScriptURL: (input) => ({ trusted: rules.createScriptURL(input) }) }; + }, + }; + const p = loadPage(memoryStorage(), { api: ok([push(1)]), trustedTypes }); + await submit(p, 'octo'); + await submit(p, 'other'); + assert.deepEqual(created, ['commitling'], 'one policy, with the name the CSP allows'); + const scripts = p.doc.head.children.filter((c) => c.tagName === 'SCRIPT'); + assert.equal(scripts.length, 1); + assert.deepEqual(scripts[0].src, { trusted: 'wasm_exec.js' }, 'the script URL is a trusted value, not a string'); + assert.equal(p.calls.render.length, 2); + }, + + async 'without Trusted Types the script URL is the plain allowed string'() { + const p = loadPage(memoryStorage(), { api: ok([push(1)]) }); + await submit(p, 'octo'); + const scripts = p.doc.head.children.filter((c) => c.tagName === 'SCRIPT'); + assert.equal(scripts[0].src, 'wasm_exec.js'); + }, + async 'a server error does not offer the demo'() { for (const status of [500, 503]) { const p = loadPage(memoryStorage(), { api: () => ({ status }) }); diff --git a/internal/gallery/testdata/install.test.js b/internal/gallery/testdata/install.test.js index 6189f9f..4b0c89d 100644 --- a/internal/gallery/testdata/install.test.js +++ b/internal/gallery/testdata/install.test.js @@ -18,7 +18,7 @@ const api = sandbox.window.commitlingInstall; assert.ok(api); const users = ['', 'octocat', '007', 'a-b-9']; -const species = ['moss', 'mushroom']; +const species = ['moss', 'mushroom', 'cactus']; const themes = ['light', 'dark', 'both']; const sizes = ['full', 'compact']; diff --git a/internal/gallery/testdata/theme.test.js b/internal/gallery/testdata/theme.test.js new file mode 100644 index 0000000..479b74f --- /dev/null +++ b/internal/gallery/testdata/theme.test.js @@ -0,0 +1,99 @@ +// Behaviour test of theme.js. Run with: +// node internal/gallery/testdata/theme.test.js internal/gallery/theme.js +'use strict'; +const fs = require('node:fs'); +const vm = require('node:vm'); +const assert = require('node:assert/strict'); + +function element(attrs) { + const values = Object.assign({}, attrs); + return { + checked: false, + hidden: true, + listeners: {}, + getAttribute(name) { return Object.prototype.hasOwnProperty.call(values, name) ? values[name] : null; }, + setAttribute(name, value) { values[name] = String(value); }, + removeAttribute(name) { delete values[name]; }, + addEventListener(name, fn) { this.listeners[name] = fn; }, + fire(name) { if (this.listeners[name]) this.listeners[name].call(this); }, + value: values.value, + get media() { return values.media; } + }; +} + +function run(saved, broken) { + const source = fs.readFileSync(process.argv[2] || 'theme.js', 'utf8'); + const root = element({}); + const sources = [element({ media: '(prefers-color-scheme: dark)' })]; + const metas = [element({ media: '(prefers-color-scheme: light)' }), element({ media: '(prefers-color-scheme: dark)' })]; + const radios = ['system', 'light', 'dark'].map((value) => element({ value })); + const pick = { hidden: true, querySelectorAll() { return radios; } }; + const store = { + data: Object.assign({}, saved), + getItem(key) { if (broken) throw new Error('blocked'); return Object.prototype.hasOwnProperty.call(this.data, key) ? this.data[key] : null; }, + setItem(key, value) { if (broken) throw new Error('blocked'); this.data[key] = value; }, + removeItem(key) { if (broken) throw new Error('blocked'); delete this.data[key]; } + }; + const document = { + readyState: 'complete', documentElement: root, + querySelectorAll(selector) { return selector.indexOf('source') >= 0 ? sources : metas; }, + getElementById() { return pick; }, addEventListener() {} + }; + const sandbox = { console, document, window: { localStorage: store } }; + vm.runInNewContext(source, sandbox); + return { api: sandbox.window.commitlingTheme, root, sources, metas, radios, pick, store }; +} + +function ok(name, fn) { fn(); console.log('ok ' + name); } + +ok('elección guardada fuerza el tema', () => { + const r = run({ 'commitling:theme': 'dark' }); + assert.equal(r.api.read(), 'dark'); + assert.equal(r.root.getAttribute('data-theme'), 'dark'); + assert.equal(r.sources[0].getAttribute('media'), 'all'); + assert.equal(r.metas[1].getAttribute('media'), 'all'); + assert.equal(r.metas[0].getAttribute('media'), 'not all'); + assert.equal(r.radios[2].checked, true); + assert.equal(r.pick.hidden, false); +}); +ok('valor inválido se ignora y se borra', () => { + for (const value of ['`) + if script < 0 || script > strings.Index(page, ``) { + t.Error("theme.js must be in head before style.css") + } + for _, value := range []string{"system", "light", "dark"} { + if !strings.Contains(page, `name="site-theme" value="`+value+`"`) { + t.Errorf("theme selector lacks %q", value) + } + } + if !strings.Contains(page, `