P-04
Direto ao Ponto
An AI assistant that only answers with a source, with spend capped at four layers.
A free public chat that explains a constitutional change to working hours in Brazil. Answers come from 37 fact sheets reviewed in git, with mandatory citations and the legal status of each rule. The site and API run on one Cloudflare Worker, backed by Supabase with RLS on every table, atomic Postgres quotas and an admin panel that runs everything without a deploy.
- cloudflare
- supabase
- postgres
- rls
- rag
- llm
- streaming
- astro
- rate-limiting
- lgpd
01Overview
Direto ao Ponto ("Straight to the Point") is a free public platform that explains, in plain Portuguese, the end of Brazil's 6-on-1-off work schedule (the "6x1") and the transition to a shorter working week. Its centerpiece is an AI chat. You say whether you're a worker, an employer or just curious, ask your question, and get a short answer that cites an official source for every claim. Each answer also states clearly what is already in force, what has passed but isn't in effect yet, and what still depends on collective bargaining or future regulation.
The chat sits next to a calculator ("What changes for me?") that does its math in deterministic code rather than through the AI, a timeline of the legislative process and a page that explains the editorial method. The same chat can also be dropped into other websites as a single JavaScript file.
The backend was built for a service that is open to the whole internet. Every answer is limited to a curated knowledge base, AI spend has a ceiling at four separate layers, and a small team runs everything from an admin panel with no redeploys.
02The problem
- Changes to labor law set off a wave of practical questions ("will my pay go down?", "when does it start?", "does it cover domestic workers?"). Meanwhile the information that circulates mixes the approved text with alternative proposals, projections and opinion.
- A generic chatbot makes this worse. It invents deadlines, rounds numbers and presents rules that are still phasing in as if they were already law.
- A public AI chat is also a target: anyone can fire off thousands of questions and turn curiosity into an invoice.
- The team had to update content as events unfolded (the amendment was enacted and published during development) without rewriting the system.
03The solution
- Knowledge base versioned in git: 37 Markdown fact sheets, one fact each. Every sheet carries a status (in force, approved, scheduled, depends on bargaining, under debate, estimate), sources and a last-updated date, and 47 sources are cataloged. A build step validates everything and fails on a missing status or a reference to an unknown source.
- Mandatory citations: the model cites sheets by ID (
[[salario-mantido]]) and the frontend turns each ID into a numbered reference linked to its source. The model never writes links. Every link comes from the knowledge base. - Rich answers: the model writes lean Markdown plus blocks (
:::cards,:::numeros,:::linha-do-tempo,:::estudo,:::atencao…). A custom parser that tolerates incomplete input turns them into components while the answer streams. - Profiles (worker, employer, just curious) change the angle of the answer without breaking the prompt cache.
- Demo mode: with no AI key, or with the panel switch on, the chat assembles answers from the knowledge base through keyword matching, at no cost.
- Calculator for days off, weekly hours and hourly pay, all computed in deterministic code.
- Embeddable widget:
npm run widgetproduces a single.jsfile (Preact plus the public knowledge base, about 25 KB gzipped per the README) that any site mounts on a<div data-chat-6x1>. - Admin panel with six tabs: AI account balance, usage and cost, conversations, feedback, operations (model, kill switch, demo mode, RAG, quotas, answer length) and admin management.
- RAG built, measured and switched off on purpose: hybrid search on pgvector is one click away. It stays off while the whole knowledge base still fits in the cached prompt.
- Locked-down database: RLS on every table, anon/authenticated grants revoked, 9 admin-only policies
- Spend capped at four layers: native rate limit, atomic fail-closed daily quota in Postgres, credit-limited key and a panel kill switch
- A ~25k-token prompt kept byte-for-byte stable for caching: US$0.0006–0.0011 per answer measured in production
- Mandatory citations: the model never writes links; every link comes from fact sheets versioned in git
- Hybrid RAG (pgvector + FTS + RRF) measured at 22/22 recall and deliberately left off
- Admin revocation takes effect immediately: the Worker re-checks the current role on every request, not just the JWT




04Architecture
Read the diagram as a list (14 components, 16 connections)
Components
- Clients: Browser<br>Astro + Preact site, Embedded widget<br>partner sites, CORS allowlist, /admin panel<br>email OTP login
- Cloudflare Worker: site + API on the same origin: Static assets<br>Astro dist/, /api/chat · /api/feedback<br>/api/saude · /api/admin/*, Native rate limit<br>20 questions/min per IP hash, kb.json bundled at build<br>37 fact sheets + cacheable prompt, Hourly cron<br>balance + alert, Workers AI<br>bge-m3 embeddings
- Supabase: Postgres + pgvector + pg_cron<br>RLS on every table, consumir_cota()<br>daily quota per person and global, Supabase Auth<br>closed signup · app_metadata.role
Connections
- Browser<br>Astro + Preact site → Static assets<br>Astro dist/
- Browser<br>Astro + Preact site → /api/chat · /api/feedback<br>/api/saude · /api/admin/* (POST, streamed text)
- Embedded widget<br>partner sites, CORS allowlist → /api/chat · /api/feedback<br>/api/saude · /api/admin/* (POST, streamed text)
- /admin panel<br>email OTP login → /api/chat · /api/feedback<br>/api/saude · /api/admin/* (JWT Bearer)
- /admin panel<br>email OTP login → Postgres + pgvector + pg_cron<br>RLS on every table (reads via PostgREST + RLS)
- /api/chat · /api/feedback<br>/api/saude · /api/admin/* → Native rate limit<br>20 questions/min per IP hash
- Native rate limit<br>20 questions/min per IP hash → consumir_cota()<br>daily quota per person and global
- /api/chat · /api/feedback<br>/api/saude · /api/admin/* → kb.json bundled at build<br>37 fact sheets + cacheable prompt
- /api/chat · /api/feedback<br>/api/saude · /api/admin/* → Workers AI<br>bge-m3 embeddings (optional RAG mode)
- /api/chat · /api/feedback<br>/api/saude · /api/admin/* → Postgres + pgvector + pg_cron<br>RLS on every table (secret key)
- /api/chat · /api/feedback<br>/api/saude · /api/admin/* → OpenRouter<br>Claude Haiku with prompt cache (SSE)
- /api/chat · /api/feedback<br>/api/saude · /api/admin/* → Supabase Auth<br>closed signup · app_metadata.role (getClaims + current role)
- Hourly cron<br>balance + alert → OpenRouter<br>Claude Haiku with prompt cache (/credits)
- Hourly cron<br>balance + alert → Postgres + pgvector + pg_cron<br>RLS on every table
- kb/ in git<br>editorial source of truth → kb.json bundled at build<br>37 fact sheets + cacheable prompt (build-kb)
- kb/ in git<br>editorial source of truth → Postgres + pgvector + pg_cron<br>RLS on every table (sincronizar-kb: embeddings only for what changed)
The design rests on three decisions:
- Site and API share one Worker.
run_worker_first = ["/api/*"]serves pages straight from the asset cache and runs code only for the API. Because the main site is same-origin, it needs no CORS. - The prompt comes from the build, not the database. The Worker ships the same
kb.jsonthe site uses to render citations, so the model never sees a sheet the frontend can't resolve. The database holds a copy for search, metrics, quotas and configuration. - Git is the source of truth and the database is a copy. Editorial content is never edited in Postgres. The sync script re-embeds only the sheets that changed.
05Under the hood
- TypeScript Cloudflare Worker (
src/worker/, 16 modules): routing, chat, quotas, validation, feedback, admin, admin management, model catalog, an OpenRouter client with a custom SSE parser, RAG and balance collection. - 12 API routes: 4 public (
/api/chat,/api/feedback,/api/saude,/api/config-publica) and 8 admin (/api/admin/eu,openrouter,saldo/coletar,config,modelos,adminsGET/POST,admins/remover). - End-to-end streaming: the Worker consumes OpenRouter's SSE and re-emits plain text through a
TransformStream. Each conversation is logged insidectx.waitUntilonce the response has gone out: tokens, cache hits, real cost, latency, cited vs. retrieved sheets and stop reason. - Supabase Postgres: 6 migrations, 8 tables, 4
security_invokerviews and 3pg_cronretention jobs. - Hybrid RAG:
vector(1024)with a cosine HNSW index, a Portuguesetsvectorwith a GIN index, and abuscar_fichasfunction that merges both rankings with Reciprocal Rank Fusion. Embeddings come from the multilingual@cf/baai/bge-m3model through the Workers AI binding, so there is no extra vendor. Each query uses the last two user questions so follow-ups still retrieve the right sheets. - Live configuration: a
configjsonb table holds the model, the kill switch, quotas and limits. Each isolate caches it for 30 s, so a panel change reaches every server within 30 seconds without a deploy. - Prompt caching: the instructions and every sheet form a stable
systemblock markedcache_control: ephemeral, with the provider pinned to Anthropic (allow_fallbacks: false). Date, profile and origin are appended to the last user message and never to the system prompt, so the cache stays intact.
- Astro 7 + Preact 11: static pages (home with chat, calculator, timeline, method, 404, admin) with interactive islands.
- Streaming answer parser (
src/lib/formato.ts, unit-tested) that interprets Markdown and blocks as tokens arrive and tolerates broken syntax. Everything renders as JSX; the codebase has noinnerHTMLordangerouslySetInnerHTML. - Custom design system with tokens, View Transitions between pages and motion that respects
prefers-reduced-motion. - Admin panel in Preact. It authenticates with Supabase Auth (8-digit email OTP), reads data directly through PostgREST under RLS and writes only through the Worker.
- Widget (
src/widget/) bundled as a single file. The host site owns the styling (cx-*classes); the script only emits markup.
- Cloudflare Workers with static assets, the Rate Limiting and Workers AI bindings, an hourly Cron Trigger,
version_metadata(the version shows up in/api/saude) and observability enabled. - Managed Supabase (São Paulo region) with pgvector and pg_cron. The full stack also runs locally through
supabase start(Docker), with Mailpit catching login emails. - Deploy pipeline:
supabase db push→ knowledge-base sync →wrangler deploy→ HTTP contract test against production. The docs spell out the order for adding versus removing sheets, because the frontend only resolves citations that were in its build. - Three levels of rollback:
wrangler rollbackfor the Worker, demo mode or the kill switch for the chat alone, and additive migrations with documented undo steps. - OpenRouter simulator (
scripts/testes/mock-openrouter.mjs) for exercising AI mode locally, including 402, 429 and 5xx errors, without spending anything.
06Security
8 attacks considered, 8 defenses in production.
Skipping the interface to talk straight to the database or API with the public key in hand.
Read conversations or feedback straight from the database API using the public key
RLS on every table with anon/authenticated grants revoked; only admins (app_metadata.role) can read, and a script tests the access matrix
Someone with some access trying to get more: becoming admin, reading what they shouldn't, keeping revoked access.
Keep using the panel after admin access is revoked
Besides verifying the JWT against the JWKS, the Worker re-reads the user's current role on every request; public signup is closed and the role lives only in app_metadata
CSRF, fake webhooks, reused tokens, signed links and open redirects.
Call the chat API from any website
CORS only for an allowlist of embedding origins; the rest of the API is same-origin
XSS, iframes, CSV formulas, disguised uploads and AI prompt manipulation.
Send an oversized payload or a forged history to manipulate the prompt
Body read with a real byte cap (413), questions up to 1,000 chars, a 12-message window, protocol markers stripped, profile and origin allowlisted
Get the model to inject links or HTML into the page
The model cites sheet IDs only; links come from the versioned base and answers render as JSX components, never innerHTML
Blowing up the bill, exhausting quotas, flooding logs and knocking functions down with load.
Fire thousands of questions to run up the AI bill
Native 20/min rate limit, per-person and global daily quotas checked in Postgres before the model is called (fail-closed), a credit-capped key and a kill switch
Enumerating who is in the base, scraping personal data, tying questions to people, extracting secrets.
Trace who asked what from the logs
IPs are never stored: quotas key on sha256(IP + day + salt); the conversation log has no IP or session ID and pg_cron deletes it after 90 days
Fiddling with counts, wiping the base, editing history or denying what was authorized.
A compromised admin writes arbitrary config or a nonexistent model
Typed, range-checked validators on write and again on read; model changes limited to catalog IDs; column-level update grant
Access model: the public never talks to the database.
- RLS is on for every table. The base migration revokes all grants from
anonandauthenticatedand grants access explicitly toservice_rolealone, which only the Worker uses. - Admins are Supabase Auth users with
app_metadata.role = 'admin'.eh_admin()reads the role from the JWT. Only the server writesapp_metadata, neveruser_metadata, which the user can edit. - There are 9 policies, all gated on
eh_admin(): read access on 8 tables, plus update onconfiglimited by a column-level grant tovalor,atualizado_emandatualizado_por. An admin can't rename a config key, insert feedback or delete a knowledge sheet. EXECUTEonconsumir_cotaandbuscar_fichasis revoked frompublic,anonandauthenticated. Every function issecurity invokerwithsearch_path = '', and every view is created withsecurity_invoker = trueso the RLS of the underlying tables still applies.scripts/testes/acesso-banco.shchecks an anonymous × regular user × admin matrix across 12 objects through PostgREST, along with closed signup and RPC access.
Admin authentication.
- Passwordless login uses an 8-digit OTP that expires after 600 s, and public signup is disabled. The login screen shows the same message for any email, so it never reveals who is an admin.
- The Worker verifies the JWT with
auth.getClaims()(ES256 signature checked against the JWKS) and requiresaud = authenticatedand the admin role. Because a token lives up to an hour, the Worker also re-reads the user's current role through the Admin API on every request. Revoking an admin therefore takes effect immediately for everything that goes through the Worker. - Nobody can revoke their own access, and the last admin can't be removed.
Cost and abuse: a ceiling at four layers.
- Cloudflare's native rate limit: 20 questions and 30 feedback posts per minute per person.
- Daily quotas per person (150 by default) and site-wide (5,000) in Postgres. A single atomic statement (
insert … on conflict do update … returning count <= limit) enforces them before the model is called. - A credit limit on the OpenRouter key itself.
- A kill switch and demo mode in the panel, with no deploy needed.
The daily quota fails closed: if the database is down, the chat answers 429 rather than spend without a meter. The per-minute limiter deliberately fails open because the Postgres layer still applies.
Privacy (Brazil's LGPD).
- In the quota tables a "person" is
sha256(IP + day + salt). The IP is never stored, and the key rotates daily. Rotating the salt resets every quota. conversas_logkeeps the question text for 90 days (pg_cron) with no IP, user ID or session ID. Quotas are kept for 30 days and balance snapshots for a year.- The calculator keeps the salary a user types inside the browser.
API validation and hardening.
- Request bodies are read as a stream with a byte cap that doesn't trust
content-lengthalone (50 KB for chat, 16 KB for feedback, 2–4 KB for admin) and return 413 when exceeded. - Chat history is strictly validated: only allowed roles, questions up to 1,000 characters, a 12-message window that always starts with the user, and earlier answers stripped of protocol markers and capped at 4,000 characters. Profile and origin values must be on an allowlist.
- Every config write goes through typed, range-checked validators (
max_tokens500–8000,rag_top_k3–15…). A model change is accepted only if the ID exists in OpenRouter's catalog, and config read back from the database is validated again before use. - CORS on
/api/chatand/api/feedbackis limited to an allowlist of origins that embed the widget. - Headers:
nosniff,X-Frame-Options: DENY,Referrer-Policy, and aPermissions-Policythat blocks camera, microphone and geolocation./adminis served withnoindexandno-store.
Secrets. The OpenRouter key has a credit cap. A separate management key, created with an expiry date, can only read the balance. The Supabase secret key exists only as a Worker secret. Rotation steps are documented for each secret, and wrangler.toml holds only values that are public by design.
Content safety. The model answers only from the knowledge base, under explicit rules on neutrality and on separating fact, projection and opinion. Links come only from the knowledge base, and answers render as components, never as model-supplied HTML. The avaliar.mjs suite (29 cases) checks for the expected citations and for forbidden patterns, including a who-should-I-vote-for question that must be declined.
07Technical challenges
Streaming that arrived all at once
With compression on, both Cloudflare and the local runtime buffered the whole answer, so it appeared fully formed instead of streaming. The fix was to serve /api/chat with cache-control: no-store, no-transform and content-encoding: identity, and to use a custom SSE parser that re-emits plain text.
Predictable cost with a ~25k-token prompt
Sending the whole knowledge base with every question is expensive without caching, and any change to the system prompt invalidates the cache. The prompt is byte-for-byte stable: date, profile and origin go into the last message, and the provider is pinned so caching is guaranteed. Measured production cost was US$0.0006–0.0011 per cached answer, and the panel tracks the cache-hit rate to catch regressions.
Answers cut off by reasoning tokens
Answers with rich blocks (cards, tables, timelines) were being truncated. The conversation log showed stop = length: the model's reasoning tokens count against the same max_tokens budget. The limit became a panel setting, a migration raised it to 6,000, and the log now records reasoning tokens.
RAG: measure before switching it on
The hybrid search was built and evaluated (22/22 recall at top-7 over 22 cases) and then left off. With 37 sheets the whole base fits in the cached prompt, so there is no risk of retrieval missing the right sheet. The evaluation also caught a paraphrase that RRF pushed out of the top 7, which is now documented as a gate before enabling RAG. If search or embedding fails, the Worker falls back to the full base.
08Results
- 16 commits between Oct 15 and Oct 21, 2026, covering the MVP, the Workers backend, the post-enactment content update and the embeddable widget.
- Running in production on Cloudflare, with the model switchable from the panel without a deploy.
- Measured cost of US$0.0006–0.0011 per cached answer (about US$0.0035 when the cache has to be written), per the operations docs dated Oct 15, 2026.
- Hybrid search recall of 22/22 on the evaluation cases (top-7).
- 37 unit tests (answer parser, SSE, validation, publication), plus an HTTP contract test, a quota test and a database access matrix.
- 16
- commits
- Oct 15 → Oct 21, 2026
- timeframe
- 6
- migrations
- 8 / 4
- tables / views
- 9
- RLS policies
- 3
- pg_cron jobs
- 12
- API routes
- 37 / 47
- fact sheets / sources
- 37
- unit tests
- 29
- evaluation cases
- 22/22
- RAG recall (top-7)
- US$ 0.0006–0.0011
- cost per answer
- 5,739
- TS/TSX lines
- 2,603 / 2,067 / 558
- Astro/CSS/SQL lines
how we measured
git log --oneline | wc -l (HEAD 5c317d4)
how we measured
dates of the first and last commit in git log
how we measured
supabase/migrations/ at HEAD
how we measured
create table / create view in the migrations
how we measured
create policy in the migrations (8 admin_le + 1 admin_edita)
how we measured
cron.schedule in 20261015190000_operacao.sql
how we measured
src/worker/index.ts and src/worker/admin.ts (4 public + 8 admin)
how we measured
node scripts/build-kb.mjs --check
how we measured
test()/it() in *.test.ts at commit HEAD
how we measured
CASOS array in scripts/avaliar.mjs
how we measured
docs/backend/RAG.md, measured on 2026-10-15
how we measured
docs/backend/OPERACAO.md, measured in production on 2026-10-15 (with cache)
how we measured
wc -l at HEAD: .ts 2,634 (30 files) + .tsx 3,105 (16), no generated types
how we measured
wc -l at HEAD; SQL from the migrations only
09Timeline
- 15 Oct 2026
MVP: site, chat and knowledge base
- 16 Oct 2026
Cloudflare Workers backend: chat, pgvector RAG, admin panel and operations
- 16 Oct 2026
Knowledge-base source dossier
- 16 Oct 2026
Content updated after the amendment was enacted
- 16 Oct 2026
Rich answers: Markdown and blocks rendered as components
- 16 Oct 2026
Max_tokens raised to 6000 after tracing truncation to reasoning tokens
- 21 Oct 2026
Chat embeddable on partner sites
10Stack
- Astro 7
- Preact 11
- TypeScript
- CSS com tokens
- View Transitions
- Cloudflare Workers
- TypeScript
- SSE streaming
- Cron Triggers
- Rate Limiting binding
- Supabase Postgres
- pgvector (HNSW)
- Full-text search (portuguese)
- pg_cron
- PostgREST
- Cloudflare Workers static assets
- Supabase gerenciado
- Wrangler
- Supabase CLI
- Docker (local)
- Row Level Security
- Supabase Auth OTP
- JWT via JWKS
- Cotas atômicas em Postgres
- IP hasheado com sal diário
- Retenção via pg_cron
- CORS por allowlist
- OpenRouter
- Claude Haiku
- Prompt caching
- Workers AI bge-m3
- RAG híbrido (RRF)
11Tech sheet
- type
- public AI assistant
- stack
- Astro · Preact · CF Workers
- db
- Postgres + pgvector (RLS on all)
- auth
- Supabase OTP · app_metadata.role
- ai
- Claude Haiku · prompt cache · hybrid RAG
- guard
- 4-layer cost cap · fail-closed
- deploy
- wrangler deploy · edge
- status
- in production
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.
A public reporting channel with a triage panel where authorization lives in the database: role-based RLS, contacts only through an audited function, instant session revocation and a bot that saves evidence before it expires.
CRM and website for a computer repair shop: customers, service orders, price tags and storefront, running at the edge with RLS as the final word.
Want a system like this for your operation?
Node designs, builds and protects tailor-made platforms for campaigns, elected officials and movements.

TECHNOLOGY AND POLITICAL INTELLIGENCE
© 2026 NODE. All rights reserved.