diff --git a/.env.example b/.env.example index 19ca4a8..feb424e 100644 --- a/.env.example +++ b/.env.example @@ -13,6 +13,11 @@ # navegador — as do backend abaixo nunca são expostas. VITE_SOCKET_URL=ws://localhost:8080 +# Endereço oficial do site (ex.: https://webchat.gcruz.dev.br). Com ele, quem +# abre o site pelo endereço do Render (*.onrender.com) é redirecionado para o +# mesmo caminho e convite no domínio próprio. Vazia: sem redirecionamento. +# VITE_PUBLIC_URL= + # ─── Backend ──────────────────────────────────────────────────────────── # Origens autorizadas a abrir conexão, separadas por vírgula, no formato # esquema://host[:porta], sem caminho (ex.: https://meuchat.com,http://localhost:5173). diff --git a/backend/src/config.js b/backend/src/config.js index 6ca6786..3036324 100644 --- a/backend/src/config.js +++ b/backend/src/config.js @@ -216,7 +216,7 @@ export const loadConfig = (env) => { throw new ConfigError( "ALLOWED_ORIGINS", "ALLOWED_ORIGINS é obrigatória em produção (NODE_ENV=production): informe a origem " + - "do frontend, ex.: https://chat-frontend-g42t.onrender.com.", + "do frontend, ex.: https://webchat.gcruz.dev.br.", ); } diff --git a/docs/DEPLOY_RENDER.md b/docs/DEPLOY_RENDER.md index ad6a5d0..7f9872f 100644 --- a/docs/DEPLOY_RENDER.md +++ b/docs/DEPLOY_RENDER.md @@ -18,15 +18,32 @@ a sala está no teto de conexões. Como health check, isso faria o Render reinic serviço exatamente no momento de maior uso. `/healthz` só confirma que o processo responde. +## Domínios + +| Serviço | Domínio próprio | Endereço do Render (continua ativo) | +| --------------- | -------------------------- | ----------------------------------- | +| `chat-frontend` | `webchat.gcruz.dev.br` | `chat-frontend-g42t.onrender.com` | +| `chat-backend` | `webchat-api.gcruz.dev.br` | `chat-backend-3sxv.onrender.com` | + +Os dois domínios são registros CNAME na Cloudflare, com o proxy desligado (DNS +only), apontando para o endereço do Render de cada serviço; o certificado é +emitido pelo Render. Durante a transição, `ALLOWED_ORIGINS` aceita as duas +origens do site e o `connect-src` da CSP aceita os dois endereços do backend. +Quando os endereços do Render forem desativados, remova-os das duas listas. +Com `VITE_PUBLIC_URL` definida no build, quem abre o site pelo +`chat-frontend-g42t.onrender.com` é redirecionado para o mesmo caminho e +convite em `webchat.gcruz.dev.br` (`frontend/src/publicHost.js`). + ## Variáveis de ambiente -| Serviço | Variável | Valor | Natureza | -| --------------- | ----------------- | ----------------------------------------- | ----------------------------------------- | -| `chat-backend` | `NODE_VERSION` | `22` | Pública — igual ao CI | -| `chat-backend` | `ALLOWED_ORIGINS` | `https://chat-frontend-g42t.onrender.com` | Pública | -| `chat-backend` | `ADMIN_KEY` | definida no painel (`sync: false`) | **Segredo** — nunca no repositório | -| `chat-frontend` | `NODE_VERSION` | `22` | Pública | -| `chat-frontend` | `VITE_SOCKET_URL` | `wss://chat-backend-3sxv.onrender.com` | Pública — embutida no JavaScript no build | +| Serviço | Variável | Valor | Natureza | +| --------------- | ----------------- | ---------------------------------------------------------------------- | ----------------------------------------- | +| `chat-backend` | `NODE_VERSION` | `22` | Pública — igual ao CI | +| `chat-backend` | `ALLOWED_ORIGINS` | `https://webchat.gcruz.dev.br,https://chat-frontend-g42t.onrender.com` | Pública | +| `chat-backend` | `ADMIN_KEY` | definida no painel (`sync: false`) | **Segredo** — nunca no repositório | +| `chat-frontend` | `NODE_VERSION` | `22` | Pública | +| `chat-frontend` | `VITE_SOCKET_URL` | `wss://webchat-api.gcruz.dev.br` | Pública — embutida no JavaScript no build | +| `chat-frontend` | `VITE_PUBLIC_URL` | `https://webchat.gcruz.dev.br` | Pública — redireciona o onrender.com | As demais variáveis do backend (limites, heartbeat, métricas) usam os padrões do código; a lista completa está no [README](../README.md#configuração-do-ambiente). @@ -88,14 +105,14 @@ e salve (o Render faz um novo deploy). ## Verificação depois do deploy ```bash -curl -sS https://chat-backend-3sxv.onrender.com/healthz +curl -sS https://webchat-api.gcruz.dev.br/healthz ``` ```bash -curl -sSI https://chat-frontend-g42t.onrender.com/ | grep -iE "content-security|x-frame|permissions|referrer" +curl -sSI https://webchat.gcruz.dev.br/ | grep -iE "content-security|x-frame|permissions|referrer" ``` -E no navegador, em https://chat-frontend-g42t.onrender.com: +E no navegador, em https://webchat.gcruz.dev.br: - entrar com nome completo e nome de usuário; - enviar `/ping` (resposta só para você); diff --git a/docs/PRODUCAO.md b/docs/PRODUCAO.md index f2b39d5..aa947d8 100644 --- a/docs/PRODUCAO.md +++ b/docs/PRODUCAO.md @@ -107,10 +107,10 @@ Tudo precisa passar. O CI repete essas etapas no PR. 4. Verificar: ```bash -curl -sS https://chat-backend-3sxv.onrender.com/healthz +curl -sS https://webchat-api.gcruz.dev.br/healthz ``` -5. No navegador, em https://chat-frontend-g42t.onrender.com: entrar, conferir que +5. No navegador, em https://webchat.gcruz.dev.br: entrar, conferir que o endereço virou `…/#/s/código`, abrir o link em outra aba anônima, trocar mensagens, `/ping`, Sair. diff --git a/frontend/src/main.js b/frontend/src/main.js index 9097479..9db4cca 100644 --- a/frontend/src/main.js +++ b/frontend/src/main.js @@ -1,5 +1,7 @@ // @ts-check +// Primeiro: quem chega pelo endereço antigo é levado ao domínio próprio. +import "./publicHost.js"; import { SOCKET_URL, TIMING } from "./config.js"; import { CLIENT_EVENTS, CLOSE_CODES, ERROR_CODES, REACTION_EMOJIS } from "./protocol.js"; import { routeInput } from "./commands/input.js"; diff --git a/frontend/src/publicHost.js b/frontend/src/publicHost.js new file mode 100644 index 0000000..16cc50e --- /dev/null +++ b/frontend/src/publicHost.js @@ -0,0 +1,39 @@ +// @ts-check + +/** + * Endereço antigo → domínio próprio. + * + * Com `VITE_PUBLIC_URL` definida no build (ex.: https://webchat.gcruz.dev.br), + * quem abre o site pelo endereço do Render (*.onrender.com) é levado ao mesmo + * caminho, query e fragmento no domínio próprio — um convite `#/s/código` + * continua valendo. Sem a variável, ou em qualquer outro host (o próprio + * domínio, localhost, um preview), nada acontece. + * + * Um site estático do Render não tem redirecionamento por host; por isso o + * redirecionamento é feito aqui, no primeiro módulo carregado por `main.js`. + */ + +/** + * @param {{ hostname: string, pathname: string, search: string, hash: string }} location + * @param {unknown} publicUrl + * @returns {string | null} URL de destino, ou null quando não há o que redirecionar. + */ +export const publicRedirect = (location, publicUrl) => { + if (typeof publicUrl !== "string" || publicUrl === "") return null; + let target; + try { + target = new URL(publicUrl); + } catch { + return null; + } + if (target.protocol !== "https:" && target.protocol !== "http:") return null; + const host = location.hostname.toLowerCase(); + if (!host.endsWith(".onrender.com") || host === target.hostname) return null; + return `${target.origin}${location.pathname}${location.search}${location.hash}`; +}; + +const destination = + typeof window === "undefined" + ? null + : publicRedirect(window.location, import.meta.env?.VITE_PUBLIC_URL); +if (destination) window.location.replace(destination); diff --git a/frontend/test/publicHost.test.js b/frontend/test/publicHost.test.js new file mode 100644 index 0000000..6934c13 --- /dev/null +++ b/frontend/test/publicHost.test.js @@ -0,0 +1,35 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { publicRedirect } from "../src/publicHost.js"; + +const PUBLIC = "https://webchat.gcruz.dev.br"; +const at = (hostname, pathname = "/", search = "", hash = "") => ({ + hostname, + pathname, + search, + hash, +}); + +test("endereço do Render vai para o domínio próprio com caminho, query e convite", () => { + assert.equal( + publicRedirect(at("chat-frontend-g42t.onrender.com", "/", "?a=1", "#/s/ABC123"), PUBLIC), + "https://webchat.gcruz.dev.br/?a=1#/s/ABC123", + ); + assert.equal( + publicRedirect(at("Chat-Frontend-G42T.onrender.com", "/x"), `${PUBLIC}/`), + "https://webchat.gcruz.dev.br/x", + ); +}); + +test("sem VITE_PUBLIC_URL, ou com valor inválido, nada muda", () => { + const old = at("chat-frontend-g42t.onrender.com"); + for (const bad of [undefined, "", "webchat.gcruz.dev.br", "ftp://webchat.gcruz.dev.br", 42]) { + assert.equal(publicRedirect(old, bad), null, String(bad)); + } +}); + +test("o próprio domínio, localhost e outros hosts não redirecionam", () => { + for (const host of ["webchat.gcruz.dev.br", "localhost", "127.0.0.1", "exemplo.com"]) { + assert.equal(publicRedirect(at(host), PUBLIC), null, host); + } +}); diff --git a/infra/render-frontend-headers.yaml b/infra/render-frontend-headers.yaml index 2ab9137..3920c27 100644 --- a/infra/render-frontend-headers.yaml +++ b/infra/render-frontend-headers.yaml @@ -27,7 +27,7 @@ services: headers: - path: /* name: Content-Security-Policy - value: "default-src 'self'; script-src 'self' 'sha256-Fi5GNExRuHFNJT41G5L8f9zpBwwJ0I4ywQTVAiJUGhs='; style-src 'self' https://fonts.googleapis.com; font-src https://fonts.gstatic.com; img-src 'self'; connect-src 'self' wss://chat-backend-3sxv.onrender.com; base-uri 'self'; form-action 'self'; object-src 'none'; frame-ancestors 'none'" + value: "default-src 'self'; script-src 'self' 'sha256-Fi5GNExRuHFNJT41G5L8f9zpBwwJ0I4ywQTVAiJUGhs='; style-src 'self' https://fonts.googleapis.com; font-src https://fonts.gstatic.com; img-src 'self'; connect-src 'self' wss://webchat-api.gcruz.dev.br wss://chat-backend-3sxv.onrender.com; base-uri 'self'; form-action 'self'; object-src 'none'; frame-ancestors 'none'" - path: /* name: X-Frame-Options value: DENY diff --git a/render.yaml b/render.yaml index e3388fd..6cf8d80 100644 --- a/render.yaml +++ b/render.yaml @@ -36,7 +36,7 @@ services: # domínio, acrescente-o separado por vírgula (origem completa: # esquema + host [+ porta], sem barra final e sem curinga). - key: ALLOWED_ORIGINS - value: https://chat-frontend-g42t.onrender.com + value: https://webchat.gcruz.dev.br,https://chat-frontend-g42t.onrender.com # Chave de administração (/admin). Segredo: definida só no painel. - key: ADMIN_KEY sync: false @@ -54,7 +54,10 @@ services: value: "22" # Embutido no JavaScript no momento do build (público por natureza). - key: VITE_SOCKET_URL - value: wss://chat-backend-3sxv.onrender.com + value: wss://webchat-api.gcruz.dev.br + # Endereço oficial: quem abre o site pelo onrender.com é levado para cá. + - key: VITE_PUBLIC_URL + value: https://webchat.gcruz.dev.br headers: # CSP como cabeçalho HTTP: é o único jeito de `frame-ancestors` # valer (no ele é ignorado). Espelha a CSP do index.html, com @@ -62,7 +65,7 @@ services: # tema inline — se o script mudar, o hash muda aqui e no HTML. - path: /* name: Content-Security-Policy - value: "default-src 'self'; script-src 'self' 'sha256-Fi5GNExRuHFNJT41G5L8f9zpBwwJ0I4ywQTVAiJUGhs='; style-src 'self' https://fonts.googleapis.com; font-src https://fonts.gstatic.com; img-src 'self'; connect-src 'self' wss://chat-backend-3sxv.onrender.com; base-uri 'self'; form-action 'self'; object-src 'none'; frame-ancestors 'none'" + value: "default-src 'self'; script-src 'self' 'sha256-Fi5GNExRuHFNJT41G5L8f9zpBwwJ0I4ywQTVAiJUGhs='; style-src 'self' https://fonts.googleapis.com; font-src https://fonts.gstatic.com; img-src 'self'; connect-src 'self' wss://webchat-api.gcruz.dev.br wss://chat-backend-3sxv.onrender.com; base-uri 'self'; form-action 'self'; object-src 'none'; frame-ancestors 'none'" # Navegadores antigos que não conhecem frame-ancestors. - path: /* name: X-Frame-Options