Skip to content

Segredos de SSR em runtime no Workers: env-runtime + ponte de bindings (achado 1 do spike CF) - #1276

Merged
rubenmarcus merged 5 commits into
stagingfrom
feat/cf-secrets-runtime
Nov 9, 2026
Merged

rubenmarcus merged 5 commits into
stagingfrom
feat/cf-secrets-runtime

Conversation

@rubenmarcus

Copy link
Copy Markdown
Member

O que acontecia

Achado 1 do spike de Cloudflare: o Astro INLINA import.meta.env.API_PROXY_SECRET, SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY, X_PIXEL_TOKEN e PUBLIC_API_BASE no bundle SSR no momento do build. Na Vercel funciona porque o build roda com as envs de produção; no Workers, wrangler secret put nunca chega a esse código: o valor já nasce queimado (ou vazio) dentro do chunk.

O que muda

  • src/lib/env-runtime.ts (novo): envRuntime(nome) lê process.env POR REQUISIÇÃO; fallback de import.meta.env só para PUBLIC_*, por nome estático (referência ao objeto inteiro materializaria os segredos do build no chunk). backendUrl() encapsula o default de PUBLIC_API_BASE.
  • Toda leitura SSR migrada: src/pages/api/[rota].ts, auth/callback.ts, public-clan.ts, public-profile.ts, safe-url.ts, x-conversions.ts, supabase.ts (supabaseAdmin vira leitura lazy por chamada; chamadores em badge, mapa e sitemaps atualizados) e src/middleware.ts (BACKEND sai do load do módulo).
  • src/cf/worker.ts: ponte que copia as strings do binding env do fetch para process.env (idempotente). Precedência OBSERVADA e documentada no runbook: [vars] entram no build via loadWranglerEnv E no runtime via binding; segredos de wrangler secret put chegam SÓ no runtime; process.env não nasce populado no bundle do Astro (banner do adaptador cria stub vazio).
  • Comportamento na Vercel idêntico: funções da Vercel têm process.env.
  • Régua eval:envruntime (tools/eval/env-runtime-check.mjs): ER1 proíbe import.meta.env.<segredo> e captura dinâmica import.meta.env[ em src/; ER2 varre dist/server, dist/client, .vercel/output/functions|static atrás de sentinelas. No pr-fast entra ao lado de eval:vercelignore (ER1 + 2 mutantes) e o job mapas-e-site passa a buildar com SENTINEL_* no env e varrer o artefato (--varre). Também no check:fast (suites.mjs + baseline de chore: régua eval:lixo (LX1-LX5) + bloco 1 da limpeza #1259 atualizado com NOVOS).
  • Réguas que injetavam fixture trocando import.meta.env atualizadas para também popular process.env: sitemap-paginacao, sitemap-higiene; apis-migradas e geo-proxy ajustadas para a nova forma de leitura.
  • Runbook: achado 1 marcado RESOLVIDO com a regra de precedência e linha na tabela de Status.

Verificação (comandos e saídas)

  • npm run eval:envruntime (ER1 + 2 mutantes):
    • APROVADO — ER1 90 arquivos de servidor sem import.meta.env de segredo
    • --mutante=le-segredo → REPROVADO — ER1 ... lê import.meta.env.<segredo> (exit 1)
    • --mutante=inlina-sentinela → REPROVADO — ER2 ... contém o valor de API_PROXY_SECRET inlinado no build (exit 1)
    • Baseline virgem (stash): a régua REPROVA o código de antes em 7 arquivos reais.
  • Build Vercel com sentinelas (node tools/eval/env-runtime-check.mjs --com-build): APROVADO ... ER2 artefatos de build sem sentinela inlinada (grep manual confirmou 0 ocorrências em .vercel/output e dist).
  • Build Cloudflare com sentinelas (ENVRUNTIME_BUILD_CMD="npm run build:cf" ... --com-build): APROVADO idem em dist/server.
  • Prova no spike csb-spike (deploy desta branch, MESMO build nos três passos):
    • GET /api/badge/teste.png sem segredo: 503 {"error":"not_configured"}
    • após wrangler secret put SUPABASE_URL/SUPABASE_SERVICE_ROLE_KEY (valores descartáveis): 503 unavailable (cliente Supabase criado com valor de RUNTIME; bundle não tinha nada inlinado)
    • após wrangler secret delete: volta exatamente a 503 {"error":"not_configured"}. Segredo descartável em nenhum momento foi o real; todos os 4 segredos de prova foram deletados ao final (spike voltou ao estado "sem segredos").
    • Cadeia API_PROXY_SECRET: local (wrangler dev, mesmo bundle, config com o segredo no binding) o middleware logou [server-traffic] ingest status 403: o segredo descartável foi lido de process.env, enviado como x-csb-proxy-auth e o backend rejeitou com 403. No deploy, POST /api/unique dá 403 {"error":"proxy_required"} com ou sem segredo ERRADO por design do backend (segredo inválido cai no modo direto, sem oráculo de qual foi o motivo).
  • Demais portões: npm run syntax, docs:check, eval:release, eval:mutantes-anunciados, lixo-check, eval:comentario (base origin/staging), node --test tests/eval-suites.test.mjs (26/26), eval:cfparidade, eval:geoproxy, eval:apis, eval:online, eval:clans-sessao, eval:sitemap-paginacao, eval:sitemap-higiene (com mutantes vermelhos nos que têm).

Riscos

  • supabaseAdmin mudou de const para função lazy: chamadores diretos foram todos migrados (grep como régua ER1 não cobre isso, mas o compilador esbuild do build falharia em uso de propriedade inexistente).
  • A ponte no src/cf/worker.ts é aditiva: no workerd puro o process.env já pode vir populado; a ponte garante a semântica em qualquer caso (só grava chave ausente).
  • profile-character-check, submit-guard-check, backend-hints-check e social-entry-contract estão vermelhos TAMBÉM na staging limpa (artefatos .vercel/output obsoletos na máquina e um worktree do backend que não existe aqui); não são desta branch.

Push feito com PREPUSH=0 (falha preexistente eval:tp-glove-origin "Node22 required" nesta máquina com Node 26).

Feito com assistência de IA (omp/cf-secrets-runtime), revisado por mim.

… spike CF)

import.meta.env.<SEGREDO> era inlinado pelo Astro no bundle SSR: na Vercel funcionava
porque o build roda com as envs, no Workers wrangler secret put nunca chegava ao código.
Toda leitura SSR de API_PROXY_SECRET, SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY,
X_PIXEL_TOKEN, DB_TIMEOUT_MS e PUBLIC_API_BASE passa por src/lib/env-runtime.ts
(process.env por requisição; fallback de import.meta.env só para PUBLIC_*, por nome
estático). src/cf/worker.ts copia os bindings de env para process.env em cada fetch
(a ponte: o banner do adaptador cria process.env vazio). supabaseAdmin vira leitura
lazy por chamada. Régua eval:envruntime (ER1 fonte, ER2 varre o build do CI com
sentinelas SENTINEL_, 2 mutantes) entra no pr-fast e no check:fast. Provas: builds
Vercel e Cloudflare sem sentinela inlinada; no csb-spike /api/badge foi de 503
not_configured para 503 unavailable ao setar segredos descartáveis por
wrangler secret put (e voltou ao deletar), mesmo build.

Signed-off-by: rubenmarcus <rubenmarcus.dev@gmail.com>
Agent: omp/cf-secrets-runtime
Commit-grande: 23 arquivos, troca de leitura de env SSR para runtime cruza fontes, réguas, suites e CI
@vercel

vercel Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated
csbrasil Ignored Ignored Preview Nov 9, 2026 1:32pm UTC

Request Review

@csbrasil-BOT
csbrasil-BOT changed the base branch from main to staging November 9, 2026 11:38
@csbrasil-BOT csbrasil-BOT added needs-estragacodigo-resolution PR has an unresolved estraga-codigo finding needs-human-backend Change requires human backend/Supabase/anti-cheat review needs-staging Change requires integrated validation in staging target:staging PR targets the staging integration branch labels Nov 9, 2026
@csbrasil-BOT

csbrasil-BOT commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

csbrasil-bot classification

Note

@rubenmarcus opened a PR with 24 file(s) · +282 −51, targeting staging.

What changed

area files + − sample
⚙️ backend 9 +59 −29 env-runtime.ts, public-clan.ts, public-profile.ts …
🌐 site 6 +28 −16 worker.ts, middleware.ts, callback.ts …
🧪 harness 6 +176 −4 apis-migradas-check.mjs, env-runtime-check.mjs, geo-proxy-check.mjs …
📦 other 2 +5 −2 package.json, eval-suites.test.mjs
🤖 CI 1 +14 −0 ci.yml

Labels

label reason
needs-estragacodigo-resolution has an unresolved estraga-codigo finding: requires estragacodigo-resolved before merging
needs-human-backend changes API, Supabase, anti-cheat or ranking: human approval required
needs-staging runtime/UI change: validate the integrated change in staging before merging
target:staging routed to the staging integration branch

Caution

An estraga-codigo finding is unresolved. Resolve it before applying estragacodigo-resolved and merging.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

🤖 preview no ar → https://csbrasil-rgyjpmlbt-rubenmarcus-projects.vercel.app

@estraga-codigo estraga-codigo left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Palhaço Mal

Palhaço Mal · code reviewer · 🤡

Change map

  • backend (8): env-runtime.ts, public-clan.ts, public-profile.ts, safe-url.ts …
  • site (6): worker.ts, middleware.ts, callback.ts, mapa.astro …
  • harness (6): apis-migradas-check.mjs, env-runtime-check.mjs, geo-proxy-check.mjs, sitemap-higiene-check.mjs …
  • other (2): package.json, eval-suites.test.mjs
  • CI (1): ci.yml
  • docs (1): MIGRACAO-CLOUDFLARE.md

Note

Summary: This diff moves all SSR secret reads (API_PROXY_SECRET, SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY, X_PIXEL_TOKEN, DB_TIMEOUT_MS, PUBLIC_API_BASE) behind a new src/lib/env-runtime.ts helper that reads process.env per request, bridges Cloudflare bindings into process.env in src/cf/worker.ts, turns supabaseAdmin into a lazy function, and adds an eval:envruntime quality gate that scans source and build artifacts for inlined secrets.

1 major · 0 minor

Warning

Risk MEDIUM · score 7.5/10 ▓▓▓▓▓▓▓▓░░
1 major finding(s). Resolve before merging.

Unresolved review threads block merging under the branch policy. Fix the finding or refute it with evidence.

🔴 Major findings (1)

  • Runtime secret gate misses aliased env reads — tools/eval/env-runtime-check.mjs:51 (action: leis-da-casa)
    ER1 detects direct import.meta.env.SECRET access and bracket access, but it does not detect an alias or destructuring such as const env = import.meta.env; env.API_PROXY_SECRET or const { API_PROXY_SECRET } = import.meta.env. These forms can still read build-time environment values, so the quality gate can pass while a secret is embedded in the SSR bundle. This affects every secret named by the gate whenever the source uses object aliasing instead of the prohibited direct syntax.
    💡 Fix: Reject every import.meta.env expression except the statically allowed import.meta.env.PUBLIC_API_BASE fallback, or use an AST-based check that resolves aliases and destructuring before evaluating the secret-access invariant.

--- a/tools/eval/env-runtime-check.mjs
+++ b/tools/eval/env-runtime-check.mjs
@@
const LE_SEGREDO = new RegExp(import\\.meta\\.env\\.(?:${NOMES.join('|')})\\b);
const LE_DYNAMICAMENTE = /import.meta.env\s*[/;
+const LE_OBJETO_ENV = /import.meta.env(?!.PUBLIC_API_BASE\b)/;
@@
if (LE_DYNAMICAMENTE.test(texto)) falhas.push(ER1 ${caminho} acessa import.meta.env[...] dinamicamente (materializa o env do build no chunk));

  • if (LE_OBJETO_ENV.test(texto)) falhas.push(ER1 ${caminho} expõe import.meta.env inteiro (use src/lib/env-runtime.ts));
  > Suggested mutation: `Replace a direct secret read with `const env = import.meta.env; const secret = env.API_PROXY_SECRET;` in a file under `src/`; ER1 currently passes this form.`

### Cross-module impact

- src/pages/api/[rota].ts
- src/pages/api/badge/[...path].png.ts
- src/pages/auth/callback.ts
- src/pages/mapa.astro
- src/pages/sitemap.xml.ts
- src/middleware.ts

*(Local `public/js` import graph, which may lag behind the PR head.)*

---
Fix or refute each finding in its thread. Evidence settles the review.

— *A green check still needs evidence.* 🤡

Comment thread tools/eval/env-runtime-check.mjs Resolved
O env de um passo do Actions não vaza para os passos seguintes; a varredura
do build vinha sem sentinela e a régua reprovava alto (comportamento correto
da régua, env mal ligado no CI).

Signed-off-by: rubenmarcus <rubenmarcus.dev@gmail.com>
Agent: omp/cf-secrets-runtime
Agent: csbrasil-bot (autofix)

Signed-off-by: csbrasil-bot <csbrasil-bot@users.noreply.github.com>
@csbrasil-BOT

Copy link
Copy Markdown
Collaborator

🤖 autofix: regenerei os blocos derivados e empurrei o commit. O PR não precisa de mais nada disso.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

🤖 preview no ar → https://csbrasil-j5c0hqpss-rubenmarcus-projects.vercel.app

…codigo)

const env = import.meta.env seguido de env.API_PROXY_SECRET, ou destructuring,
capturava o objeto de env do build sem acender a régua. ER1 passou a exigir
acesso membro a membro (comentários fora da análise) e src/lib/site.ts trocou
a captura PUBLIC_ENV por leituras diretas por nome. Mutante le-segredo agora
usa exatamente a forma por alias.

Signed-off-by: rubenmarcus <rubenmarcus.dev@gmail.com>
Agent: omp/cf-secrets-runtime
Signed-off-by: rubenmarcus <rubenmarcus.dev@gmail.com>
Agent: omp/cf-secrets-runtime
@rubenmarcus

Copy link
Copy Markdown
Member Author

Review do estraga-codigo (thread sobre alias/destructuring em env-runtime-check): corrigido em 26f2008. ER1 agora reprova qualquer referencia nua a import.meta.env (alias const env = import.meta.env, destructuring), com comentarios fora da analise; src/lib/site.ts trocou a captura PUBLIC_ENV por acesso membro a membro; o mutante le-segredo passa a usar exatamente a forma por alias e continua vermelho. Thread resolvida.

@rubenmarcus rubenmarcus added estragacodigo-resolved Maintainer confirmed that estraga-codigo findings are resolved and removed needs-estragacodigo-resolution PR has an unresolved estraga-codigo finding labels Nov 9, 2026
@csbrasil-BOT csbrasil-BOT added needs-estragacodigo-resolution PR has an unresolved estraga-codigo finding and removed estragacodigo-resolved Maintainer confirmed that estraga-codigo findings are resolved labels Nov 9, 2026
@github-actions

github-actions Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

🟠 preview Cloudflare → https://743733e9-csb-preview.rubenmarcus-dev.workers.dev

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

🤖 preview no ar → https://csbrasil-fqy0h4o4i-rubenmarcus-projects.vercel.app

Signed-off-by: rubenmarcus <rubenmarcus.dev@gmail.com>

Agent: Claude Code
@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

🤖 preview no ar → https://csbrasil-k1xccmodk-rubenmarcus-projects.vercel.app

@estraga-codigo estraga-codigo left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Palhaço Mal

Palhaço Mal · code reviewer · 🤡

Change map

  • backend (9): env-runtime.ts, public-clan.ts, public-profile.ts, safe-url.ts …
  • site (6): worker.ts, middleware.ts, callback.ts, mapa.astro …
  • harness (6): apis-migradas-check.mjs, env-runtime-check.mjs, geo-proxy-check.mjs, sitemap-higiene-check.mjs …
  • other (2): package.json, eval-suites.test.mjs
  • CI (1): ci.yml

Note

Summary: The diff moves server-side environment reads out of build-time import.meta.env into a new runtime helper src/lib/env-runtime.ts (process.env first, import.meta.env fallback only for PUBLIC_API_BASE), converts supabaseAdmin from a module-level value into a lazily-created function, adds a Cloudflare bridge that copies the env binding into process.env, and introduces tools/eval/env-runtime-check.mjs (ER1 static scan + ER2 sentinel scan of build artifacts) wired into CI and the eval suites.

1 major · 0 minor

Warning

Risk MEDIUM · score 7.5/10 ▓▓▓▓▓▓▓▓░░
1 major finding(s). Resolve before merging.

Unresolved review threads block merging under the branch policy. Fix the finding or refute it with evidence.

🔴 Major findings (1)

  • Comment stripping can blank real code, letting ER1 miss a secret read — tools/eval/env-runtime-check.mjs:63 (action: backend-api)
    semComentarios removes // comments with /(^|[^:])\/\/[^\n]*/g and blanks the whole match, including anything after it on the same line. A // that is not preceded by a colon — a protocol-relative URL, a '//' inside a string literal, or any path containing // — makes the regex swallow the rest of the line, so a real import.meta.env.API_PROXY_SECRET read placed after such a literal is deleted before ER1 inspects the code. The quality gate then passes on a file that does inline a secret at build time, which is the exact defect the tool exists to prevent; the mutant le-segredo does not exercise this path, so the hole is not covered.
    💡 Fix: Strip string and template literals before removing comments (replace literal contents with empty quotes), or make the comment regex only match // at the start of a line or after whitespace, and add a mutant that hides a secret read behind a protocol-relative URL on the same line.

const semComentarios = (texto) => texto

  • .replace(/(['"`])(?:\.|(?!\1)[^\])\1/g, "''")
    .replace(//*[\s\S]
    ?*//g, (b) => b.replace(/[^\n]/g, ' '))
  > Suggested mutation: `Add a line in `src/` such as `const cdn = '//cdn.example.com'; const s = import.meta.env.API_PROXY_SECRET || '';` — ER1 strips the text after the `//` and reports a passing gate.`

### Cross-module impact

- src/middleware.ts
- src/pages/api/[rota].ts
- src/pages/auth/callback.ts
- src/pages/api/badge/[...path].png.ts
- src/pages/sitemap.xml.ts
- src/pages/mapa.astro

*(Local `public/js` import graph, which may lag behind the PR head.)*

---
Fix or refute each finding in its thread. Evidence settles the review.

— *Every bug leaves a trace in the diff. I ask the questions.* 🤡


const semComentarios = (texto) => texto
.replace(/\/\*[\s\S]*?\*\//g, (b) => b.replace(/[^\n]/g, ' '))
.replace(/(^|[^:])\/\/[^\n]*/g, (b) => b.replace(/[^\n]/g, ' '));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[major] Comment stripping can blank real code, letting ER1 miss a secret read

semComentarios removes // comments with /(^|[^:])\/\/[^\n]*/g and blanks the whole match, including anything after it on the same line. A // that is not preceded by a colon — a protocol-relative URL, a '//' inside a string literal, or any path containing // — makes the regex swallow the rest of the line, so a real import.meta.env.API_PROXY_SECRET read placed after such a literal is deleted before ER1 inspects the code. The quality gate then passes on a file that does inline a secret at build time, which is the exact defect the tool exists to prevent; the mutant le-segredo does not exercise this path, so the hole is not covered.

Tip

Fix: Strip string and template literals before removing comments (replace literal contents with empty quotes), or make the comment regex only match // at the start of a line or after whitespace, and add a mutant that hides a secret read behind a protocol-relative URL on the same line.

const semComentarios = (texto) => texto
+  .replace(/(['"`])(?:\\.|(?!\1)[^\\])*\1/g, "''")
   .replace(/\/\*[\s\S]*?\*\//g, (b) => b.replace(/[^\n]/g, ' '))

Mutation: Add a line in src/such asconst cdn = '//cdn.example.com'; const s = import.meta.env.API_PROXY_SECRET || '';— ER1 strips the text after the// and reports a passing gate.

@rubenmarcus
rubenmarcus merged commit b189f27 into staging Nov 9, 2026
55 of 57 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-estragacodigo-resolution PR has an unresolved estraga-codigo finding needs-human-backend Change requires human backend/Supabase/anti-cheat review needs-staging Change requires integrated validation in staging target:staging PR targets the staging integration branch

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants