All case studies
~/cases/[classified]/rede-campus
confidential · NDAHardened landing pagesPresidential campaignOct 2026Completed

P-08

Rede Campus

A static landing page defended like an application: scoped WAF rules, a CSP with no inline scripts, a sign-up behind eight checks, traps for scanners and a fake login that records whoever tries to get in.

client████Volunteer movement from a public education network during a presidential runoff

A mobilization site for an academic community spread across hundreds of campuses, built and shipped in one afternoon: the assembly livestream, an action guide, the movement's causes and a form that writes to the CRM with LGPD proof of consent. Behind a static Astro page on Cloudflare Pages, every dynamic request goes through edge rules, a Pages Function with layered validation and a security event log in D1 that raises Telegram alerts. Scanners land in traps and in an admin panel that does not exist.

≈ 4 h
first to last commit
49
trap prefixes
24
attack-suite cases
8
security headers
  • astro
  • cloudflare
  • anti-bot
  • waf
  • csp
  • crm
  • lgpd
  • rate-limiting
  • tests
architecture.en.svgenlarge ↓

01Overview

A volunteer movement of students and staff from a public education network in Brazil needed a website for the runoff of a presidential election. Its audience is spread across hundreds of campuses nationwide and arrives almost always on a phone, from links shared in group chats.

The site brings together the assembly livestream, an action guide, the movement's causes and a "Join us" form that sends each person to the movement's CRM with state, city, campus and role (student, teacher, staff and so on). It was built, tested and shipped in one afternoon: 21 commits between 3:59 pm and 7:56 pm on the same day.

From the outside it is a static page. Underneath, every dynamic request goes through edge rules, a server function with layered validation and a security event log that pings the team on Telegram when something looks off.

02The problem

  • A deadline in hours, not weeks. The site had to be live in time to promote an assembly scheduled for that same day.
  • Political forms are targets. An open sign-up during an election draws bots, spam and people trying to pollute the list or overload the CRM.
  • Going public draws scanners. Any new domain gets probed within minutes for .env, .git, WordPress and admin panels.
  • Shared infrastructure. The site lives on a subdomain of zones that also serve another site; no security rule could affect the neighbor.
  • LGPD (Brazil's data protection law). Each contact needs proof of consent, and the security logs must not turn into a second store of personal data.

03The solution

  • A single Astro page with sections layered like stacked sheets: hero with the livestream, form, step-by-step guide, about, causes and social links.
  • A mobile-first form: phone masking, state → city with all 5,571 IBGE municipalities loaded on demand per state, and state → campus with hundreds of campuses in a custom list (the native <datalist> would not open on phones), with accent-insensitive filtering and touch and keyboard navigation.
  • CRM sign-up through a Pages Function: it creates or updates the contact, writes an LGPD consent note and adds the contact to a segment. URL UTMs become source tags.
  • Defense in depth at the edge, in the Function and in the browser (see Security).
  • Security observability: events in D1, Telegram alerts and a command-line report (npm run seguranca) with event types, IPs, countries, scanned paths and sign-ups over the last 24 hours.
  • Documented operations: architecture, operations, CRM integration, security (including an "we're under attack" runbook) and testing under docs/.
  • Eight ordered checks on POST /api/lead: request shape, Origin, a 10-per-hour per-IP limit, honeypot and timing, injection detection, Turnstile with hostname and action, validation with sanitization, and email dedupe.
  • A CSP with no 'unsafe-inline' in script-src on an Astro site: assetsInlineLimit 0, Turnstile loaded on demand and violations reported to a dedicated Function.
  • 49 scanning prefixes (/.env, /.git, /wp-*, /phpmyadmin…) hit a trap that returns 404 and logs who asked; the rest of the site never touches Functions.
  • An /admin that does not exist: it redirects to a fake login that always fails after a 1.1 s delay and keeps what was tried, along with a browser fingerprint.
  • WAF and rate-limit rules applied by script on zones shared with another site, scoped to the subdomain and tagged, with a dry run before writing.
  • Telegram alerts per event type and threshold, with no duplicates under concurrency thanks to an atomic reservation in D1.

04Architecture

real architecture · hover over the nodes
Read the diagram as a list (14 components, 16 connections)

Components

  • Cloudflare · zone rules scoped to the subdomain: WAF<br>methods · POST on 3 routes only<br>23 attack UAs · empty UA, Edge rate limit<br>POST: 5 req / 10 s per IP
  • Cloudflare Pages: Static Astro<br>CSP without unsafe-inline<br>HSTS · COOP · CORP, POST /api/lead<br>shape · Origin · D1 limit<br>honeypot · injection · Turnstile<br>validation · dedupe, POST /api/csp<br>CSP reports, [[armadilha]]<br>49 prefixes → 404, /admin → fake /login<br>delayed 401 · fingerprint

Connections

  • Visitor<br>(phone, WhatsApp links) → WAF<br>methods · POST on 3 routes only<br>23 attack UAs · empty UA
  • Scanners and bots → WAF<br>methods · POST on 3 routes only<br>23 attack UAs · empty UA
  • WAF<br>methods · POST on 3 routes only<br>23 attack UAs · empty UA → Edge rate limit<br>POST: 5 req / 10 s per IP
  • Edge rate limit<br>POST: 5 req / 10 s per IP → Static Astro<br>CSP without unsafe-inline<br>HSTS · COOP · CORP
  • Edge rate limit<br>POST: 5 req / 10 s per IP → POST /api/lead<br>shape · Origin · D1 limit<br>honeypot · injection · Turnstile<br>validation · dedupe
  • Edge rate limit<br>POST: 5 req / 10 s per IP → /admin → fake /login<br>delayed 401 · fingerprint
  • WAF<br>methods · POST on 3 routes only<br>23 attack UAs · empty UA → [[armadilha]]<br>49 prefixes → 404
  • Static Astro<br>CSP without unsafe-inline<br>HSTS · COOP · CORP → POST /api/csp<br>CSP reports (report-uri)
  • POST /api/lead<br>shape · Origin · D1 limit<br>honeypot · injection · Turnstile<br>validation · dedupe → Turnstile<br>siteverify<br>hostname + action (siteverify)
  • POST /api/lead<br>shape · Origin · D1 limit<br>honeypot · injection · Turnstile<br>validation · dedupe → Mautic<br>contact · LGPD note<br>segment (REST · Basic Auth)
  • POST /api/lead<br>shape · Origin · D1 limit<br>honeypot · injection · Turnstile<br>validation · dedupe → D1<br>events · honeypot
  • POST /api/csp<br>CSP reports → D1<br>events · honeypot
  • [[armadilha]]<br>49 prefixes → 404 → D1<br>events · honeypot
  • /admin → fake /login<br>delayed 401 · fingerprint → D1<br>events · honeypot
  • D1<br>events · honeypot → Telegram<br>threshold alert<br>atomic reservation
  • GitHub<br>push to main = production<br>branch = preview → Pages

Content is served as static files from the CDN. Only the paths listed in public/_routes.json (the API, the honeypot and the traps) invoke Functions, so legitimate read traffic uses no execution quota and exposes no server surface.

05Under the hood

Backend and data

Pages Functions (5 files plus 1 shared module)

Route What it does
POST /api/lead sign-up: eight ordered checks, then the CRM (contact, consent note, segment)
POST /api/csp receives CSP violation reports and logs the directive, blocked URI and sample
/admin 302 to /login, logged as scanning
GET/POST /login fake login: serves the page, always answers 401 after 1.1 s and captures the attempt
[[armadilha]] any of the 49 scanning prefixes: 404 with the real error page, plus a log entry

src/server/seguranca.js holds what the Functions share: client details from headers and Cloudflare's cf object (IP, country, ASN, network, cf-ray), per-IP counting, key-based dedupe, SHA-256 hashing, sanitization and alert dispatch.

D1 (SQLite at the edge), 3 migrations

  • eventos: timestamp, type, severity, IP, country, ASN, network, user agent, method, path, host, cf-ray, detail and an indexed chave key (email hash for dedupe, or the alert type sent). Thirteen event types, from cadastro (sign-up) to injecao (injection).
  • honeypot: fake-login attempts, with time from page load to submit, language, headers and a browser fingerprint.
  • Six indexes, all composite with the timestamp, because every query is "from this IP/type/key in the last N minutes".

CRM integration. The Function talks to Mautic's REST API with a dedicated API user. Quirks that only surface in production are handled in code: Mautic silently drops custom fields that don't exist, so the response is checked and the log states whether the campus and role fields were saved; and the instance rejected ISO 8601 dateTime on notes, so the exact time goes in the note text instead. Failures on the note or segment only go to the log, since the contact is already saved.

Frontend
  • Astro 7 with output: 'static', 12 components and three pages (home, a real 404 and the fake login screen, built with the same visual identity so it looks convincing).
  • All visible copy in one file (src/content/textos.ts), including the consent wording, which the Function imports so the note records exactly what the person ticked.
  • Hand-written CSS with tokens, three typographic voices from a single variable font (width axis from 62% to 125%), and official fonts wired up to switch on once the licensed files arrive.
  • Minimal JavaScript: the form (masking, state → city, validation, Turnstile, a 15 s request timeout) and the campus combobox, with aria-expanded, aria-activedescendant and aria-selected.
  • Turnstile loaded on first interaction with the form, invisible and with an explicit action.
  • prefers-reduced-motion honored by the header marquee and by the star that rotates on scroll.
  • Social preview image generated from the hero itself by a script (npm run og, an 87 KB JPEG).
Infrastructure and deploy
  • Cloudflare Pages with Git integration: pushing to main deploys to production; any other branch gets its own preview URL. The project was recreated through the API to be Git-linked, since a direct-upload project can't be converted.
  • No wrangler.toml at the root, on purpose: with one, Pages would ignore the bindings and secrets set in the dashboard. The test config lives under tests/.
  • Zone rules as code: scripts/seguranca-zona.mjs generates WAF, rate-limit and redirect rules for the three domains, dry-runs by default and only writes with --aplicar.
  • Full local stack (npm run stack:local): a build with Turnstile's test key, a local D1 created from the migrations, a fake CRM in Node that logs every call to a JSONL file, and the Functions running in Wrangler.
  • Weekly Dependabot with grouped updates.

06Security

8 attacks considered, 8 defenses in production.

attackdefense
Bots and fake sign-ups

Scripts that flood forms, inflate numbers or sweep the site for openings.

  • A bot mass-submits the form with fake data

    Honeypot hits and submissions under 2 s get a fake 200; past that, an invisible Turnstile verified server-side and an edge rate limit of 5 POSTs per 10 s

  • Automated scanning for .env, .git, WordPress and admin panels

    23 attack tools and empty user agents blocked at the WAF; 49 prefixes fall into a 404 trap that logs IP, country and network; /admin leads to a fake login that never authenticates

Forged origin and requests

CSRF, fake webhooks, reused tokens, signed links and open redirects.

  • Replay a Turnstile token issued on another site

    Beyond being valid, the token must carry one of the site's hostnames and the 'lead' action; otherwise a 403 logged as a high-severity event

  • Host a fake form on another domain pointing at the API

    The Origin header must be one of the site's domains or a project preview; anything else gets a 403

Injection and hostile content

XSS, iframes, CSV formulas, disguised uploads and AI prompt manipulation.

  • Inject HTML, script, template or SQL that ends up in the CRM dashboard

    Injection patterns are caught before Turnstile (the attempted value is logged), then sanitized with Unicode NFC and no control, invisible or <> characters, and validated against a closed list of categories

  • Inject script into the site via XSS or frame it

    A CSP with no 'unsafe-inline' in script-src, object-src 'none', frame-ancestors 'none', X-Frame-Options DENY and violations reported to /api/csp, alerting above 10 in 10 minutes

Cost and availability abuse

Blowing up the bill, exhausting quotas, flooding logs and knocking functions down with load.

  • Flood the log or the alerts to exhaust quotas or blind the team

    A cap of 40 rows per IP every 10 minutes in D1 and in the honeypot; at most 1 alert per type every 30 minutes, decided by an atomic reservation

Tampering and audit trail

Fiddling with counts, wiping the base, editing history or denying what was authorized.

  • Dispute that the person ever consented

    Each sign-up writes a note on the contact with UTC timestamp, IP, browser, page, UTMs and the exact consent wording, plus an aceite-lgpd tag; in the security log the email only appears as a SHA-256 hash

Static content on a CDN is hard to take down. The real targets are the form, automated scanning for weaknesses and the accounts. Defenses sit in three layers.

1. Edge (Cloudflare zone rules)

The zones are shared with another site, so every rule is scoped to the subdomain's host and tagged with its own prefix. The script only deletes and recreates rules carrying that tag; other projects' rules are counted and left untouched.

  • Methods other than GET, HEAD and POST: 403.
  • POST outside /api/lead, /api/csp and /login: 403.
  • 23 attack tools by user agent (sqlmap, nuclei, gobuster, nikto, wpscan, ffuf…), case-insensitive, plus requests with no user agent: 403.
  • Edge rate limit: more than 5 POSTs in 10 s per IP on /api/lead or /login gets blocked. The free plan allows a single rule, so one rule covers both the sign-up and the honeypot (without /login in it, brute force on the fake login would burn the same Functions and D1 quota as real sign-ups).
  • A challenge for traffic from outside the country is ready behind a flag, exempting verified bots and link-preview crawlers (WhatsApp, Telegram and others).
  • Zone-wide settings (Bot Fight Mode, Security Level, minimum TLS) were left alone because they would affect the neighboring site.

2. Application (POST /api/lead)

In order, from cheapest to most expensive:

  1. Shape: application/json only (415) and a body up to 8 KB, checked on Content-Length and again on the body read (413). Invalid JSON or a non-object: 400.
  2. Origin: must be one of the site's domains or a project preview (403).
  3. Per-IP limit: 10 submissions per hour, counted in D1 from sign-up, duplicate, Turnstile, validation and bot events (429).
  4. Honeypot and timing: a filled hidden field or a submission under 2 s gets a fake 200 and is dropped, so the bot gets no signal to adapt.
  5. Injection: HTML, on…= attributes, javascript:, data:text/html, {{ }} and ${ } templates, <?php, UNION SELECT, DROP TABLE → 400 and a high-severity event with the attempted value. It runs before Turnstile on purpose, to log intent even from requests without a token.
  6. Turnstile: the token must be valid, carry one of the site's hostnames and have action set to lead. That rejects tokens minted by another site's widget.
  7. Validation and sanitization: name, email, a WhatsApp number with a valid area code and mobile prefix, a two-letter state, a role from a closed list and a boolean consent. All text is normalized to Unicode NFC with no control, invisible or <> characters, because the CRM is a web dashboard.
  8. Dedupe: the same email within 10 minutes gets an ok without hitting the CRM again.

Without CRM credentials configured, the Function returns 503 instead of accepting data that would go nowhere. Any CRM failure triggers an immediate alert.

3. Browser (public/_headers)

  • CSP with script-src 'self' plus Turnstile and Web Analytics, no 'unsafe-inline'; object-src 'none', frame-ancestors 'none', base-uri and form-action 'self', upgrade-insecure-requests and report-uri /api/csp.
  • One-year HSTS, X-Frame-Options: DENY, nosniff, Referrer-Policy, Permissions-Policy (camera, microphone, geolocation, payment, USB), COOP and CORP.
  • The API answers with Cache-Control: no-store and X-Robots-Tag: noindex; hashed assets get a one-year immutable cache.
  • The video is embedded from youtube-nocookie.com.

Traps and honeypot

  • 49 scanning prefixes (/.env, /.git, /wp-*, /phpmyadmin, /vendor, /actuator, /docker-compose…) go through a Function that returns the real 404 page and logs IP, country and network.
  • Fake admin panel: /admin redirects to a /login styled like the rest of the site. The POST never authenticates: it answers 401 after 1.1 s (it looks like a real login and slows brute force) and records the attempt with a browser fingerprint (canvas, WebGL, screen, time zone) and the time from page load to submit, which gives automation away. robots.txt lists /admin and /login under Disallow as bait: legitimate crawlers obey, malicious scanners head straight there.
  • Anti-flood: at most 40 writes per IP every 10 minutes in both tables, so an attack can't exhaust D1's daily write quota; the honeypot stops alerting from the 4th attempt by the same IP.

Logging, alerts and LGPD

  • Every rejection and every sign-up becomes a row in eventos, written with waitUntil so it doesn't delay the response. Emails are stored only as SHA-256 hashes.
  • Telegram alerts fire when a type crosses its threshold within 10 minutes (injection: 3; CRM failure: 1; CSP: 10; scanning: 40…), with at most one alert per type every 30 minutes.
  • Proof of consent on the contact's timeline: UTC timestamp, IP, user agent, page, UTMs and the exact consent wording, plus an aceite-lgpd tag. The privacy notice mentions IP and browser.
  • Fail-open by design: if D1, Telegram or Turnstile itself is down, sign-up keeps working with the remaining layers. During a campaign, losing legitimate sign-ups costs more than letting a few extra through for a few minutes.
  • Secrets live only in the Pages dashboard, typed without echo; the variable that accepts Turnstile's test keys exists only locally.

Security tests

tests/ataques.mjs runs 24 cases against any environment: wrong method and content type, missing Origin, a foreign Origin, a 20 KB body, broken JSON, the honeypot, five injection payloads (XSS, attribute breakout, SQL, template, UNION), a missing Turnstile token, five traps, a real 404 and a CSP report. With --completo (local only) it adds a valid submission, dedupe, a forged role and the per-IP 429.

07Technical challenges

A strict CSP on an Astro site

Astro inlines small scripts by default, which would require 'unsafe-inline' in script-src. The fix was vite.build.assetsInlineLimit: 0 (every script becomes a file), loading Turnstile programmatically with render=explicit, and keeping even the honeypot's collector as an external file. After deploying, CSP reports showed a violation on every visit: the Web Analytics beacon injected by the zone itself. It was added to the policy and the noise stopped, without a blanket exception.

A per-IP limit that survives a day of traffic

Workers KV is the obvious first choice, but the free plan allows 1,000 writes a day and KV is eventually consistent across regions. The limit became a count in D1 over the event table that already existed for auditing, with no extra structure. To keep a flood from exhausting D1's 100,000 daily writes, each IP writes at most 40 rows every 10 minutes.

Alerts without duplicates under concurrency

During an attack, dozens of requests cross the threshold at once and each would send a message. The decision to alert became an INSERT … SELECT … WHERE NOT EXISTS in D1: only the request that manages to write the reservation row sends the message. If Telegram fails, the reservation is deleted so the next alert isn't muted for 30 minutes.

Edge rules on zones this site doesn't own alone

WAF and rate limiting had to exist without touching the neighboring site or its rules. The script scopes every expression to the subdomain's host, tags its rules with a prefix, counts everyone else's, only replaces its own and dry-runs by default. The same logic produces the 301 redirects from the secondary domains to the canonical one.

08Results

  • Live on the day of the first commit, with 21 commits between 3:59 pm and 7:56 pm on Oct 8, 2026.
  • Sign-ups written to the CRM with per-contact proof of consent.
  • Edge defenses applied and verified in production, per the repository's security documentation.
  • A reproducible attack suite: 23 of 24 cases passed locally in a test environment without the Turnstile key; the remaining case depends on exactly that key.
  • Operations, security and testing documentation versioned alongside the code.
21
commits
how we measured

git log --oneline | wc -l

≈ 4 h
first to last commit
how we measured

git log: 2026-10-08, from 15:59 to 19:56

5
Pages Functions
how we measured

functions/api/lead.js, functions/api/csp.js, functions/admin.js, functions/login.js, functions/[[armadilha]].js

49
trap prefixes
how we measured

public/_routes.json (51 entries, minus /api/* and /api) and docs/SEGURANCA.md

23
attack user agents blocked
how we measured

WAF rule in scripts/seguranca-zona.mjs (plus empty UA)

8
security headers
how we measured

/* block of public/_headers, checked with curl -I on wrangler pages dev

2 / 3
D1 tables / migrations
how we measured

migrations/0001_eventos.sql, 0002_chave.sql, 0003_honeypot.sql

10
alerting event types
how we measured

ALERTA object in src/server/seguranca.js

24
attack-suite cases
how we measured

tests/ataques.mjs with --completo; 23 passed locally without TURNSTILE_SECRET (the 'no token' case depends on it)

≈ 3,700
lines of code
how we measured

tracked non-empty lines: .astro 1,676, .js 654, .ts 505, .mjs 439, .css 338, .sql 51, .sh 25 (data JSON excluded)

09Timeline

  1. 08 Oct 2026 · 15:59

    Astro site with hero, guide, causes and a browser-validated form

  2. 08 Oct 2026 · 16:04

    Git-based deploy on Cloudflare Pages with per-branch previews

  3. 08 Oct 2026 · 16:09

    The form writes to the CRM, with an LGPD consent note and a check on custom fields

  4. 08 Oct 2026 · 17:11

    API defenses, scanning traps, a strict CSP, D1 events and alerts

  5. 08 Oct 2026 · 17:19

    WAF and rate-limit rules applied at the edge, scoped to the subdomain

  6. 08 Oct 2026 · 17:55

    Documentation, browser tests and an attack suite in the repository

  7. 08 Oct 2026 · 18:22

    An /admin → fake /login honeypot captures access attempts

10Stack

Frontend
  • Astro 7 (output estático)
  • TypeScript
  • CSS próprio com tokens
  • Archivo variável (self-hosted)
  • Combobox acessível próprio
Backend
  • Cloudflare Pages Functions
  • Módulo de segurança compartilhado (src/server/seguranca.js)
Data
  • Cloudflare D1 (SQLite)
  • Mautic (API REST)
  • Municípios do IBGE e unidades do INEP em JSON estático
Infra
  • Cloudflare Pages com integração Git
  • Regras de zona via API (script próprio)
  • Wrangler
  • Dependabot
Security
  • Cloudflare Turnstile (hostname + action)
  • WAF e rate limit de borda escopados por host
  • CSP sem 'unsafe-inline' em script-src + report-uri
  • Limite por IP no D1
  • Detecção de injeção
  • Armadilhas de varredura
  • Honeypot de login
  • Alertas no Telegram
  • Prova de consentimento LGPD

11Tech sheet

node@rede-campus: ~/cases/rede-campus
node@rede-campus ─────────────
type
landing page + edge functions
stack
astro 7 · typescript · css
runtime
cloudflare pages functions
db
d1 (events · honeypot)
crm
mautic (rest api)
antibot
waf · turnstile · honeypot · edge rate limit
deploy
git push → pages
status
completed
$ npm run stack:local
→ build com a chave de teste do Turnstile
→ esquema do D1 local
Mautic falso em http://localhost:9999
→ site em http://localhost:8788
$ node tests/ataques.mjs http://localhost:8788 --completo
✔ sem Origin → 403
✔ corpo de 20 KB → 413
✔ honeypot preenchido (finge sucesso) → 200
✔ injeção "<img src=x onerror=alert(1)>" → 400
✔ armadilha /.git/config → 404
✔ limite por IP → 429
$ curl -s -o /dev/null -w '%{http_code}\n' localhost:8788/.env
404
[SEG:varredura] aviso rota=/.env
$ curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' localhost:8788/admin
302 http://localhost:8788/login
$ curl -s -o /dev/null -w '%{http_code}\n' -X POST localhost:8788/login -d 'usuario=admin&senha=admin123'
401 # sempre, depois de 1,1 s; a tentativa vai para a tabela honeypot
$ curl -sI localhost:8788/ | grep -iE 'policy|frame'
content-security-policy: default-src 'self'; script-src 'self' https://challenges.cloudflare.com …; object-src 'none'; frame-ancestors 'none'; report-uri /api/csp
permissions-policy: camera=(), microphone=(), geolocation=(), payment=(), usb=()…
referrer-policy: strict-origin-when-cross-origin
x-frame-options: DENY

© 2026 NODE. All rights reserved.