diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..f7acb37 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,11 @@ +node_modules +dist +.astro +salida +referencia +.git +.github +.lighthouseci +*.md +!README.md +.DS_Store diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..a928025 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,65 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +jobs: + verificar: + name: Tipos, build, contenido y Lighthouse + runs-on: ubuntu-latest + env: + ASTRO_TELEMETRY_DISABLED: 1 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + - run: npm ci + - name: astro check + run: npm run check + - name: Build + run: npm run build + - name: Palabras prohibidas en dist/ + run: npm run verificar:prohibidas + - name: Métricas sin método + run: npm run verificar:metricas + - name: Currículum en PDF + run: | + npx playwright install --with-deps chromium + npm run cv:pdf + - name: Lighthouse CI (móvil, umbral 95) + run: npx lhci autorun + - uses: actions/upload-artifact@v4 + if: always() + with: + name: lighthouse + path: .lighthouseci + retention-days: 14 + + imagen: + name: Imagen Docker + runs-on: ubuntu-latest + needs: verificar + steps: + - uses: actions/checkout@v4 + - uses: docker/setup-buildx-action@v3 + - name: Construir (sin publicar) + uses: docker/build-push-action@v6 + with: + context: . + push: false + load: true + tags: collina-sitio:ci + - name: Arrancar y comprobar cabeceras + run: | + docker run -d --rm -p 8080:8080 --name sitio collina-sitio:ci + sleep 3 + curl -sSfI http://localhost:8080/ | tee cabeceras.txt + grep -qi "content-security-policy" cabeceras.txt + grep -qi "strict-transport-security" cabeceras.txt + grep -qi "x-content-type-options: nosniff" cabeceras.txt + curl -sSf -o /dev/null http://localhost:8080/curriculum/collina-systems-curriculum.pdf + docker stop sitio diff --git a/.gitignore b/.gitignore index adee56b..19c3c14 100644 --- a/.gitignore +++ b/.gitignore @@ -25,3 +25,6 @@ pnpm-debug.log* # PDF generado del currículum salida/ + +# Lighthouse CI +.lighthouseci/ diff --git a/BRIEF.md b/BRIEF.md index 530b735..f9cf4ad 100644 --- a/BRIEF.md +++ b/BRIEF.md @@ -182,6 +182,11 @@ de muestra). ## 12. Pendientes conocidos (TODO) +- Documentar con cada equipo la operación anterior ("Por documentar") de las + fichas cotizador, polizas, contratos, monitor-gasolineras y extractor-tablas. +- Validar la construcción de la imagen Docker en CI (en local no había demonio + de Docker activo al cerrar la fase 5). + - Confirmar método y periodo de las cifras del inicio (`src/content/cifras/`). - Producir los videos reales (fondo del inicio y capturas de cada ficha); hoy hay posters de muestra. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..cbfc8ae --- /dev/null +++ b/Dockerfile @@ -0,0 +1,28 @@ +# syntax=docker/dockerfile:1.7 +# Etapa 1: build con Node y Chromium (Playwright) para generar el sitio, el PDF +# del currículum y los archivos precomprimidos. +FROM mcr.microsoft.com/playwright:v1.64.1-noble AS build +WORKDIR /app +ENV CI=true PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 ASTRO_TELEMETRY_DISABLED=1 +COPY package.json package-lock.json ./ +RUN npm ci --no-audit --no-fund +COPY . . +RUN npm run check \ + && npm run build \ + && npm run verificar:prohibidas \ + && npm run verificar:metricas \ + && npm run cv:pdf \ + && node scripts/comprimir.mjs + +# Etapa 2: nginx sin privilegios sirviendo dist/ en el puerto 8080. +FROM nginxinc/nginx-unprivileged:1.31-alpine AS runtime +USER root +RUN mkdir -p /etc/nginx/snippets \ + && rm -f /etc/nginx/conf.d/default.conf +COPY nginx/seguridad.conf /etc/nginx/snippets/seguridad.conf +COPY nginx/default.conf /etc/nginx/conf.d/default.conf +COPY --from=build --chown=nginx:nginx /app/dist /usr/share/nginx/html +USER nginx +EXPOSE 8080 +HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ + CMD wget -q -O /dev/null http://127.0.0.1:8080/salud || exit 1 diff --git a/README.md b/README.md index ed98eee..bc065a0 100644 --- a/README.md +++ b/README.md @@ -19,3 +19,19 @@ Comprobaciones: `npm run verificar:prohibidas`, `npm run verificar:metricas`, `node scripts/capturas.mjs "/,/proyectos"`. Imagen Open Graph: `node scripts/og.mjs` regenera `public/img/og.png` con las fuentes del sitio. + +## Despliegue + +- `Dockerfile` multi-etapa: build con Node y Chromium (imagen de Playwright, + genera sitio, PDF del currículum y archivos precomprimidos) y `nginx` + sin privilegios en el puerto **8080** sirviendo `dist/`. +- Cabeceras de seguridad en `nginx/seguridad.conf` (CSP sin `unsafe-inline`, + HSTS, nosniff, Referrer-Policy, Permissions-Policy). Caché inmutable de un año + para `/_astro/` y `/fonts/`; HTML con `no-cache`. +- Salud: `GET /salud` responde `ok`. +- Coolify: aplicación tipo Dockerfile, puerto 8080, Traefik termina TLS. +- CI (`.github/workflows/ci.yml`): `astro check`, build, palabras prohibidas, + métricas sin método, PDF, Lighthouse CI con umbral 95 y presupuesto + (≤ 1.5 MB, ≤ 50 KB de JS), y construcción de la imagen con comprobación de + cabeceras. +- Lighthouse local: `npm run lighthouse` (informes en `.lighthouseci/`). diff --git a/lighthouserc.cjs b/lighthouserc.cjs new file mode 100644 index 0000000..db83948 --- /dev/null +++ b/lighthouserc.cjs @@ -0,0 +1,30 @@ +// Lighthouse CI: umbrales del BRIEF §9 en móvil sobre dist/. +// Presupuesto: ≤ 1.5 MB por página sin video y ≤ 50 KB de JS. +const paginas = ['/', '/proyectos/', '/proyectos/multisucursal/', '/proyectos/cotizador/', '/ingenieria/', '/firma/', '/contacto/', '/curriculum/']; + +module.exports = { + ci: { + collect: { + staticDistDir: './dist', + url: paginas.map((p) => `http://localhost${p}`), + numberOfRuns: 1, + settings: { + formFactor: 'mobile', + screenEmulation: { mobile: true, width: 412, height: 823, deviceScaleFactor: 1.75, disabled: false }, + onlyCategories: ['performance', 'accessibility', 'best-practices', 'seo'], + }, + }, + assert: { + assertions: { + 'categories:performance': ['error', { minScore: 0.95 }], + 'categories:accessibility': ['error', { minScore: 0.95 }], + 'categories:best-practices': ['error', { minScore: 0.95 }], + 'categories:seo': ['error', { minScore: 0.95 }], + 'resource-summary:script:size': ['error', { maxNumericValue: 51200 }], + 'resource-summary:total:size': ['error', { maxNumericValue: 1572864 }], + 'errors-in-console': ['error', { maxLength: 0 }], + }, + }, + upload: { target: 'filesystem', outputDir: '.lighthouseci' }, + }, +}; diff --git a/nginx/default.conf b/nginx/default.conf new file mode 100644 index 0000000..05ec3a4 --- /dev/null +++ b/nginx/default.conf @@ -0,0 +1,58 @@ +# Sitio estático de Collina Systems. nginx sin privilegios (puerto 8080) detrás +# de Traefik (Coolify), que termina TLS. Las cabeceras de seguridad se incluyen +# en cada location porque add_header no se hereda cuando un bloque define otras. + +server { + listen 8080; + listen [::]:8080; + server_name _; + root /usr/share/nginx/html; + index index.html; + + server_tokens off; + absolute_redirect off; + + # Compresión: archivos precomprimidos en el build (.gz) y gzip al vuelo como respaldo. + gzip on; + gzip_static on; + gzip_vary on; + gzip_min_length 1024; + gzip_types text/plain text/css text/javascript application/javascript application/json application/xml image/svg+xml font/woff2; + + include /etc/nginx/snippets/seguridad.conf; + + # Assets con hash en el nombre: caché larga e inmutable. + location /_astro/ { + include /etc/nginx/snippets/seguridad.conf; + add_header Cache-Control "public, max-age=31536000, immutable"; + try_files $uri =404; + } + + # Fuentes: nombres estables; se renombran si cambian. + location /fonts/ { + include /etc/nginx/snippets/seguridad.conf; + add_header Cache-Control "public, max-age=31536000, immutable"; + try_files $uri =404; + } + + location ~* \.(png|jpg|jpeg|webp|avif|svg|ico|mp4|webm|pdf)$ { + include /etc/nginx/snippets/seguridad.conf; + add_header Cache-Control "public, max-age=604800"; + try_files $uri =404; + } + + # HTML: siempre revalidar. + location / { + include /etc/nginx/snippets/seguridad.conf; + add_header Cache-Control "no-cache"; + try_files $uri $uri/ $uri.html =404; + } + + error_page 404 /404.html; + + location = /salud { + access_log off; + add_header Content-Type text/plain; + return 200 "ok\n"; + } +} diff --git a/nginx/seguridad.conf b/nginx/seguridad.conf new file mode 100644 index 0000000..5f51c33 --- /dev/null +++ b/nginx/seguridad.conf @@ -0,0 +1,12 @@ +# Cabeceras de seguridad. "always" para que también salgan en errores. +# CSP sin 'unsafe-inline': Astro compila scripts y estilos a archivos externos +# (assetsInlineLimit 0, inlineStylesheets never). frame-src solo para las +# demostraciones largas incrustadas (componente Video, modo externo). +add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; media-src 'self'; frame-src https://www.youtube-nocookie.com https://player.vimeo.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests" always; +add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always; +add_header X-Content-Type-Options "nosniff" always; +add_header Referrer-Policy "strict-origin-when-cross-origin" always; +add_header X-Frame-Options "DENY" always; +add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=(), usb=()" always; +add_header Cross-Origin-Opener-Policy "same-origin" always; +add_header Cross-Origin-Resource-Policy "same-origin" always; diff --git a/package.json b/package.json index bb8383d..0badf39 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,10 @@ "check": "astro check", "verificar:prohibidas": "node scripts/verificar-prohibidas.mjs", "verificar:metricas": "node scripts/verificar-metricas.mjs", - "cv:pdf": "node scripts/cv-pdf.mjs" + "cv:pdf": "node scripts/cv-pdf.mjs", + "comprimir": "node scripts/comprimir.mjs", + "lighthouse": "lhci autorun", + "verificar": "npm run check && npm run build && npm run verificar:prohibidas && npm run verificar:metricas" }, "dependencies": { "@astrojs/sitemap": "^3.7.4", diff --git a/scripts/comprimir.mjs b/scripts/comprimir.mjs new file mode 100644 index 0000000..66c96be --- /dev/null +++ b/scripts/comprimir.mjs @@ -0,0 +1,23 @@ +// Precomprime los archivos de texto de dist/ en gzip (.gz) y brotli (.br) para +// que nginx los sirva con gzip_static / brotli_static. Uso: node scripts/comprimir.mjs +import { readdirSync, readFileSync, writeFileSync, statSync } from 'node:fs'; +import path from 'node:path'; +import { gzipSync, brotliCompressSync, constants } from 'node:zlib'; + +const dist = path.resolve(process.argv[2] ?? 'dist'); +const TEXTO = new Set(['.html', '.css', '.js', '.mjs', '.xml', '.txt', '.json', '.svg']); +let n = 0; +function* archivos(dir) { + for (const nombre of readdirSync(dir)) { + const ruta = path.join(dir, nombre); + if (statSync(ruta).isDirectory()) yield* archivos(ruta); + else if (TEXTO.has(path.extname(nombre)) && statSync(ruta).size > 1024) yield ruta; + } +} +for (const ruta of archivos(dist)) { + const datos = readFileSync(ruta); + writeFileSync(ruta + '.gz', gzipSync(datos, { level: 9 })); + writeFileSync(ruta + '.br', brotliCompressSync(datos, { params: { [constants.BROTLI_PARAM_QUALITY]: 11 } })); + n++; +} +console.log(`${n} archivos precomprimidos (gz y br)`); diff --git a/scripts/verificar-metricas.mjs b/scripts/verificar-metricas.mjs new file mode 100644 index 0000000..5b27431 --- /dev/null +++ b/scripts/verificar-metricas.mjs @@ -0,0 +1,47 @@ +// Falla si alguna métrica (fichas de proyectos) o cifra (inicio) trae +// resultado sin método, o no declara explícitamente resultado y periodo. +// Complementa al esquema zod: corre sin construir el sitio. +// Uso: node scripts/verificar-metricas.mjs +import { readdirSync, readFileSync } from 'node:fs'; +import path from 'node:path'; +import { parse } from 'yaml'; + +const raiz = process.cwd(); +const errores = []; + +function revisar(origen, m, i) { + const donde = `${origen} #${i + 1} (${m?.medicion ?? m?.texto ?? 'sin nombre'})`; + if (!m || typeof m !== 'object') return errores.push(`${donde}: no es un objeto`); + if (!('resultado' in m) && !('valor' in m)) errores.push(`${donde}: falta "resultado" (usa null para "por medir")`); + if (!('periodo' in m)) errores.push(`${donde}: falta "periodo" (usa null si no aplica)`); + const resultado = m.resultado ?? m.valor ?? null; + const metodo = typeof m.metodo === 'string' ? m.metodo.trim() : ''; + if (!metodo) errores.push(`${donde}: sin método`); + if (resultado !== null && typeof resultado !== 'string') errores.push(`${donde}: el resultado debe ser texto o null`); + if (resultado !== null && !metodo) errores.push(`${donde}: resultado "${resultado}" sin método`); +} + +const proyectos = path.join(raiz, 'src', 'content', 'proyectos'); +for (const nombre of readdirSync(proyectos).filter((n) => n.endsWith('.md'))) { + const texto = readFileSync(path.join(proyectos, nombre), 'utf8'); + const fm = /^---\n([\s\S]*?)\n---/.exec(texto); + if (!fm) { + errores.push(`${nombre}: sin frontmatter`); + continue; + } + const datos = parse(fm[1]); + if (!Array.isArray(datos.metricas) || !datos.metricas.length) errores.push(`${nombre}: sin métricas`); + else datos.metricas.forEach((m, i) => revisar(nombre, m, i)); +} + +const cifras = path.join(raiz, 'src', 'content', 'cifras'); +for (const nombre of readdirSync(cifras).filter((n) => /\.ya?ml$/.test(n))) { + const datos = parse(readFileSync(path.join(cifras, nombre), 'utf8')); + revisar(`cifras/${nombre}`, datos, 0); +} + +if (errores.length) { + console.error(`Métricas inválidas:\n ${errores.join('\n ')}`); + process.exit(1); +} +console.log('Todas las métricas y cifras tienen método; resultado y periodo declarados.'); diff --git a/scripts/verificar-prohibidas.mjs b/scripts/verificar-prohibidas.mjs new file mode 100644 index 0000000..75186fe --- /dev/null +++ b/scripts/verificar-prohibidas.mjs @@ -0,0 +1,34 @@ +// Falla si en dist/ aparece alguna palabra prohibida (BRIEF §2). Revisa los +// archivos de texto publicados: HTML, CSS, JS, XML, TXT, JSON, SVG, incluidos +// comentarios y metadatos. Uso: node scripts/verificar-prohibidas.mjs [dist] +import { readdirSync, readFileSync, statSync } from 'node:fs'; +import path from 'node:path'; + +const dist = path.resolve(process.argv[2] ?? 'dist'); +const PROHIBIDAS = /\b(PLD|Odoo|lavado|CHM|115\/2026)\b/i; +const TEXTO = new Set(['.html', '.css', '.js', '.mjs', '.xml', '.txt', '.json', '.svg', '.webmanifest']); + +function* archivos(dir) { + for (const nombre of readdirSync(dir)) { + const ruta = path.join(dir, nombre); + if (statSync(ruta).isDirectory()) yield* archivos(ruta); + else if (TEXTO.has(path.extname(nombre))) yield ruta; + } +} + +const hallazgos = []; +let revisados = 0; +for (const ruta of archivos(dist)) { + revisados++; + const lineas = readFileSync(ruta, 'utf8').split('\n'); + lineas.forEach((linea, i) => { + const m = PROHIBIDAS.exec(linea); + if (m) hallazgos.push(`${path.relative(dist, ruta)}:${i + 1}: "${m[1]}"`); + }); +} + +if (hallazgos.length) { + console.error(`Palabras prohibidas en ${hallazgos.length} línea(s):\n ${hallazgos.join('\n ')}`); + process.exit(1); +} +console.log(`Sin palabras prohibidas en ${revisados} archivos de ${path.relative(process.cwd(), dist) || '.'}`); diff --git a/src/pages/404.astro b/src/pages/404.astro new file mode 100644 index 0000000..20b11e7 --- /dev/null +++ b/src/pages/404.astro @@ -0,0 +1,23 @@ +--- +import Base from '../layouts/Base.astro'; +--- + + +
+
+

Error 404

+

Esta página no existe.

+

Puede que la dirección haya cambiado. Las secciones del sitio están en el menú.

+

Ver los proyectos

+
+
+ + +