All case studies
~/cases/fim-das-bets
Platforms & CRMsNational movementsMay 2026 → todayIn production

P-02

Fim das Bets

The platform that brought content creators into the campaign to end online betting in Brazil: nationwide sign-ups, an inflation-proof public counter and a brute-force-hardened admin panel.

clientNational civil-society campaign to end online betting

Platform for the civil-society campaign that rallied content creators across Brazil to end online betting, a cause that became reality with Provisional Measure 1,394/2026, which banned betting platforms in Brazil in September 2026. Live since May, the platform combines a landing page with a two-step sign-up (personal data, then social profiles), a public counter of people and combined reach, per-state WhatsApp groups, downloadable campaign assets and an admin panel with moderation, geographic BI and exports. TanStack Start with SSR on Cloudflare Workers, Supabase with 45 migrations and 27 RLS policies, and every public form guarded by Turnstile, a honeypot, an origin allowlist and database-backed rate limiting.

27
RLS policies
19
SQL functions
37
server functions
45
migrations
  • react
  • ssr
  • cloudflare
  • supabase
  • postgres
  • rls
  • anti-bot
  • rate-limiting
  • csp
  • lgpd
architecture.en.svgenlarge ↓

01Overview

Fim das Bets is the digital platform behind the campaign that asked content creators across Brazil to lend their reach to the fight against online betting. In September 2026, four months after the platform went live, Provisional Measure 1,394/2026 banned betting in the country, and on October 6 betting platforms went offline. Visitors land on a page that explains the ask, shows a live counter of how many people have joined and how many followers they add up to, and sign up in two steps: personal details first, then their social profiles (Instagram, TikTok, YouTube and X) with follower counts for each.

Once signed up, people get the link to their state's WhatsApp group and access to a page of ready-to-post campaign assets in feed and stories formats. Their data flows into the campaign's organizing CRM, which handles communication from there.

On the other side, the campaign team works in an admin panel: moderating sign-ups, deciding what counts toward the public number, managing state groups and assets, following adoption in a BI dashboard and exporting the base. There are two access levels: admins and operators.

02The problem

The campaign needed three things at once:

  • A fast mobile sign-up that wouldn't lose people who drop off halfway and wouldn't let the same person in twice.
  • A credible public number. The combined-reach counter was the main communication asset, so it couldn't be inflated by bots, duplicates or self-reported follower counts nobody had checked.
  • A protected database. Names, e-mails, WhatsApp numbers and cities of creators from all over Brazil, in a highly visible campaign, are an obvious target. The form and the login had to withstand spam and brute force without a paid WAF.

03The solution

Public side

  • Landing page with a live counter (people and combined reach), refreshed every 60 seconds.
  • Two-step sign-up: personal details with international phone input (including people living abroad), then 1 to 4 social profiles with handle and follower count.
  • After signing up, a link to the state's WhatsApp group; the click is recorded as a tag in the CRM.
  • Assets page with feed and stories pieces, fullscreen preview and download.
  • Terms of use and privacy policy grounded in Brazil's data protection law (LGPD).

Admin panel (/admin)

  • Paginated list (up to 200 per page) with search by name, e-mail, phone and city, filters by state, network, follower band, status and step, and sorting by followers.
  • Moderation: verify, reject, remove from the counter, edit follower band, add notes, create entries manually.
  • BI dashboard: KPIs compared with the previous period, timeline, SVG map of Brazil, state and city rankings, breakdown by follower band and network, a weekday × hour heatmap and top profiles. Filters for state, band, "verified only", "include partial" and "partial only".
  • Paginated CSV export and PNG export of the dashboard.
  • Management of per-state WhatsApp groups and of assets (upload, ordering, activation).
  • Security screen with the latest 200 login attempts and account unlock.
  • User management: admins create, reset passwords for and remove operators.
  • Two-step sign-up that saves the partial record, reuses it when the person comes back and detects cross-tab races on completion
  • Admin login with Turnstile, a honeypot, three rate-limit windows and a 1-hour lockout after 10 failures, applied only to staff accounts
  • BI dashboard backed by 8 SQL functions that return aggregates only and check the caller's role inside the database
  • CRM sync through the OSDI API with a 4 req/s queue and exponential backoff that never blocks the sign-up
  • Public counter served by a function that exposes exactly two numbers: people and combined reach

04Architecture

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

Components

  • Clients: Content creator<br>(mobile), Campaign staff<br>(/admin · admin and operator)
  • Cloudflare: Turnstile<br>anti-bot, Worker · TanStack Start SSR<br>server functions + zod<br>Origin allowlist, /admin headers<br>CSP · HSTS · frame-ancestors none
  • Postgres: influencer_signups<br>partial → complete, signup_attempts<br>admin_login_attempts<br>admin_account_state, 19 SQL functions<br>SECURITY DEFINER + has_role, 27 RLS policies<br>admin · operator
  • Supabase: Auth<br>email and password, PostgREST<br>anon: INSERT and counter only, PG, Storage<br>campaign assets

Connections

  • Content creator<br>(mobile) → Worker · TanStack Start SSR<br>server functions + zod<br>Origin allowlist (step 1 + token)
  • Content creator<br>(mobile) → Turnstile<br>anti-bot
  • Worker · TanStack Start SSR<br>server functions + zod<br>Origin allowlist → Turnstile<br>anti-bot (siteverify)
  • Campaign staff<br>(/admin · admin and operator) → /admin headers<br>CSP · HSTS · frame-ancestors none
  • /admin headers<br>CSP · HSTS · frame-ancestors none → Worker · TanStack Start SSR<br>server functions + zod<br>Origin allowlist
  • Worker · TanStack Start SSR<br>server functions + zod<br>Origin allowlist → Auth<br>email and password (ephemeral login)
  • Worker · TanStack Start SSR<br>server functions + zod<br>Origin allowlist → PostgREST<br>anon: INSERT and counter only (public key)
  • PostgREST<br>anon: INSERT and counter only → influencer_signups<br>partial → complete
  • Worker · TanStack Start SSR<br>server functions + zod<br>Origin allowlist → signup_attempts<br>admin_login_attempts<br>admin_account_state (service role, server only)
  • Worker · TanStack Start SSR<br>server functions + zod<br>Origin allowlist → 19 SQL functions<br>SECURITY DEFINER + has_role (user JWT)
  • 19 SQL functions<br>SECURITY DEFINER + has_role → influencer_signups<br>partial → complete
  • 27 RLS policies<br>admin · operator → influencer_signups<br>partial → complete
  • Worker · TanStack Start SSR<br>server functions + zod<br>Origin allowlist → Storage<br>campaign assets (signed upload URL)
  • Worker · TanStack Start SSR<br>server functions + zod<br>Origin allowlist → Mobilization CRM<br>OSDI API · 4 req/s (best effort + backoff)

The browser never writes to the database directly. Every sign-up, login and admin action goes through a TanStack Start server function running on a Cloudflare Worker, which validates input with zod, checks the origin and only then calls Supabase. The browser's only direct database access is reading the public counter.

05Under the hood

Backend and data
  • 45 migrations, 7 tables, 19 SQL functions and 27 RLS policies, all versioned in supabase/migrations.
  • influencer_signups holds the sign-up: personal data, profiles as jsonb (with a GIN index to find duplicate handles), total followers, primary network, band (nano, micro, mid, macro, mega), moderation flags (verified, rejected, excluded_from_counter) and funnel state (completed, step). Request metadata (IP, user agent, country from the Cloudflare header) is kept alongside for auditing.
  • signup_attempts and admin_login_attempts record every attempt, with success or failure reason, and are what the rate limits count against. E-mails are stored in signup_attempts as SHA-256 hashes.
  • admin_account_state tracks consecutive failures and temporary lockouts for each staff account.
  • user_roles with an app_role enum (admin, operator) and two SECURITY DEFINER functions, has_role() and is_staff(), used inside the policies.
  • BI in the database. The 8 admin_dashboard_* functions compute everything in SQL (in the America/Sao_Paulo time zone, daily series via generate_series, comparison with a previous period of equal length) and take optional filters that default to NULL, so new filters never broke existing callers. A helper, _band_matches, turns follower bands into numeric ranges.
  • Public counter. get_public_counter_stats() is the only function open to anon, and it returns just people and reach. It only counts complete, non-rejected, non-excluded sign-ups that are verified or have up to 115k followers.
  • Auto-verification. A BEFORE INSERT OR UPDATE trigger marks complete sign-ups with up to 115k followers as verified; larger profiles wait for a human check.
  • CRM integration via the OSDI API: each completed sign-up becomes a person with per-network custom fields and tags; clicking the WhatsApp group link adds another tag.
Frontend
  • TanStack Start + React 19 with SSR, file-based routing (10 pages) and TanStack Query for the counter and the panel.
  • Tailwind CSS 4 and shadcn/ui (Radix) components in the panel; the landing page has its own protest-poster identity: Anton and Permanent Marker type, black, red and cream, hard offset shadows and an SVG wave pattern.
  • Per-step client validation, international phone masking and validation (react-phone-number-input), a honeypot and the Turnstile widget.
  • Dashboard with Recharts, an interactive SVG map of Brazil (clicking a state filters by it), animated counters and PNG export via html-to-image.
Infrastructure and deploy
  • Cloudflare Workers with nodejs_compat, configured in wrangler.jsonc. SSR goes through a custom server.ts that catches rendering errors swallowed by h3 and serves a branded error page instead of raw JSON.
  • Supabase for Postgres, Auth and Storage (assets bucket).
  • Bun as package manager, with a 24-hour minimumReleaseAge in bunfig.toml: versions published less than a day ago are never installed, a cheap defense against freshly compromised packages.
  • Secrets (service role, Turnstile secret, CRM token) live only on the server; the client only gets the Supabase URL and public key.

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.

  • Flood the public sign-up with bots

    Turnstile token verified server-side, a hidden honeypot, a zod schema rejecting control characters and a fixed delay on error responses

  • Fire many sign-ups from one IP or reuse the same e-mail

    Rate limiting counted in Postgres: 30 attempts per minute and 5 successes per 10 minutes per IP, 1 success per e-mail hash every 24 hours, all audited in signup_attempts

API shortcut

Skipping the interface to talk straight to the database or API with the public key in hand.

  • Call the dashboard functions directly through the API with the public key

    EXECUTE revoked from anon and PUBLIC; inside each SECURITY DEFINER function, has_role(auth.uid()) stops non-staff callers; results are aggregates only

Accounts and login

Brute force, rogue account creation, password reset and account takeover.

  • Brute-force a staff password

    Turnstile, per-IP, per-e-mail and burst limits, a 1-hour lockout after 10 consecutive failures (staff accounts only, so nobody can lock out a stranger) and a log of every attempt with IP and country

Privilege escalation

Someone with some access trying to get more: becoming admin, reading what they shouldn't, keeping revoked access.

  • An operator trying to create accounts or promote themselves to admin

    User management requires the admin role, checked server-side; user_roles is only written with the service role, and only to create or remove operators

Forged origin and requests

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

  • Post the form from another site (CSRF)

    Every public server function checks the Origin header against an allowlist before anything else

Injection and hostile content

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

  • Frame the admin panel or inject script into it

    /admin routes respond with a strict CSP, frame-ancestors 'none', X-Frame-Options DENY, HSTS with preload, Referrer-Policy no-referrer and noindex

  • Abuse asset uploads to host arbitrary files

    Signed upload URLs issued to staff only, with a MIME allowlist (JPEG, PNG, WebP, MP4, MOV, WebM) and a size cap validated by zod

Public sign-up. Step 1 goes through seven gates, in order: an Origin allowlist, a zod schema (maximum lengths and a regex that rejects <, > and control characters), a honeypot, phone validation (10–11 digits in Brazil, 8–15 abroad), Turnstile verified server-side with the client IP, rate limiting and deduplication. Each rejection is logged in signup_attempts with its reason, and error responses carry a fixed 300 ms delay so attackers don't get a timing oracle. Text fields also go through sanitizeText, which strips control characters and <> and collapses whitespace.

Rate limiting in the database, no extra infrastructure. Limits are counted with count: exact, head: true on signup_attempts, backed by indexes on (ip_address, created_at DESC) and (email_hash, created_at DESC):

  • burst: 30 attempts per minute per IP (30-minute block);
  • window: 5 successful sign-ups per 10 minutes per IP (15 minutes);
  • e-mail: 1 success per 24 hours per hash.

Deduplication. E-mail (case-insensitive), phone and every normalized handle are checked before writing. If the e-mail belongs to a partial sign-up, that record is reused instead of duplicated.

Admin login. Login is a server function, not the SDK in the browser:

  1. Origin allowlist and honeypot;
  2. rate limits per IP (10 in 10 min), per e-mail (5 failures in 10 min) and burst (100 per minute);
  3. Turnstile;
  4. account lock check (is_admin_account_locked);
  5. authentication on an ephemeral Supabase client that never persists a session on the server;
  6. role confirmation (admin or operator) after sign-in;
  7. on failure, record_admin_login_failure bumps the counter and locks the account for 1 hour after 10 consecutive failures.

Lockout only applies to staff accounts, so nobody can lock a stranger out by typing wrong passwords. Every attempt lands in admin_login_attempts with IP, country, user agent and the Turnstile result, and the team sees it on the security screen.

Layered authorization. Every admin server function goes through the requireSupabaseAuth middleware (JWT validated with getClaims) and a server-side assertAdmin. In the database, SECURITY DEFINER functions pin search_path, have EXECUTE revoked from anon and PUBLIC, and repeat the has_role(auth.uid(), 'admin') check on their first line. User management requires the admin role specifically, and user_roles is only written with the service role, to create or remove operators.

RLS. anon can only insert sign-ups within bounds (name up to 120 characters, two-letter state, up to 10 billion followers, rejected and excluded_from_counter forced to false) and log attempts with length-capped fields. Reading and changing sign-ups, inactive assets and groups is restricted to is_staff().

Panel headers. Every /admin/* route responds with a CSP (default-src 'self', scripts only from the app and Turnstile, frame-ancestors 'none', object-src 'none', form-action 'self'), X-Frame-Options DENY, two-year HSTS with preload, Referrer-Policy: no-referrer, a Permissions-Policy turning off camera, microphone and geolocation, COOP same-origin and X-Robots-Tag: noindex.

Uploads. Assets go straight to Storage via signed URLs issued only to staff, with a MIME allowlist and size cap validated on the server.

External integration. The CRM token is read inside the handler and never logged; API errors become generic user-facing messages with no upstream details.

LGPD. Signing up requires accepting terms that describe purpose, sharing and data-subject rights under Law 13.709/2018. E-mails appear in attempt logs only as hashes.

07Technical challenges

A two-step sign-up that neither loses nor duplicates anyone

Splitting the form lowers friction on mobile but creates in-between states. Step 1 saves a partial record (completed = false) and returns its id. If the person comes back with the same e-mail, the partial is updated rather than duplicated; if the e-mail already has a complete sign-up, the step is refused. Completion runs UPDATE ... WHERE id = ? AND completed = false and checks how many rows changed: zero means another tab already finished, and the system treats it as a race rather than a success. Loading the record also tells "doesn't exist" apart from "infrastructure failure", so nobody is sent back to step 1 because of a server error. The panel got a drop-off funnel for free: partials older than a minute become filterable.

Syncing with a CRM that accepts 4 requests per second

Sign-up spikes after a big profile posts can blow past the API limit. The OSDI client keeps a 4 req/s sliding window shared across the isolate, with slot reservation serialized through a promise chain so concurrent calls can't slip past the check together. 429 and 5xx responses are retried with 250, 500 and 1000 ms backoff. Sync is best effort: the sign-up is already saved before the call, so a CRM failure never turns into an error for the person signing up.

A public counter worth trusting

Combined reach is a communication number, and follower counts are self-reported. The rule lives in the database: the counter only adds complete, non-rejected, non-excluded, verified sign-ups; a trigger auto-verifies profiles with up to 115k followers, and anything above that gets a human check. The team can also pull a sign-up out of the counter without rejecting it. The public function returns two numbers and not a single row of the table.

A dashboard that gained filters every week

The BI started with period and state, then picked up follower band, name exclusion, "verified only", "include partial" and "partial only". Each new filter became a defaulted parameter across all 8 functions, so existing calls kept working, and the switch from a manually assigned tier to a band computed from follower count was handled by a single helper function. All the math happens in Postgres; the browser only receives aggregates.

08Results

  • Live since May 2026, supporting the mobilization through the betting ban enacted by Provisional Measure 1,394/2026, signed on September 25, 2026.
  • 1,151 commits between May and October 2026.
  • 45 migrations, 7 tables, 27 RLS policies and 19 SQL functions under version control.
  • 37 server functions, every one with zod input validation.
1,151
commits
how we measured

git log --oneline | wc -l

May–Oct 2026
active period
how we measured

git log: first product commit 2026-05-25, last 2026-10-09

45
migrations
how we measured

ls supabase/migrations | wc -l

7
tables
how we measured

CREATE TABLE in the migrations

27
RLS policies
how we measured

distinct CREATE POLICY names in the migrations

19
SQL functions
how we measured

distinct CREATE OR REPLACE FUNCTION public.* names in the migrations

37
server functions
how we measured

export const ... = createServerFn in src/

11.6k
TS/TSX lines
how we measured

wc -l on tracked .ts/.tsx files, excluding shadcn/ui components and generated routeTree.gen.ts and types.ts

2.8k
SQL lines
how we measured

wc -l on supabase/migrations/*.sql

09Timeline

  1. May 2026

    Landing page and creator sign-up form; database wired up and CRM integration through the OSDI API

  2. Jun 2026

    Admin panel with moderation, per-state groups and manual entry

  3. Jun 2026

    Security pass: Turnstile, honeypot, rate limiting, admin login with lockout and signed-URL uploads

  4. Jun 2026

    BI dashboard with an SVG map of Brazil, city rankings, follower bands and a time-of-day heatmap

  5. Jun 2026

    Sign-up split into two steps, with the drop-off funnel visible in the panel

  6. Aug 2026

    Operator role with restricted access and RLS based on is_staff()

  7. Sep 2026

    Downloadable assets page rebuilt with a fullscreen viewer

  8. Sep 2026

    Provisional Measure 1,394/2026 bans betting in Brazil; betting platforms go offline on October 6

10Stack

Frontend
  • React 19
  • TanStack Start / Router
  • TypeScript 5
  • Tailwind CSS 4
  • shadcn/ui (Radix)
  • TanStack Query
  • react-phone-number-input
  • Recharts
  • html-to-image
Backend
  • TanStack Start server functions
  • zod
  • PL/pgSQL
Data
  • PostgreSQL (Supabase)
  • Row Level Security
  • Supabase Storage
  • unaccent
Infra
  • Cloudflare Workers (wrangler)
  • Vite 7
  • Bun
Security
  • Cloudflare Turnstile
  • Supabase Auth
  • RBAC admin/operador
  • Rate limiting no Postgres
  • Lockout de conta
  • CSP + HSTS no /admin
  • Allowlist de Origin

11Tech sheet

node@fim-das-bets: ~/cases/fim-das-bets
node@fim-das-bets ─────────────
type
civic platform · signup + BI
stack
TanStack Start · React 19 · TS
db
Postgres (Supabase) · 7 tables · 27 policies
auth
Supabase Auth · admin/operator RBAC
edge
Cloudflare Workers · Turnstile
deploy
wrangler · SSR
modules
signup · counter · BI · assets · groups
status
in production
$ supabase db reset
Applying 45 migrations ... ok
7 tables · 27 RLS policies · 19 functions
$ curl -s -X POST "$APP/_serverFn/submitSignupStep1" -H 'Origin: https://outro-site.example' -d @cadastro.json
{"ok":false,"code":"forbidden_origin"}
# tentativa registrada em signup_attempts
$ curl -s -X POST "$SUPABASE_URL/rest/v1/rpc/admin_dashboard_kpis" -H "apikey: $PUBLISHABLE_KEY"
{"code":"42501","message":"permission denied for function admin_dashboard_kpis"}
# EXECUTE revogado de anon; com JWT, has_role() ainda decide
$ for i in $(seq 6); do login_admin --email equipe@example.org --password errada; done
1..5 → {"ok":false,"code":"bad_credentials"}
6 → {"ok":false,"code":"rate_limited_email","retry_after":900}
$ curl -s -X POST "$SUPABASE_URL/rest/v1/rpc/get_public_counter_stats" -H "apikey: $PUBLISHABLE_KEY"
[{"people":…,"reach":…}]
# o único dado que a chave pública lê: dois totais

© 2026 NODE. All rights reserved.