From dc7a777d9fda7e9d28500a9d837a240e69a3a26c Mon Sep 17 00:00:00 2001 From: Do Siki Date: Tue, 29 Sep 2026 13:23:23 +0200 Subject: [PATCH] feat(deploy): indexability guard and production SEO launch suite (MITHOME-127) The staging noindex (MITHOME-116) hinges on a build variable; leaking it into production would silently drop the site from Google. deploy.sh now refuses to build production when NEXT_PUBLIC_DEPLOY_ENV=staging is set, and after every deploy runs scripts/check-indexability.sh, expecting an indexable production and a blocked staging (node tests cover both ways, stray noindex and unreachable endpoints; added to pre-deploy tests). A separate Playwright project, production-seo (npm run test:seo:production), checks robots.txt, that all 12 sitemap URLs are final/indexable with self canonicals and sitemap hreflangs, SSR content and links, the / -> /hu redirect and real 404s; host redirects are gated until the production domain is live. Verified on a production-mode build of a staging DB copy (5 passed) and failing as expected against staging. eslint now ignores generated test output (playwright-report, test-results, coverage), which broke the pre-deploy lint after local e2e runs. Co-Authored-By: Claude Opus 5.5 --- .agent/workflows/deploy.md | 25 ++++++--- deploy.sh | 24 ++++++++ proto/e2e/production-seo.spec.ts | 73 ++++++++++++++++++++++++ proto/eslint.config.mjs | 4 ++ proto/package.json | 3 +- proto/playwright.config.ts | 17 +++++- scripts/check-indexability.sh | 59 ++++++++++++++++++++ scripts/check-indexability.test.js | 90 ++++++++++++++++++++++++++++++ scripts/pre-deploy-tests.sh | 1 + 9 files changed, 286 insertions(+), 10 deletions(-) create mode 100644 proto/e2e/production-seo.spec.ts create mode 100755 scripts/check-indexability.sh create mode 100644 scripts/check-indexability.test.js diff --git a/.agent/workflows/deploy.md b/.agent/workflows/deploy.md index 38fbf75..cc2f4c1 100644 --- a/.agent/workflows/deploy.md +++ b/.agent/workflows/deploy.md @@ -74,15 +74,26 @@ cd ./deploy.sh production ``` -### Élesítés előtti SEO-ellenőrzés (MITHOME-127) +### Indexelhetőségi őr és élesítési SEO-ellenőrzés (MITHOME-127) -A staging tiltása (`noindex`, mindent tiltó `robots.txt`, üres sitemap) a `NEXT_PUBLIC_DEPLOY_ENV=staging` build-változón múlik (MITHOME-116). **Első éles deploy után és minden élesítéskor** ellenőrizni kell, hogy az éles oldal indexelhető: +A staging tiltása (`noindex`, mindent tiltó `robots.txt`, üres sitemap) a `NEXT_PUBLIC_DEPLOY_ENV=staging` build-változón múlik (MITHOME-116). Ha ez véletlenül az éles buildbe kerül, a Google csendben kiveszi az oldalt a találatok közül. Ezért a `deploy.sh` automatikusan véd: -- [ ] Egyik publikus oldalon sincs ``. -- [ ] A `https://mozdit.hu/robots.txt` nem tiltja a publikus oldalakat, és a sitemapre mutat. -- [ ] A `https://mozdit.hu/sitemap.xml` az éles domainnel mind a 12 URL-t tartalmazza, és mindegyik 200-at ad, átirányítás nélkül. -- [ ] A canonical és a hreflang az éles, végleges URL-re mutat. -- [ ] Az átirányítások egy lépésben mennek (`http→https`, `www→` preferált host, `/→/hu`); ismeretlen oldal 404-et ad. +- **Build előtt (csak production):** ha az `.env.production` vagy a `docker-compose.prod.yml` `NEXT_PUBLIC_DEPLOY_ENV=staging`-et állít, a deploy el sem indul. +- **Deploy után (mindkét környezet):** `scripts/check-indexability.sh ` — productionben indexelhető, stagingen tiltott állapotot vár. Eltérésnél a deploy hibával áll le (productionben rollback-utasítással). + +**Élesítéskor és minden éles kiadás után** futtasd a teljes SEO-csomagot is (`proto/` mappából): + +```bash +BASE_URL=https://mozdit.hu npm run test:seo:production +``` + +A csomag ellenőrzi: +- a `robots.txt` enged, és a sitemapre mutat; +- a sitemap mind a 12 URL-je végleges (200, átirányítás nélkül), nincs rajtuk `noindex`, a canonical önmagára mutat, a hreflang-párok sitemap-URL-ek; +- a tartalom és a belső linkek JavaScript nélkül is a HTML-ben vannak; +- a `/` egy lépésben a `/hu`-ra irányít, és az ismeretlen oldal 404-et ad. + +A host-átirányítások (`http→https`, `www→` preferált host) az Nginx feladatai (MITHOME-15): amint az éles domain él, `SEO_CHECK_HOST_REDIRECTS=1`-gyel ezek is ellenőrizhetők. Élesítés után: Google Search Console beállítása, sitemap beküldése, kulcsoldalak URL-vizsgálata (MITHOME-128). diff --git a/deploy.sh b/deploy.sh index 9c1bfa1..917056f 100755 --- a/deploy.sh +++ b/deploy.sh @@ -49,6 +49,16 @@ env_value() { } APP_PORT_VALUE="$(env_value APP_PORT)" +# 2b. Indexelhetőségi őr — build ELŐTT (MITHOME-127) +# WHY: a NEXT_PUBLIC_DEPLOY_ENV=staging build-változó noindex-et és mindent +# tiltó robots.txt-t süt az image-be (MITHOME-116). Productionben ez csendben +# kivenné az oldalt a Google-találatok közül, ezért ott meg sem építjük. +if [ "$ENV" = "production" ] && grep -hsE '^[[:space:]-]*NEXT_PUBLIC_DEPLOY_ENV[=:][[:space:]]*"?staging' "$ENV_FILE" "$COMPOSE_FILE" > /dev/null; then + echo "❌ Hiba: productionben NEXT_PUBLIC_DEPLOY_ENV=staging van beállítva ($ENV_FILE vagy $COMPOSE_FILE)." + echo " Ez noindexelné az éles oldalt. Töröld a beállítást, és futtasd újra a deployt." + exit 1 +fi + # 3. Docker konténerek újraépítése és indítása echo "🐳 Build és indítás..." # A friss Dockerfile- vagy build-arg-változásoknak is új konténerben kell érvényesülniük. @@ -73,6 +83,20 @@ if [ "$HEALTHY" -ne 1 ]; then exit 1 fi +# 4b. Indexelhetőség ellenőrzése — deploy UTÁN (MITHOME-127) +# Production: indexelhető kell legyen; staging: tiltott (MITHOME-116). +EXPECTED_INDEXING="blocked" +if [ "$ENV" = "production" ]; then + EXPECTED_INDEXING="indexable" +fi +if ! ./scripts/check-indexability.sh "http://localhost:${APP_PORT_VALUE:-$DEFAULT_PORT}" "$EXPECTED_INDEXING"; then + echo "❌ Az indexelhetőség nem az elvárt ($EXPECTED_INDEXING) — a deploy HIBÁS." + if [ "$ENV" = "production" ]; then + echo " Az éles oldal most keresőkből kizárt állapotban fut: állítsd vissza az előző kiadást (lásd .agent/workflows/deploy.md → Rollback)." + fi + exit 1 +fi + # 5. Payload admin felhasználó biztosítása (MITHOME-97 follow-up) # # WHY: minden friss adatbázisú deploy (első staging/prod indítás, vagy egy diff --git a/proto/e2e/production-seo.spec.ts b/proto/e2e/production-seo.spec.ts new file mode 100644 index 0000000..b899f2a --- /dev/null +++ b/proto/e2e/production-seo.spec.ts @@ -0,0 +1,73 @@ +import { expect, test, type APIRequestContext } from '@playwright/test' + +/** + * MITHOME-127 — production launch SEO checks (run at go-live and after every + * production release): `BASE_URL=https://mozdit.hu npm run test:seo:production`. + * + * The site must be indexable, every sitemap URL must be final (200, no + * redirect), canonical/hreflang must point at those final URLs, and content + + * internal links must be in the server-rendered HTML (no JS needed). + * Host-level redirects (http→https, www→apex) are nginx's job (MITHOME-15): + * set SEO_CHECK_HOST_REDIRECTS=1 once the production domain is live. + */ + +const text = async (request: APIRequestContext, path: string) => { + const response = await request.get(path, { maxRedirects: 0 }) + expect(response.status(), `${path} status`).toBe(200) + return response.text() +} + +const locs = (xml: string) => [...xml.matchAll(/([^<]+)<\/loc>/g)].map((m) => m[1]) +const attr = (html: string, pattern: RegExp) => html.match(pattern)?.[1] + +test('robots.txt allows crawling and points to the sitemap', async ({ request, baseURL }) => { + const robots = await text(request, '/robots.txt') + expect(robots).not.toMatch(/^Disallow:\s*\/\s*$/im) + expect(robots).toContain(`Sitemap: ${baseURL}/sitemap.xml`) +}) + +test('every sitemap URL is final, indexable and correctly annotated', async ({ request, baseURL }) => { + const urls = locs(await text(request, '/sitemap.xml')) + expect(urls).toHaveLength(12) + + for (const url of urls) { + expect(url.startsWith(`${baseURL}/`), `${url} is on ${baseURL}`).toBe(true) + const html = await text(request, url) + expect(html, `${url} has no noindex`).not.toMatch(/]*name="robots"[^>]*noindex/i) + expect(attr(html, / { + const html = await text(request, '/hu') + expect(html).toMatch(/]*>[^<]+/) + for (const path of ['/hu/rolunk', '/hu/szolgaltatasok', '/hu/kapcsolat', '/en']) { + expect(html, `link to ${path}`).toContain(`href="${path}"`) + } +}) + +test('the site root redirects to /hu in one step', async ({ request }) => { + const response = await request.get('/', { maxRedirects: 0 }) + expect([301, 302, 307, 308]).toContain(response.status()) + expect(new URL(response.headers()['location'], 'http://x').pathname).toBe('/hu') +}) + +test('unknown pages return a real 404', async ({ request }) => { + const response = await request.get('/hu/nincs-ilyen-oldal', { maxRedirects: 0 }) + expect(response.status()).toBe(404) +}) + +test('host variants redirect to the canonical origin in one step', async ({ request, baseURL }) => { + test.skip(!process.env.SEO_CHECK_HOST_REDIRECTS, 'nginx host redirects are checked once the production domain is live (MITHOME-15)') + const canonical = new URL(baseURL!) + const variants = [`http://${canonical.host}/hu`, `https://www.${canonical.host}/hu`] + for (const variant of variants) { + const response = await request.get(variant, { maxRedirects: 0 }) + expect([301, 308], `${variant} status`).toContain(response.status()) + expect(response.headers()['location'], `${variant} target`).toBe(`${canonical.origin}/hu`) + } +}) diff --git a/proto/eslint.config.mjs b/proto/eslint.config.mjs index 9a7c15a..996d4d8 100755 --- a/proto/eslint.config.mjs +++ b/proto/eslint.config.mjs @@ -16,6 +16,10 @@ const eslintConfig = [ "out/**", "build/**", "next-env.d.ts", + // Generated test output (Playwright report/traces, Jest coverage) — not source. + "playwright-report/**", + "test-results/**", + "coverage/**", ], }, { diff --git a/proto/package.json b/proto/package.json index f723e0d..43882fc 100755 --- a/proto/package.json +++ b/proto/package.json @@ -14,7 +14,8 @@ "test:browser": "jest --config jest.config.js src/__tests__/browser-integration.test.ts", "test:integration": "INTEGRATION_TESTS=1 jest --config jest.config.integration.js src/__tests__/integration.test.ts", "test:e2e": "E2E_TESTS=1 jest --config jest.config.integration.js src/__tests__/e2e-docker.test.ts", - "test:smoke:staging": "playwright test --config=playwright.config.ts", + "test:smoke:staging": "playwright test --config=playwright.config.ts --project=staging", + "test:seo:production": "playwright test --config=playwright.config.ts --project=production-seo", "test:docker": "npm run test:integration && npm run test:e2e", "test:all": "npm run test:unit && npm run test:browser && npm run test:docker", "test:report": "npm test -- --json --outputFile=test-results.json --silent && node ../scripts/sync-test-management.js", diff --git a/proto/playwright.config.ts b/proto/playwright.config.ts index 2e859b5..ba93932 100644 --- a/proto/playwright.config.ts +++ b/proto/playwright.config.ts @@ -1,15 +1,28 @@ import { defineConfig, devices } from '@playwright/test' +// MITHOME-127: two projects with opposite indexing expectations — +// `staging` (smoke, expects noindex) and `production-seo` (expects an +// indexable site). BASE_URL overrides the target of either. export default defineConfig({ testDir: './e2e', timeout: 30_000, retries: process.env.CI ? 1 : 0, reporter: [['list'], ['html', { open: 'never' }]], use: { - baseURL: process.env.BASE_URL || 'https://stage.mozdit.hu', trace: 'retain-on-failure', screenshot: 'only-on-failure', video: 'retain-on-failure', }, - projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }], + projects: [ + { + name: 'staging', + testMatch: 'staging-smoke.spec.ts', + use: { ...devices['Desktop Chrome'], baseURL: process.env.BASE_URL || 'https://stage.mozdit.hu' }, + }, + { + name: 'production-seo', + testMatch: 'production-seo.spec.ts', + use: { ...devices['Desktop Chrome'], baseURL: process.env.BASE_URL || 'https://mozdit.hu' }, + }, + ], }) diff --git a/scripts/check-indexability.sh b/scripts/check-indexability.sh new file mode 100755 index 0000000..b254a45 --- /dev/null +++ b/scripts/check-indexability.sh @@ -0,0 +1,59 @@ +#!/usr/bin/env bash +# MITHOME-127: indexelhetőségi őr — a telepített oldal robots.txt-je, +# sitemapje és noindex-jelölése egyezik-e a környezet elvárásával. +# +# Használat: scripts/check-indexability.sh +# indexable — production: nincs noindex, a robots.txt enged és a sitemapre +# mutat, a sitemap nem üres +# blocked — staging: noindex, mindent tiltó robots.txt, üres sitemap +# +# WHY: a staging tiltása a NEXT_PUBLIC_DEPLOY_ENV build-változón múlik +# (MITHOME-116). Ha az éles build hibásan kapja meg, a Google csendben +# kiveszi az oldalt a találatok közül — ezt a deploy azonnal jelezze. +# Kilépési kód: 0 = egyezik, 1 = eltérés, 2 = hibás használat / elérhetetlen. + +set -uo pipefail + +BASE_URL="${1:-}" +EXPECT="${2:-}" +if [ -z "$BASE_URL" ] || { [ "$EXPECT" != "indexable" ] && [ "$EXPECT" != "blocked" ]; }; then + echo "Használat: $0 " >&2 + exit 2 +fi +BASE_URL="${BASE_URL%/}" + +fetch() { + # -f: a 4xx/5xx válasz (pl. hiányzó robots.txt) is hiba, nem üres tartalom. + curl -fsS --max-time 20 "$BASE_URL$1" +} + +ROBOTS="$(fetch /robots.txt)" || { echo "❌ robots.txt nem érhető el: $BASE_URL/robots.txt" >&2; exit 2; } +SITEMAP="$(fetch /sitemap.xml)" || { echo "❌ sitemap.xml nem érhető el: $BASE_URL/sitemap.xml" >&2; exit 2; } +HOME_HTML="$(fetch /hu)" || { echo "❌ A főoldal nem érhető el: $BASE_URL/hu" >&2; exit 2; } + +has_disallow_all=0 +printf '%s\n' "$ROBOTS" | grep -qiE '^Disallow:[[:space:]]*/[[:space:]]*$' && has_disallow_all=1 +has_sitemap_ref=0 +printf '%s\n' "$ROBOTS" | grep -qi '^Sitemap:' && has_sitemap_ref=1 +has_noindex=0 +printf '%s' "$HOME_HTML" | grep -qiE ']*name="robots"[^>]*noindex' && has_noindex=1 +url_count="$(printf '%s' "$SITEMAP" | grep -o '' | wc -l | tr -d ' ')" + +errors=() +if [ "$EXPECT" = "indexable" ]; then + [ "$has_disallow_all" -eq 0 ] || errors+=("a robots.txt mindent tilt (Disallow: /)") + [ "$has_sitemap_ref" -eq 1 ] || errors+=("a robots.txt nem hivatkozik a sitemapre") + [ "$has_noindex" -eq 0 ] || errors+=("a főoldalon noindex jelölés van") + [ "$url_count" -gt 0 ] || errors+=("a sitemap üres") +else + [ "$has_disallow_all" -eq 1 ] || errors+=("a robots.txt nem tilt mindent") + [ "$has_noindex" -eq 1 ] || errors+=("a főoldalon nincs noindex jelölés") + [ "$url_count" -eq 0 ] || errors+=("a sitemap nem üres ($url_count URL)") +fi + +if [ "${#errors[@]}" -gt 0 ]; then + echo "❌ Indexelhetőség nem az elvárt ($EXPECT) — $BASE_URL:" >&2 + printf ' - %s\n' "${errors[@]}" >&2 + exit 1 +fi +echo "✅ Indexelhetőség rendben ($EXPECT): $BASE_URL (sitemap: $url_count URL)" diff --git a/scripts/check-indexability.test.js b/scripts/check-indexability.test.js new file mode 100644 index 0000000..1db6477 --- /dev/null +++ b/scripts/check-indexability.test.js @@ -0,0 +1,90 @@ +// MITHOME-127: tests for scripts/check-indexability.sh against a local HTTP +// server that impersonates an indexable (production) or blocked (staging) site. +const { test, before, after } = require('node:test') +const assert = require('node:assert/strict') +const http = require('node:http') +const { spawn } = require('node:child_process') +const path = require('node:path') + +const SCRIPT = path.join(__dirname, 'check-indexability.sh') + +const SITES = { + indexable: { + '/robots.txt': 'User-Agent: *\nAllow: /\nDisallow: /admin\n\nSitemap: https://mozdit.hu/sitemap.xml\n', + '/sitemap.xml': 'https://mozdit.hu/huhttps://mozdit.hu/en', + '/hu': 'mozdITok', + }, + blocked: { + '/robots.txt': 'User-Agent: *\nDisallow: /\n', + '/sitemap.xml': '', + '/hu': 'ok', + }, + // production build that wrongly got NEXT_PUBLIC_DEPLOY_ENV=staging for the page only + leakyNoindex: { + '/robots.txt': 'User-Agent: *\nAllow: /\n\nSitemap: https://mozdit.hu/sitemap.xml\n', + '/sitemap.xml': 'https://mozdit.hu/hu', + '/hu': '', + }, +} + +let server +let origin + +before(async () => { + server = http.createServer((req, res) => { + const [, site, ...rest] = req.url.split('/') + const body = SITES[site]?.['/' + rest.join('/')] + res.writeHead(body === undefined ? 404 : 200) + res.end(body ?? 'not found') + }) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + origin = `http://127.0.0.1:${server.address().port}` +}) + +after(() => server.close()) + +function check(site, expect) { + return new Promise((resolve) => { + const child = spawn('bash', [SCRIPT, `${origin}/${site}`, expect]) + let out = '' + child.stdout.on('data', (d) => (out += d)) + child.stderr.on('data', (d) => (out += d)) + child.on('close', (code) => resolve({ code, out })) + }) +} + +test('accepts an indexable production site', async () => { + const { code, out } = await check('indexable', 'indexable') + assert.equal(code, 0, out) + assert.match(out, /sitemap: 2 URL/) +}) + +test('accepts a blocked staging site', async () => { + assert.equal((await check('blocked', 'blocked')).code, 0) +}) + +test('fails when production is blocked, listing every problem', async () => { + const { code, out } = await check('blocked', 'indexable') + assert.equal(code, 1) + assert.match(out, /mindent tilt/) + assert.match(out, /noindex/) + assert.match(out, /sitemap üres/) +}) + +test('fails on a stray noindex even if robots.txt looks fine', async () => { + const { code, out } = await check('leakyNoindex', 'indexable') + assert.equal(code, 1) + assert.match(out, /noindex/) +}) + +test('fails when staging became indexable', async () => { + const { code } = await check('indexable', 'blocked') + assert.equal(code, 1) +}) + +test('returns 2 for bad usage or an unreachable site', async () => { + assert.equal((await check('indexable', 'maybe')).code, 2) + const missing = await check('missing', 'indexable') + assert.equal(missing.code, 2, missing.out) + assert.match(missing.out, /robots\.txt nem érhető el/) +}) diff --git a/scripts/pre-deploy-tests.sh b/scripts/pre-deploy-tests.sh index 9cefcc0..7ebd3ad 100755 --- a/scripts/pre-deploy-tests.sh +++ b/scripts/pre-deploy-tests.sh @@ -40,6 +40,7 @@ run "content: séma-validáció (minden JSON)" node "${ROOT}/scripts/test-conten # ── Infra ──────────────────────────────────────────────────────────────────── run "plane: sync unit tesztek" node --test "${ROOT}/scripts/plane/plane-sync.test.js" +run "infra: indexelhetőségi őr (MITHOME-127)" node --test "${ROOT}/scripts/check-indexability.test.js" # ── Összegzés ──────────────────────────────────────────────────────────────── printf '\n────────────────────────────────────────\n'