Skip to content

hotfix: corrige double-encoding em robots.txt, sitemap.xml, cors.ts e .tsc-baseline.json (PR #618)#622

Merged
adm01-debug merged 4 commits into
mainfrom
hotfix/double-encoded-20260602
Jun 3, 2026
Merged

hotfix: corrige double-encoding em robots.txt, sitemap.xml, cors.ts e .tsc-baseline.json (PR #618)#622
adm01-debug merged 4 commits into
mainfrom
hotfix/double-encoded-20260602

Conversation

@adm01-debug
Copy link
Copy Markdown
Owner

@adm01-debug adm01-debug commented Jun 3, 2026

🔥 Hotfix: Corrige Double-Encoding (PR #618)

Diagnóstico

Todos os 4 arquivos tinham seus conteúdos corretos codificados em base64 dentro do arquivo, ao invés do texto/código real. Isso aconteceu porque na criação do PR #618, o conteúdo já estava pré-codificado em base64 antes de ser passado ao github_create_or_update_file, causando dupla codificação.

Prova da Correção (comparação de tamanhos)

Arquivo Antes (double-encoded) Depois (correto) Redução
public/robots.txt 284 bytes (base64) 212 bytes (texto)
public/sitemap.xml 2.160 bytes (base64) 1.618 bytes (XML)
cors.ts 11.580 bytes (base64) 8.683 bytes (TypeScript)
.tsc-baseline.json 9.516 bytes (base64) 7.137 bytes (JSON)

Impacto Real dos Bugs

Arquivo Impacto no sistema
robots.txt SEO quebrado — bots viam string base64, não as diretivas
sitemap.xml SEO quebrado — Google indexava base64, não as 11 URLs
cors.ts Edge functions Supabase quebradas — deploy falhava (TypeScript inválido)
.tsc-baseline.json CI Quality Gate falhava — JSON inválido para tsc/eslint

Arquivos NÃO alterados (já corretos)

  • src/hooks/auth/useProfileRoles.ts — TypeScript real, BUG-01/02/03 corretos (20/20 checks)
  • index.html — HTML real, BUG-06 correto

Validação Pós-Merge

# robots.txt: deve iniciar com "User-agent:"
curl -s https://www.promogifts.com.br/robots.txt | head -1

# sitemap.xml: deve iniciar com "<?xml"
curl -s https://www.promogifts.com.br/sitemap.xml | head -1

# cors.ts: TypeScript real (não base64)
head -1 supabase/functions/_shared/cors.ts
# Esperado: // supabase/functions/_shared/cors.ts

# .tsc-baseline.json: JSON válido
python3 -c "import json; d=json.load(open('.tsc-baseline.json')); print('totalErrors:', d['totalErrors'])"
# Esperado: totalErrors: 335

Summary by cubic

Fixes double-encoded files and tightens CORS defaults. Restores valid text/XML/TS/JSON so SEO, edge functions, and CI work as expected.

  • Bug Fixes

    • Replaced base64 content with real text in public/robots.txt and real XML in public/sitemap.xml to restore SEO.
    • Restored TypeScript in supabase/functions/_shared/cors.ts and valid JSON in .tsc-baseline.json (now totalErrors: 335) to fix edge deploys and CI.
  • Security

    • CORS fallback for unknown origins now points to https://www.promogifts.com.br.
    • Removed https://pqpdolkaeqlyzpdpbizo.supabase.co from the allowlist.

Written for commit cf8108d. Summary will update on new commits.

Review in cubic

Summary by CodeRabbit

Release Notes

  • Chores
    • Atualização de configurações de segurança (CORS) nas edge functions.
    • Otimização e reformatação de arquivos de SEO (robots.txt e sitemap.xml).
    • Ajustes internos de baseline de tipo TypeScript.

…cript UTF-8 direto; fallback→www.promogifts.com.br; remove pqpdolkaeqlyzpdpbizo
…N UTF-8 direto; useProfileRoles removido, totalErrors 337→335
Copilot AI review requested due to automatic review settings June 3, 2026 00:03
@chatgpt-codex-connector
Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@vercel
Copy link
Copy Markdown

vercel Bot commented Jun 3, 2026

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

Project Deployment Actions Updated (UTC)
we-dream-big Ready Ready Preview, Comment Jun 3, 2026 12:03am

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jun 3, 2026

Review Change Stack

Caution

Review failed

Pull request was closed or merged during review

Walkthrough

Atualização de configuração centralizada de CORS para edge functions com fallback para produção, reformatação de arquivos estáticos SEO (robots/sitemap) e recalibração do baseline de erros TypeScript.

Changes

SEO Static Files

Layer / File(s) Summary
Robots and Sitemap formatting
public/robots.txt, public/sitemap.xml
Robots.txt reescrito com regras explícitas para User-agents específicos (Googlebot, Bingbot, Twitterbot, facebookexternalhit) e padrão (*); sitemap.xml reformatado em múltiplas linhas preservando URLs, changefreq e priority sem alteração de conteúdo.

TypeScript Baseline Update

Layer / File(s) Summary
Error counts recalibration
.tsc-baseline.json
Timestamp atualizado para 2026-06-02T23:38:00.000Z, totalErrors ajustado de 333 para 335 e mapa counts recalibrado com redistribuição de erros por arquivo e código TypeScript.

CORS Configuration and Validation

Layer / File(s) Summary
Allowlist and headers configuration
supabase/functions/_shared/cors.ts
Allowlist de origens agora usa conjunto exato + padrões (ALLOWED_ORIGIN_PATTERNS); headers permitidos normalizados em set/value; SECURITY_HEADERS e CORS_HEADERS_BASE definidos para composição de respostas CORS + políticas de segurança.
Origin and header validation functions
supabase/functions/_shared/cors.ts
parseHeaderList() normaliza headers solicitados; isAllowedOrigin() valida contra allowlist exato e padrões; getBestAllowedOrigin() muda fallback para URL de produção (https://www.promogifts.com.br) em vez de Lovable dev.
Structured CORS event logging
supabase/functions/_shared/cors.ts
logCorsEvent mantém estrutura de eventos com bootLogged; logPreflightFromRequest() processa OPTIONS com leitura case-insensitive de headers, calcula missing_headers e origin_allowed, registra eventos warn com hints para rejeições.
Public CORS header API
supabase/functions/_shared/cors.ts
getCorsHeaders() espelha Access-Control-Allow-Origin com melhor valor permitido e aciona logging; handleCorsPreflightIfNeeded() retorna Response para OPTIONS; buildPublicCorsHeaders() monta headers para endpoints públicos com wildcard + SECURITY_HEADERS; handleCorsPreflight() unifica tratamento público/restrito; publicCorsHeaders e CORS_INTROSPECTION exportados para testes/introspecção.

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

  • adm01-debug/promo-gifts-v4#560: Ambas atualizam .tsc-baseline.json com novos totais e distribuições de erros TypeScript no "baseline ratchet".
  • adm01-debug/promo-gifts-v4#39: Ambas alteram lógica de allowlist e validação de Origin em supabase/functions/_shared/cors.ts.
  • adm01-debug/promo-gifts-v4#136: Refatoração em cors.ts (buildPublicCorsHeaders, allowlist, headers) diretamente relacionada a como simulation-orchestrator e sync-external-db usam esses helpers.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed O título é específico e descreve com clareza a correção principal: double-encoding em quatro arquivos chave. Relacionado diretamente ao changeset.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch hotfix/double-encoded-20260602

Comment @coderabbitai help to get the list of available commands and usage tips.

@supabase
Copy link
Copy Markdown

supabase Bot commented Jun 3, 2026

This pull request has been ignored for the connected project doufsxqlfjyuvxuezpln due to reaching the limit of concurrent preview branches.
Go to Project Integrations Settings ↗︎ if you wish to update this limit.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@adm01-debug adm01-debug merged commit e581db6 into main Jun 3, 2026
35 of 52 checks passed
@adm01-debug adm01-debug deleted the hotfix/double-encoded-20260602 branch June 3, 2026 00:06
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This hotfix restores four files that were accidentally committed as base64 payloads (double-encoded), replacing them with their intended plain-text content so SEO assets, Edge Functions, and CI tooling can parse them correctly.

Changes:

  • Restored readable robots.txt and valid sitemap.xml to re-enable correct crawler directives and URL discovery.
  • Restored TypeScript source for supabase/functions/_shared/cors.ts, including the intended production fallback origin and allowlist updates.
  • Restored valid JSON for .tsc-baseline.json so TypeScript/quality gates can consume the baseline again.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.

File Description
supabase/functions/_shared/cors.ts Replaces base64 content with real TypeScript CORS helper code used across Edge Functions.
public/sitemap.xml Replaces base64 content with real XML sitemap entries for www.promogifts.com.br.
public/robots.txt Replaces base64 content with real robots directives and correct sitemap URL.
.tsc-baseline.json Replaces base64 content with valid JSON baseline so CI/typecheck tooling can read it.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +66 to +71
const CORS_HEADERS_BASE = {
'Access-Control-Allow-Headers': ALLOWED_HEADERS_VALUE,
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Expose-Headers': 'x-request-id',
...SECURITY_HEADERS,
} as const;
Comment on lines +178 to +182
return {
...CORS_HEADERS_BASE,
...SECURITY_HEADERS,
'Access-Control-Allow-Origin': getBestAllowedOrigin(origin),
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants