Repository navigation
Segredos de SSR em runtime no Workers: env-runtime + ponte de bindings (achado 1 do spike CF) - #1276
Conversation
… 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
|
The latest updates on your projects. Learn more about Vercel for GitHub. |
csbrasil-bot classificationNote @rubenmarcus opened a PR with 24 file(s) · +282 −51, targeting staging. What changed
Labels
Caution An estraga-codigo finding is unresolved. Resolve it before applying |
|
🤖 preview no ar → https://csbrasil-rgyjpmlbt-rubenmarcus-projects.vercel.app |
estraga-codigo
left a comment
There was a problem hiding this comment.
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 directimport.meta.env.SECRETaccess and bracket access, but it does not detect an alias or destructuring such asconst env = import.meta.env; env.API_PROXY_SECRETorconst { 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 everyimport.meta.envexpression except the statically allowedimport.meta.env.PUBLIC_API_BASEfallback, 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.* 🤡
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>
|
🤖 autofix: regenerei os blocos derivados e empurrei o commit. O PR não precisa de mais nada disso. |
|
🤖 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
|
Review do estraga-codigo (thread sobre alias/destructuring em env-runtime-check): corrigido em 26f2008. ER1 agora reprova qualquer referencia nua a |
|
🟠 preview Cloudflare → https://743733e9-csb-preview.rubenmarcus-dev.workers.dev |
|
🤖 preview no ar → https://csbrasil-fqy0h4o4i-rubenmarcus-projects.vercel.app |
Signed-off-by: rubenmarcus <rubenmarcus.dev@gmail.com> Agent: Claude Code
|
🤖 preview no ar → https://csbrasil-k1xccmodk-rubenmarcus-projects.vercel.app |
estraga-codigo
left a comment
There was a problem hiding this comment.
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)
semComentariosremoves//comments with/(^|[^:])\/\/[^\n]*/gand 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 realimport.meta.env.API_PROXY_SECRETread 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 mutantle-segredodoes 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, ' ')); |
There was a problem hiding this comment.
[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 insrc/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.
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_TOKENePUBLIC_API_BASEno bundle SSR no momento do build. Na Vercel funciona porque o build roda com as envs de produção; no Workers,wrangler secret putnunca 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.envPOR REQUISIÇÃO; fallback deimport.meta.envsó paraPUBLIC_*, por nome estático (referência ao objeto inteiro materializaria os segredos do build no chunk).backendUrl()encapsula o default dePUBLIC_API_BASE.src/pages/api/[rota].ts,auth/callback.ts,public-clan.ts,public-profile.ts,safe-url.ts,x-conversions.ts,supabase.ts(supabaseAdminvira leitura lazy por chamada; chamadores em badge, mapa e sitemaps atualizados) esrc/middleware.ts(BACKEND sai do load do módulo).src/cf/worker.ts: ponte que copia as strings do bindingenvdo fetch paraprocess.env(idempotente). Precedência OBSERVADA e documentada no runbook:[vars]entram no build vialoadWranglerEnvE no runtime via binding; segredos dewrangler secret putchegam SÓ no runtime;process.envnão nasce populado no bundle do Astro (banner do adaptador cria stub vazio).process.env.eval:envruntime(tools/eval/env-runtime-check.mjs): ER1 proíbeimport.meta.env.<segredo>e captura dinâmicaimport.meta.env[emsrc/; ER2 varredist/server,dist/client,.vercel/output/functions|staticatrás de sentinelas. No pr-fast entra ao lado deeval:vercelignore(ER1 + 2 mutantes) e o jobmapas-e-sitepassa a buildar comSENTINEL_*no env e varrer o artefato (--varre). Também nocheck:fast(suites.mjs + baseline de chore: régua eval:lixo (LX1-LX5) + bloco 1 da limpeza #1259 atualizado com NOVOS).import.meta.envatualizadas para também popularprocess.env:sitemap-paginacao,sitemap-higiene;apis-migradasegeo-proxyajustadas para a nova forma de leitura.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)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/outputedist).ENVRUNTIME_BUILD_CMD="npm run build:cf" ... --com-build):APROVADOidem emdist/server.csb-spike(deploy desta branch, MESMO build nos três passos):GET /api/badge/teste.pngsem segredo:503 {"error":"not_configured"}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)wrangler secret delete: volta exatamente a503 {"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").wrangler dev, mesmo bundle, config com o segredo no binding) o middleware logou[server-traffic] ingest status 403: o segredo descartável foi lido deprocess.env, enviado comox-csb-proxy-authe o backend rejeitou com 403. No deploy,POST /api/uniquedá403 {"error":"proxy_required"}com ou sem segredo ERRADO por design do backend (segredo inválido cai no mododireto, sem oráculo de qual foi o motivo).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
supabaseAdminmudou 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).src/cf/worker.tsé aditiva: no workerd puro oprocess.envjá pode vir populado; a ponte garante a semântica em qualquer caso (só grava chave ausente).profile-character-check,submit-guard-check,backend-hints-checkesocial-entry-contractestão vermelhos TAMBÉM na staging limpa (artefatos.vercel/outputobsoletos 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 preexistenteeval:tp-glove-origin"Node22 required" nesta máquina com Node 26).Feito com assistência de IA (omp/cf-secrets-runtime), revisado por mim.