Merge branch 'gitea/master': CI/CD en Gitea Actions + despliegue en nginx

Trae el trabajo de Edgar: pipeline de Gitea Actions (build en cada PR,
deploy en push a master), vhost de nginx para
remigracion.jumpingcrab.com (HTTP sin TLS a proposito, con bloqueo de
rastreadores y cabeceras noindex), script de despliegue
(scripts/deploy.sh) y los retoques de index.html/robots.txt para que el
entorno de previsualizacion no sea indexable. Se basaba en nuestro commit
7f3711c, asi que no hay conflictos con el trabajo de la Fase 3.
This commit is contained in:
remigracion-dev
2026-11-11 14:35:15 +00:00
6 changed files with 376 additions and 0 deletions
+78
View File
@@ -0,0 +1,78 @@
# CI/CD de Remigración (React + Vite) en el host de localesp.es.
#
# El runner self-hosted de Gitea corre como root en el mismo host que sirve
# git.localesp.es y remigracion.jumpingcrab.com, así que no hay SSH ni
# secretos: el job compila y, si toca desplegar, ejecuta scripts/deploy.sh.
#
# En pull_request el pipeline corre ENTERO menos el despliegue: sirve para
# validar el build y las comprobaciones antes de mergear. Sólo se despliega
# en push a master (o con workflow_dispatch).
#
# Destino: /opt/remigracion/dist + vhost nginx HTTP. Entorno privado:
# noindex por cabecera, meta robots y robots.txt.
name: pipeline
on:
push:
branches:
- master
pull_request:
workflow_dispatch:
concurrency:
group: deploy-${{ github.ref }}
cancel-in-progress: true
jobs:
build:
name: Build + comprobaciones
runs-on: self-hosted
timeout-minutes: 15
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Dependencias
shell: bash
run: npm ci --no-audit --no-fund
- name: Build (vite)
shell: bash
run: npm run build
- name: Comprobar que el bundle no es indexable
shell: bash
run: |
set -euo pipefail
grep -qi 'name="robots"' dist/index.html
grep -q 'Disallow: /' dist/robots.txt
echo "OK: dist/index.html lleva meta robots y dist/robots.txt bloquea todo"
- name: Comprobar que el script de despliegue es válido
shell: bash
run: |
bash -n scripts/deploy.sh
echo "OK: scripts/deploy.sh sin errores de sintaxis"
deploy:
name: Desplegar en el host
runs-on: self-hosted
needs: build
# Clave: en PRs no se despliega nada; sólo se valida el pipeline.
if: github.event_name != 'pull_request'
timeout-minutes: 15
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Dependencias
shell: bash
run: npm ci --no-audit --no-fund
- name: Build (vite)
shell: bash
run: npm run build
- name: Desplegar en el host
shell: bash
run: bash scripts/deploy.sh
+49
View File
@@ -58,6 +58,55 @@ El JSON tiene tres claves:
- `menu` — ítems del menú principal con `title` y `url` (la mayoría son anclas `#seccion`). - `menu` — ítems del menú principal con `title` y `url` (la mayoría son anclas `#seccion`).
- `sections` — lista de secciones con `anchor`, `headings`, `paragraphs`, `images`, `lists`. - `sections` — lista de secciones con `anchor`, `headings`, `paragraphs`, `images`, `lists`.
## Despliegue
Entorno de previsualización privado en **<http://remigracion.jumpingcrab.com/>**
(mismo host que `localesp.es` y `git.localesp.es`).
- **Sin TLS a propósito:** el DNS de `remigracion.jumpingcrab.com` no permite
emitir un certificado Let's Encrypt, así que se sirve sólo por HTTP.
- **No indexable:** el entorno no debe aparecer en buscadores, agregadores ni
crawlers de IA. Se aplica en tres capas independientes:
1. nginx devuelve `403` a los user-agents de rastreadores conocidos.
2. Cabecera `X-Robots-Tag: noindex, nofollow, noarchive, nosnippet,
noimageindex, notranslate, noai, noimageai` en todas las respuestas.
3. `public/robots.txt` (`Disallow: /`) y `<meta name="robots">` en
`index.html`.
Automatización: `.gitea/workflows/deploy.yml` (workflow `pipeline`) tiene dos
jobs:
- **`build`** (siempre): `npm ci`, `npm run build`, comprobación de que el
bundle lleva `meta robots` + `robots.txt`, y `bash -n` del script de deploy.
- **`deploy`** (sólo si NO es una PR): repite el build y ejecuta
`scripts/deploy.sh`.
En las **pull requests** el pipeline corre entero menos el despliegue, así que
sirve para verificar el CI antes de mergear. Se despliega en cada push a
`master` y también a mano con `workflow_dispatch`. El runner self-hosted de
Gitea corre como root en el mismo host, así que el job no necesita SSH ni
secretos.
Artefactos y servicios en el host (mismo patrón que
`prototipo-yb01-ef.localesp.es`):
| Elemento | Ruta |
|---|---|
| Build estático (raíz de nginx) | `/opt/remigracion/dist` |
| vhost nginx (fuente en `deploy/nginx.conf`) | `/etc/nginx/conf.d/remigracion.jumpingcrab.com.conf` |
| Script de despliegue | `scripts/deploy.sh` |
Despliegue manual:
```bash
npm ci && npm run build
sudo bash scripts/deploy.sh
```
El script sincroniza `dist/`, etiqueta el árbol para SELinux
(`httpd_sys_content_t`), instala el vhost si cambió (con rollback si
`nginx -t` falla), recarga nginx y verifica `200` + `X-Robots-Tag`.
## Próximos pasos ## Próximos pasos
1. Añadir las páginas legales (`/cookies`, `/aviso-legal`) con React Router. 1. Añadir las páginas legales (`/cookies`, `/aviso-legal`) con React Router.
+48
View File
@@ -0,0 +1,48 @@
# remigracion.jumpingcrab.com — entorno privado de previsualización.
#
# Sin TLS a propósito: el DNS de este dominio no permite emitir un certificado
# Let's Encrypt, así que se sirve sólo por HTTP.
#
# No indexación (objetivo doble):
# 1. Cabecera X-Robots-Tag en TODAS las respuestas (incluidos 4xx/5xx).
# 2. 403 en el borde a los rastreadores conocidos, antes de servir nada.
# El bundle también declara <meta name="robots"> y sirve un robots.txt
# con "Disallow: /" (ver public/robots.txt e index.html).
server {
listen 80;
listen [::]:80;
server_name remigracion.jumpingcrab.com;
root /opt/remigracion/dist;
index index.html;
charset utf-8;
add_header X-Robots-Tag "noindex, nofollow, noarchive, nosnippet, noimageindex, notranslate, noai, noimageai" always;
add_header Referrer-Policy "no-referrer" always;
add_header X-Content-Type-Options "nosniff" always;
# Rastreadores de buscadores, agregadores SEO y crawlers de IA.
if ($http_user_agent ~* "(googlebot|google-inspectiontool|bingbot|bingpreview|msnbot|yandex|baiduspider|duckduckbot|slurp|ahrefs|semrush|mj12bot|dotbot|petalbot|applebot|gptbot|ccbot|claudebot|perplexitybot|bytespider|amazonbot)") {
return 403;
}
# robots.txt generado aquí mismo: el deploy no depende del build para esto.
location = /robots.txt {
add_header Content-Type "text/plain; charset=utf-8" always;
add_header X-Robots-Tag "noindex, nofollow, noarchive, nosnippet, noimageindex, notranslate, noai, noimageai" always;
return 200 "User-agent: *\nDisallow: /\n";
}
# Assets con hash de Vite: cacheables para siempre.
location /assets/ {
try_files $uri =404;
expires 1y;
add_header Cache-Control "public, immutable" always;
add_header X-Robots-Tag "noindex, nofollow, noarchive, nosnippet, noimageindex, notranslate, noai, noimageai" always;
}
# SPA: cualquier ruta desconocida vuelve al index.
location / {
try_files $uri $uri/ /index.html;
}
}
+6
View File
@@ -6,6 +6,12 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Remigración.es | La remigración es inevitable</title> <title>Remigración.es | La remigración es inevitable</title>
<meta name="description" content="La remigración es inevitable. Información, medidas y precedentes históricos." /> <meta name="description" content="La remigración es inevitable. Información, medidas y precedentes históricos." />
<!-- Entorno privado de previsualización: fuera de buscadores, agregadores y
crawlers de IA. Se refuerza en el servidor con X-Robots-Tag,
USER-AGENT blocking y robots.txt (deploy/nginx.conf). -->
<meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex, notranslate" />
<meta name="googlebot" content="noindex, nofollow, noarchive, nosnippet, noimageindex, notranslate" />
<meta name="bingbot" content="noindex, nofollow, noarchive, nosnippet, noimageindex, notranslate" />
<link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link <link
+2
View File
@@ -0,0 +1,2 @@
User-agent: *
Disallow: /
+193
View File
@@ -0,0 +1,193 @@
#!/usr/bin/env bash
# scripts/deploy.sh — Publica el build de Vite de Remigración en el host.
#
# Lo ejecuta el runner self-hosted de Gitea (usuario root) en cada push a
# master: ver .gitea/workflows/deploy.yml. También sirve a mano:
#
# npm ci && npm run build && ./scripts/deploy.sh
#
# Destino (mismo patrón que prototipo-yb01-ef.localesp.es):
# /opt/remigracion/dist + vhost nginx remigracion.jumpingcrab.com (HTTP)
# El vhost vive en el repo (deploy/nginx.conf) y se instala si cambia.
set -euo pipefail
APP_NAME="remigracion"
APP_HOST="remigracion.jumpingcrab.com"
DEPLOY_ROOT="/opt/remigracion"
VHOST_PATH="/etc/nginx/conf.d/remigracion.jumpingcrab.com.conf"
BACKUP_DIR="/var/backups/nginx"
usage() {
echo "Usage: $0" >&2
exit 2
}
log() {
printf '\033[1;34m[%s]\033[0m %s\n' "$APP_NAME" "$*"
}
fail() {
printf '\033[1;31m[%s:ERROR]\033[0m %s\n' "$APP_NAME" "$*" >&2
exit 1
}
host::require_root() {
if [ "$(id -u)" -ne 0 ]; then
fail "hay que ejecutarlo como root (el runner self-hosted ya lo hace)"
fi
}
host::require_tools() {
local tool
for tool in rsync curl nginx; do
if ! command -v "$tool" >/dev/null 2>&1; then
fail "falta la herramienta '$tool' en el host"
fi
done
}
artifact::require_build() {
local root="$1"
if [ ! -f "$root/dist/index.html" ]; then
fail "falta dist/index.html — ejecuta 'npm run build' antes del deploy"
fi
}
artifact::sync() {
local root="$1"
mkdir -p "$DEPLOY_ROOT/dist"
rsync -a --delete "$root/dist/" "$DEPLOY_ROOT/dist/"
log "build sincronizado en $DEPLOY_ROOT/dist"
}
# SELinux (AlmaLinux, Enforcing): nginx no puede leer /opt si el contexto no
# es httpd_sys_content_t. Se persiste la regla y se etiqueta el árbol.
selinux::label() {
local pattern
local rules
if ! command -v selinuxenabled >/dev/null 2>&1; then
return 0
fi
if ! selinuxenabled; then
return 0
fi
pattern="$DEPLOY_ROOT(/.*)?"
if command -v semanage >/dev/null 2>&1; then
# Se captura y se compara en memoria: 'grep -q' cierra el pipe antes de
# tiempo y con 'set -o pipefail' el SIGPIPE del emisor daria un falso
# negativo, volviendo a ejecutar semanage -a en cada deploy.
rules="$(semanage fcontext -l 2>/dev/null || true)"
if [[ "$rules" != *"$pattern"* ]]; then
semanage fcontext -a -t httpd_sys_content_t "$pattern"
fi
fi
if command -v restorecon >/dev/null 2>&1; then
restorecon -RF "$DEPLOY_ROOT" 2>/dev/null || true
elif command -v chcon >/dev/null 2>&1; then
chcon -R -t httpd_sys_content_t "$DEPLOY_ROOT"
fi
log "contexto SELinux aplicado a $DEPLOY_ROOT"
}
vhost::test() {
nginx -t >/dev/null 2>&1
}
# Instala el vhost del repo. Devuelve 1 si no había cambios (nada que recargar)
# y aborta restaurando el anterior si nginx rechaza la configuración.
vhost::install() {
local root="$1"
local source="$root/deploy/nginx.conf"
local backup
if [ ! -f "$source" ]; then
fail "falta $source en el repo"
fi
if [ -f "$VHOST_PATH" ] && cmp -s "$source" "$VHOST_PATH"; then
log "vhost sin cambios ($VHOST_PATH)"
return 1
fi
mkdir -p "$BACKUP_DIR"
if [ -f "$VHOST_PATH" ]; then
backup="$BACKUP_DIR/$(basename "$VHOST_PATH").$(date +%Y%m%d-%H%M%S)"
cp -a "$VHOST_PATH" "$backup"
fi
install -m 0644 "$source" "$VHOST_PATH"
if vhost::test; then
log "vhost instalado ($VHOST_PATH)"
return 0
fi
if [ -n "$backup" ] && [ -f "$backup" ]; then
mv -f "$backup" "$VHOST_PATH"
fail "nginx rechaza la configuración nueva: restaurado el vhost anterior"
fi
rm -f "$VHOST_PATH"
fail "nginx rechaza la configuración nueva: vhost eliminado"
}
nginx::reload() {
systemctl reload nginx
log "nginx recargado"
}
http::expect() {
local url="$1"
local expected="$2"
local attempt
local code
# nginx recarga en segundo plano: se reintenta antes de dar el deploy por fallido.
for attempt in $(seq 1 15); do
code="$(curl -s -o /dev/null -m 5 -w '%{http_code}' -H "Host: $APP_HOST" "$url" || true)"
if [ "$code" = "$expected" ]; then
return 0
fi
sleep 1
done
fail "esperaba $expected en $url y obtuve ${code:-sin respuesta}"
}
http::verify() {
local headers
http::expect "http://127.0.0.1/" "200"
http::expect "http://127.0.0.1/robots.txt" "200"
headers="$(curl -sI -m 10 -H "Host: $APP_HOST" "http://127.0.0.1/" | tr -d '\r')"
if ! grep -qi '^X-Robots-Tag:.*noindex' <<< "$headers"; then
fail "falta la cabecera X-Robots-Tag: noindex en la respuesta"
fi
log "verificado: HTTP 200 y X-Robots-Tag: noindex"
}
main() {
local root
root="$(cd "$(dirname "$0")/.." && pwd)"
host::require_root
host::require_tools
artifact::require_build "$root"
artifact::sync "$root"
selinux::label
if vhost::install "$root"; then
nginx::reload
fi
http::verify
log "LISTO: http://$APP_HOST/ (sin TLS, no indexable)"
}
main "$@"