Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
2 changes: 1 addition & 1 deletion backend/src/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
);
}

Expand Down
37 changes: 27 additions & 10 deletions docs/DEPLOY_RENDER.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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ê);
Expand Down
4 changes: 2 additions & 2 deletions docs/PRODUCAO.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 2 additions & 0 deletions frontend/src/main.js
Original file line number Diff line number Diff line change
@@ -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";
Expand Down
39 changes: 39 additions & 0 deletions frontend/src/publicHost.js
Original file line number Diff line number Diff line change
@@ -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);
35 changes: 35 additions & 0 deletions frontend/test/publicHost.test.js
Original file line number Diff line number Diff line change
@@ -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);
}
});
2 changes: 1 addition & 1 deletion infra/render-frontend-headers.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 6 additions & 3 deletions render.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -54,15 +54,18 @@ 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 <meta> ele é ignorado). Espelha a CSP do index.html, com
# o WebSocket restrito ao backend oficial. O hash é o do script de
# 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
Expand Down
Loading