All case studies
~/cases/plantao-ga
Platforms & CRMsOther sectorsApr 2026 → May 2026In production

P-14

Plantão Gaúcho

A news portal with a newsroom panel, a curated front page and proper WhatsApp previews.

clientRegional news portal in Rio Grande do Sul, southern Brazil

A regional news portal with an admin panel for a non-technical newsroom: rich-text editor, in-browser image compression, drag-and-drop front-page curation and a newsletter. A React SPA on Supabase with every access rule in Row Level Security, plus a Cloudflare Worker on the domain that serves Open Graph to preview bots so links shared on WhatsApp show a photo and headline.

15
RLS policies
1 + 1
edge functions + workers
4 public · 7 admin
routes
Apr 10 → May 14, 2026
timeframe
  • react
  • supabase
  • postgres
  • rls
  • cloudflare
architecture.en.svgenlarge ↓

01Overview

Plantão Gaúcho is a news portal covering the state of Rio Grande do Sul, in southern Brazil: a front page with a lead story and highlights picked by the editors, a breaking-news ticker, sections (Politics, Economy, Brazil, World, Countryside, Culture, Health, Public Safety, Opinion and more), search, an article page with share buttons, and a newsletter sign-up.

Behind the public site sits a full admin panel for the newsroom: a rich-text editor, image uploads that compress themselves in the browser, draft/published/hidden states, drag-and-drop front-page curation, site settings (SEO, footer, social links) and the newsletter subscriber list with CSV export.

It went from the first layout to a database-backed portal with an admin panel and proper WhatsApp link previews in about five weeks (April to May 2026).

02The problem

A regional outlet needed its own portal, easy for a small newsroom to run, without leaning on a generic CMS. Three constraints shaped the build:

  • The people publishing aren't technical. Editors must write, upload a photo, pick the lead story and publish on their own, often from a phone.
  • Distribution happens on WhatsApp and social media. If a shared link doesn't show a photo and a headline, nobody taps it. A React SPA alone can't fix that: preview bots don't run JavaScript.
  • Photos come straight off the camera at 10–20 MB, above the roughly 5 MB WhatsApp accepts for a preview.

03The solution

Public portal

  • A front page with one lead story and two secondary highlights chosen by the editors, backed by a fallback chain (explicit slot → story flagged as featured → most recent) so the page is never empty.
  • A horizontal latest-news ticker that pauses on hover.
  • 11 browsable sections (10 real ones plus a virtual "Latest" view), per-section pages, and search over title, subtitle and section.
  • Article pages with reading time, related stories from the same section (or the latest ones as a fallback) and WhatsApp, Facebook and X share buttons that use the portal's clean URL.
  • A newsletter popup after 10 seconds on the first visit, with validation and a Brazilian phone mask; a cookie notice.

Newsroom panel (/admin)

  • Dashboard with published, draft and hidden counts.
  • Article list with filters, status and featured toggles, and deletion.
  • Article form with a TipTap editor (bold, italics, lists, quotes, links, inline images), editable slug, author, tags, image caption and front-page slot.
  • Drag-and-drop (dnd-kit) ordering of the secondary highlights.
  • Per-section article counts, site settings, and newsletter management with search and CSV export (BOM-prefixed so it opens cleanly in Excel).
  • A "you're viewing the site as an admin" bar when browsing the portal while signed in.

Social link previews

  • A Cloudflare Worker on the domain's /artigo/* route serves Open Graph HTML to preview bots and passes human requests through untouched.
  • No custom backend between browser and database: 15 RLS policies across 4 tables decide who reads and who writes.
  • Roles live in a table with no write policy: nobody can promote themselves to admin through the public API.
  • Drafts don't leak: knowing an unpublished story's slug returns nothing to non-admins.
  • A Cloudflare Worker on the domain serves Open Graph to preview bots and passes human readers through untouched.
  • 10–20 MB camera photos are resized in the browser (1600 px, JPEG 0.82) before upload.
  • Unique slugs generated by a Postgres trigger, with unaccent and respect for manual edits.

04Architecture

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

Components

  • Clients: Reader<br>public portal (SPA), Newsroom<br>/admin panel, Preview crawlers<br>WhatsApp · Facebook · X
  • Cloudflare (portal domain): og-meta Worker<br>route /artigo/*<br>detects crawlers by User-Agent
  • PostgreSQL · RLS on 4 tables · 15 policies: articles<br>slug · status · hero_slot, user_roles<br>has_role() SECURITY DEFINER, site_settings, newsletter_subscribers
  • Supabase: Auth<br>email + password, PostgREST<br>anon key + JWT, og-meta Edge Function<br>(Deno), PG, Storage<br>article-images bucket

Connections

  • Reader<br>public portal (SPA) → og-meta Worker<br>route /artigo/*<br>detects crawlers by User-Agent
  • Preview crawlers<br>WhatsApp · Facebook · X → og-meta Worker<br>route /artigo/*<br>detects crawlers by User-Agent
  • og-meta Worker<br>route /artigo/*<br>detects crawlers by User-Agent → Static SPA<br>React 18 + Vite<br>React Query · TipTap (human: pass through)
  • og-meta Worker<br>route /artigo/*<br>detects crawlers by User-Agent → PostgREST<br>anon key + JWT (crawler: HTML with OG)
  • og-meta Worker<br>route /artigo/*<br>detects crawlers by User-Agent → Image proxy<br>1200×630 JPEG q80 (og:image)
  • Newsroom<br>/admin panel → Static SPA<br>React 18 + Vite<br>React Query · TipTap
  • Static SPA<br>React 18 + Vite<br>React Query · TipTap → Auth<br>email + password
  • Static SPA<br>React 18 + Vite<br>React Query · TipTap → PostgREST<br>anon key + JWT
  • Static SPA<br>React 18 + Vite<br>React Query · TipTap → Storage<br>article-images bucket (compressed in-browser upload)
  • PostgREST<br>anon key + JWT → PG
  • og-meta Edge Function<br>(Deno) → PostgREST<br>anon key + JWT
  • articles<br>slug · status · hero_slot → user_roles<br>has_role() SECURITY DEFINER (policies call)

The app is a static SPA that talks to Supabase directly with the public (anon) key. There's no custom backend between the browser and the database: every access rule lives in Postgres as Row Level Security. The only hand-written server code runs at the edge: the Cloudflare Worker that handles link previews.

05Under the hood

Backend and data
  • 4 tables across 7 migrations: articles, user_roles, site_settings and newsletter_subscribers, plus the article-images Storage bucket.
  • Enums for role (app_role) and article status (published, draft, hidden) instead of free text.
  • Slugs generated in the database. generate_slug runs unaccent, normalizes to [a-z0-9-] and appends a numeric suffix until the value is free. A BEFORE INSERT OR UPDATE trigger sets the slug on creation and regenerates it when the title changes, unless an editor set it by hand. The column is NOT NULL and UNIQUE; the migration that added it backfilled existing articles before applying the constraints.
  • Front-page curation in the schema. hero_slot only accepts main or secondary (CHECK) and hero_order sets the order; two partial indexes (WHERE hero_slot IS NOT NULL) serve the front-page queries without indexing the rest of the table. An idempotent seed migration filled the front page from featured stories, without touching anything if editors had already made picks.
  • Trigger-maintained updated_at on articles and site_settings.
  • Key/value settings (site_settings): SEO title and description, Analytics ID, footer copy and social links, editable from the panel without a deploy.
  • og-meta Edge Function (Deno): the first version of link previews, serving Open Graph HTML to bots and redirecting humans to the portal URL.
Frontend
  • React 18 + Vite + TypeScript, Tailwind CSS and shadcn/ui (Radix) components, Lucide icons.
  • TanStack React Query for all data access with a 5-minute staleTime, so moving between front page, section and article reuses the cache instead of refetching.
  • Routes: 4 public (/, /artigo/:slug, /categoria/:slug, /busca), a login page and 7 panel routes behind ProtectedRoute.
  • TipTap editor with inline image uploads straight to Storage under random file names (inline/<timestamp>-<random>; cover images use crypto.randomUUID()).
  • In-browser image compression before upload: max width 1600 px, JPEG at quality 0.82, skipping files that are already small (≤ 400 KB and within the width) and keeping the original whenever the compressed version isn't smaller. SVG and GIF pass through untouched.
  • Zod-validated newsletter form (name, email and city length; phone 10–20 characters of digits and ()+-) with a Brazilian phone mask.
  • Front-page ordering with dnd-kit, persisting each item's hero_order.
Infrastructure and deploy
  • Frontend: a static Vite build served by an SPA hosting platform, with the portal's domain behind Cloudflare.
  • og-meta Cloudflare Worker on two routes (domain/artigo/* and www.domain/artigo/*). For bots it fetches the article from PostgREST with a 300 s cf.cacheTtl and replies with Cache-Control: public, max-age=300 and an X-OG-Worker: hit header (or fallback on error). For humans it forwards the request to the SPA origin unchanged.
  • Supabase for Postgres, Auth, Storage and the Edge Function (verify_jwt = false on that one only, since bots don't send tokens).
  • Step-by-step Worker runbook in the repo (routes, testing with curl -A "WhatsApp/2.0", rollback by deleting the routes) so the client's team can operate it without the developer.

06Security

6 attacks considered, 6 defenses in production.

attackdefense
API shortcut

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

  • Read drafts or hidden stories by guessing the slug or querying the API

    The public policy only allows status = 'published'; anything else requires has_role(auth.uid(), 'admin')

Privilege escalation

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

  • Call the API with the public key and insert yourself as admin in user_roles

    user_roles only has a SELECT-own-row policy; INSERT/UPDATE/DELETE are denied by RLS

  • Publish, edit or delete stories and images with a regular account

    Every write on articles, site_settings and the bucket checks a SECURITY DEFINER has_role() with a pinned search_path

Forged origin and requests

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

  • Abuse the Edge Function redirect as an open redirect

    The target is always the portal's fixed URL + /artigo/<slug>; there is no destination parameter

Injection and hostile content

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

  • Inject HTML/script into the bot-facing preview through a title or subtitle

    The Worker and Edge Function escape & < > " ' and strip tags from the body before building the HTML

Data leakage and tracking

Enumerating who is in the base, scraping personal data, tying questions to people, extracting secrets.

  • Dump the newsletter list (name, email, phone, city)

    Write-only table for the public: SELECT and DELETE are admin-only

The design starts from one assumption: the anon key ships in the browser bundle, and anyone can call the Supabase API directly. So no rule depends on the frontend; the database is what counts.

Authentication

  • Newsroom login with email and password on Supabase Auth, with a single error message ("wrong email or password") that doesn't reveal whether the account exists.
  • There's no sign-up screen: accounts are created by the administrators, and having an account isn't enough to reach the panel.

Authorization and RLS

  • RLS enabled on all 4 tables, 15 policies in total (Storage included).
  • Roles in a dedicated table (user_roles), not a profile column the user can edit. It only has a SELECT policy for the user's own rows; there are no INSERT, UPDATE or DELETE policies, so nobody can promote themselves to admin through the API.
  • has_role() as SECURITY DEFINER with a pinned search_path, used by every write policy. That avoids RLS recursion and prevents function hijacking through a malicious schema on the search path.
  • Drafts and hidden articles don't leak. The public can only read status = 'published'. Knowing a draft's slug doesn't help: the query comes back empty for non-admins. Editors can preview unpublished stories because the admin policy allows the read, not because the frontend hides something.
  • Admin-only writes on articles, site_settings and the image bucket (INSERT, UPDATE and DELETE all check has_role(auth.uid(), 'admin')).
  • Write-only newsletter for the public. Any visitor can subscribe (INSERT), but listing and deleting subscribers requires the admin role. The anon key can't read any personal data.
  • Client-side role check fails closed. If the role query errors out, the panel treats the user as a non-admin.

Public edge surface

  • The Worker and the Edge Function only use the anon key, bound by the same policies: they can only read published articles and hold no service credential.
  • Every database value is escaped (& < > " ') before going into the Open Graph HTML; article bodies are stripped to plain text before becoming a description.
  • The Edge Function always redirects humans to the portal's fixed URL built from the slug: there's no destination parameter to abuse as an open redirect.

Validation and personal data

  • Zod validation with length limits on the newsletter form; email lower-cased and UNIQUE in the database, with error 23505 handled as "you're already subscribed" rather than a failure.
  • Integrity enforced in the schema: enums, NOT NULL, UNIQUE on slug and email, CHECK on hero_slot.

07Technical challenges

Link previews for an SPA

WhatsApp and Facebook bots don't execute JavaScript, so every article showed the generic title and image from index.html. The first fix was an Edge Function serving Open Graph HTML, but it meant sharing links on the Supabase domain. The final version is a Worker on the portal's own domain, scoped to /artigo/*: it spots bots by User-Agent (21 patterns), fetches the published article from PostgREST with a 5-minute edge cache, escapes everything and returns minimal HTML. Human readers get the SPA untouched, and any error yields a generic preview rather than a broken share. The shared URL stays the portal's own.

Camera photos above WhatsApp's limit

10–20 MB photos produced previews with no image. The fix has two layers: on upload, the browser resizes to at most 1600 px and re-encodes as JPEG 0.82, so new photos land in Storage already light; in the Worker, og:image goes through an image proxy that serves 1200×630 JPEG q80, which also covers older articles without reprocessing anything.

Curated front page with fallbacks

Editors wanted to pick the lead and highlights, but the page couldn't break when nobody picked. The answer combines schema (hero_slot with CHECK, hero_order, partial indexes), a seed migration that only acts when no slot is set, and a query with a fallback chain that tops up the secondary highlights with the latest stories that have an image, never repeating the lead.

Session race and a blank login screen

The panel had a race between restoring the saved session and Auth's initial event, and on a flaky network loading could hang. The auth provider now restores the session first, ignores the already-handled INITIAL_SESSION event, drops responses after unmount, treats a failed role check as "not admin", and releases the loading state after 8 seconds in the worst case.

08Results

  • Portal and panel delivered in about 5 weeks: the first code commit is from April 10, 2026, the last from May 14, 2026.
  • 220 commits (145 excluding merges), 202 of them in April 2026.
  • 7 migrations, 4 tables, 15 RLS policies, 1 Edge Function and 1 Cloudflare Worker.
  • About 4,770 lines of hand-written code (non-blank, excluding generated shadcn/ui components and generated database types): 3,429 TSX, 712 TS, 296 SQL, 187 JS and 145 CSS.
220
commits
how we measured

git log --oneline | wc -l (145 excluding merges)

Apr 10 → May 14, 2026
timeframe
how we measured

dates of the first and last code commits in git log (excluding the template and README commits)

7
migrations
how we measured

ls supabase/migrations

4
tables
how we measured

CREATE TABLE in the migrations

15
RLS policies
how we measured

grep -c 'CREATE POLICY' in the migrations (includes 4 for Storage)

1 + 1
edge functions + workers
how we measured

supabase/functions/og-meta and cloudflare-worker/og-meta-worker.js

4 public · 7 admin
routes
how we measured

src/App.tsx

~4.8k
lines of code
how we measured

non-empty lines in src, supabase and cloudflare-worker, excluding generated shadcn/ui and types.ts (TSX 3,429, TS 712, SQL 296, JS 187, CSS 145)

09Timeline

  1. 10 Apr 2026

    Base layout with sticky header, front page, feed, ticker, footer and article page on mock data

  2. 13 Apr 2026

    Supabase database with RLS, admin panel, TipTap editor and Postgres-generated slugs

  3. 16 Apr 2026

    Reading suggestions, per-section counts and cookie notice

  4. 17 Apr 2026

    Front-page curation with lead story, highlights and drag-and-drop ordering

  5. Apr 2026

    Apr 20–24: dynamic Open Graph, first through an Edge Function, then a Cloudflare Worker on the domain

  6. 04 May 2026

    In-browser image compression and resizing, plus an image proxy for previews

  7. 06 May 2026

    Newsletter with a subscriber panel and CSV export

  8. 14 May 2026

    Fix for a session race that left the login screen blank

10Stack

Frontend
  • React 18
  • TypeScript
  • Vite 5
  • Tailwind CSS 3
  • shadcn/ui
  • TanStack React Query
  • TipTap 3
  • dnd-kit
  • Zod
Backend
  • Supabase Auth
  • PostgREST
  • Supabase Edge Functions (Deno)
  • Supabase Storage
Data
  • PostgreSQL
  • Row Level Security
  • PL/pgSQL
  • Triggers
  • unaccent
Infra
  • Cloudflare Workers
  • Cloudflare Worker Routes
  • Hospedagem estática de SPA
Security
  • RLS em todas as tabelas
  • Papéis em tabela própria
  • SECURITY DEFINER com search_path fixo
  • Escape de HTML na borda
  • Validação com Zod

11Tech sheet

node@plantao-ga: ~/cases/plantao-ga
node@plantao-ga ─────────────
type
news portal + newsroom panel
stack
React 18 · Vite · Supabase
db
Postgres · 4 tables · 15 policies
auth
Supabase Auth + user_roles
edge
Cloudflare Worker (Open Graph)
deploy
static SPA + Cloudflare
modules
front page · sections · search · editor · newsletter
status
in production
$ ls supabase/migrations | wc -l && cat supabase/migrations/*.sql | grep -c 'CREATE POLICY'
7
15
$ curl -s "$SUPABASE_URL/rest/v1/newsletter_subscribers?select=email" -H "apikey: $ANON_KEY"
[]
# anon pode se inscrever, mas não lê ninguém
$ curl -s -X POST "$SUPABASE_URL/rest/v1/user_roles" -H "apikey: $ANON_KEY" -H "Authorization: Bearer $USER_JWT" -d '{"user_id":"<meu-id>","role":"admin"}'
{"code":"42501","message":"new row violates row-level security policy for table \"user_roles\""}
$ curl -sI -A "WhatsApp/2.0" https://portal.example/artigo/<slug> | grep -i -E 'x-og-worker|cache-control'
cache-control: public, max-age=300, s-maxage=300
x-og-worker: hit

© 2026 NODE. All rights reserved.